<template>
  <el-drawer
    title="批次信息"
    :with-header="false"
    v-model="visible"
    direction="rtl"
    size="100%"
  >
    <div class="page-container form-container">
      <div class="form-btns-container">
        <span class="title-label">
          <el-icon><Document /></el-icon>
          <span>批次信息</span>
        </span>
        <el-button type="primary" @click="handleSave()"> 保存 </el-button>
        <div class="close-btn" @click="cancel">
          <i class="fa fa-times" aria-hidden="true" />
          <!-- <span>关闭</span> -->
        </div>
      </div>
      <div class="form-container">
        <div style="padding: 16px 16px 0 16px">
          <el-row :gutter="20" style="margin-top: 15px; padding-bottom: 10px">
            <el-col :span="4">
              <span class="leftInfo">客户简称</span>
              <span class="rightInfo">{{ detailInfo.companyAlias }}</span>
            </el-col>
            <el-col :span="4">
              <span class="middleInfo">计划单号</span>
              <span class="rightInfo">{{ detailInfo.productionPlanNo }}</span>
            </el-col>
            <el-col :span="7">
              <span class="middleInfo">产品描述</span>
              <span class="rightInfo">{{ detailInfo.productDescription }}</span>
            </el-col>
            <el-col :span="3">
              <span class="middleInfo">工艺版本</span>
              <span class="rightInfo">{{ detailInfo.technologyVersion }}</span>
            </el-col>
            <el-col :span="4">
              <span class="middleInfo">总投产量</span>
              <span class="rightInfo">{{ detailInfo.productionQuantity }}</span>
            </el-col>
          </el-row>
          <el-row
            :gutter="20"
            style="
              margin-top: 15px;
              padding-bottom: 10px;
              border-bottom: 1px solid #999;
            "
          >
            <el-col :span="4">
              <span class="leftInfo">总批数</span>
              <span class="rightInfo">{{ detailInfo.totalLotNumber }}</span>
            </el-col>
            <el-col :span="4">
              <span class="middleInfo">单批量</span>
              <span class="rightInfo">{{ detailInfo.oneLotQuantity }}</span>
            </el-col>
            <el-col :span="7">
              <span class="middleInfo">尾批量</span>
              <span class="rightInfo">{{ detailInfo.lastLotQuantity }}</span>
            </el-col>
            <el-col :span="3">
              <span class="middleInfo">领料部门</span>
              <span class="rightInfo" style="padding-left: 15px">{{
                detailInfo.requisitionDepartmentName
              }}</span>
            </el-col>
            <el-col :span="4">
              <span class="middleInfo">追增批数</span>
              <span class="rightInfo">{{ detailInfo.superadditionTotalNumber }}</span>
            </el-col>
          </el-row>

          <el-row :gutter="20" style="margin-top: 15px; margin-bottom: 15px">
            <el-col :span="6">
              <el-button type="primary"  v-hasPermi="['business:productionBatch:addLot']" @click="handleAdd()">
                追增批次
              </el-button>
              <el-button type="danger"  v-hasPermi="['business:productionBatch:removeLot']" @click="handleMultiplyDelete()">
                删除
              </el-button>
            </el-col>
          </el-row>
        </div>
      </div>
      <div class="el-table-container">
        <el-table
          v-loading="loading"
          :data="lotList"
          size="small"
          border
          height="100%%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="40" align="center" />
          <el-table-column
            type="index"
            label="序号"
            width="50"
            align="center"
          />
          <el-table-column
            label="批次号"
            prop="lotCode"
            align="center"
            width="200px"
          >
            <template #default="scope">
              <el-button v-if="scope.row.id!=null"
                link
                type="primary"
                @click="handleColumnClick(scope.row.lotCode)"
                ><span>{{ scope.row.lotCode }}</span></el-button
              >
              <span v-else>{{ scope.row.lotCode }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="投产量"
            align="center"
            prop="productionQuantity"
            width="200px"
          >
       <template #default="scope">
        <el-input-number v-if="scope.row.editStatus"
                v-model="scope.row.productionQuantity"
                style="width: 200px"
                :min="0"
                :max="99999"
                :precision="0"
                controls-position="right"
              />
              <span v-else>{{ scope.row.productionQuantity }}</span>
       </template>
      </el-table-column>
          <el-table-column
            label="追增批次"
            align="center"
            prop="isSuperaddition"
            width="200"
          >
            <template #default="scope">
              <dict-tag
                :options="yes_no"
                :value="scope.row.isSuperaddition"
              /> </template
          ></el-table-column>
          <el-table-column label="标识" align="center">
            <template #default="scope">
              <el-tag
                v-if="scope.row.isWaste == 1"
                class="spacing"
                type="danger"
                >{{ "批废" }}</el-tag
              >
              <el-tag
                v-if="scope.row.isAmend == 1"
                class="spacing"
                type="danger"
                >{{ "工艺修改" }}</el-tag
              >
              <el-tag
                v-if="scope.row.isWasteRecycling == 1"
                class="spacing"
                type="primary"
                >{{ "废品回用" }}</el-tag
              >
              <el-tag v-if="scope.row.fromId !=null&&scope.row.fromId != 0  " class="spacing" type="warning">{{ "分批" }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200px" align="center">
            <template #default="scope">
              <el-button
                v-if="
                  !scope.row.editStatus &&
                  scope.row.isSuperaddition == 1 &&
                  !scope.row.hasDaywork
                "
                link
                type="primary"
                v-hasPermi="['business:productionBatch:editLot']"
                @click="handleUpDate(scope.row)"
                >修改</el-button
              >
              <el-button
                v-if="scope.row.isSuperaddition == 1 &&
                  !scope.row.hasDaywork"
                link
                type="danger"
                v-hasPermi="['business:productionBatch:removeLot']"
                @click="handleDelete(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <!-- 追加批次 -->
    <add-lot-dialog ref="addLotDialogRef" @handleAddLotNum="handleAddLotNum" />
  </el-drawer>
</template>

<script setup>
import { getAllLot,getLastLot } from "@/api/business/lot.js";
import { addLot } from "@/api/business/productionPlanDetail.js";
import router from "@/router";
import addLotDialog from "./DialogAddLot.vue"
const emit = defineEmits(["handleSaveSuccess"]);
import { ref } from "vue";
const { proxy } = getCurrentInstance();
//字典
const { yes_no } = proxy.useDict("yes_no");
/** 表单抽屉 页变量 */
const loading = ref(false);
const lotList = ref([]);
const detailInfo = ref({});
const visible = ref(false);
const lastLot = ref(null);
const selections = ref([])
//列表是否曾经有过追加批次
const hadSuperaddition = ref(false);

/****************************  方法区  ****************************/
/** 打开抽屉 */
const open = (row) => {
  visible.value = true;
  console.log(row);
  detailInfo.value = proxy.deepClone(row);
  getLotList(row);
};

/** 取消按钮 */
const cancel = () => {
  visible.value = false;
};
//多选框选中数据
function handleSelectionChange(selection) {
  selections.value = selection;
  console.log(selections.value)
}
//多选删除
function handleMultiplyDelete() {
  console.log(selections.value)
  let flag = true
  selections.value.forEach((item) => {
    if (item.isSuperaddition == 0) {
      flag = false
      proxy.$modal.msgError("不能删除不是追加的批次");
      return;
    }else{
    if(item.hasDaywork) {
      flag = false
      proxy.$modal.msgError(item.lotCode+"有投产，不能删除");
      return
    }
  }
  });
  if(flag) {
   lotList.value = lotList.value.filter(
      (item) => !selections.value.some((selectedItem) => selectedItem === item))
      getLastLotCode()
      //判断列表的追加批次是不是都删完了,如果曾经有，但是删完了，则添加追加批次时的批次号做判断
      lotList.value.findIndex(item => item.isSuperaddition == 1) == -1 ? hadSuperaddition.value = true : hadSuperaddition.value = false
      detailInfo.value.superadditionTotalNumber =  detailInfo.value.superadditionTotalNumber - selections.value.length
   }
}
function getLastLotCode() {
  const maxLotCodeObj = lotList.value.reduce((max, current) => {
  // 提取每个lotCode中间的三位数，并转换为数字
  const maxCode = parseInt(max.lotCode.substr(8, 3), 10);
  const currentCode = parseInt(current.lotCode.substr(8, 3), 10);
  // 比较并返回具有最大值的对象
  return currentCode > maxCode ? current : max;
});

// 输出最大的lotCode
console.log(maxLotCodeObj.lotCode);
lastLot.value = maxLotCodeObj.lotCode
}
//删除
function handleDelete(row) {
  if (row.isSuperaddition == 0) {
      proxy.$modal.msgError("不能删除不是追加的批次");
      return;
    }else{
    if(row.hasDaywork) {
      proxy.$modal.msgError(row.lotCode+"有投产，不能删除");
      return
    }else{
      lotList.value.splice(lotList.value.indexOf(row), 1);
      getLastLotCode()
      lotList.value.findIndex(item => item.isSuperaddition == 1) == -1 ? hadSuperaddition.value = true : hadSuperaddition.value = false
      detailInfo.value.superadditionTotalNumber =  detailInfo.value.superadditionTotalNumber - 1
    }
  }
}
//修改
function handleUpDate(row) {
 row.editStatus = true
}

function getLotList(row) {
  loading.value = true;
  getAllLot({id:row.id}).then((res) => {
    if (res.code == 200) {
      res.data.forEach(item =>{
        item.editStatus = false
      })
      lotList.value = res.data;
      loading.value = false;
    }
  });
}
//保存
function handleSave() {
  let superadditionList = lotList.value.filter(item => item.isSuperaddition == 1)
  let flag = true
  superadditionList.forEach(item =>{
    if(item.productionQuantity ==0) {
      flag = false
      proxy.$modal.msgError(item.lotCode+"追加批次投产数量不能为0");
    }
  })
  if(flag) {
  detailInfo.value.lotList = superadditionList
  console.log(detailInfo.value)
  addLot(detailInfo.value).then((res) => {
    if (res.code == 200) {
      proxy.$modal.msgSuccess("保存成功");
      emit("handleSaveSuccess");
      visible.value = false;
    }
  })
  }
}
//追加批次
function handleAdd() {
  //判断如果此时已经追加了，但没保存
  if(lotList.value.findIndex(item => item.id == null) > -1 ||hadSuperaddition.value) {
    proxy.$refs.addLotDialogRef.open(lastLot.value)
  }else {
    getLastLot({
      productionPlanDetailId: detailInfo.value.id,
    }).then((res) => {
      if (res.code == 200) {
        var lastLot = res.data.lotCode;
        proxy.$refs.addLotDialogRef.open(lastLot)
      }
    })
  }
}
//批次带回
function handleAddLotNum(data) {
  lastLot.value = data[data.length - 1]
  detailInfo.value.superadditionTotalNumber =  detailInfo.value.superadditionTotalNumber + data.length
  console.log(data)
  data.forEach(item =>{
    lotList.value.unshift({id:null,lotCode:item,productionQuantity:detailInfo.value.oneLotQuantity,isSuperaddition:1, editStatus: true,
      productionPlanDetailId:detailInfo.value.id,technologicalProcessId:detailInfo.value.technologicalProcessId,
      technologyVersion:detailInfo.value.technologyVersion,productId:detailInfo.value.productId})
  })
}
/** 打开批次详情页 */
function handleColumnClick(lotCode) {
  router.push({ path: "/reviseBath/lotFormParticulars/" + lotCode });
}

/** 暴露给父组件的方法 */
defineExpose({
  open,
});
</script>
<style scoped>
.leftInfo {
  font-size: 16px;
  width: 120px;
  display: inline-block;
}
.middleInfo {
  font-size: 16px;
  width: 120px;
  display: inline-block;
}
.rightInfo {
  font-size: 16px;
  padding-left: 20px;
}
:deep(
    .column-container > .el-drawer__wrapper .el-drawer__body,
    .column-container .el-drawer__body,
    .row-container .el-drawer__body
  ) {
  padding: 8px;
  margin-bottom: 20px;
}
</style>
