<!-- 新建、编辑、详情 -->
<script lang="ts" setup name="SampleEdit">
import type { Ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, UploadUserFile } from 'element-plus'
import { ref } from 'vue'
import { Calendar, Search } from '@element-plus/icons-vue'
import type { ISampleEdit, SimpleCertification, SimpleMeasureRecord } from './sample_list_interface'
import sampleDialog from './sampleDialog.vue'
import showPhoto from '@/views/system/tool/showPhoto.vue'
import { SCHEDULE } from '@/utils/scheduleDict'
import TemplateTable from '@/views/customer/customerInfo/templateTable.vue'
import { addSample, getSapmleDetail, updateSample } from '@/api/customer/sampleList'
import countries from '@/components/AddressSelect/country-code.json'
import { UploadFile } from '@/api/measure/file'
import type { TableColumn } from '@/components/NormalTable/table_interface'

const textMap: { [key: string]: string } = {
  edit: '编辑',
  add: '新建',
  detail: '详情',
}// 字典
const pageType = ref('add') // 页面类型: add, edit, detail
const countryList = ref(countries) // 国家列表
const loading = ref(false) // 表单加载状态
const infoId = ref('') // id
const visible = ref(false) // 控制对话框显隐
const mesureCategoryMap: { [key: string]: string } = {
  edit: '编辑',
  add: '新建',
  detail: '详情',
}// 字典
const mesureCategoryList = [
  {
    label: '检定',
    value: 'jd',
  },
  {
    label: '检测',
    value: 'jc',
  },
  {
    label: '验收检定',
    value: 'ysjd',
  },
  {
    label: '抽检',
    value: 'cj',
  },
  {
    label: '校准',
    value: 'jz',
  },
  {
    label: '测试',
    value: 'cs',
  },
  {
    label: '验收校准',
    value: 'ysjz',
  },
]// 校检类别
const mesureResultList = [
  {
    label: '合格',
    value: 'hg',
  },
  {
    label: '修后合格',
    value: 'xhhg',
  },
  {
    label: '限用',
    value: 'xy',
  },
  {
    label: '准用',
    value: 'zy',
  },
  {
    label: '不合格',
    value: 'bhg',
  },
  {
    label: '漏检',
    value: 'lj',
  },
  {
    label: '逾期未检定',
    value: 'yqwjd',
  },
]
const mesureTypeList = [
  {
    label: '外检',
    value: 'wj',
  },
  {
    label: '外包',
    value: 'wb',
  },
]// 检定方式
const dataForm: Ref<ISampleEdit> = ref({
  id: '',
  sampleNo: '', // 样品编号
  sampleName: '', // 样品名称
  sampleModel: '', // 样品型号
  manufacturingNo: '', // 出厂编号
  customerNo: '', // 委托方代码
  customerName: '', // 委托方名称
  phone: '', // 委托方电话
  postalCode: '', // 委托方邮编
  companyAddress: '', // 委托方地址
  mesureCategory: '', // 检校类别
  manufacturer: '', // 生产厂家
  manufacturerCountry: '', // 厂家国别
  manufacturingDate: '', // 出厂年月
  ABC: '', // ABC
  // deliverer: '', // 送检人
  // delivererTel: '', // 送检人联系方式
  mesureContent: '', // 检定项目
  mesurePeriod: '', // 检定周期
  remark: '', // 备注
  minioFileName: '', // 说明书
  labelBind: '', // 标签绑定
  mesureType: '', // 检定方式
})
const ruleFormRef = ref<FormInstance>()

// 自定义校验规则--检定周期为正整数
const validateMesurePeriod = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback()
  }
  else if (!(/(^[1-9]\d*$)/.test(value))) {
    callback(new Error('请输入一个正整数'))
  }
  else {
    callback()
  }
}

