<!-- 添加 / 编辑 -->group
<script name="AddProductDialog" lang="ts" setup>
import { ElMessage, ElMessageBox, dayjs } from 'element-plus'
import type { IDictType } from '../common-interface'
import type { IProductInfo } from './product-info'
import { addProduct, updateProduct } from '@/api/basic/product'
import { ca } from 'element-plus/es/locale'

const emit = defineEmits(['recordSaved'])

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

const title = ref('')

const infoFormRef = ref()

const productInfo = ref<IProductInfo>({
  id: '',
  productNo: '', // 产品编号
  name: '', // 产品名称
  accessType: '', // 接入类型
  powerType: '', // 供电方式
  encipherType: '', // 加密类型
  communicationProtocol: '', // 协议类型
  productType: '',  // 产品类别
  deviceType: '',  // 设备类型
  model: '',  // 型号
  offlineRule: '',
  description: '', // 产品描述
  owners: '', // 产品负责人
  createUserId: '',
  createTime: '',
})

const groupInfoRules = ref({
  name: [{ required: true, message: '产品名称不能为空', trigger: 'blur' }],
  deviceType: [{ required: true, message: '设备类型不能为空，请选择', trigger: ['blur', 'change'] }],
  model: [{ required: true, message: '设备型号不能为空，请选择', trigger: 'blur' }],
  encipherType: [{ required: true, message: '加密方式不能为空，请选择', trigger: 'blur' }],
}) // 表单验证规则

const showDialog = ref<boolean>(false)
const canEdit = ref<boolean>(true)

const deviceTypeDict = ref<Array<IDictType>>([])
const accessTypeDict = ref<Array<IDictType>>([])
const powerTypeDict = ref<Array<IDictType>>([])
const encipherTypeDict = ref<Array<IDictType>>([])
const communicationDict = ref<Array<IDictType>>([])

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

  productInfo.value = {
    id: '',
    productNo: '', // 产品编号
    name: '', // 产品名称
    accessType: '', // 接入类型
    powerType: '', // 供电方式
    encipherType: '', // 加密类型
    communicationProtocol: '', // 协议类型
    productType: '',  // 产品类别
    deviceType: '',  // 设备类型
    model: '',  // 型号
    offlineRule: '',
    description: '', // 产品描述
    owners: '', // 产品负责人
    createUserId: '',
    createTime: '',
  }

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

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

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

      resetForm()
      emit('recordSaved')
    }
    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) => {
  getDict()

  // 从路由中获取参数
  type.value = params.type
  id.value = params.id !== undefined ? params.id : ''

  setTimeout(() => {
    switch (params.type) {
      case 'create':
        title.value = '新增产品'
        canEdit.value = true
        break

      case 'update':
        title.value = '编辑产品'
        canEdit.value = true
        productInfo.value = JSON.parse(sessionStorage.getItem('productInfo')!)
        break

      case 'detail':
        title.value = '产品详情'
        canEdit.value = false
        productInfo.value = JSON.parse(sessionStorage.getItem('productInfo')!)
        break

      default:
        title.value = ''
        break
    }

    showDialog.value = true
  }, 100)
}

// 获取在用状态字典值
const getDeviceTypeDict = () => {
  deviceTypeDict.value = JSON.parse(sessionStorage.getItem("deviceType")!)
}
const getAccessTypeDict = () => {
  accessTypeDict.value = JSON.parse(sessionStorage.getItem("accessType")!)
}
const getPowerTypeDict = () => {
  powerTypeDict.value = JSON.parse(sessionStorage.getItem("powerType")!)
}
const getEncipherTypeDict = () => {
  encipherTypeDict.value = JSON.parse(sessionStorage.getItem("encipherType")!)
}
const getCommunicationDict = () => {
  communicationDict.value = JSON.parse(sessionStorage.getItem("communicationProtocol")!)
}
const getDict = async () => {
  getDeviceTypeDict()
  getAccessTypeDict()
  getPowerTypeDict()
  getEncipherTypeDict()
  getCommunicationDict()
}

defineExpose({
  initDialog,
})
</script>

<template>
  <el-dialog v-model="showDialog" :title="title" :append-to-body="true" :close-on-click-modal="false">
    <detail-block title="">
      <el-form ref="infoFormRef" :model="productInfo" :rules="groupInfoRules" label-position="right" label-width="110px"
        border stripe>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="产品编号">
              <el-input v-model="productInfo.productNo" :disabled="true" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="产品名称" prop="name">
              <el-input v-model="productInfo.name" placeholder="请输入产品名称" :disabled="!canEdit" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="设备类型" prop="deviceType">
              <el-select v-model="productInfo.deviceType" :placeholder="type === 'detail' ? '' : '请选择设备类型'" :disabled="!canEdit" clearable
                style="width: 100%;">
                <el-option v-for="dict in deviceTypeDict" :key="dict.id" :label="dict.name" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="设备型号" prop="model">
              <el-input v-model="productInfo.model" :placeholder="type === 'detail' ? '' : '请输入设备型号'" :disabled="!canEdit" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="通信方式" prop="communicationProtocol">
              <el-select v-model="productInfo.communicationProtocol" :placeholder="type === 'detail' ? '' : '请选择通信方式'" :disabled="!canEdit"
                clearable style="width: 100%;">
                <el-option v-for="dict in communicationDict" :key="dict.id" :label="dict.name" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="加密方式" prop="encipherType">
              <el-select v-model="productInfo.encipherType" :placeholder="type === 'detail' ? '' : '请选择加密方式'" :disabled="!canEdit" clearable
                style="width: 100%;">
                <el-option v-for="dict in encipherTypeDict" :key="dict.id" :label="dict.name" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="接入类型" prop="accessType">
              <el-select v-model="productInfo.accessType" :placeholder="type === 'detail' ? '' : '请选择接入类型'" :disabled="!canEdit" clearable
                style="width: 100%;">
                <el-option v-for="dict in accessTypeDict" :key="dict.id" :label="dict.name" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="供电方式">
              <el-select v-model="productInfo.powerType" :placeholder="type === 'detail' ? '' : '请选择供电方式'" :disabled="!canEdit" clearable
                style="width: 100%;">
                <el-option v-for="dict in powerTypeDict" :key="dict.id" :label="dict.name" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="产品负责人">
              <el-input v-model="productInfo.owners" :placeholder="type === 'detail' ? '' : '请输入产品负责人'" :disabled="!canEdit" clearable />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="离线规则（天）">
              <el-input v-model="productInfo.offlineRule" :placeholder="type === 'detail' ? '' : '请输入离线规则（天）'" :disabled="!canEdit" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="产品描述">
              <el-input v-model="productInfo.description" :placeholder="type === 'detail' ? '' : '请输入产品描述'"
                type="textarea" :rows="3" :disabled="!canEdit" clearable />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </detail-block>

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

      </span>
    </template>
  </el-dialog>
</template>
