<!-- 添加 / 编辑 -->
<script name="AddDeviceDialog" lang="ts" setup>
import { ElMessage, ElMessageBox, dayjs } from 'element-plus'
import type { IDeviceInfo, IDeviceType } from './device-info'
import { addDevice, getDeviceModelList, updateDevice } from '@/api/basic/device'
import { getLocateListSelect } from '@/api/basic/locate'

const emit = defineEmits(['recordSaved'])

// 从路由中传过来的参数
const type = ref<string>('')
const id = ref<string>('')

const title = ref('')

const infoFormRef = ref()

const deviceInfo = ref<IDeviceInfo>({
  id: '',
  devcode: '',
  deviceName: '',
  deviceType: '',
  watchType: '',
  version: '',
  wellId: '',
  wellCode: '',
})

const deviceInfoRules = ref({
  devcode: [{ required: true, message: '设备编号不能为空', trigger: 'blur' }],
  wellCode: [{ required: true, message: '点位编号不能为空', trigger: ['blur', 'change'] }],
  deviceType: [{ required: true, message: '设备类型不能为空，请选择', trigger: ['blur', 'change'] }],
  version: [{ required: true, message: '设备型号不能为空，请选择', trigger: ['blur', 'change'] }],
}) // 表单验证规则

const deviceTypeDict = ref<Array<IDeviceType>>([])
const deviceModelDict = ref<Array<IDeviceType>>([])
const locateList = ref<Array<IDeviceType>>([])

const showDialog = ref<boolean>(false)

// 逻辑
const resetForm = () => {
  sessionStorage.removeItem('deviceInfo') // 返回列表时 将缓存中的数据删除

  deviceInfo.value = {
    id: '',
    devcode: '',
    deviceName: '',
    deviceType: '',
    watchType: '',
    version: '',
    wellId: '',
    wellCode: '',
  }

  infoFormRef.value.clearValidate()
  showDialog.value = false
}

// 添加
const saveInfo = () => {
  addDevice(deviceInfo.value).then((res) => {
    if (res.code === 200) {
      // 提示保存成功
      ElMessage.success('保存成功')

      emit('recordSaved')
      resetForm()
    }
    else {
      // 提示失败信息
      ElMessage.error(`保存失败：${res.message}`)
    }
  })
}
// 编辑
const updateInfoById = () => {
  updateDevice(deviceInfo.value).then((res) => {
    if (res.code === 200) {
      // 提示保存成功
      ElMessage.success('保存成功')

      emit('recordSaved')
      resetForm()
    }
    else {
      // 提示失败信息
      ElMessage.error(`保存失败：${res.message}`)
    }
  })
}

// 保存
const saveForm = async () => {
  if (!infoFormRef) { return }

  await infoFormRef.value.validate((valid: boolean, fields: any) => {
    if (valid === true) {
      ElMessageBox.confirm(
        '确认保存吗？',
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        },
      ).then(() => {
        if (type.value === 'create') {
          saveInfo()
        }
        else if (type.value === 'update') {
          updateInfoById()
        }
      })
    }
  })
}

const initLocateSelect = () => {
  getLocateListSelect({}).then((res) => {
    if (res.code === 200) {
      locateList.value = res.data
    }
  })
}

const deviceTypeChangeHandler = () => {
  if (deviceInfo.value.deviceType === '') {
    deviceModelDict.value = []
  }
  else {
    getDeviceModelList(deviceInfo.value.deviceType).then((res) => {
      if (res.code === 200) {
        deviceModelDict.value = res.data
      }
      else {
        deviceModelDict.value = []
      }
    })
  }
}

const initDialog = (params: any) => {
  // 从路由中获取参数
  type.value = params.type
  id.value = params.id !== undefined ? params.id : ''

  if (sessionStorage.getItem('deviceType') !== undefined) {
    deviceTypeDict.value = JSON.parse(sessionStorage.getItem('deviceType')!)
  }

  switch (params.type) {
    case 'create' :
      title.value = '新增设备'

      initLocateSelect()
      deviceInfo.value.installDate = dayjs().format('YYYY-MM-DD')

      break
    case 'update':
      title.value = '编辑设备'

      deviceInfo.value = JSON.parse(sessionStorage.getItem('deviceInfo')!)

      break
    default:
      title.value = ''
      break
  }

  nextTick(() => {
    infoFormRef.value.clearValidate()
  })

  showDialog.value = true
}

defineExpose({
  initDialog,
})
</script>

<template>
  <el-dialog v-model="showDialog" :title="title" :append-to-body="true" :close-on-click-modal="false" @closed="resetForm">
    <detail-block title="">
      <el-form ref="infoFormRef" :model="deviceInfo" :rules="deviceInfoRules" label-position="right" label-width="110px" stripe>
        <el-row :gutter="24">
          <el-col :span="12" :offset="3">
            <el-form-item label="设备编号" prop="devcode">
              <el-input v-model="deviceInfo.devcode" placeholder="请输入设备编号" :disabled="type === 'update'" clearable />
              <el-input v-model="deviceInfo.deviceName" type="hidden" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12" :offset="3">
            <el-form-item label="安装点位" prop="wellCode">
              <el-select v-if="type === 'create'" v-model="deviceInfo.wellCode" placeholder="请选择安装点位" filterable clearable style="width: 100%;">
                <el-option v-for="dict in locateList" :key="dict.value" :value="dict.name" :label="dict.name" />
              </el-select>
              <el-input v-if="type === 'update'" v-model="deviceInfo.wellCode" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12" :offset="3" prop="deviceType">
            <el-form-item label="设备类型" prop="deviceType">
              <el-select v-if="type === 'create'" v-model="deviceInfo.deviceType" placeholder="请选择设备类型" filterable clearable style="width: 100%;" @change="deviceTypeChangeHandler">
                <el-option v-for="dict in deviceTypeDict" :key="dict.value" :value="dict.value" :label="dict.name" />
              </el-select>
              <el-input v-if="type === 'update'" v-model="deviceInfo.deviceTypeName" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12" :offset="3">
            <el-form-item label="设备型号" prop="version">
              <el-select v-if="type === 'create'" v-model="deviceInfo.version" placeholder="请选择设备型号" clearable filterable style="width: 100%;">
                <el-option v-for="dict in deviceModelDict" :key="dict.value" :value="dict.value" :label="dict.name" />
              </el-select>
              <el-input v-if="type === 'update'" v-model="deviceInfo.modelName" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12" :offset="3">
            <el-form-item label="安装日期">
              <el-date-picker v-model="deviceInfo.installDate" placeholder="请选择安装日期" type="date" clearable style="width: 100%;" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- <el-row :gutter="24">
          <el-col :span="12" :offset="3">
            <el-form-item label="设备IMEI">
              <el-input v-model="deviceInfo.imei" placeholder="请输入设备IMEI号" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12" :offset="3">
            <el-form-item label="ICCID">
              <el-input v-model="deviceInfo.iccid" placeholder="请输入ICCID号" clearable />
            </el-form-item>
          </el-col>
        </el-row> -->
      </el-form>
    </detail-block>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="resetForm">取消</el-button>
        <el-button type="primary" @click="saveForm">
          保存
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