// 校验规则
const rules = ref({
  sampleName: [{ required: true, message: '样品名称不能为空', trigger: 'blur' }],
  sampleModel: [{ required: true, message: '样品型号不能为空', trigger: 'blur' }],
  manufacturingNo: [{ required: true, message: '出厂编号不能为空', trigger: 'blur' }],
  customerNo: [{ required: true, message: '委托方代码不能为空', trigger: 'change' }],
  customerName: [{ required: true, message: '委托方名称不能为空', trigger: 'blur' }],
  phone: [{ required: true, message: '委托方电话不能为空', trigger: 'blur' }],
  postalCode: [{ required: true, message: '委托方邮编不能为空', trigger: 'blur' }],
  companyAddress: [{ required: true, message: '委托方地址不能为空', trigger: 'blur' }],
  mesureContent: [{ required: true, message: '检定项目不能为空', trigger: 'blur' }],
  mesurePeriod: [{ validator: validateMesurePeriod, trigger: 'blur' }],
}) // 表单验证规则

// 其他关联数据列表
const dataList = ref({
  measureRecords: [] as SimpleMeasureRecord[],
  certificationRecords: [] as SimpleCertification[],
})

// 获取检定记录
const fetchMeasureRecords = function (query = null) {
  dataList.value.measureRecords = []
}
// 获取检定证书
const fetchCertifications = function (query = null) {
  dataList.value.certificationRecords = []
}
interface Menu {
  name: string
  columns: TableColumn[]
  pagination: boolean
  list: 'measureRecords' | 'certificationRecords'
  searchFunc: Function
}
// 菜单
const menu: Menu[] = [
  {
    name: '检定记录',
    columns: [
      { text: '委托单编号', value: 'orderCode' },
      { text: '委托单日期', value: 'orderTime' },
      { text: '委托方代码', value: 'customerCode' },
      { text: '委托方名称', value: 'customerName' },
      { text: '送检人', value: 'deliverer' },
      { text: '送检日期', value: 'deliverTime' },
    ],
    list: 'measureRecords',
    pagination: true,
    searchFunc: fetchMeasureRecords,
  },
  {
    name: '检定证书',
    columns: [
      { text: '证书编号', value: 'certificationCode' },
      { text: '证书名称', value: 'certificationName' },
      { text: '证书类型', value: 'certificationType' },
      { text: '证书出具日期', value: 'effectiveDate' },
      { text: '证书有效期', value: 'expirationDate' },
    ],
    list: 'certificationRecords',
    pagination: true,
    searchFunc: fetchCertifications,
  },
]

const currentMenu = ref('检定记录')
const currentMenuObj = computed(() => {
  return menu.find(item => item.name === currentMenu.value)
})

// 从路由中获取页面类型参数
const $route = useRoute()
if ($route.params && $route.params.type) {
  pageType.value = $route.params.type as string
  if ($route.params.id) {
    infoId.value = $route.params.id as string
  }
}
const $router = useRouter()
// 关闭新增页面的回调
const close = () => {
  $router.back()
}

// 打印表单
const printObj = ref({
  id: 'form', // 需要打印元素的id
  popTitle: '样品详情', // 打印配置页上方的标题
  extraHead: '<div style="display: flex;flex-direction: column;text-align: center"><h3>样品详情</h3></div>', // 最上方的头部文字，附加在head标签上的额外标签，使用逗号分割
  preview: false, // 是否启动预览模式，默认是false
  standard: '',
  extarCss: '',
})

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) {
        dataForm.value.minioFileName = res.data[0]
        // 重置当前验证
        ElMessage.success('文件上传成功')
      }
      else {
        ElMessage.error(res.message)
      }
    })
  }
}
const upload = () => {
  fileRef.value.click()
}

// 委托方代码获取焦点
const customerNoFocus = () => {
  visible.value = true
  console.log(visible.value)
}

// 选好委托方
const confirmCheckout = (val: any) => {
  dataForm.value.customerNo = val[0].customerNo
  dataForm.value.customerName = val[0].customerName
  dataForm.value.phone = val[0].phone
  dataForm.value.postalCode = val[0].postalCode
  dataForm.value.companyAddress = val[0].briefName
}

// 控制选择委托方对话框显隐
const changeVisible = (val: boolean) => {
  visible.value = val
}

