<script lang="ts" setup name="standardListAdd">
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, UploadProps, UploadUserFile } from 'element-plus'
import type { IOptions } from '../standard_interface'
import { getStaffList } from '@/api/measure/person'
import { getTypeSelect } from '@/api/system/price'
import { getStandardLisUpdate, getStandardListAdd, getStandardListDetail, getUsersDept } from '@/api/device/standard'
import { UploadFile } from '@/api/measure/file'
const props = defineProps({
  infoId: {
    type: String,
    default: '0',
  },
  buttonType: {
    type: String,
    default: '',
  },
})
const emit = defineEmits(['close']) // 关闭
const ruleFormRef = ref<FormInstance>()
// 逻辑代码
const formInline = ref({
  assessDate: '',
  assessmentUnit: '',
  category: null,
  categoryName: '',
  constructionStandardProject: '',
  constructionStandardUnitName: '',
  contactInfo: '',
  createTime: null,
  createUser: null,
  id: '',
  isDel: null,
  laboratoryOwner: null,
  laboratoryOwnerContact: null,
  laboratoryOwnerName: null,
  managerState: null,
  managerStateName: '',
  measureMajor: null,
  fileList: [],
  measureMajorName: '',
  mesureRange: '',
  organizeNo: '',
  preparationDate: '',
  projectNo: '',
  remark: '',
  standardHumidity: null,
  standardLaboratory: null,
  standardLaboratoryName: '',
  standardLevel: null,
  standardLevelName: '',
  standardName: '',
  standardNo: '',
  standardOwner: null,
  standardOwnerName: '',
  standardTemperature: null,
  totalInvestment: null,
  transmitRange: null,
  transmitRangeName: '',
  uncertainty: '',
  updateTime: null,
  version: null,
})
const checkTypeOptions = ref<IOptions[]>([])

