<!-- 任务分发 -->
<script lang="ts" setup name="TaskEdit">
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { ref } from 'vue'
import dayjs from 'dayjs'
import ProcessConfig from '@/views/business/schedule/task/components/processConfig.vue'
import type { ISampleMeasure, ITaskDetail } from '@/views/business/schedule/task/task-interface.js'
import type { Menu, SimpleCertification, SimpleMeasureRecord, dictType } from '@/views/customer/sample/list/sample_list_interface'
import showPhoto from '@/views/system/tool/showPhoto.vue'
import { getTaskDetail } from '@/api/business/schedule/task'
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'
import { getCertification, getMesureRecords } from '@/api/customer/sampleList'
import TemplateTable from '@/views/customer/customerInfo/templateTable.vue'
const roleType = ref('distribute') // 角色类型: distribute待分发(分发人员), dispatch待分配(实验室分配工作人员),
const countryList = ref(countries) // 国家列表
const loading = ref(false) // 表单加载状态
const sampleId = ref('') // 样品详情id
const orderId = ref('') // 委托书id
const mesureCategoryList = ref<dictType[]>([]) // 校检类别
const mesureTypeList = ref<dictType[]>([]) // 检定方式

// 获取字典值
function getDict() {
  // 获取样品属性
  getDictByCode('measureCategory').then((response) => {
    mesureCategoryList.value = response.data
  })
  // 获取检定方式
  getDictByCode('measureType').then((response) => {
    mesureTypeList.value = response.data
  })
}
getDict()

// 基本信息表单
const sampleForm = ref<ISampleMeasure>({
  id: '', // 样品id
  sampleNo: '', // 样品编号
  sampleName: '', // 样品名称
  sampleModel: '', // 样品型号
  manufacturingNo: '', // 出厂编号
  customerId: '', // 委托方id
  customerNo: '', // 委托方代码
  customerName: '', // 委托方名称
  phone: '', // 委托方电话
  postalCode: '', // 委托方邮编
  customerAddress: '', // 委托方地址
  measureCategory: '', // 检校类别
  manufacturer: '', // 生产厂家
  manufacturerCountry: '', // 厂家国别
  manufacturingDate: '', // 出厂年月
  abc: '', // ABC
  measurePeriod: '', // 检定周期
  remark: '', // 备注
  minioFileName: '', // 说明书
  labelBind: '', // 标签绑定
  measureType: '1', // 检定方式  1自检、2外包、3外检
  measureTypeName: '', // 检定方式
  measureLastTime: '', // 检定日期
  validDeadline: '', // 有效日期
  powerVoltage: '', // 电源电压
  sampleBelong: '', // 样品所属
  sampleBelongName: '', // 样品所属
})
const taskForm = ref <ITaskDetail> ({
  measureContent: '', // 检定项目
  specialRequire: '', // 客户特殊要求
  orderId: '', // 委托单id
  orderCode: '', // 委托单编号
  certifications: '', // 证书类别
  planDeliverTime: '', // 预约送达时间
  requireOverTime: '', // 要求检完时间
  measureProcessList: [], // 检定流程
  measureSendBackList: [], // 退回信息
  remark: '', // 备注
  deliverer: '', // 送检人
  delivererTel: '', // 送检人联系方式
})
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({
  mesurePeriod: [{ validator: validateMesurePeriod, trigger: 'blur' }],
}) // 表单验证规则

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

// ----------------------------------检定证书、检定记录-----------------------------
const listQuery = ref<IRecord>({
  sampleId: sampleId.value, // 样品id
  customerId: '', // 客户id
  offset: 1,
  limit: 10,
})
const totalRecords = ref(0) // 检定记录总条数
const totalCertifications = ref(0) // 检定证书总条数
// 获取检定记录
const fetchMeasureRecords = (query = null) => {
  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) => {
  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)
  })
}

