<!-- 委托书详情 -->
<script lang="ts" setup name="OrderListEdit">
import type { Ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules, UploadUserFile } from 'element-plus'
import type { IOrderDetail, ISampleList } from './orderList_interface'
import selectSample from './selectSample.vue'
import { UploadFile } from '@/api/measure/file'
import selectCustomer from '@/views/customer/sample/list/selectCustomer.vue'
import type { ICustomer } from '@/views/customer/customerInfo/customer_interface'
import showPhoto from '@/views/system/tool/showPhoto.vue'
import { getUid } from '@/utils/getUid'

const pageType = ref('add') // 页面类型: add, edit, detail
const infoId = ref('') // id
const visible = ref(false) // 控制选择委托方对话框显隐
const sampleVisible = ref(false) // 控制选择样品对话框显隐
const printHiddenButton = ref(false) // 打印的时候需要隐藏打印和关闭两个按钮
// 表单
const dataForm: Ref<IOrderDetail> = ref({
  id: '',
  orderCode: '', // 委托书编号
  deliverer: '', // 送检人
  delivererTel: '', // 送样人联系方式
  orderTime: '', // 委托日期
  planDeliverTime: '', // 预计送达时间
  requireOverTime: '', // 要求检完时间
  customerNo: '', // 委托方代码
  customerName: '', // 委托方名称
  phone: '', // 委托方电话
  companyAddress: '', // 委托方地址
  remark: '', // 备注
  minioFileName: '', // 附件
  isUrgent: '', // 是否加急
  certifications: '', // 证书类别
})

const customerInfo = [
  {
    label: '通信地址',
    value: 'address',
  },
  {
    label: '邮编',
    value: 'email',
  },
  {
    label: '电话',
    value: 'phone',
  },
  {
    label: '传真',
    value: 'fax',
  },
]

// 是否加急
const isUrgentMap = [
  {
    label: '是',
    value: '1',
  },
  {
    label: '否',
    value: '2',
  },
]

// 证书类别
const certificationsMap = [
  {
    label: '检测报告',
    value: '1',
  },
  {
    label: '校准报告',
    value: '2',
  },
]
const list = ref<ISampleList[]>([])// 表格数据
// 电源电压
const powerVoltageMap = [
  {
    label: '220V',
    value: '220',
  },
  {
    label: '110V',
    value: '110',
  },
]
// 选中的内容
const checkoutList = ref([])
// 表头
const columns = ref([
  { text: '样品编号', value: 'sampleNo', align: 'center', width: '170', disabled: true },
  { text: '样品名称', value: 'sampleName', align: 'center', disabled: false },
  { text: '型号', value: 'sampleModel', align: 'center', disabled: false },
  { text: '出厂编号', value: 'manufacturingNo', align: 'center', disabled: false },
  { text: '电源电压', value: 'powerVoltage', align: 'center', disabled: false },
  { text: '检定项目', value: 'mesureContent', align: 'center', disabled: false },
  { text: '备注', value: 'remark', align: 'center' },
  { text: '附件说明', value: 'appendixState', align: 'center', disabled: false },
])
// 校验规则
const rules = reactive<FormRules>({
  deliverer: [{ required: true, message: '送样人不能为空', trigger: 'blur' }],
  delivererTel: [{ required: true, message: '送样人联系方式不能为空', trigger: 'blur' }],
  customerNo: [{ required: true, message: '委托方代码不能为空', trigger: 'change' }],
  customerName: [{ required: true, message: '委托方名称不能为空', trigger: 'blur' }],
  phone: [{ required: true, message: '委托方电话不能为空', trigger: 'blur' }],
  companyAddress: [{ required: true, message: '委托方地址不能为空', trigger: 'blur' }],
  orderTime: [{ type: 'date', required: true, message: '委托日期不能为空', trigger: 'change' }],
  planDeliverTime: [{ type: 'date', required: true, message: '预计送达时间不能为空', trigger: 'change' }],
  requireOverTime: [{ type: 'date', required: true, message: '要求检完时间不能为空', trigger: 'change' }],
  certifications: [{ required: true, message: '要求证书类别不能为空', trigger: 'change' }],
  isUrgent: [{ required: true, message: '要求是否加急不能为空', trigger: 'change' }],
}) // 表单验证规则

