<!-- 扫描操作弹窗 -->
<script setup lang="ts" name="BarCodeBind">
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import scanImg from '@/assets/images/scan.png'
import { getDictByCode } from '@/api/system/dict'
import { getReadList, getReaderEquipmentList } from '@/api/reader'
// 扫描状态,未开始0，正在扫描1，扫描结束2

const props = defineProps({
  // 对话框标题
  title: {
    type: String,
    default: '扫描收入',
  },
})
const emits = defineEmits(['confirm'])
const dialogVisible = ref(false) // 弹窗显示
const scanStatus = ref('0')
const isBinding = ref(false) // 是否是标签绑定
const pageType = ref('') // 页面类型、表格list、需要提醒是否绑定，detail详情不提醒
const singleChecked = ref('') // 单选选中id

// 扫描到的标签列表
const list = ref([])

// 获取数据
const mesureTypeMap = ref({}) as any
const managerStateMap = ref({}) as any
const getDict = async () => {
  // 获取检定方式
  const responseMeasureType = await getDictByCode('measureType')
  responseMeasureType.data.forEach((item: { value: string; name: string }) => {
    mesureTypeMap.value[item.value] = item.name
  })
  // 获取管理状态
  const responseManagerState = await getDictByCode('managerState')
  responseManagerState.data.forEach((item: { value: string; name: string }) => {
    managerStateMap.value[item.value] = item.name
  })
}

// 关闭弹窗
const closeDialog = () => {
  dialogVisible.value = false
}

// 点击确定，保存选择的成员配置
const confirm = () => {
  if (isBinding.value && !singleChecked.value) { // 标签绑定
    ElMessage.warning('请选中')
    return false
  }
  const message = isBinding.value ? '确认绑定吗？' : `确认${props.title}列表中的设备吗？`
  if (list.value.length) {
    if (isBinding.value) { // 标签绑定
      // if (pageType.value === 'detail') {
      //   emits('confirm', singleChecked.value)
      //   singleChecked.value = '' // 清除单选选中
      // }
      // else {
      //   ElMessageBox.confirm(
      //     message,
      //     '提示',
      //     { confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning' },
      //   ).then(() => {
      //     emits('confirm', singleChecked.value)
      //     singleChecked.value = ''
      //   })
      // }
      emits('confirm', singleChecked.value)
      singleChecked.value = '' // 清除单选选中
    }
    else {
      emits('confirm', list.value)
    }
  }
  else {
    ElMessage.warning('暂无样品数据, 请重新扫描或取消')
  }
}

// 扫描/ 重新扫描
const scan = () => {
  singleChecked.value = ''// 清除选中
  // 扫描到的标签及样品信息列表
  getReadList('readerWriter').then((res) => {
    const response = res.data
    if (response.code === 200 && response.data.length) {
      if (isBinding.value) { // 标签绑定
        list.value = response.data.map((item: string) => {
          return {
            rfid: item,
          }
        })
      }
      else {
        getReaderEquipmentList(response.data).then((res) => {
          list.value = res.data.map((item: { validDate: string; compulsoryVerification: string | number; mesureType: string ;managerState: string }) => {
            return {
              ...item,
              validDate: item.validDate ? dayjs(item.validDate).format('YYYY-MM-DD') : item.validDate,
              compulsoryVerification: item.compulsoryVerification === 1 ? '是' : item.compulsoryVerification === 0 ? '否' : '',
              mesureTypeName: mesureTypeMap.value[item.mesureType], // 检定方式
              managerStateName: managerStateMap.value[item.managerState], // 管理状态
            }
          })
        })
      }
    }
    scanStatus.value = '2' // 扫描完成
  }).catch(() => {
    ElMessage.warning('扫描出错，请联系管理员')
  })
}
// 重新扫描
const reScan = () => {
  scanStatus.value = '1' // 正在扫描
  scan()
}
const deleteRow = (index: number) => {
  list.value.splice(index, 1)
}

