<!-- 扫描操作弹窗 -->
<script setup lang="ts" name="BarCodeBind">
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { ISampleScan } from './scan-interface'
import scanImg from '@/assets/images/scan.png'
import { getReadList, getReaderSampleList } 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') // 页面类型 list需要提醒是否绑定、detail不需要提醒
const businessType = ref('') // 业务场景--1：设备收发场景，2：委托单场景，3：我的检测场景，4：部门检测场景
const businessStatus = ref('') // 场景状态--场景1（1：待收入状态，2：已收入状态，3：待归还状态，4：已超期状态）；场景3（1：待检测状态,2：检测中状态）；场景4（1：检测中状态）
const singleChecked = ref('') // 单选选中id
const customerId = ref('') // 委托方id
// 扫描到的标签列表
const list = ref<ISampleScan[]>([])

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 = ''// 清除选中
        })
      }
    }
    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 {
            labelBind: item,
          }
        })
      }
      else {
        const param = {
          customerId: customerId.value, // 委托方id
          sceneNo: businessType.value, // 业务场景
          status: businessStatus.value, // 场景状态
          strSet: response.data, // 扫码集合
        }
        getReaderSampleList(param).then((res) => {
          list.value = res.data
        })
      }
    }
    scanStatus.value = '2' // 扫描完成
  }).catch(() => {
    ElMessage.warning('扫描出错，请联系管理员')
  })
}
// 重新扫描
const reScan = () => {
  scanStatus.value = '1' // 正在扫描
  scan()
}
const deleteRow = (index: number) => {
  list.value.splice(index, 1)
}

/**
 * 打开弹窗
 * @param isBindingValue 是否是标签绑定
 * @param businessTypeParam 业务场景，1：设备收发场景，2：委托单场景，3：我的检测场景，4：部门检测场景
 * @param businessStatusParam 场景状态，场景1（1：待收入状态，2：已收入状态，3：待归还状态，4：已超期状态）；场景3（1：待检测状态,2：检测中状态）；场景4（1：检测中状态）
 * @param pageTypeParam 页面类型 list需要提醒是否绑定、detail不需要提醒
 * @param customerIdParam 委托方id
 */
const initDialog = (isBindingValue = false, businessTypeParam: string, businessStatusParam: string, pageTypeParam = 'list', customerIdParam = '') => {
  isBinding.value = isBindingValue
  businessType.value = businessTypeParam
  businessStatus.value = businessStatusParam
  customerId.value = customerIdParam
  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 }} 个样品{{ list.length > 1 ? '，请移除不需要绑定的样品。' : '' }}
        </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="sampleNo" label="样品编号" align="center" width="160px" />
          <el-table-column v-if="!isBinding" show-overflow-tooltip prop="sampleName" label="样品名称" align="center" />
          <el-table-column v-if="!isBinding" show-overflow-tooltip prop="sampleModel" label="型号" align="center" />
          <el-table-column v-if="!isBinding" show-overflow-tooltip prop="manufacturingNo" label="出厂编号" align="center" />
          <el-table-column v-if="!isBinding && !customerId" show-overflow-tooltip prop="orderCode" label="委托单编号" align="center" width="160px" />
          <el-table-column v-if="!isBinding && !customerId" show-overflow-tooltip prop="customerNo" label="委托方代码" align="center" width="160px" />
          <el-table-column v-if="!isBinding && !customerId" show-overflow-tooltip prop="customerName" label="委托方名称" align="center" />
          <el-table-column show-overflow-tooltip prop="labelBind" 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 @click="closeDialog">
        取 消
      </el-button>
      <el-button type="primary" @click="confirm">
        确 定
      </el-button>
    </template>
  </el-dialog>
</template>

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

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

.el-radio__label {
  display: none !important;
}
</style>