// 从路由中获取页面类型参数
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 customerNoFocus = () => {
  visible.value = true
}

// 点击从样品库添加
const multiAdd = () => {
  sampleVisible.value = true
}

// 选好委托方
const confirmCheckout = (val: Array<ICustomer>) => {
  if (val && val.length) {
    const getValue = val[0]
    dataForm.value.customerNo = getValue.customerNo // 委托方代码
    dataForm.value.customerName = getValue.customerName // 委托方名称
    dataForm.value.phone = getValue.phone // 委托方电话
    dataForm.value.companyAddress = getValue.briefName // 委托方地址
  }
}

// 选择好样品
const clickConfirmSample = (val: Array<ISampleList>) => {
  val.forEach((item: ISampleList) => {
    // 只添加列表里不存在的
    const index = list.value.findIndex((i: ISampleList) => item.sampleNo === i.sampleNo)
    if (index === -1) {
      list.value.push(item)
    }
  })
}

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

// 控制选择样品对话框显隐
const changeSampleVisible = (val: boolean) => {
  sampleVisible.value = val
}

// 多选发生改变时
const handleSelectionChange = (e: any) => {
  checkoutList.value = e
  console.log(e)
}

// 增加行
const addRow = () => {
  list.value.push({
    sampleNo: '', // 样品编号
    sampleName: '', // 样品名称
    sampleModel: '', // 样品型号
    manufacturingNo: '', // 出厂编号
    powerVoltage: '', // 电源电压
    appendixState: '', // 附件说明
    mesureContent: '', // 检定项目
    remark: '', // 备注
    isEdit: true, // 是否可编辑
    delId: getUid(),
  })
}

// 删除行
const delRow = () => {
  if (checkoutList.value.length <= 0) {
    ElMessage({
      message: '请选中要删除的行',
      type: 'warning',
    })
  }
  else {
    checkoutList.value.forEach((item: ISampleList) => {
      list.value.forEach((element, index) => {
        if (!item.sampleNo) { // 点击增加行--手动增加的项目需要判断前端添加的delID
          if (element.delId === item.delId) {
            list.value.splice(index, 1)
          }
        }
        else { // 从样品库中选择的项目
          if (element.sampleNo === item.sampleNo) {
            list.value.splice(index, 1)
          }
        }
      })
    })
  }
}

const fileRef = ref() // 文件上传input
const onFileChange = (event: any) => {
  // 原生上传
  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 $router = useRouter()
// 关闭新增页面的回调
const close = () => {
  $router.back()
}

// 点击保存
const saveForm = (formEl: FormInstance | undefined) => {
  if (!formEl) { return }
  formEl.validate((valid) => {
    if (valid) {
      ElMessageBox.confirm(
        '确认保存吗？',
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        },
      ).then(() => {
      })
    }
  })
}

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

