<template>
  <div style="position: fixed; z-index: 99999;">
  <Mask :top="50" :height="700" :width="900" :is-show="show">
    <CloseBtn @click="show = false"></CloseBtn>
    <el-card>
      <template #header>
        <div class="header">追溯码采集</div>
      </template>
      <div class="detail">
        <el-input placeholder="请输入追溯码" v-model="inputIdCode" clearable @keydown.enter="openAssociationIdCode()">
          <template #prefix>
            <el-icon>
              <Monitor/>
            </el-icon>
          </template>
        </el-input>
        <div class="list">
          <table class="simple-table">
            <thead>
            <tr>
              <th>发药项目</th>
              <th>产品标识码</th>
              <th>采购数量</th>
              <th>已采/应采</th>
              <th>追溯码</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="(item,index) in list" :key="index">
              <td>{{ item.name }}</td>
              <td>
                <IdCodeListShow :idCodeList="item.idCode" v-if="item.idCode.length>0"/>
                <div v-else>未关联</div>
              </td>
              <td>{{ item.wholeNumber }}{{ item.packagingUnit }}</td>
              <td>{{ item.traceabilityCodeList.length }}/{{ item.wholeNumber }}</td>
              <td>
                {{ item.traceabilityCode }}
<!--                <TraceabilityCodeAdd :item="item"/>-->
              </td>
            </tr>
            </tbody>
          </table>

        </div>

      </div>
      <template #footer>
        <div class="bottom-btn">
          <el-button @click="saveRetail()" type="primary">确定</el-button>
          <el-button @click="show = false">关闭</el-button>
        </div>
      </template>
    </el-card>
    <AssociationIdCode ref="associationIdCodeRef" @addIdCode="cleanInputIdCode"></AssociationIdCode>
  </Mask>
    </div>
</template>
<script setup lang="ts">
import Mask from "@/components/Mask.vue";
import CloseBtn from "@/components/CloseBtn.vue";
import {nextTick, ref} from "vue";
import IdCodeListShow from "@/components/retail/IdCodeListShow.vue";
import AssociationIdCode from "@/components/retail/AssociationIdCode.vue";
import TraceabilityCodeAdd from "@/components/retail/TraceabilityCodeAdd.vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {post} from "@/utils/request.ts";


const show = ref(false)
const list = ref()
const orderInfo = ref()
const init = (data: any) => {
  list.value = data
  show.value = true
  //cleanInputIdCode()
}
const close = () => {
  show.value = false
}
defineExpose({init, close})
const emit = defineEmits(['confirm'])
const saveRetail = () => {
  if (!checkTraceCode()) {
    ElMessageBox.confirm(
        `追溯码采集未完成是否继续？`,
        'Warning',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
      emit('confirm',list.value)
    })

    return
  }
  emit('confirm',list.value)
}
const checkTraceCode = () => {
  for (let i = 0; i < list.value.length; i++) {
    const item = list.value[i];
    if (item.wholeNumber !== item.traceabilityCodeList.length) {
      return false;
    }
  }
  return true;
}
const inputIdCode = ref()
const associationIdCodeRef = ref()
const openAssociationIdCode = () => {
  for (let i = 0; i < list.value.length; i++) {
    let item = list.value[i];
    //校验待采集/已采集数量
    if (item.wholeNumber == item.traceabilityCodeList.length) {
      ElMessage({
        message: '采集数量已满',
        type: 'warning',
      })
      return
    }
    item.traceabilityCodeList.push(inputIdCode.value)
    item.traceabilityCode = item.traceabilityCodeList.join(',');
    let idCode = inputIdCode.value.slice(0, 7);
    if (!item.idCode.includes(idCode)) {
      item.idCode.push(idCode)
      cleanInputIdCode()
    }
    item.idCodes = item.idCode.join(',');
    if (item.wholeNumber == item.traceabilityCodeList.length) {
      ElMessage({
        message: '采集数量已满',
        type: 'warning',
      })
      return
    }
  }
  // if (addTraceAbilityCode()) {
  //   return
  // }
  // nextTick(() => {
  //   associationIdCodeRef.value.init(inputIdCode.value, list.value)
  // })
}
const addTraceAbilityCode = () => {
  for (let i = 0; i < list.value.length; i++) {
    let item = list.value[i];
    let idCode = inputIdCode.value.slice(0, 7);
    if (item.idCode.includes(idCode)) {
      addTraceabilityCodeDo(item);
      return true
    }
  }
  return false

}

const addTraceabilityCodeDo = (item: any) => {
  if (!item.traceAbilityCodeList) {
    item.traceAbilityCodeList = []
  }
  if (item.retailNumber == item.gatherNumber) {
    ElMessage({
      message: '采集数量已满',
      type: 'warning',
    })
    return
  }
  const index = item.traceAbilityCodeList.findIndex((codeObj: any) => codeObj.code === inputIdCode.value);
  if (index == -1 && item.selectedUnit == item.packagingUnit) {
    item.traceAbilityCodeList.push({
      code: inputIdCode.value,
      number: 1
    })
    cleanInputIdCode()
    getGatherNumber(item)
    return;
  }
  if (index == -1 && item.selectedUnit == item.minPackagingUnit) {

    let needCodeCount = item.retailNumber - item.gatherNumber;
    let number = 1;
    if (needCodeCount >= item.minPackagingNumber) {
      number = item.minPackagingNumber;
    }
    if (needCodeCount < item.minPackagingNumber) {
      number = needCodeCount;
    }
    item.traceAbilityCodeList.push({
      code: inputIdCode.value,
      number: number
    })
    cleanInputIdCode()
    getGatherNumber(item)
    return;
  }
  if (item.selectedUnit == item.packagingUnit) {
    //没拆零 追溯码只能用一次
    ElMessage({
      message: '该追溯码已达到最大使用限制',
      type: 'warning',
    })
    return;
  } else {
    //拆零每一个追溯码最多使用minPackagingNumber次
    if (item.traceAbilityCodeList[index].number == item.minPackagingNumber) {
      ElMessage({
        message: '该追溯码已达到最大使用限制',
        type: 'warning',
      })
      return;
    }
    item.traceAbilityCodeList[index].number += 1;
  }
  cleanInputIdCode()
  getGatherNumber(item)
  //console.log("item", item)
}
const getGatherNumber = (item: any) => {
  let gatherNumber = 0;
  for (let subItem of item.traceAbilityCodeList) {
    gatherNumber += subItem.number;
  }
  item.gatherNumber = gatherNumber;
}

const cleanInputIdCode = () => {
  inputIdCode.value = ''
}


</script>
<style scoped lang="scss">
.header {
  font-size: 18px;
  font-weight: bold;
}

.detail {
  .list {
    height: 400px;
  }
}
</style>