<template>
  <div class="popUp" v-if="modelValue">
    <div class="header" style="height: 3vh">
      <div class="headerTittle" style="font-weight: border; font-size: 28px">
        物料采集详情
      </div>
    </div>
    <div
      class="header"
      style="display: flex; justify-content: center; margin: 20px"
    >
      <div class="box" @click.stop>
        <div class="boxItem">
          <div class="describeText">
            需采集物料：{{ showInfo.materialName }}
          </div>
          <div class="describeText">型号：{{ showInfo.materialCode }}</div>
          <div class="describeText">单管需要：{{ showInfo.totalNum }}</div>
        </div>
      </div>
    </div>
    <div class="body">
      <div class="container1" @click.stop>
        <div class="boxTittle">
          批次号列表(共&nbsp;{{
            batchNoTableData.length
          }}&nbsp;批次，完成绑定&nbsp;{{
            batchNoOkSum
          }}&nbsp;批次,本次完成绑定<span style="color: green">
            &nbsp;
            {{ tabledata.filter((item) => item.num == 0).length }} &nbsp;</span
          >批次 )
        </div>
        <el-divider style="margin-top: 20px !important" />
        <div style="display: flex; margin-bottom: 20px; align-items: center">
          <div class="seqSearchInput">
            <el-input
              v-model="searchBatchNo"
              placeholder="搜索批次号"
              class="searchInput"
              clearable
            />
          </div>
          <el-button
            @click="batchNoOk = true"
            :type="batchNoOk ? 'primary' : ''"
            >数量绑定完成</el-button
          >
          <el-button
            :type="!batchNoOk ? 'primary' : ''"
            @click="batchNoOk = false"
            >还可绑定</el-button
          >
          <el-button style="width: 300px" type="success" @click="autoAll"
            >按需全批次自动绑定</el-button
          >
        </div>

        <el-table
          border
          class="seqTable"
          :data="showTableData"
          :row-class-name="tableRowClassName1"
          style="flex: 1"
        >
          <el-table-column align="center" label="批次号" prop="batchNo" />
          <el-table-column
            align="center"
            label="总可绑数量"
            prop="surplusNum"
          />
          <el-table-column align="center" label="本次绑定管号">
            <template #default="scope">
              <el-scrollbar max-height="300px">
                <el-select
                  multiple
                  clearable
                  filterable
                  placeholder="管号"
                  v-model="batchNoTableData[scope.$index].selectSeqNo"
                  @change="
                    (value) =>
                      setSelectSeq(
                        value,
                        scope.$index,
                        batchNoTableData[scope.$index].batchNo
                      )
                  "
                  @clear="clear(scope.$index)"
                  @remove-tag="(tagValue) => removeTag(tagValue, scope.$index)"
                >
                  <el-option
                    v-for="item in seqNoDataList"
                    :key="item"
                    :label="item.seqNo"
                    :value="item.seqNo"
                    :disabled="
                      item.selectBatchNoList.includes(
                        batchNoTableData[scope.$index].batchNo
                      )
                        ? false
                        : tabledata[scope.$index].num == 0
                          ? true
                          : item.remainingNum == 0
                            ? true
                            : false
                    "
                  >
                  </el-option>
                </el-select>
              </el-scrollbar>
            </template>
          </el-table-column>
          <el-table-column align="center" width="200" label="绑定管号详情">
            <template #default="scope">
              <el-scrollbar max-height="300px">
                <el-form
                  :model="item"
                  v-for="(item, index) in scope.row.selectSeq"
                  :key="index"
                >
                  <el-form-item
                    :rules="{
                      message: '该选项为必选',
                      trigger: 'change',
                    }"
                    label="管号："
                    prop="seqNo"
                    >{{ item.seqNo }}
                  </el-form-item>
                  <el-form-item
                    :rules="{
                      required: true,
                      message: '该选项为必选',
                      trigger: 'change',
                    }"
                    label="数量："
                    prop="num"
                  >
                    <el-input-number
                      v-model="
                        batchNoTableData[scope.$index].selectSeq[index].num
                      "
                      :min="0"
                      :max="
                        batchNoTableData[scope.$index].selectSeq[index].num +
                        getMaxNum(
                          batchNoTableData[scope.$index].batchNo,
                          batchNoTableData[scope.$index].selectSeq[index].seqNo
                        )
                      "
                    />
                  </el-form-item>
                </el-form>
              </el-scrollbar>
            </template>
          </el-table-column>
          <el-table-column align="center" label="剩余可绑数量" prop="num">
          </el-table-column>
          <el-table-column align="center" width="160" label="操作">
            <template #default="scope">
              <el-button
                style="width: 120px"
                type="primary"
                @click="
                  toAutoItem(
                    scope.$index,
                    batchNoTableData[scope.$index].batchNo
                  )
                "
                >按需自动绑定</el-button
              >
            </template>
          </el-table-column>
          <template #empty>
            <div class="empty">
              <Empty />
            </div>
          </template>
        </el-table>
        <div class="btns">
          <el-button type="primary" @click="submitInfoStatus = true"
            >绑定确认</el-button
          >
          <el-button @click="handleClose">取消</el-button>
        </div>
      </div>
      <div class="container2" @click.stop>
        <div class="boxTittle">
          管号列表(共 {{ seqList.length }} 个，完成绑定
          {{ seqNoOkSum }} 个，本次完成绑定<span style="color: green">
            &nbsp;
            {{ seqNoDataList.filter((item) => item.remainingNum == 0).length }}
            &nbsp;</span
          >个 )
        </div>
        <el-divider />
        <div style="display: flex; margin-bottom: 20px; align-items: center">
          <div class="seqSearchInput">
            <el-input
              v-model="searchSeqNo"
              placeholder="搜索管号"
              class="searchInput"
              clearable
            />
          </div>
          <el-button @click="seqNoOk = true" :type="seqNoOk ? 'primary' : ''"
            >完成绑定</el-button
          >
          <el-button :type="!seqNoOk ? 'primary' : ''" @click="seqNoOk = false"
            >未完成</el-button
          >
        </div>
        <el-table
          border
          class="seqTable"
          :row-class-name="tableRowClassName2"
          :data="seqNoOk ? showOKseqData : seqNoDataList"
          style="flex: 1"
        >
          <el-table-column align="center" label="管号" prop="seqNo" />
          <el-table-column
            align="center"
            label="已绑定批次号及数量"
            prop="batchNo"
          >
            <template #default="scope">
              <template
                v-if="scope.row.batchNo.length > 0"
                v-for="item in scope.row.batchNo"
              >
                <div class="selectInfo">
                  <div class="batchNo">批次号: {{ item.batchNo }}</div>
                  <div class="num">数量: {{ item.num }}</div>
                </div>
              </template>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column
            label="剩余需要绑定数量"
            sortable
            prop="remainingNum"
            align="center"
          />
          <el-table-column
            align="center"
            v-if="!seqNoOk"
            label="本次绑定批次号及数量"
          >
            <template #default="scope">
              <template
                v-if="scope.row.selectList.length > 0"
                v-for="item in scope.row.selectList"
              >
                <div class="selectInfo">
                  <div class="batchNo">批次号: {{ item.batchNo }}</div>
                  <div class="num">数量: {{ item.num }}</div>
                </div>
              </template>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <template #empty>
            <div class="empty">
              <Empty />
            </div>
          </template>
        </el-table>
      </div>
    </div>
    <saveBatchInfoPop
      v-model="submitInfoStatus"
      :showInfo="showInfo"
      @close="handleClose"
      @data-list="dataList"
    />
  </div>