// 保存
function saveForm(formEl: FormInstance | undefined) {
  if (!formEl) { return }
  formEl.validate((valid, fields) => {
    if (valid) {
      ElMessageBox.confirm(
        '确认保存吗？',
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        },
      ).then(() => {
        if (dataForm.value.id) {
          updateSample(dataForm.value).then((res) => {
            if (res.code === 200) {
              dataForm.value.id = res.data.id
              dataForm.value.customerNo = res.data.customerNo
              ElMessage.success('已保存')
              $router.go(-1)
            }
          })
        }
        else {
          addSample(dataForm.value).then((res) => {
            if (res.code === 200) {
              dataForm.value.id = res.data.id
              dataForm.value.customerNo = res.data.customerNo
              ElMessage.success('已保存')
              $router.go(-1)
            }
          })
        }
      })
    }
  })
}

// 提交表单
function submitForm() {
  if (dataForm.value.id) {
    const params = {
      id: dataForm.value.id,
      formId: SCHEDULE.SUPPLIER_APPROVAL, // 表单id
    }
    addSample(params).then((res) => {
      ElMessage.success('提交成功')
      close()
    })
  }
  else {
    ElMessage.info('请先保存再提交！')
  }
}

const getInfo = () => {
  getSapmleDetail({ id: infoId.value }).then((res) => {
    // res.data = {
    //   ABC: 'A',
    //   companyAddress: '北京/北京市',
    //   customerName: '京东集团',
    //   customerNo: 'sygf202211290001',
    //   id: '',
    //   labelBind: '11222',
    //   manufacturer: '北京某厂家',
    //   manufacturerCountry: 'CN',
    //   manufacturingDate: '2023-03',
    //   manufacturingNo: '123121',
    //   mesureCategory: 'jd',
    //   mesureContent: '项目1',
    //   mesurePeriod: '1',
    //   mesureType: 'wj',
    //   minioFileName: '小程序工期表-1117_1674961769128.xlsx',
    //   phone: '950618',
    //   postalCode: 'test',
    //   remark: '无备注',
    //   sampleModel: '型号1',
    //   sampleName: '样品1',
    //   sampleNo: '',
    // }
    dataForm.value = res.data
    for (const item of menu) {
      item.searchFunc()
    }
  })
}

// 非添加页面获取详情
if (pageType.value !== 'add') {
  getInfo()
}
</script>