const standardOwnerOptions = ref<IOptions[]>([]) // 标准负责人
const fileList = ref<UploadUserFile[]>([]) // 文件对象数组
const measureMajorList = ref<IOptions[]>([]) // 计量专业下拉框
const standardManagerStateList = ref<IOptions[]>([]) // 管理状态下拉框
const standardLevelList = ref<IOptions[]>([]) // 标准等级下拉框
const transmitRangeList = ref<IOptions[]>([]) // 传递范围下拉框
// 标准所在部门下拉框
const standardUsersDeptList = ref<IOptions[]>([])
// 获取下拉框
const getSelectList = (code: string) => {
  getTypeSelect(code).then((res) => {
    if (code === 'measureMajor') {
      measureMajorList.value = res.data
    }
    else if (code === 'standardManagerState') {
      standardManagerStateList.value = res.data
    }
    else if (code === 'standardLevel') {
      standardLevelList.value = res.data
    }
    else if (code === 'transmitRange') {
      transmitRangeList.value = res.data
    }
    else if (code === 'standardCategory') {
      checkTypeOptions.value = res.data
    }
  })
}
getSelectList('measureMajor') // 获取计量专业下拉框
getSelectList('standardManagerState') // 获取管理状态下拉框
getSelectList('standardLevel') // 获取标准等级下拉框
getSelectList('transmitRange') // 获取传递范围下拉框
getSelectList('standardCategory') // 获取类别下拉框
// 获取部门信息
getUsersDept({
  createTime: '',
  director: '',
  meterMajor: '',
  organizeName: '',
  organizeNo: '',
  organizeType: '2',
  pdeptId: null,
  offset: 1,
  limit: 999999,
}).then((res) => {
  standardUsersDeptList.value = res.data.rows
})
// 获取到标准负责人数组
const getStandardOwnerOptions = () => {
  const params = {
    staffNo: '', // 人员编号
    name: '', // 姓名
    deptId: '', // 工作部门
    major: '', // 计量专业
    verifierCertificateNo: '', // 证书号
    certificateStatus: '', // 证书状态
    limit: 100000,
    offset: 1,
  }
  getStaffList(params).then((res) => {
    standardOwnerOptions.value = res.data.records
  })
}
getStandardOwnerOptions()
// 关闭
const close = () => {
  emit('close')
}
const rules = ref({
  standardName: [{ required: true, message: '标准名称不能为空', trigger: 'blur' }],
  projectNo: [{ required: true, message: '项目编号不能为空', trigger: 'blur' }],
  constructionStandardProject: [{ required: true, message: '建标项目不能为空', trigger: 'blur' }],
  organizeNo: [{ required: true, message: '组织机构代码不能为空', trigger: 'blur' }],
  constructionStandardUnitName: [{ required: true, message: '建标单位名称不能为空', trigger: 'blur' }],
  standardOwner: [{ required: true, message: '标准负责人不能为空', trigger: 'blur' }],
  contactInfo: [{ required: true, message: '联系方式不能为空', trigger: 'blur' }],
  category: [{ required: true, message: '类 别不能为空', trigger: 'blur' }],
  standardLevel: [{ required: true, message: '标准等级不能为空', trigger: 'blur' }],
  transmitRange: [{ required: true, message: '传递范围不能为空', trigger: 'blur' }],
  preparationDate: [{ required: true, message: '筹建日期不能为空', trigger: 'blur' }],
  managerState: [{ required: true, message: '管理状态不能为空', trigger: 'blur' }],
  measureMajor: [{ required: true, message: '计量专业不能为空', trigger: 'blur' }],
  assessmentUnit: [{ required: true, message: '考核单位不能为空', trigger: 'blur' }],
  assessDate: [{ required: true, message: '考核日期不能为空', trigger: 'blur' }],
  uncertainty: [{ required: true, message: '不确定度不能为空', trigger: 'blur' }],
  mesureRange: [{ required: true, message: '测量范围不能为空', trigger: 'blur' }],
  standardTemperature: [{ required: true, message: '标准温度不能为空', trigger: 'blur' },
    { pattern: /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/, message: '标准温度只能为数字', trigger: 'blur' }],
  standardHumidity: [{ required: true, message: '标准湿度不能为空', trigger: 'blur' },
    { pattern: /(^-?\d\d*\.\d*$)|(^-?\d\d*$)|(^-?\.\d\d*$)/, message: '标准湿度只能为数字', trigger: 'blur' }],
}) // 表单验证规则
// 上传请求
const uploadQuarterlyEvaluateFile = (file: File) => {
  const fd = new FormData()
  fd.append('multipartFile', file.file)
  UploadFile(fd).then((res) => {
    if (res.code === 200) {
      formInline.value.fileList = res.data
      // 重置当前验证
      ElMessage.success('文件上传成功')
    }
  })
}
const handleExceed: UploadProps['onExceed'] = (files, uploadFiles) => {
  ElMessage.warning('只能上传一个文件')
}
// 移除时触发
const beforeRemove: UploadProps['beforeRemove'] = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm(
    `确认移除${uploadFile.name}文件吗 ?`,
  ).then(
    () => true,
    () => false,

  )
}
// 点击文件预览
const uploadShow = (e: any) => {
  const URL = window.URL || window.webkitURL
  window.open(URL.createObjectURL(e.raw))
}
const testForm = ref({
  fileList: [],
  fileContent: '',
})
const handleFileChange = (files: any, fileList: any) => {
  testForm.value.fileList = fileList
  const reader = new FileReader()
  reader.readAsText(files.raw)
  // reader.onload = (e) => {
  //   testForm.value.fileContent = e.target!.result?.replace(
  //     /\n|\r\n/g,
  //     '<br/>',
  //   )
  // }
}
// 编辑获取详情的提交按钮
const submitFormDetail = () => {
  if (props.buttonType === '编辑') {
    formInline.value.id = props.infoId
    getStandardLisUpdate(formInline.value).then((res) => {
      if (res.code === 200) {
        close()
      }
    })
  }
  else {
    // 打印
    const printObj = ref({
      id: 'print', // 需要打印元素的id
      popTitle: '测量标准装置', // 打印配置页上方的标题
      extraHead: '', // 最上方的头部文字，附加在head标签上的额外标签，使用逗号分割
      preview: false, // 是否启动预览模式，默认是false
      standard: '',
      extarCss: '',
    })
  }
}
// 提交
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) { return }
  if (props.buttonType === '详情') { return submitFormDetail() }
  formEl.validate((valid, fields) => {
    if (valid) {
      ElMessageBox.confirm(
        '确认提交吗？',
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        },
      ).then(() => {
        props.buttonType === ''
          ? getStandardListAdd(formInline.value).then((res) => {
            if (res.code === 200) {
              close()
            }
          })
          : submitFormDetail()
      })
    }
  })
}
// 标准实验室发生改变row类型
interface rowReturn {
  phone: string
  director: string
}
// 标准实验室发生改变
const changeDeptList = (row: object) => {
  formInline.value.laboratoryOwnerContact = row.phone
  formInline.value.laboratoryOwner = row.director
}
// 标准实验室清空时
const clearDeptList = () => {
  formInline.value.laboratoryOwnerContact = null
  formInline.value.laboratoryOwner = null
}
// 获取详情信息
const getInfo = () => {
  getStandardListDetail({ id: props.infoId }).then((res) => {
    Object.keys(res.data).map((item) => {
      if (typeof (res.data[item]) === 'number') {
        res.data[item] = res.data[item].toString()
      }
    })
    formInline.value = res.data
  })
}
if (props.buttonType !== '') {
  getInfo()
}
</script>