</template>

<script setup>
import saveBatchInfoPop from "./saveBatchInfoPop.vue";
import { useProcessStore } from "@/store";
import { getunProcessedList } from "@/api/prosteps";
import { includes } from "lodash-es";
import internal from "stream";
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  showInfo: {
    type: Object,
  },
});
const batchNoOk = ref(false);
const submitInfoStatus = ref(false);
const seqNoOk = ref(false);
const emits = defineEmits(["update:modelValue", "dataList"]);
const store = useProcessStore();
//批次号绑定
const batchNoTableData = ref([]);
const batchNoOkSum = computed(() => {
  return batchNoTableData.value.filter((item) => item.ok).length;
});
provide("batchNoTableData", batchNoTableData);
const removeTag = (tagValue, index) => {
  batchNoTableData.value[index].selectSeq = batchNoTableData.value[
    index
  ].selectSeq.filter((item) => item.seqNo != tagValue);
};
const clear = (index) => {
  batchNoTableData.value[index].selectSeq = [];
};
//存放当前已绑定结果
let resetArray = [];
const setResArray = () => {
  resetArray = [];
  for (let i = 0; i < props.showInfo.collectList.length; i++) {
    for (let j = 0; j < props.showInfo.collectList[i].batchNo.length; j++) {
      resetArray.push({
        ...props.showInfo.collectList[i].batchNo[j],
        seqNo: props.showInfo.collectList[i].seqNo,
      });
    }
  }
};
//设置BactchData
const setBatchNoTableData = () => {
  let myMap = new Map();
  let listObj = {};
  // 设置回显现阶段绑定数据
  if (props.showInfo.collectList.length > 0) {
    for (let i = 0; i < resetArray.length; i++) {
      //设置数字
      if (myMap.has(resetArray[i].batchNo)) {
        myMap.set(
          resetArray[i].batchNo,
          Number(myMap.get(resetArray[i].batchNo)) + Number(resetArray[i].num)
        );
      } else {
        myMap.set(resetArray[i].batchNo, resetArray[i].num);
      }
      //设置obj
      if (listObj[resetArray[i].batchNo]) {
        listObj[resetArray[i].batchNo].push(resetArray[i]);
      } else {
        listObj[resetArray[i].batchNo] = [resetArray[i]];
      }
    }
  }
  batchNoTableData.value = JSON.parse(JSON.stringify(props.showInfo.batchList));
  batchNoTableData.value.forEach((item) => {
    //本次绑定管号字段
    item.selectSeqNo = [];
    //本次绑定具体字段和数量
    item.selectSeq = [];
    item.seqNo = listObj[item.batchNo];
    item.ok = item.surplusNum > 0 ? false : true;
    item.soNum = item.surplusNum;
    item.surplusNum = myMap.get(item.batchNo)
      ? item.surplusNum + myMap.get(item.batchNo)
      : item.surplusNum;
  });
};

