<script lang="ts" setup name="EditArea">
import type { FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getDictByCode } from '@/api/system/dict'
import { addDeviceList, updateDeviceList } from '@/api/api/index'
const emits = defineEmits(['refresh'])
const dataFormRef = ref()
const dialogFormVisible = ref(false) // 对话框是否显示
const dialogStatus = ref('') // 对话框类型：create,update
const isEditMode = ref(true)
const areaForm = ref({
  deviceName: '', // 设备名称
  deviceType: '', // 设备类型
  deviceNo: '', // 设备编号
  installLocaltion: '', // 安装位置
  installTime: '', // 安装时间
  ptn: '', // 所属分区
  stat: '', // 状态
  monitorObj: '', // 监测对象
  facilityArea: '', // 设施面积

}) // 表单
const textMap: { [key: string]: string } = {
  update: '编辑',
  create: '新增',
} // 表头显示标题
const btnLoading = ref(false) // 保存按钮的加载中状态
const rules: FormRules = {
  deviceName: [{ required: true, message: '设备名称不能为空', trigger: ['blur', 'change'] }],
  deviceType: [{ required: true, message: '设备类型不能为空', trigger: ['blur', 'change'] }],
  installLocaltion: [{ required: true, message: '安装位置不能为空', trigger: ['blur', 'change'] }],
  deviceNo: [{ required: true, message: '设备编号为空', trigger: ['blur', 'change'] }],
  installTime: [{ required: true, message: '安装时间不能为空', trigger: ['blur', 'change'] }],
  ptn: [{ required: true, message: '所属分区不能为空', trigger: ['blur', 'change'] }],
  stat: [{ required: true, message: '状态不能为空', trigger: ['blur', 'change'] }],
  monitorObj: [{ required: true, message: '监测对象不能为空', trigger: ['blur', 'change'] }],
  facilityArea: [{ required: true, message: '设施面积不能为空', trigger: ['blur', 'change'] }],
} // 前端校验规则

// 重置表单
const resetForm = () => {
  areaForm.value = {
    deviceName: '', // 设备名称
    deviceType: '', // 设备类型
    deviceNo: '', // 设备编号
    installLocaltion: '', // 安装位置
    installTime: '', // 安装时间
    ptn: '', // 所属分区
    stat: '', // 状态
    monitorObj: '', // 监测对象
    facilityArea: '', // 设施面积
  }
}
const ptnList = ref([])
// 获取所属分区列表
const fetchptnList = () => {
  getDictByCode('ptn_type').then((res) => {
    ptnList.value = res.data
  })
}
fetchptnList()
// 获取监测对象
const monitorObjList = ref<any>([])
const fetchMonitorObj = () => {
  getDictByCode('monitor_obj').then((res) => {
    monitorObjList.value = res.data
  })
}
fetchMonitorObj()
const deviceTypeList = ref([])
// 获取设备类型列表
const fetchDeviceType = () => {
  getDictByCode('device_type').then((res) => {
    deviceTypeList.value = res.data
  })
}
const deviceStatusList = ref([])
// 获取设备状态列表
const fetchDeviceStatus = () => {
  getDictByCode('stat_type').then((res) => {
    deviceStatusList.value = res.data
  })
}
fetchDeviceType()
fetchDeviceStatus()
// 初始化对话框
const initDialog = (dialogStatusValue: string, row: any) => {
  dialogStatus.value = dialogStatusValue
  dialogFormVisible.value = true
  btnLoading.value = false
  if (dialogStatus.value === 'create') { // 如果是新增，清除验证
    resetForm()
    isEditMode.value = false
    nextTick(() => {
      dataFormRef.value.clearValidate()
    })
  }
  else if (dialogStatus.value === 'update') { // 如果是修改，将row中数据填写到输入框中
    areaForm.value = row
    isEditMode.value = true
  }
}
defineExpose({
  initDialog,
})