/**
 * 打开弹窗
 * @param sampleid 设备id， 需要在弹窗内完成绑定操作的传, 不需要传空字符串
 */
const initDialog = (isBindingValue = false, pageTypeParam = '') => {
  getDict().then(() => {
    isBinding.value = isBindingValue
    pageType.value = pageTypeParam
    scanStatus.value = '1'
    scan()
    dialogVisible.value = true
  })
}
// ----定义对外暴露的方法 初始化弹窗， 关闭弹窗
defineExpose({ initDialog, closeDialog })
</script>

<template>
  <el-dialog v-model="dialogVisible" :title="title" width="80%" append-to-body>
    <div style="margin-top: -20px;width: 100%;">
      <div v-if="scanStatus === '1'" class="wait-scan">
        <div>请使用扫码枪或读写器扫描标签</div>
        <el-image :src="scanImg" class="scan-img" />
      </div>
      <!-- 扫描结果 -->
      <div v-else-if="scanStatus === '2'">
        <div v-if="!isBinding">
          扫描到 {{ list.length }} 个设备
        </div>
        <div v-if="isBinding">
          扫描到 {{ list.length }} 个标签{{ list.length > 1 ? '，请选择需要绑定的标签' : '' }}
        </div>
        <el-table ref="multipleTableRef" :data="list" style="width: 100%;margin-top: 10px;" border stripe>
          <el-table-column type="index" label="序号" width="55" align="center" />
          <el-table-column v-if="isBinding" label="" width="60" align="center">
            <template #default="scope">
              <el-radio v-model="singleChecked" :label="scope.row" class="radio" />
            </template>
          </el-table-column>
          <el-table-column v-if="!isBinding" show-overflow-tooltip prop="equipmentNo" label="设备编号" align="center" width="160px" />
          <el-table-column v-if="!isBinding" show-overflow-tooltip prop="equipmentName" label="名称" align="center" />
          <el-table-column v-if="!isBinding" show-overflow-tooltip prop="model" label="型号规格" align="center" />
          <el-table-column v-if="!isBinding" show-overflow-tooltip prop="manufactureNo" label="出厂编号" align="center" width="90px" />
          <el-table-column v-if="!isBinding" show-overflow-tooltip prop="checkCycle" label="检定周期" align="center" width="120px" />
          <el-table-column v-if="!isBinding" show-overflow-tooltip prop="usePosition" label="使用岗位" align="center" width="120px" />
          <el-table-column v-if="!isBinding" show-overflow-tooltip prop="directorName" label="负责人" align="center" />
          <!-- <el-table-column v-if="!isBinding" show-overflow-tooltip prop="certificateValid" label="证书有效期" align="center" width="120px" /> -->
          <el-table-column show-overflow-tooltip prop="rfid" label="标签信息" align="center" />
          <!-- <el-table-column v-if="!isBinding" label="操作" align="center" width="60px" fixed="right">
            <template #default="scope">
              <el-button size="small" link type="primary" @click="deleteRow (scope.$index)">
                详情
              </el-button>
            </template>
          </el-table-column> -->
        </el-table>
      </div>
    </div>
    <!-- </div> -->
    <template #footer>
      <el-button v-if="scanStatus === '2'" type="primary" @click="reScan">
        重新扫描
      </el-button>
      <el-button v-if="isBinding" @click="closeDialog">
        取 消
      </el-button>
      <el-button v-if="isBinding" type="primary" @click="confirm">
        确 定
      </el-button>
      <el-button v-if="!isBinding" @click="closeDialog">
        关 闭
      </el-button>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.wait-scan {
  font-size: 18px;
  font-weight: bold;
  text-align: center;
  line-height: 3;

  .scan-img {
    margin-top: 20px;
    width: 128px;
    height: 128px;
  }
}

.radio {
  ::v-deep(.el-radio__label) {
    display: none !important;
  }
}
</style>

