<!-- 任务单列表 -->
<script lang="ts" setup name="Task">
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import selectDevice from '@/views/tested/MeasurementPlan/plan/components/selectDevice.vue'
import selectDeviceSinge from '@/views/tested/device/group/components/selectDevice.vue'
import showPhoto from '@/views/tested/device/info/components/showPhotoSinge.vue'
import { uploadApi } from '@/api/system/notice'
import { useCheckList } from '@/utils/useCheckList'
const $props = defineProps({
  data: {
    type: Array,
    default: () => ([]),
  },
})
const $route = useRoute()
// 表头显示标题
const columns = ref([
  {
    text: '统一编号',
    value: 'sampleNo',
    required: true,
    isBtn: true,
    isUpload: false,
  },
  {
    text: '设备名称',
    value: 'sampleName',
    required: true,
    isBtn: false,
    isUpload: false,
  },
  {
    text: '型号',
    value: 'sampleModel',
    required: false,
    isBtn: false,
    isUpload: false,
  },
  {
    text: '附件',
    value: 'appendixDescn',
    required: true,
    isBtn: false,
    isUpload: true,
    width: '350px',
  },
  {
    text: '外观和功能检查',
    value: 'appearanceInspect',
    required: false,
    isBtn: false,
    isUpload: false,
  },
  {
    text: '特殊要求',
    value: 'specialRequire',
    required: false,
    isBtn: false,
    isUpload: false,
  },
  {
    text: '检校项目',
    value: 'measureContent',
    required: false,
    isBtn: false,
    isUpload: false,
  },
])
const list = ref<any[]>([])
// 检查数据列表
function checkCertificateList() {
  return useCheckList(list.value, columns.value, '任务单列表')
}
// 将列表置为不可编辑状态
function setAllRowReadable() {
  for (const item of list.value) {
    item.editable = false
  }
}
// 双击行显示输入框
const dblclickRow = (row: any) => {
  if ($route.path.includes('detail')) {
    return
  }
  setAllRowReadable()
  row.editable = true
}
const SelectionList = ref()
// 表格选中
const handleSelectionChange = (e: any[]) => {
  SelectionList.value = e
}
// 添加行
const addRow = () => {
  if (checkCertificateList()) {
    setAllRowReadable()
    list.value.push({
      appearanceInspect: '',
      appendixDescn: '',
      measureContent: '',
      sampleModel: '',
      sampleId: '',
      sampleNo: '',
      sampleName: '',
      specialRequire: '',
      editable: true,
    })
  }
}
// 删除行
const removeRow = () => {
  list.value = list.value.filter((item) => {
    return !SelectionList.value.includes(item)
  })
}
const initDialog = () => {
  list.value = $props.data
}
watch(() => $props.data, (newVal) => {
  if (newVal) {
    list.value = newVal
  }
}, {
  deep: true,
})
initDialog()
defineExpose({
  list, checkCertificateList,
})
// 设备弹窗组件
const deviceRef = ref()
const deviceSingeRef = ref()
// 选中的行
const selectRow = ref()
// 单选设备
const select = (text: string, index: any) => {
  if (text === '统一编号') {
    deviceSingeRef.value.initDialog()
    selectRow.value = index
  }
}
// 多选设备
const batch = () => {
  if (!checkCertificateList()) { return }
  setAllRowReadable()
  deviceRef.value.initDialog(true)
}
// 确认选择设备
const confirm = (device: any) => {
  // 判断是单选还是多选
  if (Array.isArray(device)) {
    // 多选
    device.forEach((item) => {
      list.value.push({
        appearanceInspect: '',
        appendixDescn: '',
        measureContent: '',
        sampleModel: item.model,
        sampleNo: item.equipmentNo,
        sampleId: item.id,
        sampleName: item.equipmentName,
        specialRequire: '',
        editable: true,
      })
    })
  }
  else {
    // 单选
    const row = {
      appearanceInspect: '',
      appendixDescn: '',
      measureContent: '',
      sampleModel: device.model,
      sampleId: device.id,
      sampleNo: device.equipmentNo,
      sampleName: device.equipmentName,
      specialRequire: '',
      editable: true,
    }
    list.value[selectRow.value] = row
  }
}
const fileRef = ref() // 文件上传input
const currentIndex = ref()
const onFileChange = (event: any) => {
  if (event.target.files?.length !== 0) {
    // 创建formdata对象
    const fd = new FormData()
    const loading = ElLoading.service({
      lock: true,
      background: 'rgba(255, 255, 255, 0.8)',
    })
    fd.append('multipartFile', event.target.files[0])
    uploadApi(fd).then((res) => {
      if (res.code === 200) {
        list.value[currentIndex.value].appendixDescn = res.data[0]
        // 重置当前验证
        ElMessage.success('文件上传成功')
        fileRef.value.value = ''
        loading.close()
      }
      else {
        ElMessage.error(res.message)
        loading.close()
      }
    })
  }
}
const upload = (index: number) => {
  currentIndex.value = index
  fileRef.value.click()
}
</script>

<template>
  <detail-block-switch title="任务单列表">
    <!-- 选择设备弹窗 -->
    <select-device ref="deviceRef" @add="confirm" />
    <select-device-singe ref="deviceSingeRef" @add="confirm" />
    <!-- 上传组件 -->
    <input ref="fileRef" style="display: none;" type="file" @change="onFileChange">
    <template v-if="!$route.path.includes('detail')" #btns>
      <el-button type="primary">
        二维码扫描增加
      </el-button>
      <el-button type="primary">
        RFID扫描增加
      </el-button>
      <el-button type="primary" @click="batch">
        批量增加
      </el-button>
      <el-button type="primary" @click="addRow">
        增加行
      </el-button>
      <el-button type="info" @click="removeRow">
        删除行
      </el-button>
    </template>
    <el-table
      ref="multipleTableRef" :data="list" style="width: 100%;" border @selection-change="handleSelectionChange"
      @row-dblclick="dblclickRow"
    >
      <el-table-column v-if="!$route.path.includes('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" :width="item.width" :prop="item.value" :label="item.text"
        align="center"
      >
        <template #header>
          <span v-show="item.required && !$route.path.includes('detail')" style="color: red;">*</span><span>{{ item.text }}</span>
        </template>
        <template #default="scope">
          <span v-if="!scope.row.editable">{{ scope.row[item.value] }}</span>
          <el-input
            v-if="scope.row.editable && !item.isBtn && !item.isUpload" v-model="scope.row[item.value]" :autofocus="true"
            :placeholder="`${item.text}`" class="input"
          />
          <el-input
            v-if="scope.row.editable && item.isBtn && !item.isUpload" v-model="scope.row[item.value]" :autofocus="true"
            :placeholder="`${item.text}`" class="input" @focus="select(item.text, scope.$index)"
          >
            <template #append>
              <span @click="select(item.text, scope.$index)">选择</span>
            </template>
          </el-input>
          <span v-if="scope.row.editable && item.isUpload && !item.isBtn" style="display: flex;">
            <show-photo :minio-file-name="scope.row[item.value]" />
            <el-button v-if="!$route.path.includes('detail')" type="primary" @click="upload(scope.$index)">
              {{ scope.row[item.value] ? '更换' : '上传' }}
            </el-button>
          </span>
        </template>
      </el-table-column>
    </el-table>
  </detail-block-switch>
</template>

<style lang="scss" scoped>
.el-dialog {
  width: 700px;
}

.el-select {
  width: 100%;
}
</style>
