<!-- 新建、编辑、详情 -->
<script lang="ts" setup name="SampleEdit">
import type { Ref } from 'vue'
import { ref } from 'vue'
import { Search } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import type { ISampleDetail, SimpleCertification, SimpleMeasureRecord, dictType } from './overtime_list_interface'
import showPhoto from '@/views/system/tool/showPhoto.vue'
import TemplateTable from '@/views/customer/customerInfo/templateTable.vue'
import { getCertification, getMesureRecords, getSapmleDetail } from '@/api/customer/sampleList'
import countries from '@/components/AddressSelect/country-code.json'
import type { TableColumn } from '@/components/NormalTable/table_interface'
import { getDictByCode } from '@/api/system/dict'
import type { IRecord } from '@/views/business/schedule/interchange/interchange_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 mesureCategoryList = ref<dictType[]>([]) // 校检类别
const measureTypeList = ref<dictType[]>([]) // 检定方式
const powerVoltageList = ref<dictType[]>([]) // 电源电压
const ABCList = ref<dictType[]>([]) // ABC

const dataForm: Ref<ISampleDetail> = ref({
  id: '',
  sampleNo: '', // 样品编号
  sampleName: '', // 样品名称
  sampleModel: '', // 样品型号
  manufacturingNo: '', // 出厂编号
  customerNo: '', // 委托方代码
  customerName: '', // 委托方名称
  phone: '', // 委托方电话
  postalCode: '', // 委托方邮编
  customerAddress: '', // 委托方地址
  measureCategory: '', // 检校类别
  manufacturer: '', // 生产厂家
  manufacturerCountry: '', // 厂家国别
  manufacturingDate: '', // 出厂年月
  ABC: '', // ABC
  deliverer: '', // 送检人
  delivererTel: '', // 送检人联系方式
  planDeliverTime: '', // 预计送达时间
  requireOverTime: '', // 要求检完时间
  measureContent: '', // 检定项目
  measurePeriod: '', // 检定周期
  remark: '', // 备注
  minioFileName: '', // 说明书
  labelBind: '', // 标签绑定
  measureType: '1', // 检定方式 1自检、2外包、3外检
  measureLastTime: '', // 检定日期
  validDeadline: '', // 有效日期
  powerVoltage: '', // 电源电压
})

// 获取字典值
function getDict() {
  // 校检类别
  getDictByCode('measureCategory').then((response) => {
    mesureCategoryList.value = response.data
  })
  // 检定方式
  getDictByCode('measureType').then((response) => {
    measureTypeList.value = response.data
  })
  // 电源电压
  getDictByCode('powerVoltage').then((response) => {
    powerVoltageList.value = response.data
  })
  // ABC
  getDictByCode('ABC').then((response) => {
    ABCList.value = response.data
  })
}
getDict()

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

const listQuery = ref<IRecord>({
  sampleId: infoId.value, // 样品id
  customerId: '', // 客户id
  offset: 1,
  limit: 10,
})
const totalRecords = ref(0) // 检定记录
const totalCertifications = ref(0) // 检定证书
// 获取检定记录
const fetchMeasureRecords = (query = null) => {
  if (pageType.value === 'detail') {
    getMesureRecords(listQuery.value).then((res) => {
      dataList.value.measureRecords = res.data.rows.map((item: { orderTime: string; deliverTime: string }) => {
        return {
          ...item,
          orderTime: item.orderTime ? dayjs(item.orderTime).format('YYYY-MM-DD') : '',
          deliverTime: item.deliverTime ? dayjs(item.deliverTime).format('YYYY-MM-DD') : '',
        }
      })
      totalRecords.value = parseInt(res.data.total)
    })
  }
}

// 获取检定证书
const fetchCertifications = (query = null) => {
  if (pageType.value === 'detail') {
    getCertification(listQuery.value).then((res) => {
      dataList.value.certificationRecords = res.data.rows.map((item: { effectiveDate: string; expirationDate: string }) => {
        return {
          ...item,
          effectiveDate: item.effectiveDate ? dayjs(item.effectiveDate).format('YYYY-MM-DD') : '',
          expirationDate: item.expirationDate ? dayjs(item.expirationDate).format('YYYY-MM-DD') : '',

        }
      })
      totalCertifications.value = parseInt(res.data.total)
    })
  }
}
interface Menu {
  name: string
  columns: TableColumn[]
  pagination: boolean
  list: 'measureRecords' | 'certificationRecords'
  searchFunc: Function
}
// 菜单
const menu: Menu[] = [
  {
    name: '检定记录',
    columns: [
      { text: '委托单编号', value: 'orderCode', align: 'center', width: '160' },
      { text: '委托单日期', value: 'orderTime', align: 'center', width: '120' },
      { text: '委托方代码', value: 'customerCode', align: 'center', width: '160' },
      { text: '委托方名称', value: 'customerName', align: 'center' },
      { text: '送检人', value: 'deliverer', align: 'center' },
      { text: '送检日期', value: 'deliverTime', align: 'center', width: '120' },
    ],
    list: 'measureRecords',
    pagination: true,
    searchFunc: fetchMeasureRecords,
  },
  {
    name: '检定证书',
    columns: [
      { text: '证书编号', value: 'certificationCode', align: 'center', width: '160' },
      { text: '证书名称', value: 'certificationName', align: 'center' },
      { text: '证书类型', value: 'certificationClassName', align: 'center' },
      { text: '证书出具日期', value: 'effectiveDate', align: 'center', width: '120' },
      { text: '证书有效期', value: 'expirationDate', align: 'center', width: '120' },
    ],
    list: 'certificationRecords',
    pagination: true,
    searchFunc: fetchCertifications,
  },
]