// 菜单
const menu: Menu[] = [
  {
    name: '检定记录',
    columns: [
      { text: '委托单编号', value: 'orderCode', align: 'center' },
      { text: '委托单日期', value: 'orderTime', align: 'center', width: 120 },
      { text: '委托方代码', value: 'customerCode', align: 'center' },
      { 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' },
      { 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 $router = useRouter()
// 关闭新增页面的回调
const close = () => {
  $router.back()
}

// 获取分发详情
const getInfo = () => {
  // 获取任务详情
  getTaskDetail({ orderId: orderId.value, sampleId: sampleId.value }).then((res) => {
    taskForm.value.specialRequire = res.data.specialRequire // 客户特殊要求
    taskForm.value.deliverer = res.data.deliverer // 送检人
    taskForm.value.delivererTel = res.data.delivererTel // 送检人联系方式
    taskForm.value.measureContent = res.data.measureContent // 检定项目
    taskForm.value.measureProcessList = res.data.measureProcessList // 检定流程
    taskForm.value.measureSendBackList = res.data.measureSendBackList // 退回流程
    // 改用一个接口获取
    sampleForm.value = res.data
    listQuery.value.sampleId = sampleId.value
    for (const item of menu) {
      item.searchFunc()
    }
  })
}

// 流程配置组件
const processConfigRef = ref()

// 从路由中获取页面类型参数
const $route = useRoute()
if ($route.params) {
  roleType.value = 'detail'

  if ($route.params.id) {
    sampleId.value = $route.params.id as string
    orderId.value = $route.query.order as string
    // 获取分发详情
    getInfo()
    // getSampleInfo() // 取消
  }
}
</script>

<template>
  <app-container>
    <detail-page title="样品详情">
      <template #btns>
        <el-button type="info" @click="close">
          关闭
        </el-button>
      </template>
      <div id="form">
        <el-form
          ref="ruleFormRef"
          :model="sampleForm"
          :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="sampleForm.sampleNo"
                  :placeholder="roleType === 'detail' ? '' : ''"
                  :class="{ 'detail-input': roleType === 'detail' }"
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="样品名称:" prop="sampleName">
                <el-input
                  v-model="sampleForm.sampleName"
                  :placeholder="roleType === 'detail' ? '' : ''"
                  :class="{ 'detail-input': roleType === 'detail' }"
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="样品型号:" prop="sampleModel">
                <el-input
                  v-model="sampleForm.sampleModel"
                  :placeholder="roleType === 'detail' ? '' : ''"
                  :class="{ 'detail-input': roleType === 'detail' }"
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="出厂编号:" prop="manufacturingNo">
                <el-input
                  v-model="sampleForm.manufacturingNo"
                  :placeholder="roleType === 'detail' ? '' : ''"
                  :class="{ 'detail-input': roleType === 'detail' }"
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="委托方代码" prop="customerNo">
                <el-input
                  v-model="sampleForm.customerNo"
                  :placeholder="roleType === 'detail' ? '' : ''"
                  :class="{ 'detail-input': roleType === 'detail' }"
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="委托方名称" prop="customerName">
                <el-input
                  v-model="sampleForm.customerName"
                  :placeholder="roleType === 'detail' ? '' : '请输入委托方名称'"
                  :class="{ 'detail-input': roleType === 'detail' }"
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="委托方电话" prop="phone">
                <el-input
                  v-model="sampleForm.phone"
                  :placeholder="roleType === 'detail' ? '' : '请输入委托方电话'"
                  :class="{ 'detail-input': roleType === 'detail' }"
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="委托方邮编" prop="postalCode">
                <el-input
                  v-model="sampleForm.postalCode"
                  :placeholder="roleType === 'detail' ? '' : '请输入委托方邮编'"
                  :class="{ 'detail-input': roleType === 'detail' }"
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col :span="18">
              <el-form-item label="委托方地址:" prop="companyAddress">
                <el-input
                  v-model="sampleForm.customerAddress"
                  type="textarea"
                  autosize
                  :placeholder="roleType === 'detail' ? '' : '请输入委托方地址'"
                  :class="{ 'detail-input': roleType === 'detail' }"
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="校检类别:">
                <el-select
                  v-model="sampleForm.measureCategory"
                  :placeholder="roleType === 'detail' ? '' : '请选择校检类别'"
                  :disabled="roleType === '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="sampleForm.manufacturer"
                  :placeholder="roleType === 'detail' ? '' : '请输入生产厂家'"
                  :class="{ 'detail-input': roleType === 'detail' }"
                  :disabled="roleType === 'detail'"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="厂家国别:">
                <el-select
                  v-model="sampleForm.manufacturerCountry"
                  :placeholder="roleType === 'detail' ? '' : '请选择厂家国别'"
                  :disabled="roleType === '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="sampleForm.manufacturingDate"
                  type="month"
                  format="YYYY-MM"
                  value-format="YYYY-MM"
                  class="full-width-input"
                  :placeholder="roleType === 'detail' ? '' : '请输入出厂年月'"
                  :class="{ 'detail-input': roleType === 'detail' }"
                  :disabled="roleType === 'detail'"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="ABC:">
                <el-select
                  v-model="sampleForm.abc"
                  :placeholder="roleType === 'detail' ? '' : '请选择ABC'"
                  :disabled="roleType === '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="taskForm.deliverer"
                  :placeholder="roleType === 'detail' ? '' : ''"
                  :class="{ 'detail-input': roleType === 'detail' }"
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="联系方式:">
                <el-input
                  v-model="taskForm.delivererTel"
                  :placeholder="roleType === 'detail' ? '' : ''"
                  :class="{ 'detail-input': roleType === 'detail' }"
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="检定项目:" prop="mesureContent">
                <el-input
                  v-model="taskForm.measureContent"
                  :placeholder="roleType === 'detail' ? '' : ''"
                  disabled
                  :class="{ 'detail-input': roleType === 'detail' }"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="检定周期（月）:">
                <el-input
                  v-model="sampleForm.measurePeriod"
                  :placeholder="roleType === 'detail' ? '' : '请输入检定周期'"
                  :class="{ 'detail-input': roleType === 'detail' }"
                  :disabled="roleType === 'detail'"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="备注:">
                <el-input
                  v-model="sampleForm.remark"
                  type="textarea"
                  :rows="2"
                  :placeholder="roleType === 'detail' ? '' : ''"
                  disabled
                  :class="{ 'detail-input': roleType === 'detail' }"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="检定方式:">
                <el-select
                  v-model="sampleForm.measureType"
                  :placeholder="roleType === 'detail' ? '' : '请选择检定方式'"
                  :disabled="roleType === 'detail'"
                  class="full-width-input"
                >
                  <el-option v-for="item of mesureTypeList" :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="sampleForm.labelBind"
                  :placeholder="roleType === 'detail' ? '' : '标签绑定'"
                  :disabled="roleType === 'detail'"
                  :class="{ 'detail-input': roleType === 'detail' }"
                >
                  <!-- <template #append>
                    <el-button>扫描</el-button>
                  </template> -->
                </el-input>
              </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="sampleForm.minioFileName" :minio-file-name="sampleForm.minioFileName" />
                <span v-else-if="roleType === 'detail'">无</span>
                <input v-show="roleType === ''" ref="fileRef" type="file">
                <el-button v-if="roleType !== 'detail'" id="file" type="primary" :disabled="roleType === 'detail'" :style="{ 'margin-left': sampleForm.minioFileName === '' ? '0px' : '20px' }">
                  {{ sampleForm.minioFileName === '' ? '上传' : '更换附件' }}
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </detail-page>
    <detail-block v-if="taskForm.measureProcessList && taskForm.measureProcessList.length >= 1" title="检定流程">
      <!-- <template #btns>
        <el-button type="primary" style="margin-bottom: 10px;" @click="batchProcessAdd">
          批量添加
        </el-button>
        <el-button type="primary" style="margin-bottom: 10px;" @click="saveProcess">
          保存
        </el-button>
      </template> -->
      <process-config ref="processConfigRef" :type="roleType" :order-id="orderId" :list="taskForm.measureProcessList" :sample-id="sampleId" :detail="true" />
    </detail-block>
    <!-- 退回流程 -->
    <detail-block v-if="taskForm.measureSendBackList && taskForm.measureSendBackList.length >= 1" title="退回流程">
      <process-config ref="processConfigRef" :type="roleType" :order-id="orderId" :list="taskForm.measureSendBackList" :sample-id="sampleId" :detail="true" />
    </detail-block>
    <!-- 检定记录、检定证书 -->
    <!-- 检定记录、检定证书 -->
    <detail-block-switch :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" /> -->
      <template-table v-if="currentMenuObj" :total="currentMenu === '检定记录' ? totalRecords : totalCertifications" :columns="currentMenuObj.columns" :list="dataList[currentMenuObj.list]" :loading="false" :pagination="currentMenuObj.pagination" @change-page="changePage" />
    </detail-block-switch>
  </app-container>
</template>

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