<template>
  <app-container>
    <detail-page :title="`样品-${textMap[pageType]}`">
      <template #btns>
        <el-button v-if="pageType === 'detail'" v-print="printObj" type="primary">
          打印
        </el-button>
        <el-button v-if="pageType !== 'detail'" type="primary" @click="saveForm(ruleFormRef)">
          保存
        </el-button>
        <el-button type="info" @click="close">
          关闭
        </el-button>
      </template>
      <div id="form">
        <el-form
          ref="ruleFormRef"
          :model="dataForm"
          :label-width="120"
          label-position="right"
          :rules="rules"
        >
          <el-row :gutter="24">
            <el-col :span="6">
              <el-form-item label="样品编号:" prop="sampleNo">
                <el-input
                  v-model="dataForm.sampleNo"
                  :placeholder="pageType === 'detail' ? '' : '系统自动生成'"
                  :class="{ 'detail-input': pageType === 'detail' }"
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="样品名称:" prop="sampleName">
                <el-input
                  v-model="dataForm.sampleName"
                  :placeholder="pageType === 'detail' ? '' : '请输入样品名称'"
                  :class="{ 'detail-input': pageType === 'detail' }"
                  :disabled="pageType === 'detail'"
                />
              </el-form-item>
            </el-col><el-col :span="6">
              <el-form-item label="样品型号:" prop="sampleModel">
                <el-input
                  v-model="dataForm.sampleModel"
                  :placeholder="pageType === 'detail' ? '' : '请输入样品型号'"
                  :class="{ 'detail-input': pageType === 'detail' }"
                  :disabled="pageType === 'detail'"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="出厂编号:" prop="manufacturingNo">
                <el-input
                  v-model="dataForm.manufacturingNo"
                  :placeholder="pageType === 'detail' ? '' : '请输入出厂编号'"
                  :class="{ 'detail-input': pageType === 'detail' }"
                  :disabled="pageType === 'detail'"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="委托方代码" prop="customerNo">
                <el-input
                  v-model="dataForm.customerNo"
                  :placeholder="pageType === 'detail' ? '' : '请输入委托方代码'"
                  :class="{ 'detail-input': pageType === 'detail' }"
                  :disabled="pageType === 'detail'"
                  @focus="customerNoFocus"
                >
                  <template #suffix>
                    <el-icon class="el-input__icon">
                      <search />
                    </el-icon>
                    <!-- <el-button v-if="pageType !== 'detail'" @click="upload">
                      xuanze
                    </el-button> -->
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="委托方名称" prop="customerName">
                <el-input
                  v-model="dataForm.customerName"
                  :placeholder="pageType === 'detail' ? '' : '请输入委托方名称'"
                  :class="{ 'detail-input': pageType === 'detail' }"
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="委托方电话" prop="phone">
                <el-input
                  v-model="dataForm.phone"
                  :placeholder="pageType === 'detail' ? '' : '请输入委托方电话'"
                  :class="{ 'detail-input': pageType === 'detail' }"
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="委托方邮编" prop="postalCode">
                <el-input
                  v-model="dataForm.postalCode"
                  :placeholder="pageType === 'detail' ? '' : '请输入委托方邮编'"
                  :class="{ 'detail-input': pageType === 'detail' }"
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col :span="18">
              <el-form-item label="委托方地址:" prop="companyAddress">
                <el-input
                  v-model="dataForm.companyAddress"
                  type="textarea"
                  autosize
                  :placeholder="pageType === 'detail' ? '' : '请输入委托方地址'"
                  :class="{ 'detail-input': pageType === 'detail' }"
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="校检类别:">
                <el-select
                  v-model="dataForm.mesureCategory"
                  :placeholder="pageType === 'detail' ? '' : '请选择校检类别'"
                  :disabled="pageType === 'detail'"
                  class="full-width-input"
                >
                  <el-option v-for="item of mesureCategoryList" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="生产厂家:">
                <el-input
                  v-model="dataForm.manufacturer"
                  :placeholder="pageType === 'detail' ? '' : '请输入生产厂家'"
                  :class="{ 'detail-input': pageType === 'detail' }"
                  :disabled="pageType === 'detail'"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="厂家国别:">
                <el-select
                  v-model="dataForm.manufacturerCountry"
                  :placeholder="pageType === 'detail' ? '' : '请选择厂家国别'"
                  :disabled="pageType === 'detail'"
                  class="full-width-input"
                >
                  <el-option v-for="country of countryList" :key="country.code" :label="country.CNName" :value="country.code" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="出厂年月:">
                <el-date-picker
                  v-model="dataForm.manufacturingDate"
                  type="month"
                  format="YYYY-MM"
                  value-format="YYYY-MM"
                  class="full-width-input"
                  :placeholder="pageType === 'detail' ? '' : '请输入出厂年月'"
                  :class="{ 'detail-input': pageType === 'detail' }"
                  :disabled="pageType === 'detail'"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="ABC:">
                <el-select
                  v-model="dataForm.ABC"
                  :placeholder="pageType === 'detail' ? '' : '请选择ABC'"
                  :disabled="pageType === 'detail'"
                  class="full-width-input"
                >
                  <el-option v-for="item of ['A', 'B', 'C']" :key="item" :label="item" :value="item" />
                </el-select>
              </el-form-item>
            </el-col>
            <!-- <el-col :span="6">
              <el-form-item label="送检人:">
                <el-input
                  v-model="dataForm.deliverer"
                  :placeholder="pageType === 'detail' ? '' : '请输入送检人'"
                  :class="{ 'detail-input': pageType === 'detail' }"
                  :disabled="pageType === 'detail'"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="联系方式:">
                <el-input
                  v-model="dataForm.delivererTel"
                  :placeholder="pageType === 'detail' ? '' : '请输入联系方式'"
                  :class="{ 'detail-input': pageType === 'detail' }"
                  :disabled="pageType === 'detail'"
                />
              </el-form-item>
            </el-col> -->
            <el-col :span="18">
              <el-form-item label="检定项目:" prop="mesureContent">
                <el-input
                  v-model="dataForm.mesureContent"
                  :placeholder="pageType === 'detail' ? '' : '请输入检定项目'"
                  :disabled="pageType === 'detail'"
                  :class="{ 'detail-input': pageType === 'detail' }"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="检定周期（月）:">
                <el-input
                  v-model="dataForm.mesurePeriod"
                  :placeholder="pageType === 'detail' ? '' : '请输入检定周期'"
                  :class="{ 'detail-input': pageType === 'detail' }"
                  :disabled="pageType === 'detail'"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item v-if="pageType === 'detail'" label="检定日期:">
                <el-date-picker
                  v-model="dataForm.manufacturingDate"
                  type="date"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  class="full-width-input"
                  :placeholder="pageType === 'detail' ? '' : '请输入检定日期'"
                  :class="{ 'detail-input': pageType === 'detail' }"
                  :disabled="pageType === 'detail'"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item v-if="pageType === 'detail'" label="有效日期:">
                <el-date-picker
                  v-model="dataForm.manufacturingDate"
                  type="date"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  class="full-width-input"
                  :placeholder="pageType === 'detail' ? '' : '请输入有效日期'"
                  :class="{ 'detail-input': pageType === 'detail' }"
                  :disabled="pageType === 'detail'"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item v-if="pageType === 'detail'" label="检定结果:">
                <el-select
                  v-model="dataForm.mesureCategory"
                  :placeholder="pageType === 'detail' ? '' : '请选择检定结果'"
                  :disabled="pageType === 'detail'"
                  class="full-width-input"
                >
                  <el-option v-for="item of mesureResultList" :key="item.value" :label="item.label" :value="item.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="dataForm.remark"
                  type="textarea"
                  autosize
                  :placeholder="pageType === 'detail' ? '' : '请输入备注'"
                  :disabled="pageType === 'detail'"
                  :class="{ 'detail-input': pageType === 'detail' }"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="检定方式:">
                <el-select
                  v-model="dataForm.mesureType"
                  :placeholder="pageType === 'detail' ? '' : '请选择检定方式'"
                  :disabled="pageType === 'detail'"
                  class="full-width-input"
                >
                  <el-option v-for="item of mesureTypeList" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="标签绑定:">
                <el-input
                  v-model="dataForm.labelBind"
                  :placeholder="pageType === 'detail' ? '' : '标签绑定'"
                  :disabled="pageType === 'detail'"
                  :class="{ 'detail-input': pageType === 'detail' }"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24" class="marg">
            <el-col :span="14">
              <el-form-item label="说明书:">
                <show-photo v-if="dataForm.minioFileName" :minio-file-name="dataForm.minioFileName" />
                <span v-else-if="pageType === 'detail'">无</span>
                <input v-show="pageType === ''" ref="fileRef" type="file" @change="onFileChange">
                <el-button v-if="pageType !== 'detail'" id="file" type="primary" :disabled="pageType === 'detail'" :style="{ 'margin-left': dataForm.minioFileName === '' ? '0px' : '20px' }" @click="upload">
                  {{ dataForm.minioFileName === '' ? '上传' : '更换附件' }}
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </detail-page>

    <!-- 检定记录、检定证书 -->
    <detail-block-switch v-if="pageType === 'detail'" :title="currentMenu">
      <template #menu>
        <el-radio-group v-model="currentMenu">
          <el-radio-button v-for="item in menu" :key="item.name" :label="item.name">
            {{ item.name }}
          </el-radio-button>
        </el-radio-group>
      </template>
      <template-table v-if="currentMenuObj" :columns="currentMenuObj.columns" :list="dataList[currentMenuObj.list]" :loading="false" :pagination="currentMenuObj.pagination" @change-page="currentMenuObj?.searchFunc" />
    </detail-block-switch>

    <!-- 选择委托方组件 -->
    <sample-dialog v-model:visible="visible" @confirmCheckout="confirmCheckout" @changeVisible="changeVisible" />
  </app-container>
</template>

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

