<template>
  <el-popover
      title="追溯码："
      placement="bottom-start"
      trigger="click"
      width="300px"
  >
    <template #reference>
      <el-input
          placeholder="追溯码"
          clearable
          v-model="inputTraceabilityCode"
          style="width: 300px;"
          @keydown.enter="addTraceabilityCode(props.item)"
      ></el-input>
    </template>
    <template #default>
      <div v-for="(subItem,index) in item.traceAbilityCodeList" class="list">
        <div class="code"> {{ subItem.code }}</div>
        <div class="number">
          <el-input
              size="small"
              v-model.number="changeNumber"
              v-if="subItem.showNumberInput"
              @keydown.enter="subItem.showNumberInput = false"
              @change="handleNumberChange(subItem)"
          ></el-input>
            <span v-else @click="openNumberInput(subItem)">x{{ subItem.number }}</span>
        </div>
        <div class="remove" @click="removeTraceAbility(item)">
          <el-icon>
            <CloseBold/>
          </el-icon>
        </div>
      </div>
    </template>
  </el-popover>
</template>
<script setup lang="ts">
import {ref,watch} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {CloseBold} from "@element-plus/icons-vue";
import {post} from "@/utils/request.ts";
interface TraceAbilityCode {
  code: string;
  number: number;
  showNumberInput?: boolean;
}
const props = defineProps({
  item: {
    type: Object as () => {
      id?: number|undefined;
      traceAbilityCodeList: TraceAbilityCode[];
      retailNumber: number;
      gatherNumber: number;
      selectedUnit: string;
      idCode: string[];
      packagingUnit: string;
      minPackagingUnit: string;
      minPackagingNumber: number;
    },
    default: () => ({
      traceAbilityCodeList: [],
      retailNumber: 0,
      gatherNumber: 0,
      selectedUnit: "",
      idCode:[],
      packagingUnit: "",
      minPackagingUnit: "",
      minPackagingNumber: 0,
    }),
  },
})
const getGatherNumber = (item: any) => {
  let gatherNumber = 0;

  for (let subItem of item.traceAbilityCodeList) {
    gatherNumber += subItem.number;
  }
  item.gatherNumber = gatherNumber;
}
const inputTraceabilityCode = ref("");
const addTraceabilityCode = (item: any) => {
  if (!item.traceAbilityCodeList) {
    item.traceAbilityCodeList = []
  }
  if (item.retailNumber == item.gatherNumber) {
    ElMessage({
      message: '采集数量已满',
      type: 'warning',
    })
    return
  }
  let idCode = inputTraceabilityCode.value?inputTraceabilityCode.value.slice(0, 7):"";
  const index = item.traceAbilityCodeList.findIndex((codeObj: any) => codeObj.code === inputTraceabilityCode.value);
  if (index == -1 && item.selectedUnit == item.packagingUnit){
    item.traceAbilityCodeList.push({
      code: inputTraceabilityCode.value,
      number: 1
    })
    inputTraceabilityCode.value = "";
    getGatherNumber(item)
    addIdCode(idCode)
    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: inputTraceabilityCode.value,
      number: number
    })
    inputTraceabilityCode.value = "";
    getGatherNumber(item)
    addIdCode(idCode)
    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;
  }
  inputTraceabilityCode.value = "";
  getGatherNumber(item)
  addIdCode(idCode)
}
const removeTraceAbility = (item: any) => {
  item.traceAbilityCodeList.splice(item.traceAbilityCodeList.findIndex((codeObj: any) => codeObj.code === inputTraceabilityCode.value), 1)
  getGatherNumber(item)
}
const changeNumber=ref(0);
const openNumberInput = (subItem: any) => {
  subItem.showNumberInput = true;
  changeNumber.value = subItem.number;
}
const handleNumberChange = (subItem:any)=>{
  let limit = 1;
  if (props.item.selectedUnit == props.item.minPackagingUnit){
    limit = props.item.minPackagingNumber;
  }
  if (changeNumber.value>limit) {
    ElMessage({
      message: '单个追溯码采集数量超过限制',
      type: 'warning',
    })
   subItem.showNumberInput = false;
    return
  }
  // 可以在这里添加具体的处理逻辑
  let totalNumber = 0;
  for (let subItem of props.item.traceAbilityCodeList) {
    totalNumber += subItem.number;
  }
  totalNumber = totalNumber - subItem.number + changeNumber.value;
  if (totalNumber > props.item.retailNumber) {
    ElMessage({
      message: '采集数量超过上限',
      type: 'warning',
    })
    subItem.showNumberInput = false;
    return;
  }
  subItem.number = changeNumber.value;
}
const addIdCode = (idCode:any)=>{
  if (idCode==null || idCode.value ==""){
    return;
  }
  if (props.item.idCode.includes(idCode)){
    return;
  }
  ElMessageBox.confirm(
      `当前标识码未绑定是否确认绑定标识码？`,
      'Warning',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
    post("goods/goods/addIdCode",{goodsId:props.item.id,idCode:idCode}).then((res:any)=>{
      props.item.idCode.push(idCode);
    })
  })
}
</script>
<style scoped lang="scss">
.list {
  display: flex;

  .code {
    width: 100px;
  }

  .number {
    width: 100px;
  }

  .remove {
    font-size: 16px;
    width: 50px;

    &:hover {
      color: #409eff;
    }
  }
}

</style>