<!-- 设备规格型号-编辑 -->
<script lang="ts" setup name="DeviceModelEdit">
import type { FormInstance, FormRules, UploadUserFile } from 'element-plus'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import tableList from './technology.vue'
import { getDictByCode } from '@/api/system/dict'
import { getDeviceNameList, getModelAllList, handlerFunApi } from '@/api/eqpt/device/model'
import useUserStore from '@/store/modules/user'
import { getUserDept } from '@/api/system/user'
import { uploadApi } from '@/api/system/notice'
import showPhoto from '@/views/tested/device/info/components/showPhoto.vue'
const $route = useRoute()
const $router = useRouter()
const userStore = useUserStore()
const ruleFormRef = ref<FormInstance>() // from组件
const title = ref('')
// 显示标题
const textMap: { [key: string]: string } = {
  update: '编辑',
  create: '新增',
  detail: '详情',
}
// 对话框类型：create,update
const dialogStatus = ref('create')
const ruleForm = ref({
  category: '', // 设备分类
  categoryName: '', // 设备分类名称
  checkCycle: '', // 检定周期
  createDeptId: '',
  createTime: '',
  createUserId: '',
  equipmentName: '', // 设备名称
  helpInstruction: '', // 辅助字段
  id: '',
  instructionsFile: '', // 附件
  model: '', // 规格型号
  modelNo: '', // 规格型号编号
  remark: '', // 备注
  technicalTargetList: [], // 技术指标
  updateTime: '',
}) // 表单
// 设备名称验证规则

const rules = ref<FormRules>({
  equipmentName: [{ required: true, message: '设备名称名称必填', trigger: ['blur', 'change'] }],
  category: [{ required: true, message: '设备分类必选', trigger: ['blur', 'change'] }],
  model: [{ required: true, message: '规格型号必填', trigger: ['blur', 'change'] }],
  checkCycle: [{ required: true, message: '检定周期必填', trigger: ['blur', 'change'] }],
}) // 表单验证规则
// 弹窗初始化
const initDialog = () => {
  dialogStatus.value = $route.params.type as string
  ruleFormRef.value?.resetFields()
  if ($route.params.type === 'create') {
    ruleForm.value.createTime = dayjs().format('YYYY-MM-DD HH:mm:ss') // 创建时间
    ruleForm.value.createUserId = userStore.id
    ruleForm.value.createDeptId = userStore.deptId
    // 获取当前用户所在单位
    // getUserDept().then((res) => {
    //   ruleForm.value.createDeptId = res.data.id
    // })
  }
  else {
    console.log($route.query.row, 'data')
    const data = JSON.parse($route.query.row as string)
    // detailGroup({ groupId: data.id }).then((res) => {
    ruleForm.value = data
    console.log(ruleForm.value, 'ruleForm.value')
    // })
  }
}
onMounted(() => {
  initDialog()
})
// 关闭弹窗
const close = () => {
  $router.back()
}
const tableRef = ref()

