<!--
  Description: 设备新增or编辑
  Author: 李亚光
  Date: 2023-04-24
 -->
<script lang="ts" setup name="EditPerson">
import { defineExpose, nextTick, reactive, ref } from 'vue'
import type { FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { device } from './device-interface'
import { getDictByCode } from '@/api/system/dict'
import { addDevice, updateDevice } from '@/api/device'
const emits = defineEmits(['watchChild'])
const dataFormRef = ref()
const dialogFormVisible = ref(false) // 对话框是否显示
const dialogStatus = ref('') // 对话框类型：create,update
const isEditMode = ref(true)
const deviceForm = ref<device>({
  deviceType: '', // 设备类型
  deviceCode: '', // 设备编号
  deviceBatch: '', // 设备批次
  isPowerSupply: '', // 是否供电
  manufacturer: '', // 厂家
  id: '',
  createTime: '',
  cameraIp: '', // 摄像头ip
  cameraPort: '', // 摄像头端口
  cameraCode: '', // 摄像头编号
  gasCode: '', // 激甲编号
  gasIp: '', // 激甲ip
  gasPort: '', // 激甲端口
  hatLiningCode: '', // 只能帽衬编号

}) // 表单
const textMap: { [key: string]: string } = {
  update: '编辑',
  create: '新增',
} // 表头显示标题
const btnLoading = ref(false) // 保存按钮的加载中状态
// 身份证号码验证规则
const validateIP = (rule: any, value: any, callback: any) => {
  const rr = /^((25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))$/
  if (rr.test(value)) {
    callback()
  }
  else {
    callback(new Error('验证失败'))
  }
}
const validatePort = (rule: any, value: any, callback: any) => {
  if (Number(value) > 1 && Number(value) < 65535) {
    callback()
  }
  else {
    callback(new Error('验证失败'))
  }
}
const rules: FormRules = {
  deviceType: [{ required: true, message: '请选择设备类型', trigger: ['blur', 'change'] }],
  deviceCode: [{ required: true, message: '请输入设备编号', trigger: ['blur', 'change'] }],
  deviceBatch: [{ required: true, message: '请输入设备批次', trigger: ['blur', 'change'] }],
  isPowerSupply: [{ required: true, message: '请输入设备是否供电', trigger: ['blur', 'change'] }],
  manufacturer: [{ required: true, message: '请输入设备厂家', trigger: ['blur', 'change'] }],
  cameraPort: [{ required: true, message: '端口号不合法或为空', trigger: ['blur', 'change'], validator: validatePort }],
  cameraIp: [{ required: true, message: 'IP地址不合法或为空', trigger: ['blur', 'change'], validator: validateIP }],
  gasIp: [{ required: true, message: 'IP地址不合法或为空', trigger: ['blur', 'change'], validator: validateIP }],
  gasPort: [{ required: true, message: '端口号不合法或为空', trigger: ['blur', 'change'], validator: validatePort }],
  hatLiningCode: [{ required: true, message: '请输入帽衬编号', trigger: ['blur', 'change'] }],
} // 前端校验规则

// 重置表单
const resetForm = () => {
  deviceForm.value = {
    deviceType: '', // 设备类型
    deviceCode: '', // 设备编号
    deviceBatch: '', // 设备批次
    isPowerSupply: '', // 是否供电
    manufacturer: '', // 厂家
    id: '',
    createTime: '',
    cameraIp: '', // 摄像头ip
    cameraPort: '', // 摄像头端口
    cameraCode: '', // 摄像头编号
    gasCode: '', // 激甲编号
    gasIp: '', // 激甲ip
    gasPort: '', // 激甲端口
    hatLiningCode: '', // 只能帽衬编号
  }
  // dataFormRef.value.clearValidate()
}
// 获取设备类型
const deviceTypeList = ref()
const fetchDeviceType = () => {
  getDictByCode('deviceType').then((response) => {
    deviceTypeList.value = response.data
  })
}
fetchDeviceType()
// 是否供电
const isPowerSupplyList = ref()
const fetchisPowerSupplyType = () => {
  getDictByCode('isPowerSupply').then((response) => {
    isPowerSupplyList.value = response.data
  })
}
fetchisPowerSupplyType()
// 初始化对话框
const initDialog = (dialogStatusValue: string, row: any) => {
  console.log(dialogStatusValue, 'dialogStatusValuedialogStatusValue')
  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中数据填写到输入框中
    deviceForm.value = {
      deviceType: row.deviceType, // 设备类型
      deviceCode: row.deviceCode, // 设备编号
      deviceBatch: row.deviceBatch, // 设备批次
      isPowerSupply: row.isPowerSupply, // 是否供电
      manufacturer: row.manufacturer, // 厂家
      id: row.id,
      createTime: row.createTime,
      cameraIp: row.cameraIp, // 摄像头ip
      cameraPort: row.cameraPort, // 摄像头端口
      cameraCode: row.cameraCode, // 摄像头编号
      gasCode: row.gasCode, // 激甲编号
      gasIp: row.gasIp, // 激甲ip
      gasPort: row.gasPort, // 激甲端口
    }
    isEditMode.value = true
  }
}
defineExpose({
  initDialog,
})