// 新增数据
const createData = () => {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      btnLoading.value = true
      addDeviceList(areaForm.value).then((response) => {
        if (response.code === 200) {
          btnLoading.value = false
          // 通知父组件刷新状态
          setTimeout(() => {
            emits('refresh')
          })
          ElMessage({
            message: '添加成功',
            type: 'success',
          })
          dialogFormVisible.value = false
        }
      }).catch((_) => { // 异常情况，loading置为false
        btnLoading.value = false
      })
    }
  })
}

// 修改数据
const updateData = () => {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      btnLoading.value = true
      updateDeviceList(areaForm.value).then((response) => {
        if (response.code === 200) {
          ElMessage({
            message: '修改成功',
            type: 'success',
          })
          dataFormRef.value.clearValidate()
          setTimeout(() => {
            emits('refresh')
          })
          dialogFormVisible.value = false
        }
      }).catch((_) => { // 异常情况，loading置为false
        btnLoading.value = false
      })
    }
  })
}

// 保存数据
const saveData = () => {
  if (dialogStatus.value === 'update') {
    updateData()
  }
  else if (dialogStatus.value === 'create') {
    createData()
  }
}
const cancel = () => {
  dialogFormVisible.value = false
}
</script>

<template>
  <el-dialog v-model="dialogFormVisible" :title="textMap[dialogStatus]" append-to-body>
    <el-form ref="dataFormRef" :rules="rules" :model="areaForm" label-position="right" label-width="120px">
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="设备名称:" prop="deviceName">
            <el-input v-model="areaForm.deviceName" :placeholder="dialogStatus === 'create' ? '请输入设备名称' : ''" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备类型" prop="deviceType">
            <el-select
              v-model="areaForm.deviceType" class="m-2" :placeholder="dialogStatus === 'create' ? '请选择设备类型' : ''"
              style="width: 100%;"
            >
              <el-option v-for="item in deviceTypeList" :key="item.id" :label="item.name" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="设备编号:" prop="deviceNo">
            <el-input v-model="areaForm.deviceNo" :placeholder="dialogStatus === 'create' ? '请输入设备编号' : ''" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="安装位置:" prop="installLocaltion">
            <el-input v-model="areaForm.installLocaltion" :placeholder="dialogStatus === 'create' ? '请输入安装位置' : ''" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="安装时间:" prop="installTime">
            <el-date-picker
              v-model="areaForm.installTime" type="datetime"
              :placeholder="dialogStatus === 'create' ? '请选择安装时间' : ''" style="width: 100%;"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属分区" prop="ptn">
            <el-select
              v-model="areaForm.ptn" class="m-2" :placeholder="dialogStatus === 'create' ? '请选择所属分区' : ''"
              style="width: 100%;"
            >
              <el-option v-for="item in ptnList" :key="item.id" :label="item.name" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="设备状态" prop="stat">
            <el-select
              v-model="areaForm.stat" class="m-2" :placeholder="dialogStatus === 'create' ? '请选择状态' : ''"
              style="width: 100%;"
            >
              <el-option v-for="item in deviceStatusList" :key="item.value" :label="item.name" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="监测对象" prop="ptn">
            <el-select
              v-model="areaForm.monitorObj" class="m-2" :placeholder="dialogStatus === 'create' ? '请选择监测对象' : ''"
              style="width: 100%;"
            >
              <el-option v-for="item in monitorObjList" :key="item.id" :label="item.name" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="areaForm.deviceType === '2'" :gutter="24">
        <el-col :span="12">
          <el-form-item label="设施面积" prop="facilityArea">
            <el-input v-model="areaForm.facilityArea" :placeholder="dialogStatus === 'create' ? '请输入设施面积' : ''" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button :loading="btnLoading" type="primary" @click="saveData">
          保存
        </el-button>
        <el-button @click="cancel">
          取消
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.el-dialog {
  width: 700px;
}

.el-select {
  width: 100%;
}
</style>

