<!-- 添加 / 编辑 -->
<script name="AddDeviceDialog" lang="ts" setup>
import { ElMessage, ElMessageBox, dayjs } from 'element-plus'
import type { IDictType } from '../common-interface'
import type { IDeviceInfo } from './device-info'
import { addDevice, updateDevice } from '@/api/basic/device'
import useUserStore from '@/store/modules/user'
import { getProductListPage } from '@/api/basic/product'
import { getGroupListPage } from '@/api/basic/group'
import { getDictByCode } from '@/api/system/dict'
const emit = defineEmits(['recordSaved'])
const $props = defineProps({
  needGroup: {
    type: Boolean,
    default: false
  },
})
// 从路由中传过来的参数
const type = ref<string>('')
const id = ref<string>('')

const userInfo = useUserStore()
const isFirst = ref(true)

const title = ref('')

const infoFormRef = ref()

const deviceInfo = ref<IDeviceInfo>({
  id: '',
  devcode: '',
  groupId: '',
  deviceType: '',
  model: '',
  productId: '',
  encipherType: '',
  imei: '',
  iccid: '',
  createUserId: '',
  createTime: '',
})

const deviceInfoRules = ref({
  devcode: [{ required: true, message: '设备编号不能为空', trigger: 'blur' }],
  groupId: [{ required: true, message: '所属分组不能为空，请选择', trigger: ['blur', 'change'] }],
  productId: [{ required: true, message: '所属产品不能为空，请选择', trigger: ['blur', 'change'] }],
}) // 表单验证规则

const deviceTypeDict = ref<Array<IDictType>>([])  // 设备类型列表
const encipherTypeDict = ref<Array<IDictType>>([]) // 加密方式
const productLoading = ref(false)
const productList = ref<any[]>([]) // 产品列表
const groupLoading = ref(false)
const groupList = ref<any[]>([]) // 分组列表

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

  deviceInfo.value = {
    id: '',
    devcode: '',
    groupId: '',
    deviceType: '',
    model: '',
    productId: '',
    encipherType: '',
    imei: '',
    iccid: '',
    createUserId: '',
    createTime: '',
  }

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

// 添加
const saveInfo = () => {
  loadingBtn.value = true
  // 将创建时间改为提交的时间
  deviceInfo.value.createTime = dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss')
  addDevice(deviceInfo.value).then((res) => {
    if (res.code === 200) {
      // 提示保存成功
      ElMessage.success('保存成功')

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

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

// 保存
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 initDialog = (params: any) => {
  isFirst.value = true
  // 从路由中获取参数
  type.value = params.type
  id.value = params.id !== undefined ? params.id : ''

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

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

      deviceInfo.value.createUserId = userInfo.id
      deviceInfo.value.groupId = params.groupId

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

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

      break
    default:
      title.value = ''
      break
  }

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

  showDialog.value = true
  setTimeout(() => {
    isFirst.value = false
  })
}

defineExpose({
  initDialog,
})

// 获取字典相关
const fetchDict = () => {
  // 产品列表
  productLoading.value = true
  getProductListPage({ limit: 9999, offset: 1 }).then(res => {
    productList.value = res.data.rows
    productLoading.value = false
  }).catch(() => {
    productLoading.value = false
  })
  // 分组列表
  groupLoading.value = true
  getGroupListPage({ limit: 9999, offset: 1 }).then(res => {
    groupList.value = res.data.rows
    groupLoading.value = false
  }).catch(() => {
    groupLoading.value = false
  })

  // 设备类型
  getDictByCode('deviceType').then((res: any) => {
    deviceTypeDict.value = res.data
  })
  // 加密方式
  getDictByCode('encipherType').then((res: any) => {
    encipherTypeDict.value = res.data
  })
}
fetchDict()

watch(() => deviceInfo.value.productId, (newVal) => {
  // if (isFirst.value) {
  //   return
  // }
  if (newVal) {
    const product = productList.value.find(item => item.id === newVal)
    deviceInfo.value.model = product.model
    deviceInfo.value.encipherType = product.encipherType
    deviceInfo.value.deviceType = product.deviceType
  }
  else {
    deviceInfo.value.model = ''
    deviceInfo.value.encipherType = ''
    deviceInfo.value.deviceType = ''
  }
})
</script>

<template>
  <el-dialog v-model="showDialog" :title="title" :append-to-body="true" :close-on-click-modal="false" :modal="true"
    @closed="resetForm" width="450px">
    <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="22">
            <el-form-item label="设备编号" prop="devcode">
              <el-input v-model="deviceInfo.devcode" placeholder="请输入设备编号" :disabled="type === 'update'" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="22">
            <el-form-item label="所属产品" prop="productId">
              <el-select v-model="deviceInfo.productId" placeholder="请选择所属产品" clearable filterable
                :loading="productLoading">
                <el-option v-for="dict in productList" :key="dict.id" :value="dict.id" :label="dict.name" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="$props.needGroup" :gutter="24">
          <el-col :span="22">
            <el-form-item label="所属分组" prop="groupId">
              <el-select v-model="deviceInfo.groupId" placeholder="请选择所属分组" clearable filterable
                :loading="groupLoading">
                <el-option v-for="dict in groupList" :key="dict.id" :value="dict.id" :label="dict.groupName" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="22">
            <el-form-item label="设备类型" prop="deviceType">
              <el-select v-model="deviceInfo.deviceType" placeholder="" clearable disabled>
                <el-option v-for="dict in deviceTypeDict" :key="dict.id" :value="dict.value" :label="dict.name" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="22">
            <el-form-item label="设备型号">
              <!-- <el-select v-model="deviceInfo.model" placeholder="" clearable filterable disabled /> -->
              <el-input v-model="deviceInfo.model" placeholder="" clearable disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="22">
            <el-form-item label="加密方式">
              <el-select v-model="deviceInfo.encipherType" placeholder="" clearable disabled>
                <el-option v-for="dict in encipherTypeDict" :key="dict.id" :value="dict.value" :label="dict.name" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="22">
            <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="22">
            <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 type="primary" @click="saveForm" :disabled="loadingBtn" :loading="loadingBtn">
          保存
        </el-button>
        <el-button @click="resetForm">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>