//右侧列表数据
const seqNoList = ref([]);
const setSeqNoList = (seqList) => {
  const array = [];
  for (let i = 0; i < seqList.length; i++) {
    array.push({
      seqNo: seqList[i],
      //剩余可绑定数
      remainingNum: 0,
      //本次绑定数
      selectNum: 0,
      //本次绑定情况
      selectList: [],
      //已绑定情况
      batchNo: [],
      selectBatchNoList: [],
    });
    let sum = Number(props.showInfo.totalNum);
    for (let j = 0; j < resetArray.length; j++) {
      if (seqList[i] == resetArray[j].seqNo) {
        array[i].batchNo.push(resetArray[j]);
        sum = sum - resetArray[j].num;
      }
    }
    array[i].remainingNum = sum;
    if (array[i].remainingNum == 0) {
      array[i].ok = true;
    } else {
      array[i].ok = false;
    }
  }
  seqNoList.value = array;
};
//计算当前管号绑定情况
const showOKseqData = computed(() => {
  let resArray = [];
  resArray = seqNoList.value.filter((item) => item.ok == true);
  if (searchSeqNo.value) {
    const lowerCaseSearchValue = searchSeqNo.value.toLowerCase();
    resArray.filter(
      (item) =>
        item.seqNo && item.seqNo.toLowerCase().includes(lowerCaseSearchValue)
    );
  }
  return resArray;
});
const seqNoDataList = computed(() => {
  let resArray = [];
  resArray = JSON.parse(JSON.stringify(seqNoList.value)).filter(
    (item) => item.ok != true
  );
  //对本次采集过滤
  const selectArray = [];
  //此处batchNoTableData为本计算属性主驱动
  const batchNoArray = JSON.parse(JSON.stringify(batchNoTableData.value));
  for (let i = 0; i < batchNoArray.length; i++) {
    for (let j = 0; j < batchNoArray[i].selectSeq.length; j++) {
      batchNoArray[i].selectSeq[j].batchNo = batchNoArray[i].batchNo;
    }
    selectArray.push(...batchNoArray[i].selectSeq);
  }
  resArray.forEach((item) => {
    for (let i = 0; i < selectArray.length; i++) {
      if (item.seqNo == selectArray[i].seqNo && selectArray[i].num > 0) {
        item.selectList.push(selectArray[i]);
        item.selectNum += selectArray[i].num;
        item.remainingNum -= selectArray[i].num;
        if (!item.selectBatchNoList.includes(selectArray[i].batchNo)) {
          item.selectBatchNoList.push(selectArray[i].batchNo);
        }
      }
    }
  });
  if (searchSeqNo.value) {
    const lowerCaseSearchValue = searchSeqNo.value.toLowerCase();
    resArray = resArray.filter(
      (item) =>
        item.seqNo && item.seqNo.toLowerCase().includes(lowerCaseSearchValue)
    );
  }
  return resArray;
});
const autoAll = () => {
  let setData = JSON.parse(JSON.stringify(batchNoTableData.value));
  setData.forEach((item, index) => {
    toAutoItem(index, item.batchNo);
  });
};
const toAutoItem = (index, batchNo) => {
  batchNoTableData.value[index] = autoItem(index, batchNo);
};
const autoItem = (index, batchNo) => {
  let obj = JSON.parse(JSON.stringify(batchNoTableData.value[index]));
  let resObj = autoObj(index, batchNo);
  obj.selectSeq = resObj.selectSeq;
  obj.selectSeqNo = resObj.selectSeqNo;
  return obj;
};
const autoObj = (index, batchNo) => {
  let batchNoData = JSON.parse(JSON.stringify(tabledata.value));
  let seqData = JSON.parse(JSON.stringify(seqNoDataList.value));
  let needSum = batchNoData[index].num;
  let resSelectSeqNo = batchNoTableData.value[index].selectSeqNo
    ? JSON.parse(JSON.stringify(batchNoTableData.value[index].selectSeqNo))
    : [];
  let resSelectSeq = batchNoTableData.value[index].selectSeq
    ? JSON.parse(JSON.stringify(batchNoTableData.value[index].selectSeq))
    : [];
  //本次新加的seq信息
  let addSelectSeqNo = [];
  //本次新加的seq值
  let addSelectSeq = [];
  let lastSelectSeq = [];
  for (let i = 0; i < seqData.length; i++) {
    if (needSum == 0) {
      break;
    }
    if (seqData[i].remainingNum > 0) {
      if (needSum - seqData[i].remainingNum >= 0) {
        if (!resSelectSeqNo.includes(seqData[i].seqNo)) {
          addSelectSeqNo.push(seqData[i].seqNo);
        }
        addSelectSeq.push({
          batchNo,
          seqNo: seqData[i].seqNo,
          num: seqData[i].remainingNum,
        });
        needSum = needSum - seqData[i].remainingNum;
      } else {
        //如果在此处足够了
        if (!resSelectSeqNo.includes(seqData[i].seqNo)) {
          addSelectSeqNo.push(seqData[i].seqNo);
        }
        addSelectSeq.push({
          batchNo,
          seqNo: seqData[i].seqNo,
          num: needSum,
        });
        needSum = 0;
      }
    } else {
      continue;
    }
  }
  //来处理相同的seq
  for (let i = 0; i < addSelectSeq.length; i++) {
    for (let j = 0; j < resSelectSeq.length; j++) {
      if (addSelectSeq[i].seqNo == resSelectSeq[j].seqNo) {
        addSelectSeq[i].num = addSelectSeq[i].num + resSelectSeq[j].num;
        resSelectSeq[j].num = 0;
      }
    }
  }
  lastSelectSeq = [...addSelectSeq, ...resSelectSeq];
  lastSelectSeq = lastSelectSeq.filter((item) => item.num != 0);
  return {
    selectSeq: lastSelectSeq,
    selectSeqNo: [...resSelectSeqNo, ...addSelectSeqNo],
  };
};
const showTableData = computed(() => {
  let array = JSON.parse(JSON.stringify(tabledata.value));
  if (searchBatchNo.value) {
    const lowerCaseSearchValue = searchBatchNo.value.toLowerCase();
    array = array.filter(
      (item) =>
        item.batchNo &&
        item.batchNo.toLowerCase().includes(lowerCaseSearchValue)
    );
  }
  return array;
});
//批次号data
const tabledata = computed(() => {
  let array = JSON.parse(JSON.stringify(batchNoTableData.value));
  if (batchNoOk.value) {
    return array.filter((item) => item.ok == true);
  }
  array.forEach((item) => {
    item.num = item.soNum;
    if (item.selectSeq) {
      for (let i = 0; i < item.selectSeq.length; i++) {
        item.num = item.num - item.selectSeq[i].num;
      }
    }
  });

  return array;
});
//获取当前批次号绑定某管号最大数量
const getMaxNum = (batchNo, seqNo) => {
  let sum1 = 0;
  let sum2 = 0;
  for (let i = 0; i < tabledata.value.length; i++) {
    if (tabledata.value[i].batchNo == batchNo) {
      sum1 = tabledata.value[i].num;
    }
  }
  for (let i = 0; i < seqNoDataList.value.length; i++) {
    if (seqNoDataList.value[i].seqNo == seqNo) {
      sum2 = seqNoDataList.value[i].remainingNum;
    }
  }
  if (sum1 > sum2) {
    return sum2;
  } else {
    return sum1;
  }
};
const searchBatchNo = ref("");
const searchSeqNo = ref("");