<template>
  <app-container>
    <div id="main">
      <div v-if="pageType === 'detail'" class="customer-title">
        <img src="@/assets/images/logo.png" class="img">
        <div class="title">
          航天计量检测技术（江苏）有限公司
        </div>
      </div>
      <detail-page title="检测/校准委托单">
        <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="8">
                <el-form-item label="委托书编号:" prop="orderCode">
                  <el-input
                    v-model="dataForm.orderCode"
                    :placeholder="pageType === 'detail' ? '' : '系统自动生成'"
                    :class="{ 'detail-input': pageType === 'detail' }"
                    disabled
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="送样人:" prop="deliverer">
                  <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="8">
                <el-form-item label="联系方式:" prop="delivererTel">
                  <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="8">
                <el-form-item label="委托日期:" prop="orderTime">
                  <el-date-picker
                    v-model="dataForm.orderTime"
                    type="month"
                    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="8">
                <el-form-item label="预计送达时间:" prop="planDeliverTime">
                  <el-date-picker
                    v-model="dataForm.planDeliverTime"
                    type="datetime"
                    class="full-width-input"
                    :placeholder="pageType === 'detail' ? '' : '请输入预计送达时间'"
                    :class="{ 'detail-input': pageType === 'detail' }"
                    :disabled="pageType === 'detail'"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="要求检完时间:" prop="requireOverTime">
                  <el-date-picker
                    v-model="dataForm.requireOverTime"
                    type="datetime"
                    class="full-width-input"
                    :placeholder="pageType === 'detail' ? '' : '请输入要求检完时间'"
                    :class="{ 'detail-input': pageType === 'detail' }"
                    :disabled="pageType === 'detail'"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <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 v-if="pageType !== 'detail'" class="el-input__icon">
                        <search />
                      </el-icon>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <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="8">
                <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="16">
                <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-row>
            <el-row :gutter="24">
              <el-col :span="8">
                <el-form-item label="证书类别:" prop="certifications">
                  <el-select v-model="dataForm.certifications" :placeholder="pageType === 'detail' ? '' : '请选择证书类别'" :disabled="pageType === 'detail'" class="full-width-input">
                    <el-option
                      v-for="i in certificationsMap"
                      :key="i.value"
                      :label="i.label"
                      :value="i.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="是否加急:" prop="isUrgent">
                  <el-select v-model="dataForm.isUrgent" :placeholder="pageType === 'detail' ? '' : '请选择是否加急'" :disabled="pageType === 'detail'" class="full-width-input">
                    <el-option
                      v-for="i in isUrgentMap"
                      :key="i.value"
                      :label="i.label"
                      :value="i.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24" class="marg">
              <el-col :span="16">
                <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="16">
                <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 title="样品清单">
        <template #btns>
          <el-button v-if="pageType !== 'detail'" type="primary" @click="multiAdd">
            从样品库中添加
          </el-button>
          <el-button v-if="pageType !== 'detail'" type="primary" @click="addRow">
            增加行
          </el-button>
          <el-button v-if="pageType !== 'detail'" type="info" @click="delRow">
            删除行
          </el-button>
        </template>
        <el-table
          :data="list"
          border
          style="width: 100%;"
          max-height="600"
          @selection-change="handleSelectionChange"
        >
          <el-table-column v-if="pageType !== 'detail'" type="selection" width="38" />
          <el-table-column align="center" label="序号" width="80" type="index" />
          <el-table-column
            v-for="item in columns"
            :key="item.value"
            :prop="item.value"
            :label="item.text"
            :width="item.width"
            show-overflow-tooltip
            align="center"
          >
            <template v-if="(pageType === 'add' || pageType === 'edit')" #default="scope">
              <el-input
                v-if="item.value !== 'powerVoltage' && scope.row.isEdit"
                v-model="scope.row[item.value]"
                :placeholder="item.value === 'sampleNo' ? '系统自动生成' : `请输入${item.text}`"
                :disabled="item.disabled"
                class="input"
              />
              <span v-if="item.value !== 'powerVoltage' && !scope.row.isEdit">{{ scope.row[item.value] }}</span>
              <el-select v-if="item.value === 'powerVoltage' && scope.row.isEdit" v-model="scope.row[item.value]" :placeholder="`请选择${item.text}`">
                <el-option
                  v-for="i in powerVoltageMap"
                  :key="i.value"
                  :label="i.label"
                  :value="i.value"
                />
              </el-select>
              <span v-if="item.value === 'powerVoltage' && !scope.row.isEdit">{{ scope.row[item.value] }}</span>
            </template>
          </el-table-column>
        </el-table>
      </detail-block>

      <!-- 公司信息 -->
      <div class="customer-info">
        <div v-for="item in customerInfo" :key="item.value" class="content">
          <div class="title">
            {{ item.label }}:
          </div>
          <div class="value">
            {{ item.value }}
          </div>
        </div>
      </div>
    </div>
    <!-- 选择委托方组件 -->
    <select-customer v-model:visible="visible" @confirmCheckout="confirmCheckout" @changeVisible="changeVisible" />
    <!-- 选择样品组件 -->
    <select-sample v-model:visible="sampleVisible" @clickConfirmSample="clickConfirmSample" @changeVisible="changeSampleVisible" />
  </app-container>
</template>

<style lang="scss" scoped>
.customer-title {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 24px;
  font-weight: 700;
  margin: 24px 0;

  .img {
    width: 32px;
    height: 32px;
    margin-right: 14px;
    vertical-align: middle;
  }
}

.customer-info {
  display: flex;
  justify-content: space-around;
  align-items: center;
  flex-wrap: nowrap;
  margin: 20px 0 32px;

  .content {
    display: flex;
    font-size: 14px;

    .title {
      font-weight: 600;
      color: #000;
    }

    .value {
      margin-left: 10px;
    }
  }
}
</style>