const currentMenu = ref('检定记录')
const currentMenuObj = computed(() => {
  return menu.find(item => item.name === currentMenu.value)
})
watch(currentMenuObj, () => {
  listQuery.value.offset = 1
  currentMenuObj.value?.searchFunc()
},
{
  deep: true,
  immediate: true,
})

// 监听检定记录和证书报告页数变化
const changePage = (val: any) => {
  if (val.value && currentMenuObj) {
    listQuery.value.offset = val.value.offset
    listQuery.value.limit = val.value.limit
    currentMenuObj.value?.searchFunc()
  }
}

// 从路由中获取页面类型参数
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 getInfo = () => {
  getSapmleDetail({ id: infoId.value }).then((res) => {
    dataForm.value = res.data
    dataForm.value.ABC = res.data.abc
    listQuery.value.sampleId = infoId.value
    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 type="info" @click="close">
          关闭
        </el-button>
      </template>
      <div id="form">
        <el-form
          ref="ruleFormRef"
          :model="dataForm"
          :label-width="120"
          label-position="right"
        >
          <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'"
                >
                  <template #suffix>
                    <el-icon v-if="pageType !== 'detail'" class="el-input__icon">
                      <search />
                    </el-icon>
                  </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="customerAddress">
                <el-input
                  v-model="dataForm.customerAddress"
                  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.measureCategory"
                  :placeholder="pageType === 'detail' ? ' ' : '请选择校检类别'"
                  :disabled="pageType === 'detail'"
                  class="full-width-input"
                >
                  <el-option v-for="item of mesureCategoryList" :key="item.value" :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="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 ABCList" :key="item.value" :label="item.name" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="电源电压:" prop="powerVoltage">
                <el-select
                  v-model="dataForm.powerVoltage"
                  :placeholder="pageType === 'detail' ? '' : '请选择电源电压'"
                  :disabled="pageType === 'detail'"
                  class="full-width-input"
                >
                  <el-option v-for="item of powerVoltageList" :key="item.value" :label="item.name" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="检定周期（月）:" prop="measurePeriod">
                <el-input
                  v-model="dataForm.measurePeriod"
                  :placeholder="pageType === 'detail' ? '' : '请输入检定周期'"
                  :class="{ 'detail-input': pageType === 'detail' }"
                  :disabled="pageType === 'detail'"
                />
              </el-form-item>
            </el-col>
            <el-col v-if="pageType === 'detail'" :span="6">
              <el-form-item label="检定日期:">
                <el-date-picker
                  v-model="dataForm.measureLastTime"
                  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 v-if="pageType === 'detail'" :span="6">
              <el-form-item label="有效日期:">
                <el-date-picker
                  v-model="dataForm.validDeadline"
                  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 v-if="pageType === 'detail'" :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 v-if="pageType === 'detail'" :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="6">
              <el-form-item label="预计送达时间:">
                <el-input
                  v-model="dataForm.planDeliverTime"
                  :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.requireOverTime"
                  :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.measureType"
                  :placeholder="pageType === 'detail' ? ' ' : '请选择检定方式'"
                  disabled
                  class="full-width-input"
                >
                  <el-option v-for="item of measureTypeList" :key="item.value" :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="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="12">
              <el-form-item label="检定项目:" prop="measureContent">
                <el-input
                  v-model="dataForm.measureContent"
                  :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="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-row>

          <el-row :gutter="24" class="marg">
            <el-col :span="12">
              <el-form-item label="说明书:">
                <show-photo v-if="dataForm.minioFileName" :minio-file-name="dataForm.minioFileName" />
                <span v-else-if="pageType === 'detail'">无</span>
              </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" :total="currentMenu === '检定记录' ? totalRecords : totalCertifications" :list="dataList[currentMenuObj.list]" :loading="false" :pagination="currentMenuObj.pagination" @change-page="changePage" />
      <!-- <template-table v-if="currentMenuObj" :columns="currentMenuObj.columns" :list="dataList[currentMenuObj.list]" :loading="false" :pagination="currentMenuObj.pagination" @change-page="currentMenuObj?.searchFunc" /> -->
    </detail-block-switch>
  </app-container>
</template>

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