//本次绑定change事件
const setSelectSeq = (value, index, batchNo) => {
  const value1 = ref(value);
  const array = [];
  batchNoTableData.value[index].selectSeq = batchNoTableData.value[
    index
  ].selectSeq.filter((item) => value1.value.includes(item.seqNo));
  for (let i = 0; i < batchNoTableData.value[index].selectSeq.length; i++) {
    array.push(batchNoTableData.value[index].selectSeq[i].seqNo);
  }
  const res = [];
  for (let i = 0; i < value.length; i++) {
    if (!array.includes(value[i])) {
      res.push({
        seqNo: value[i],
        num: getMaxNum(batchNo, value[i]),
        batchNo: batchNo,
      });
    }
  }
  batchNoTableData.value[index].selectSeq.push(...res);
};

const seqNoOkSum = computed(() => {
  return seqNoList.value.filter((item) => item.ok).length;
});
//获取当前物料绑定管号
const getSeqList = async () => {
  const { data } = await getunProcessedList(store.scanInfo.id);
  seqList.value = data;
  setSeqNoList(data);
};

//更新外部列表
const dataList = () => {
  emits("dataList");
};
const tableRowClassName1 = ({ row, rowIndex }) => {
  if (row.num == 0) {
    return "success-row";
  } else {
  }
};
const tableRowClassName2 = ({ row, rowIndex }) => {
  if (row.remainingNum == 0) {
    return "success-row";
  } else {
  }
};

