<!-- 新增或详情弹窗 -->
<script lang="ts" setup name="add">
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import addRow from './addRow.vue'
import type { deptType, selectType } from '@/views/device/standingBook/standingBook-interface'
import showPhoto from '@/views/system/tool/showPhoto.vue'
import { UploadFile } from '@/api/measure/file'
import { getDictByCode } from '@/api/system/dict'
import { getUserList } from '@/api/system/user'
import { getDeptTreeList } from '@/api/system/dept'
import comTreeSelect from '@/views/system/user/selecTree.vue'
import { toTreeList } from '@/utils/structure'
import type { userType } from '@/views/system/user/user-interface'
const emits = defineEmits(['resetData'])
const ruleFormRef = ref() // from组件
const dialogVisible = ref<boolean>(true)
const title = ref('')
const name = ref('')
const borrowList = ref([])
const ruleForm = ref({
  assetNo: '', // 资产编号
  assetType: '', // 资产类型
  assetSource: '', // 资产来源
  equipmentNo: '', // 设备编号
  equipmentName: '', // 设备名称
  labelBind: '', // 标签绑定
  modelNo: '', // 型号
  equipmentSpecifications: '', // 设备规格
  equipmentType: '', // 设备类型
  equipmentCategory: '', // 设备类别
  capitalSource: '', // 资本来源
  managerLevel: '', // 管理级别
  purpose: '', // 用途
  technicalLevel: '', // 技术水平
  intactState: '', // 完好状态
  manufacturerCountry: '', // 厂家国别
  manufacturer: '', // 生产厂家
  overallDimension: '', // 外形尺寸
  manufacturingNo: '', // 出厂编号
  manufacturingDate: '', // 出厂年月
  cardEstablishmentDate: '', // 立卡年月
  weight: '', // 重量
  enableDate: '', // 启用年月
  singlePrice: '', // 单价
  installIncidentalExpenses: '', //	安装及杂费
  originValue: '', //	原值
  useDept: '', //	使用部门
  installPlace: '', //	安装地点
  createUser: '', //		创建人/负责人
  depreciationPeriod: '', //	折旧年限
  depreciationMethod: '', //	折旧方法
  attribute: '', //	属性
  majorCategory: '', //	专业分类
  presentOriginValue: '', //	目前原值
  managerState: '1', //	管理状态
  fileList: [] as any[], //	说明书
  remark: '', //	备注
  mesureType: '', //	检定方式
  mesureRange: '', //	测量范围
  uncertainty: '', //	不确定度
  usePerson: '', //	使用人
  mesureDept: '', //	检定部门
  mesureCycle: '', //	检定周期
  mesureDate: '', //	检定日期
  validDate: '', //	有效日期
  mesureResult: '', //	检定结果
  abc: '', //	ABC
  isCalibrationTestEquipment: '', //	是否是技术指标需要校准检定的设备
  isMeasureAccount: '', //	是否是测量工装台账
  isStandardSupportEquipment: '', //		是否标准配套设备
  id: '',
}) // 表单
const rules = ref<FormRules>({
  assetType: [{ required: true, message: '资产类型不能为空', trigger: 'blur' }],
  equipmentName: [{ required: true, message: '设备不能为空', trigger: 'blur' }],
  manufacturer: [{ required: true, message: '生产厂家不能为空', trigger: 'blur' }],
  manufacturingNo: [{ required: true, message: '出厂编号不能为空', trigger: 'blur' }],
  manufacturingDate: [{ required: true, message: '出厂日期不能为空', trigger: 'blur' }],
  modelNo: [{ required: true, message: '型号不能为空', trigger: 'blur' }],
  abc: [{ required: true, message: 'ABC不能为空', trigger: 'blur' }],
  cardEstablishmentDate: [{ required: true, message: '立卡年月不能为空', trigger: 'blur' }],
  enableDate: [{ required: true, message: '启用日期不能为空', trigger: 'blur' }],
  mesureDate: [{ required: true, message: '检定日期不能为空', trigger: 'blur' }],
  validDate: [{ required: true, message: '有效日期不能为空', trigger: 'blur' }],
}) // 表单验证规则
const assetTypeList = ref<selectType[]>([]) // 资产类型
const ABCList = ref<selectType[]>([]) // ABC
const mesureTypeList = ref<selectType[]>([]) // 检定方式
const majorCategoryList = ref<selectType[]>([]) // 专业分类
const equipmentCategoryList = ref<selectType[]>([]) // 设备类别
const mesureResultList = ref<selectType[]>([]) //  检定结果
const equipmentTypeList = ref<selectType[]>([]) // 设备类型
const managerLevelList = ref<selectType[]>([]) // 管理级别
const depreciationMethodList = ref<selectType[]>([]) // 折旧方法
const managerStateList = ref<selectType[]>([]) // 管理状态
const capitalSourceList = ref<selectType[]>([]) // 资本来源
const usePersonList = ref<userType[]>([]) // 使用人列表
const useDeptList = ref<deptType[]>([]) // 使用部门列表
const isWhether = ref<selectType[]>([
  {
    name: '是',
    id: 'shi',
    value: '1',
  },
  {
    name: '否',
    id: 'fou',
    value: '0',
  },
])
const deptProps = reactive({
  parent: 'pid', value: 'id', label: 'name', children: 'children',
})
// 检定周期
const mesureCycleList = ref<selectType[]>([
  {
    name: '半年一检',
    id: '1',
    value: '6',
  },
  {
    name: '一年一检',
    id: '2',
    value: '12',
  },
  {
    name: '两年一检',
    id: '3',
    value: '24',
  },
  {
    name: '三年一检',
    id: '4',
    value: '36',
  },
  {
    name: '四年一检',
    id: '5',
    value: '48',
  },
  {
    name: '五年一检',
    id: '6',
    value: '60',
  },
])
// 获取下拉框数
const fetchData = () => {
// 获取资产类型
  getDictByCode('assetType').then((response) => {
    assetTypeList.value = response.data
  })
  // 获取ABC
  getDictByCode('ABC').then((response) => {
    ABCList.value = response.data
  })
  // 获取检定方式
  getDictByCode('mesureType').then((response) => {
    mesureTypeList.value = response.data
  })
  // 获取专业分类
  getDictByCode('majorCategory').then((response) => {
    majorCategoryList.value = response.data
  })
  // 获取检定结果
  getDictByCode('mesureResult').then((response) => {
    mesureResultList.value = response.data
  })
  // 获取设备类别
  getDictByCode('equipmentCategory').then((response) => {
    equipmentCategoryList.value = response.data
  })
  // 获取设备类型
  getDictByCode('equipmentType').then((response) => {
    equipmentTypeList.value = response.data
  })
  // 获取管理级别
  getDictByCode('managerLevel').then((response) => {
    managerLevelList.value = response.data
  })
  // 获取折旧方法
  getDictByCode('depreciationMethod').then((response) => {
    depreciationMethodList.value = response.data
  })
  // 获取管理状态
  getDictByCode('managerState').then((response) => {
    managerStateList.value = response.data
  })
  // 获取资本来源
  getDictByCode('capitalSource').then((response) => {
    capitalSourceList.value = response.data
  })
  // 获取用户列表
  getUserList({ offset: 1, limit: 99999 }).then((res) => {
    usePersonList.value = res.data.rows
  })
  // 获取部门列表
  getDeptTreeList().then((res) => {
    // 转成树结构
    useDeptList.value = toTreeList(res.data, '0', true)
  })
}
// 重置
const resetDATA = () => {
  ruleForm.value = {
    assetNo: '', // 资产编号
    assetType: '', // 资产类型
    assetSource: '', // 资产来源
    equipmentNo: '', // 设备编号
    equipmentName: '', // 设备名称
    labelBind: '', // 标签绑定
    modelNo: '', // 型号
    equipmentSpecifications: '', // 设备规格
    equipmentType: '', // 设备类型
    equipmentCategory: '', // 设备类别
    capitalSource: '', // 资本来源
    managerLevel: '', // 管理级别
    purpose: '', // 用途
    technicalLevel: '', // 技术水平
    intactState: '', // 完好状态
    manufacturerCountry: '', // 厂家国别
    manufacturer: '', // 生产厂家
    overallDimension: '', // 外形尺寸
    manufacturingNo: '', // 出厂编号
    manufacturingDate: '', // 出厂年月
    cardEstablishmentDate: '', // 立卡年月
    weight: '', // 重量
    enableDate: '', // 启用年月
    singlePrice: '', // 单价
    installIncidentalExpenses: '', //	安装及杂费
    originValue: '', //	原值
    useDept: '', //	使用部门
    installPlace: '', //	安装地点
    createUser: '', //		创建人/负责人
    depreciationPeriod: '', //	折旧年限
    depreciationMethod: '', //	折旧方法
    attribute: '', //	属性
    majorCategory: '', //	专业分类
    presentOriginValue: '', //	目前原值
    managerState: '1', //	管理状态
    fileList: [] as any[], //	说明书
    remark: '', //	备注
    mesureType: '', //	检定方式
    mesureRange: '', //	测量范围
    uncertainty: '', //	不确定度
    usePerson: '', //	使用人
    mesureDept: '', //	检定部门
    mesureCycle: '', //	检定周期
    mesureDate: '', //	检定日期
    validDate: '', //	有效日期
    mesureResult: '', //	检定结果
    abc: '', //	ABC
    isCalibrationTestEquipment: '', //	是否是技术指标需要校准检定的设备
    isMeasureAccount: '', //	是否是测量工装台账
    isStandardSupportEquipment: '', //		是否标准配套设备
    id: '',
  }
}
// 弹窗初始化
const initDialog = (row: any) => {
  fetchData()
  ruleFormRef.value?.resetFields()
  title.value = row.title
  name.value = row.name
  // dialogVisible.value = true
  // if (row.title !== '新建') {
  //   assetsDetailApi({ id: row.id }).then((res) => {
  //     for (const key in res.data) {
  //       if (typeof res.data[key] == 'number') {
  //         res.data[key] = String(res.data[key])
  //       }
  //     }
  //     ruleForm.value = res.data
  //   })
  // }
}
defineExpose({ initDialog })
// 关闭弹窗
const close = () => {
  resetDATA()
  dialogVisible.value = false
}
// 提交
const submitForm = async (formEl: FormInstance | undefined, flag: string) => {
  if (!formEl) { return }
  await formEl.validate((valid, fields) => {
    if (valid) {
      ElMessageBox.confirm(
    `确认${flag}吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
      ).then((res) => {
        // 提交
        if (title.value === '编辑' && ruleForm.value.fileList.length) {
          ruleForm.value.fileList[0].id = undefined
        }
        (title.value === '新建' ? assetsAddApi : assetsUpdateApi) (ruleForm.value).then((res) => {
          if (res.code == 200) {
            formEl?.resetFields()
            ElMessage.success('操作成功')
            dialogVisible.value = false
            close()
            emits('resetData')
          }
        })
        // dialogVisible.value = false
      })
    }
  })
}
// 取消
const resetForm = (formEl: FormInstance | undefined) => {
  formEl?.resetFields()
  dialogVisible.value = false
  close()
  emits('resetData')
}
const fileRef = ref() // 文件上传input
const onFileChange = (event: any) => {
  // 原生上传
  // console.log(event.target.files)
  if (event.target.files?.length !== 0) {
    // 创建formdata对象
    const fd = new FormData()
    fd.append('multipartFile', event.target.files[0])
    UploadFile(fd).then((res) => {
      if (res.code === 200) {
        console.log(res.data[0])
        // 重置当前验证
        ruleForm.value.fileList = []
        ruleForm.value.fileList.push({
          assetId: '',
          fileName: res.data[0],
          minioFileName: res.data[0],
          // id: '',
        })
        ruleFormRef.value?.clearValidate('minioFileName')
        ElMessage.success('文件上传成功')
      }
      else {
        ElMessage.error(res.message)
      }
    })
  }
}
const upload = () => {
  fileRef.value.click()
}
// 展示鉴定内容
const isShowCalibration = ref<boolean>(false)
// 若固定资产为测量设备，还需填写检定内容
watch(() => ruleForm.value.assetType, (newVal) => {
  if (newVal === '1') {
    isShowCalibration.value = true
  }
})
const columns = ref([
  {
    text: '设备名称',
    value: 'equipmentName',
    align: 'center',
  },
  {
    text: '设备编号',
    value: 'equipmentNo',
    align: 'center',
  },
  {
    text: '型号',
    value: 'modelNo',
    align: 'center',
  },
  {
    text: '测量范围',
    value: 'mesureRange',
    align: 'center',
  },
  {
    text: '使用部门',
    value: 'useDeptName',
    align: 'center',
  },
  {
    text: '使用人',
    value: 'usePersonName',
    align: 'center',
  },
  {
    text: '管理状态',
    value: 'managerLevelName',
    align: 'center',
  },
  {
    text: '有效日期',
    value: 'validDate',
    align: 'center',
  },
])
const addRowRef = ref()
// 添加行
const addRowBtn = () => {
  addRowRef.value.initDialog({ title: '添加' })
}
// 删除行
const removeRowBtn = () => {
  const removeArr = borrowList.value.filter(item => item.remove !== '')
  if (removeArr.length) {
    ElMessageBox.confirm(
      '确认删除选中的数据吗？',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      },
    ).then(() => {
      borrowList.value = borrowList.value.filter(item => item.remove === '')
      ElMessage.success('删除成功')
    })
  }
  else {
    ElMessage.warning('请先选择需要删除的数据')
  }
}
// 借用设备列表添加
const addRowMethods = (row) => {
  row.forEach((element) => {
    borrowList.value.push({ ...element, remove: '' })
  })
}
</script>

<template>
  <app-container style="overflow: hidden;">
    <!-- 借用设备列表 -->
    <add-row ref="addRowRef" @add="addRowMethods" />
    <detail-page :title="`${name}-${title}`">
      <template #btns>
        <el-button v-if="title !== '详情'" type="primary" @click="submitForm(ruleFormRef, '提交')">
          保存
        </el-button>
        <el-button type="info" @click="resetForm(ruleFormRef)">
          关闭
        </el-button>
      </template>
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-position="right" label-width="110px" class="form" :class="[title === '详情' ? 'isDetail' : '']">
        <el-row :gutter="24" class="marg">
          <el-col :span="6">
            <el-form-item label="申请单位" prop="useDept">
              <com-tree-select
                v-if="title !== '详情'"
                v-model="ruleForm.useDept" :options="useDeptList as any" :placeholder="title === '详情' ? '' : '申请单位'"
                :tree-props="deptProps"
                style="width: 100%;"
              />
              <el-select v-else v-model="ruleForm.useDept" :disabled="title === '详情'" placeholder=" " style="width: 100%;">
                <el-option v-for="item in useDeptList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="申请人" prop="usePerson">
              <el-select v-model="ruleForm.usePerson" :placeholder="title === '详情' ? '' : '申请人'" :disabled="title === '详情'" style="width: 100%;">
                <el-option v-for="item in usePersonList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="设备编号" prop="equipmentNo">
              <el-input v-model.trim="ruleForm.equipmentNo" :placeholder="title === '详情' ? '' : '设备名称'" :disabled="title === '详情'" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="设备名称" prop="equipmentName">
              <el-input v-model.trim="ruleForm.equipmentName" :placeholder="title === '详情' ? '' : '设备名称'" :disabled="title === '详情'" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="6">
            <el-form-item label="型号" prop="modelNo">
              <el-input v-model.trim="ruleForm.modelNo" :placeholder="title === '详情' ? '' : '型号'" :disabled="title === '详情'" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="设备规格" prop="equipmentSpecifications">
              <el-input v-model.trim="ruleForm.equipmentSpecifications" :placeholder="title === '详情' ? '' : '设备规格'" :disabled="title === '详情'" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="出厂编号" prop="manufacturingNo">
              <el-input v-model.trim="ruleForm.manufacturingNo" :placeholder="title === '详情' ? '' : '出厂编号'" :disabled="title === '详情'" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="生产厂家" prop="manufacturer">
              <el-input v-model.trim="ruleForm.manufacturer" :placeholder="title === '详情' ? '' : '生产厂家'" :disabled="title === '详情'" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="6">
            <el-form-item label="闲置时间" prop="manufacturingDate">
              <el-date-picker
                v-model="ruleForm.manufacturingDate" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD HH:mm:ss" :disabled="title === '详情'"
                :placeholder="title === '详情' ? '' : '闲置时间'"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item label="申请理由" prop="managerState">
              <el-input v-model.trim="ruleForm.manufacturer" :placeholder="title === '详情' ? '' : '申请理由'" :disabled="title === '详情'" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="12">
            <el-form-item label="附件" prop="minioFileName">
              <show-photo :minio-file-name="ruleForm.fileList[0]?.minioFileName || ''" />
              <input v-show="title === ''" ref="fileRef" type="file" @change="onFileChange">
              <el-button v-if="title !== '详情'" type="primary" :disabled="title === '详情'" :style="{ 'margin-left': ruleForm.fileList[0]?.minioFileName ? '20px' : '0px' }" @click="upload">
                {{ ruleForm.fileList[0]?.minioFileName ? '更换' : '上传' }}
              </el-button>
              <span v-if="title === '详情' && !ruleForm.fileList[0]?.minioFileName">暂无</span>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </detail-page>
    <div>
      <detail-block title="借用设备列表">
        <template #btns>
          <el-button type="primary" @click="addRowBtn">
            添加行
          </el-button>
          <el-button type="info" @click="removeRowBtn">
            删除行
          </el-button>
        </template>
        <normal-table
          :data="borrowList" :total="1" :columns="columns as any"
        >
          <template #preColumns>
            <el-table-column label="选择" width="55" align="center">
              <template #default="scope">
                <el-checkbox v-model="scope.row.remove" :label="scope.$index" size="large" />
              </template>
            </el-table-column>
            <el-table-column label="序号" width="60" align="center">
              <template #default="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
          </template>
        </normal-table>
      </detail-block>
      <detail-block title="审批流程">
        <el-timeline>
          <el-timeline-item timestamp="2018/4/12" placement="top">
            <el-card>
              <h4>Update Github template</h4>
              <p>Tom committed 2018/4/12 20:46</p>
            </el-card>
          </el-timeline-item>
          <el-timeline-item timestamp="2018/4/3" placement="top">
            <el-card>
              <h4>Update Github template</h4>
              <p>Tom committed 2018/4/3 20:46</p>
            </el-card>
          </el-timeline-item>
          <el-timeline-item timestamp="2018/4/2" placement="top">
            <el-card>
              <h4>Update Github template</h4>
              <p>Tom committed 2018/4/2 20:46</p>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </detail-block>
    </div>
  </app-container>
</template>

<style lang="scss" scoped>
.timeline {
  background-color: #fff;
}

:deep(.el-checkbox__label) {
  display: none;
}

.isDetail {
  ::v-deep {
    .el-form-item.is-required:not(.is-no-asterisk) .el-form-item__label-wrap > .el-form-item__label::before,
    .el-form-item.is-required:not(.is-no-asterisk) > .el-form-item__label::before {
      display: none;
    }
  }
}
</style>