// 新增数据
const createData = () => {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      btnLoading.value = true
      addDevice(deviceForm.value).then((response) => {
        if (response.code === 200) {
          ElMessage({
            message: '新增成功',
            type: 'success',
          })
          dataFormRef.value.clearValidate()
          emits('watchChild')
          dialogFormVisible.value = false
          // ElMessageBox.confirm('新增成功，是否继续新增?', '提示', {
          //   confirmButtonText: '是',
          //   cancelButtonText: '否',
          //   type: 'info',
          // }).then(() => { // 选是
          //   resetForm()
          //   btnLoading.value = false
          //   nextTick(() => {
          //     dataFormRef.value.clearValidate()
          //   })
          // }).catch(() => { // 选否,关闭窗口，并刷新页面
          //   emits('watchChild')
          //   dialogFormVisible.value = false
          // })
        }
      }).catch((_) => { // 异常情况，loading置为false
        btnLoading.value = false
      })
    }
  })
}

// 修改数据
const updateData = () => {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      btnLoading.value = true
      updateDevice(deviceForm.value).then((response) => {
        if (response.code === 200) {
          ElMessage({
            message: '修改成功',
            type: 'success',
          })
          dataFormRef.value.clearValidate()
          emits('watchChild')
          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
  resetForm()
}
// 是否安全帽
const isANQUANMAO = computed(() => {
  if (deviceTypeList.value.length) {
    return deviceTypeList.value.filter((item: any) => item.value === deviceForm.value.deviceType)[0]?.name === '安全树'
  }
  else {
    return false
  }
})
</script>

<template>
  <el-dialog v-model="dialogFormVisible" :title="textMap[dialogStatus]" append-to-body>
    <el-form ref="dataFormRef" :rules="rules" :model="deviceForm" label-position="right" label-width="110px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="设备类型" prop="deviceType">
            <el-select v-model="deviceForm.deviceType" placeholder="请选择设备类型">
              <el-option v-for="item in deviceTypeList" :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="deviceCode">
            <el-input v-model.trim="deviceForm.deviceCode" :disabled="dialogStatus === 'update'" type="text" placeholder="必填" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="设备厂家" prop="manufacturer">
            <el-input v-model.trim="deviceForm.manufacturer" type="text" placeholder="必填" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否供电" prop="isPowerSupply">
            <!-- <el-input v-model.trim="deviceForm.isPowerSupply" type="text" placeholder="是或否" /> -->
            <el-select v-model="deviceForm.isPowerSupply" placeholder="是否供电">
              <el-option v-for="item in isPowerSupplyList" :key="item.value" :label="item.name" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="批次" prop="deviceBatch">
            <el-input v-model.trim="deviceForm.deviceBatch" type="text" placeholder="必填" />
          </el-form-item>
        </el-col>
        <el-col v-if="deviceForm.deviceType === '2'" :span="12">
          <el-form-item label="智能帽衬编号" prop="hatLiningCode">
            <el-input v-model.trim="deviceForm.hatLiningCode" type="text" placeholder="必填" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="isANQUANMAO" :gutter="20">
        <el-col :span="12">
          <el-form-item label="激光甲烷IP" prop="gasIp">
            <el-input v-model.trim="deviceForm.gasIp" type="text" placeholder="必填" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="激光甲烷端口" prop="gasPort">
            <el-input v-model.trim="deviceForm.gasPort" type="text" placeholder="必填" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="isANQUANMAO" :gutter="20">
        <el-col :span="12">
          <el-form-item label="摄像头IP" prop="cameraIp">
            <el-input v-model.trim="deviceForm.cameraIp" type="text" placeholder="必填" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="摄像头端口" prop="cameraPort">
            <el-input v-model.trim="deviceForm.cameraPort" type="text" placeholder="必填" />
          </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>
