<!--
  Description: 新增/编辑升级包
  Author: 李亚光
  Date: 2025-05-29
 -->
<script name="addPackageDialog" lang="ts" setup>
const $emits = defineEmits(['closeRefresh'])
import { getDictByCode } from '@/api/system/dict'
import { ElMessage } from 'element-plus'
import { getProductListPage } from '@/api/basic/product'
import { uploadFile } from '@/api/common'
import ShowFile from './showFile.vue'
const $route = useRoute()
// 对话框类型：create,update
const dialogStatus = ref('create')
const dialogVisible = ref(false)
const ruleFormRef = ref()
// 显示标题
const textMap: { [key: string]: string } = {
  update: '编辑',
  create: '新增',
  detail: '详情'
}
const packageInfo = ref({
  id: '',
  versionName: '', // 升级包名称
  versionFile: '', //文件
  versionDesc: '', // 升级包描述
  version: '', // 版本号
  productId: '', // 产品id
  createUserName: '', // 创建用户
  createUserId: '',
  createTime: '', // 创建时间
})

const carryInfo = ref({
  deviceTypeName: '', // 设备类型
  model: '', // 设备型号
  encipherTypeName: '', // 加密方式
})
watch(() => packageInfo.value.productId, (newVal) => {
  if (newVal) {
    const productInfo = productList.value.find(item => item.id === newVal) || {}
    carryInfo.value.deviceTypeName = productInfo.deviceTypeName || ''
    carryInfo.value.model = productInfo.model || ''
    carryInfo.value.encipherTypeName = productInfo.encipherTypeName || ''
  }
  else {
    carryInfo.value = {
      deviceTypeName: '', // 设备类型
      model: '', // 设备型号
      encipherTypeName: '', // 加密方式
    }
  }
})
const packageInfoRules = ref({
  versionName: [{ required: true, message: '升级包名称不能为空', trigger: ['blur', 'change'] }],
  versionFile: [{ required: true, message: '版本文件不能为空', trigger: ['blur', 'change'] }],
  version: [{ required: true, message: '版本号不能为空', trigger: ['blur', 'change'] }],
  productId: [{ required: true, message: '所属产品不能为空', trigger: ['blur', 'change'] }],
}) // 表单验证规则

// ----------初始化、关闭对话框相关-----------------
function initDialog(dialogstatus: string, row: any) {
  dialogStatus.value = dialogstatus
  dialogVisible.value = true
  if (dialogstatus === 'create') {
    packageInfo.value = {
      id: '',
      versionName: '', // 升级包名称
      versionFile: '', //文件
      versionDesc: '', // 升级包描述
      version: '', // 版本号
      productId: '', // 产品id
      createUserName: '', // 创建用户
      createUserId: '',
      createTime: '', // 创建时间
    }
    carryInfo.value = {
      deviceTypeName: '', // 设备类型
      model: '', // 设备型号
      encipherTypeName: '', // 加密方式
    }
    nextTick(() => {
      ruleFormRef.value?.clearValidate()
    })
  }
  else {
    packageInfo.value = row
  }
}
defineExpose({ initDialog })
const productLoading = ref(false)
const productList = ref<any[]>([])
// 获取字典
const fetchDict = () => {

  // 产品列表
  productLoading.value = true
  getProductListPage({ limit: 9999, offset: 1 }).then(res => {
    productList.value = res.data.rows
    productLoading.value = false
  }).catch(() => {
    productLoading.value = false
  })
}
fetchDict()
const btnLoading = ref(false)
const saveForm = () => {
  ruleFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      // btnLoading.value = true;
      // (dialogStatus.value === 'create' ? addpackage : editpackage)({...packageInfo.value,groupId: $route.query.id}).then(res => {
      //   ElMessage.success(`${dialogStatus.value === 'create' ? '添加' : '修改'}成功`)
      //   dialogVisible.value = false
      //   $emits('closeRefresh')
      //   btnLoading.value = false
      // }).catch(() => {
      //   btnLoading.value = false
      // })
    }
  })
}
const dialogClose = () => {
  dialogVisible.value = false
}


// 上传相关逻辑
const fileRef = ref() // 文件上传input
const onFileChange = (event: any) => {
  // 原生上传
  if (event.target.files?.length !== 0) {
    // 创建formdata对象
    const fd = new FormData()
    fd.append('file', event.target.files[0])
    uploadFile(fd).then((res) => {
      if (res.code === 200) {
        ruleFormRef.value?.clearValidate('versionFile')
        packageInfo.value.versionFile = res.data[0]
        fileRef.value.value = ''
        ElMessage.success('上传成功')
      }
      else {
        ElMessage.error(res.message)
      }
    }).catch(() => {
      fileRef.value.value = ''
    })
  }
}
const upload = () => {
  fileRef.value.click()
}
</script>

<template>
  <el-dialog v-model="dialogVisible" :title="`${textMap[dialogStatus]}升级包`" :append-to-body="true"
    :close-on-click-modal="false" width="450px">
    <el-form ref="ruleFormRef" :model="packageInfo" :rules="packageInfoRules" label-position="right" label-width="110px"
      border stripe :disabled="dialogStatus === 'detail'">
      <el-row :gutter="24">
        <el-col :span="22">
          <el-form-item label="升级包名称" prop="versionName">
            <el-input v-model="packageInfo.versionName" placeholder="请输入升级包名称" clearable style="width: 100%;" />
          </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="packageInfo.productId" placeholder="请选择所属产品" style="width: 100%;"
              :loading="productLoading">
              <el-option v-for="item in productList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="22">
          <el-form-item label="设备类型" prop="">
            <el-input v-model="carryInfo.deviceTypeName" disabled clearable style="width: 100%;" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="22">
          <el-form-item label="设备型号" prop="">
            <el-input v-model="carryInfo.model" disabled clearable style="width: 100%;" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="22">
          <el-form-item label="加密方式" prop="">
            <el-input v-model="carryInfo.encipherTypeName" disabled clearable style="width: 100%;" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="22">
          <el-form-item label="版本号" prop="version">
            <el-input v-model="packageInfo.version" placeholder="请输入版本号" clearable style="width: 100%;" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="22">
          <el-form-item label="版本描述">
            <el-input v-model="packageInfo.versionDesc" :placeholder="dialogStatus === 'detail' ? '' : '请输入版本描述'"
              clearable style="width: 100%;" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="22">
          <el-form-item label="版本文件" prop="versionFile">
            <ShowFile :minio-file-name="packageInfo.versionFile"/>
            <!-- 上传组件 -->
            <input ref="fileRef" type="file" @change="onFileChange" style="display: none;" accept=".zip">
            <el-button type="primary" @click="upload" size="small"> {{ packageInfo.versionFile ? '替换' : '上传' }}</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button :loading="btnLoading" :disabled="btnLoading" type="primary" @click="saveForm">
          保存
        </el-button>
        <el-button @click="dialogClose">
          取消
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
