<!-- 任务分发 -->
<script lang="ts" setup name="TaskEdit">
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { ref } from 'vue'
import ProcessConfig from './components/processConfig.vue'
import type { ISampleMeasure, ITaskDetail } from './task-interface'
import type { SimpleCertification, SimpleMeasureRecord } 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 { getSapmleDetail, updateSample } from '@/api/customer/sampleList'
interface dictType {
  id: string
  name: string
  value: string
}
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 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 $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: '',
})

// 保存样品信息
function saveForm(formEl: FormInstance | undefined) {
  if (!formEl) { return }
  formEl.validate((valid, fields) => {
    if (valid) {
      ElMessageBox.confirm(
        '确认修改样品信息吗？',
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        },
      ).then(() => {
        if (sampleForm.value.id) {
          updateSample(sampleForm.value).then((res) => {
            if (res.code === 200) {
              ElMessage.success('已保存')
              $router.go(-1)
            }
          })
        }
      })
    }
  })
}
//
const getSampleInfo = () => {
  getSapmleDetail({ id: sampleId.value }).then((res) => {
    sampleForm.value = res.data
  })
}
// 获取分发详情
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
  })
}

// 点击标签绑定的扫描
const startScan = () => {
  // TODO
}

// 流程配置组件
const processConfigRef = ref()
// 批量添加流程按钮点击
const batchProcessAdd = () => {
  processConfigRef.value.batchProcessAdd()
}
// 保存流程按钮点击
const saveProcess = () => {
  processConfigRef.value.saveProcess()
}

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

// 从路由中获取页面类型参数
const $route = useRoute()
if ($route.params && $route.params.role) {
  roleType.value = $route.params.role as string // 使用角色

  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 v-if="roleType === 'detail'" v-print="printObj" type="primary">
          打印
        </el-button>
        <!-- <el-button v-if="roleType !== '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="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" @change="onFileChange">
                <el-button v-if="roleType !== 'detail'" id="file" type="primary" :disabled="roleType === 'detail'" :style="{ 'margin-left': sampleForm.minioFileName === '' ? '0px' : '20px' }" @click="upload">
                  {{ sampleForm.minioFileName === '' ? '上传' : '更换附件' }}
                </el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </detail-page>
    <detail-block 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-block>
    <!-- 检定记录、检定证书 -->
    <detail-block-switch :title="currentMenu">
      <template #menu>
        <el-radio-group v-model="currentMenu">
          <el-radio-button label="证书监控">
            证书监控
          </el-radio-button>
          <el-radio-button label="检定记录">
            检定记录
          </el-radio-button>
          <el-radio-button label="检定证书">
            检定证书
          </el-radio-button>
        </el-radio-group>
      </template>
      <!-- 证书监控 -->
      <certification-monitor v-if="currentMenu === '证书监控'" :sample-id="sampleId" :order-id="taskForm.orderId" />
      <!-- 检定记录 -->
      <measure-records v-if="currentMenu === '检定记录'" :sample-id="sampleId" />
      <!-- 证书记录 -->
      <certification-records v-if="currentMenu === '检定证书'" :sample-id="sampleId" />
    </detail-block-switch>
  </app-container>
</template>

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