<template>
  <app-container>
    <div class="top-info">
      <h4 class="title">
        测量标准装置
      </h4>
      <div>
        <el-button
          v-print="buttonType === '详情' ? printObj : ''"
          type="primary"
          @click="submitForm(ruleFormRef)"
        >
          {{ buttonType === '详情' ? '打印' : '提交' }}
        </el-button>
        <el-button type="warning" @click="close">
          关闭
        </el-button>
      </div>
    </div>
    <div class="info-content">
      <el-form
        ref="ruleFormRef"
        :inline="true"
        :model="formInline"
        label-position="left"
        label-width="auto"
        :rules="rules"
      >
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="标准代码:">
              <el-input
                v-model.trim="formInline.standardNo"
                placeholder="系统编号，自动生成"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="标准名称:" prop="standardName">
              <el-input
                v-model.trim="formInline.standardName"
                placeholder="标准名称"
                :disabled="buttonType === '详情'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="项目编号:" prop="projectNo">
              <el-input
                v-model.trim="formInline.projectNo"
                placeholder="项目编号"
                :disabled="buttonType === '详情'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="建标项目:" prop="constructionStandardProject">
              <el-input
                v-model.trim="formInline.constructionStandardProject"
                placeholder="建标项目"
                :disabled="buttonType === '详情'"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="组织机构代码:" prop="organizeNo">
              <el-input
                v-model.trim="formInline.organizeNo"
                placeholder="组织机构代码"
                :disabled="buttonType === '详情'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="建标单位名称:"
              prop="constructionStandardUnitName"
            >
              <el-input
                v-model.trim="formInline.constructionStandardUnitName"
                placeholder="建标单位名称"
                :disabled="buttonType === '详情'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="标准负责人:" prop="standardOwner">
              <el-select
                v-model="formInline.standardOwner"
                clearable
                placeholder="标准负责人"
                size="default"
                :disabled="buttonType === '详情'"
              >
                <el-option
                  v-for="item in standardOwnerOptions"
                  :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="contactInfo">
              <el-input
                v-model.trim="formInline.contactInfo"
                placeholder="联系方式"
                :disabled="buttonType === '详情'"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="类 别:" prop="category">
              <el-select
                v-model="formInline.category"
                clearable
                placeholder="类别"
                size="default"
                :disabled="buttonType === '详情'"
              >
                <el-option
                  v-for="item in checkTypeOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="标准等级:" prop="standardLevel">
              <el-select
                v-model.trim="formInline.standardLevel"
                clearable
                placeholder="标准等级"
                size="default"
                :disabled="buttonType === '详情'"
              >
                <el-option
                  v-for="item in standardLevelList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="传递范围:" prop="transmitRange">
              <el-select
                v-model.trim="formInline.transmitRange"
                clearable
                placeholder="传递范围"
                size="default"
                :disabled="buttonType === '详情'"
              >
                <el-option
                  v-for="item in transmitRangeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="投资总额:">
              <el-input
                v-model.trim="formInline.totalInvestment"
                placeholder="投资总额"
                :disabled="buttonType === '详情'"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="筹建日期:" prop="preparationDate">
              <el-date-picker
                v-model="formInline.preparationDate"
                type="datetime"
                placeholder="请选择筹建日期"
                format="YYYY/MM/DD HH:mm:ss"
                value-format="YYYY-MM-DD h:m:s"
                :disabled="buttonType === '详情'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="标准所在实验室:">
              <el-select
                v-model.trim="formInline.standardLaboratory"
                clearable
                placeholder="标准所在实验室"
                size="default"
                :disabled="buttonType === '详情'"
                @clear="clearDeptList"
              >
                <el-option
                  v-for="item in standardUsersDeptList"
                  :key="item.id"
                  :label="item.organizeName"
                  :value="item.deptId"
                  @click="changeDeptList(item)"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="实验室负责人:">
              <el-input
                v-model.trim="formInline.laboratoryOwner"
                placeholder="实验室负责人"
                :disabled="buttonType === '详情'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系方式:">
              <el-input
                v-model.trim="formInline.laboratoryOwnerContact"
                placeholder="联系方式"
                :disabled="buttonType === '详情'"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="管理状态:" prop="managerState">
              <el-select
                v-model.trim="formInline.managerState"
                clearable
                placeholder="管理状态"
                size="default"
                :disabled="buttonType === '详情'"
              >
                <el-option
                  v-for="item in standardManagerStateList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="计量专业:" prop="measureMajor">
              <el-select
                v-model.trim="formInline.measureMajor"
                clearable
                placeholder="计量专业"
                size="default"
                :disabled="buttonType === '详情'"
              >
                <el-option
                  v-for="item in measureMajorList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="考核单位:" prop="assessmentUnit">
              <el-input
                v-model.trim="formInline.assessmentUnit"
                placeholder="考核单位"
                :disabled="buttonType === '详情'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="考核日期:" prop="assessDate">
              <el-date-picker
                v-model="formInline.assessDate"
                type="datetime"
                placeholder="请选择考核日期"
                format="YYYY/MM/DD HH:mm:ss"
                value-format="YYYY-MM-DD h:m:s"
                :disabled="buttonType === '详情'"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="不确定度:" prop="uncertainty">
              <el-input
                v-model.trim="formInline.uncertainty"
                style="width: 500px;"
                placeholder="不确定度"
                :disabled="buttonType === '详情'"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="测量范围:" prop="mesureRange">
              <el-input
                v-model.trim="formInline.mesureRange"
                placeholder="测量范围"
                style="width: 500px;"
                :disabled="buttonType === '详情'"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="2">
            <el-form-item label="环境条件" />
          </el-col>
          <el-col :span="6">
            <el-form-item label="标准温度:" prop="standardTemperature">
              <el-input
                v-model.trim="formInline.standardTemperature"
                placeholder="标准温度℃"
                :disabled="buttonType === '详情'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="标准湿度:" prop="standardHumidity">
              <el-input
                v-model.trim="formInline.standardHumidity"
                placeholder="标准湿度%"
                :disabled="buttonType === '详情'"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="有效日期:">
              <el-date-picker
                type="datetime"
                placeholder="请选择有效日期"
                format="YYYY/MM/DD HH:mm:ss"
                value-format="YYYY-MM-DD h:m:s"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="证书编号:">
              <el-select
                clearable
                placeholder="证书编号"
                size="default"
                disabled
              >
                <el-option
                  v-for="item in standardManagerStateList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="发证单位:">
              <el-input placeholder="发证单位" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="发证日期:">
              <el-date-picker
                type="datetime"
                placeholder="请选择发证日期"
                format="YYYY/MM/DD HH:mm:ss"
                value-format="YYYY-MM-DD h:m:s"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="3">
            <el-form-item label="附件:">
              <el-upload
                v-model:file-list="fileList"
                enctype="multipart/form-data"
                :http-request="uploadQuarterlyEvaluateFile"
                :before-remove="beforeRemove"
                :on-exceed="handleExceed"
                :on-preview="uploadShow"
                :on-change="handleFileChange"
                :limit="1"
              >
                <el-button :disabled="buttonType === '详情'">
                  上传
                </el-button>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="备注:">
              <el-input
                v-model.trim="formInline.remark"
                style="width: 500px;"
                placeholder="备注"
                :disabled="buttonType === '详情'"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </app-container>
</template>

<style lang="scss" scoped>
// 样式
.top-info {
  width: 100%;
  height: 50px;
  padding-right: 10px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-radius: 10px;
  background-color: #fff;

  .title {
    width: 75%;
    text-align: center;
  }
}

.info-content {
  margin-top: 10px;
  padding: 30px;
  border-radius: 10px;
  background-color: #fff;
}

:deep .el-input .el-input--default .el-input--suffix {
  width: 200px !important;
}
</style>