const handleClose = () => {
  emits("update:modelValue", false);
};
//当前所有管号
const seqList = ref([]);

watch(
  () => props.showInfo,
  () => {
    if (props.showInfo) {
      setResArray();
      getSeqList();
      setBatchNoTableData();
    }
  }
);
</script>

<style>
.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}
.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}
</style>
<style lang="scss" scoped>
.selectInfo {
  margin-bottom: 5px;
}

:deep(.el-form-item) {
  margin-bottom: 5px !important;
}

.sumFail {
  color: black;
}
.sumOk {
  color: green;
}
.describeText {
  font-size: 20px !important;
  font-weight: bolder;
  color: black;
}
.searchInput {
  height: 40px;
}
:deep(.el-input__wrapper) {
  height: 40px !important;
}
:deep(.el-table__cell) {
  font-size: 18px !important;
}
.el-divider {
  margin-bottom: 10px;
}
.el-button {
  width: 180px;
  height: 40px;
  font-size: 18px;
  border-radius: 10px;
}
.describeText {
  line-height: 25px !important;
}
.seqTable {
  border-radius: 16px;
}
.boxTittle {
  font-size: 18px;
  font-weight: bolder;
  text-align: center;
  height: 1vh;
}
.popUp {
  position: fixed;
  width: 100vw;
  height: 100vh;
  z-index: 999;
  background-color: #00000030;
  top: 0;
  left: 0;
  backdrop-filter: blur(5px);
  .header {
    margin: 0;
    .box {
      width: 95vw;
      height: 6vh;
      background-color: #f1f3f5;
      border-radius: 16px;
      padding: 10px;
      display: flex;
      flex-direction: column;
      justify-content: space-evenly;
      .boxItem {
        display: flex;
        justify-content: space-between;
        padding: 0 5%;
        .describeText {
          font-size: 18px;
        }
      }
    }
  }
  .body {
    width: 100vw;
    height: 85vh;
    display: flex;
    justify-content: space-evenly;
    .container1 {
      width: 60vw;
      height: 100%;
      background-color: #f1f3f5;
      border-radius: 16px;
      padding: 10px;
      display: flex;
      flex-direction: column;
      .seqSearchInput {
        margin-right: 10px;
        width: 40%;
        max-width: 360px;
      }
      .btns {
        padding-top: 10px;
        display: flex;
        justify-content: space-evenly;
        align-items: center;
      }
    }
    .container2 {
      width: 32vw;
      height: 100%;
      background-color: #f1f3f5;
      border-radius: 16px;
      padding: 10px;
      display: flex;
      flex-direction: column;
      .seqSearchInput {
        margin-right: 10px;
        width: 40%;
        max-width: 360px;
      }
      .btns {
        height: 8vh;
        display: flex;
        justify-content: space-evenly;
        align-items: center;
      }
    }
  }
}
.headerTittle {
  width: 100%;
  height: 55px;
  text-align: center;
  line-height: 55px;
  font-size: 38px;
  font-weight: 500;
}
</style>