// 保存
const saveForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) { return }
  await formEl.validate((valid, fields) => {
    if (valid && tableRef.value.checkCertificateList()) {
      ElMessageBox.confirm(
        '确认保存吗？',
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        },
      ).then((res) => {
        if (!ruleForm.value.helpInstruction) {
          ruleForm.value.helpInstruction = '/'
        }
        ruleForm.value.technicalTargetList = tableRef.value.list
        if ($route.params.type === 'create') {
          handlerFunApi('create', ruleForm.value).then((res) => {
            ElMessage.success('添加成功')
            close()
          })
        }
        else {
          // ruleForm.value.technicalTargetList = tableRef.value.list
          console.log(ruleForm.value)
          handlerFunApi('update', ruleForm.value).then((res) => {
            ElMessage.success('修改成功')
            close()
          })
        }
      })
    }
  })
}
// 取消
const resetForm = (formEl: FormInstance | undefined) => {
  formEl?.resetFields()
  close()
}
const fileRef = ref() // 文件上传input
const onFileChange = (event: any) => {
  if (event.target.files?.length !== 0) {
    // 创建formdata对象
    const fd = new FormData()
    const loading = ElLoading.service({
      lock: true,
      background: 'rgba(255, 255, 255, 0.8)',
    })
    fd.append('multipartFile', event.target.files[0])
    uploadApi(fd).then((res) => {
      if (res.code === 200) {
        ruleForm.value.instructionsFile = ruleForm.value.instructionsFile ? `${ruleForm.value.instructionsFile},${res.data[0]}` : res.data[0]
        // 重置当前验证
        ruleFormRef.value?.clearValidate('minioFileName')
        ElMessage.success('文件上传成功')
        fileRef.value.value = ''
        loading.close()
      }
      else {
        // ElMessage.error(res.message)
        loading.close()
      }
    })
  }
}
// 上传
const upload = () => {
  fileRef.value.click()
}
// 删除上传的文件
const deleteFile = (fileName: string) => {
  const data = ruleForm.value.instructionsFile.split(',')
  const filterData = data.filter(item => item !== fileName)
  ruleForm.value.instructionsFile = filterData.length ? filterData.join(',') : ''
}
// 设备分类
const deviceTypeList = ref<{ id: string; value: string; name: string }[]>([])
const fetchSelect = () => {
  // 设备分类
  getDictByCode('eqptDeviceType').then((res) => {
    deviceTypeList.value = res.data
  })
  // 设备名称
  // getDeviceNameList().then((res) => {
  //   console.log(res.data, '设备名称')
  //   deviceNameList.value = res.data
  // })
  // 规格型号及辅助字段
  // getModelAllList({}).then((res) => {
  //   console.log(res.data, '规格型号')
  //   modelList.value = res.data.filter((item: any) => item.model)
  //   helpList.value = res.data.filter((item: any) => item.helpInstruction)
  // })
}
fetchSelect()
</script>

<template>
  <app-container style="overflow: hidden;">
    <approval-dialog ref="approvalDialogRef" @on-success="() => { $router.back() }" />
    <detail-page :title="`设备规格型号管理-${textMap[dialogStatus]}`">
      <template #btns>
        <el-button v-if="dialogStatus !== 'detail'" type="primary" @click="saveForm(ruleFormRef)">
          保存
        </el-button>
        <el-button type="info" @click="resetForm(ruleFormRef)">
          关闭
        </el-button>
      </template>
    </detail-page>
    <detail-block-com>
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules" label-position="right" label-width="110px" class="form"
        :disabled="dialogStatus === 'detail'"
        :class="$route.path.includes('detail') ? 'isDetail' : ''"
      >
        <el-row :gutter="24" class="marg">
          <el-col :span="8">
            <el-form-item label="规格型号编号">
              <el-input v-model.trim="ruleForm.modelNo" placeholder="系统自动生成" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="设备名称" prop="equipmentName">
              <el-input v-model.trim="ruleForm.equipmentName" placeholder="设备名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="规格型号" prop="model">
              <el-input v-model.trim="ruleForm.model" placeholder="规格型号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="8">
            <el-form-item label="辅助字段" prop="helpInstruction">
              <el-input v-model.trim="ruleForm.helpInstruction" placeholder="辅助字段" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="设备分类" prop="category">
              <el-select v-model.trim="ruleForm.category" placeholder="设备分类" style="width: 100%;">
                <el-option v-for="item in deviceTypeList" :key="item.id" :label="item.name" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="检定周期" prop="checkCycle">
              <!-- <el-input v-model.trim="ruleForm.checkCycle" placeholder="检定周期" /> -->
              <!-- <el-input-number v-model.trim="ruleForm.checkCycle" placeholder="检定周期" :min="0.1">
                <template #append>
                  月
                </template>
              </el-input-number> -->
              <el-input v-model.trim="ruleForm.checkCycle" :min="0" type="number">
                <template #append>
                  月
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="24">
            <el-form-item label="使用说明书" prop="instructionsFile">
              <!-- <el-input v-model.trim="ruleForm.helpInstruction" placeholder="辅助字段" /> -->
              <show-photo :minio-file-name="ruleForm.instructionsFile" @delete="deleteFile" />
              <input ref="fileRef" style="display: none;" type="file" accept="application/msword,application/pdf" @change="onFileChange">
              <el-button v-if="dialogStatus !== 'detail'" type="primary" @click="upload">
                上传
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="18">
            <el-form-item label="备注" prop="remark">
              <el-input v-model.trim="ruleForm.remark" type="textarea" :row="3" maxlength="100" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </detail-block-com>
    <detail-block-com>
      <table-list ref="tableRef" :data="ruleForm.technicalTargetList" :status="dialogStatus" />
    </detail-block-com>
  </app-container>
</template>

<style lang="scss" scoped>
// 样式
</style>
