<!-- 标签绑定弹窗 -->
<script setup lang="ts" name="BarCodeBind">
import { reactive, ref } from 'vue'
import scanImg from '@/assets/images/scan.png'
const emits = defineEmits(['confirm'])
const dialogVisible = ref(false) // 弹窗显示
const scanStatus = ref('0') // 扫描状态,未开始0，正在扫描1，扫描结束2

const img = ref(scanImg)
// 标签
interface ILabel {
  name: string
}
// 选中的标签
const checkedLabel = ref('')
// 样品id
const sampleId = ref('')
// 扫描到的标签列表
const list = ref<ILabel[]>([])

const closeDialog = () => {
  dialogVisible.value = false
}

// 点击确定，保存选择的成员配置
const confirm = () => {
  // TODO: 标签绑定
  if (sampleId.value) {
    // TODO: 调用接口
    emits('confirm')
  }
  else { // 不需要在此处完成绑定，将二维码返回
    emits('confirm', checkedLabel)
  }
}

// 扫描/ 重新扫描
const scan = () => {
  const res = [
    { name: '1111112548877411111' },
    // { name: '1111112548877411112' },
    // { name: '1111112548877411113' },
    // { name: '1111112548877411114' },
    // { name: '1111112548877411115' },
  ]
  // 扫描到的标签列表
  list.value = res
  checkedLabel.value = res[0].name
  scanStatus.value = '2'
}
// 重新扫描
const reScan = () => {
  scanStatus.value = '1'
  setTimeout(() => {
    scan()
  }, 3000)
}

/**
 * 打开弹窗
 * @param sampleid 样品id， 需要在弹窗内完成绑定操作的传, 不需要传空字符串
 */
const initDialog = (sampleid = '') => {
  if (sampleid) { // 如果有sampleId
    sampleId.value = sampleid
  }
  scanStatus.value = '1'
  setTimeout(() => {
    scan()
  }, 3000)
  dialogVisible.value = true
}
// ----定义对外暴露的方法
defineExpose({ initDialog })
</script>

<template>
  <el-dialog v-model="dialogVisible" title="标签绑定" width="400px" 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>
          扫描到 {{ list.length }} 个条码{{ list.length > 1 ? '，请选择要绑定的条码。' : '' }}
        </div>
        <el-radio-group v-model="checkedLabel" class="radio-group">
          <el-radio v-for="row of list" :key="row.name" :label="row.name" class="radio-line" />
        </el-radio-group>
      </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;
  }
}

.radio-group {
  width: 100%;
  margin-top: 20px;
  margin-left: 20px;

  .radio-line {
    display: block;
    width: 100%;
  }
}
</style>

