<template>
  <el-dialog
    :title="$t('editInspectionPoint.title')"
    :visible.sync="visible"
    width="80%"
    @close="handleClose"
  >
    <el-form :model="editInspectionPointInfo" label-width="120px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="$t('editInspectionPoint.pointName')" required>
            <el-input 
              v-model="editInspectionPointInfo.inspectionName"
              :placeholder="$t('editInspectionPoint.pointNamePlaceholder')"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('editInspectionPoint.inspectionType')" required>
            <el-select 
              v-model="editInspectionPointInfo.pointObjType"
              @change="handleTypeChange"
              :placeholder="$t('editInspectionPoint.typePlaceholder')"
            >
              <el-option
                v-for="item in editInspectionPointInfo.pointObjTypes"
                :key="item.statusCd"
                :label="item.name"
                :value="item.statusCd"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20" v-if="editInspectionPointInfo.pointObjType === '2002'">
        <el-col :span="12">
          <el-form-item :label="$t('editInspectionPoint.location')" required>
            <el-input 
              v-model="editInspectionPointInfo.pointObjName"
              :placeholder="$t('editInspectionPoint.locationPlaceholder')"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20" v-if="editInspectionPointInfo.pointObjType === '1001'">
        <el-col :span="12">
          <el-form-item :label="$t('editInspectionPoint.inspectionDevice')" required>
            <machine-select 
              @machine-selected="handleMachineSelected"
              :initial-machine="initialMachine"
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="$t('editInspectionPoint.inspectionItem')" required>
            <el-select 
              v-model="editInspectionPointInfo.itemId"
              :placeholder="$t('editInspectionPoint.itemPlaceholder')"
            >
              <el-option
                v-for="item in editInspectionPointInfo.items"
                :key="item.itemId"
                :label="item.itemName"
                :value="item.itemId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="NFC编码">
            <el-input 
              v-model="editInspectionPointInfo.nfcCode"
              :placeholder="$t('editInspectionPoint.nfcPlaceholder')"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="$t('editInspectionPoint.longitude')">
            <el-input 
              v-model="editInspectionPointInfo.lng"
              disabled
              :placeholder="$t('editInspectionPoint.longitudePlaceholder')"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('editInspectionPoint.latitude')">
            <el-input 
              v-model="editInspectionPointInfo.lat"
              disabled
              :placeholder="$t('editInspectionPoint.latitudePlaceholder')"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="$t('editInspectionPoint.remark')">
            <el-input 
              type="textarea"
              v-model="editInspectionPointInfo.remark"
              :placeholder="$t('editInspectionPoint.remarkPlaceholder')"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row>
        <el-col :span="24">
          <div id="editInspectionPointMap" style="width:100%;height:300px;"></div>
        </el-col>
      </el-row>
    </el-form>
    
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">{{ $t('common.cancel') }}</el-button>
      <el-button type="primary" @click="handleSave">{{ $t('common.save') }}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { updateInspectionPoint } from '@/api/inspection/editInspectionPointApi'
import { listInspectionItem } from '@/api/inspection/inspectionItemApi'
import { getDict } from '@/api/community/communityApi'
import MachineSelect from '@/components/property/machineSelect2'

export default {
  name: 'EditInspectionPoint',
  components: {
    MachineSelect
  },
  data() {
    return {
      visible: false,
      editInspectionPointInfo: {
        inspectionId: '',
        pointObjId: '',
        pointObjType: '',
        pointObjTypes: [],
        pointObjName: '',
        inspectionName: '',
        communityId: '',
        remark: '',
        items: [],
        itemId: '',
        nfcCode: '',
        lng: '',
        lat: ''
      },
      initialMachine: null
    }
  },
  methods: {
    async open(editData) {
      this.resetForm()
      
      // 加载字典数据
      try {
        const pointObjTypes = await getDict('inspection_point', 'point_obj_type')
        this.editInspectionPointInfo.pointObjTypes = pointObjTypes
      } catch (error) {
        console.error('获取字典数据失败:', error)
      }
      
      // 加载巡检项目
      try {
        const items = await listInspectionItem({
          communityId: this.editInspectionPointInfo.communityId,
          page: 1,
          row: 100
        })
        this.editInspectionPointInfo.items = items.data
      } catch (error) {
        console.error('加载巡检项目失败:', error)
      }
      
      // 填充表单数据
      Object.keys(editData).forEach(key => {
        if (this.editInspectionPointInfo.hasOwnProperty(key)) {
          this.editInspectionPointInfo[key] = editData[key]
        }
      })
      
      // 设置初始设备（如果是设备类型）
      if (this.editInspectionPointInfo.pointObjType === '1001') {
        this.initialMachine = {
          machineId: this.editInspectionPointInfo.pointObjId,
          machineName: this.editInspectionPointInfo.pointObjName
        }
      }
      
      this.visible = true
      
      this.$nextTick(() => {
        this.initMap()
      })
    },
    
    resetForm() {
      this.editInspectionPointInfo = {
        inspectionId: '',
        pointObjId: '',
        pointObjType: '',
        pointObjTypes: [],
        pointObjName: '',
        inspectionName: '',
        communityId: getCommunityId(),
        remark: '',
        items: [],
        itemId: '',
        nfcCode: '',
        lng: '',
        lat: ''
      }
      this.initialMachine = null
    },
    
    handleClose() {
      this.resetForm()
    },
    
    handleTypeChange(value) {
      if (value === '1001') {
        this.editInspectionPointInfo.pointObjId = ''
        this.editInspectionPointInfo.pointObjName = ''
      } else if (value === '2002') {
        this.editInspectionPointInfo.pointObjId = '-1'
      }
    },
    
    handleMachineSelected(machine) {
      this.editInspectionPointInfo.pointObjId = machine.machineId
      this.editInspectionPointInfo.pointObjName = machine.machineName
    },
    
    initMap() {
      // 这里初始化地图，实际实现需要根据地图API
      console.log('初始化编辑巡检点地图')
    },
    
    async handleSave() {
      // 表单验证
      if (!this.validateForm()) return
      
      try {
        await updateInspectionPoint(this.editInspectionPointInfo)
        this.$message.success(this.$t('common.saveSuccess'))
        this.visible = false
        this.$emit('saved')
      } catch (error) {
        console.error('保存巡检点失败:', error)
        this.$message.error(error.message || this.$t('common.saveFailed'))
      }
    },
    
    validateForm() {
      if (!this.editInspectionPointInfo.inspectionName) {
        this.$message.warning(this.$t('editInspectionPoint.validate.pointName'))
        return false
      }
      
      if (!this.editInspectionPointInfo.pointObjType) {
        this.$message.warning(this.$t('editInspectionPoint.validate.pointType'))
        return false
      }
      
      if (this.editInspectionPointInfo.pointObjType === '2002' && !this.editInspectionPointInfo.pointObjName) {
        this.$message.warning(this.$t('editInspectionPoint.validate.location'))
        return false
      }
      
      if (this.editInspectionPointInfo.pointObjType === '1001' && !this.editInspectionPointInfo.pointObjId) {
        this.$message.warning(this.$t('editInspectionPoint.validate.device'))
        return false
      }
      
      if (!this.editInspectionPointInfo.itemId) {
        this.$message.warning(this.$t('editInspectionPoint.validate.item'))
        return false
      }
      
      return true
    }
  }
}
</script>