<template>
  <el-drawer
    title="首序一键盘点"
    :with-header="false"
    v-model="visible"
    direction="rtl"
    size="100%"
  >
    <div class="form-container column-container">
      <div class="form-btns-container">
        <span class="title-label">
          <el-icon>
            <Document />
          </el-icon>
          <span>首序一键盘点</span>
        </span>
        <div class="close-btn" @click="cancel">
          <i class="fa fa-times" aria-hidden="true" />
          <!-- <span>关闭</span> -->
        </div>
      </div>
      <el-form
        class="list-search-container"
        :model="queryTaksParams"
        ref="queryRef"
        :inline="true"
        style="margin-right: 0px"
      >
        <el-form-item class="section-title" label="生产计划：">
          <el-select-v2
            v-model="queryTaksParams.productionPlanDetailId"
            :options="productionPlanDetaiList"
            filterable
            placeholder="请选择生产计划"
            style="width: 350px"
            @change="handleProductionPlanChange()"
          />
        </el-form-item>
        <el-form-item class="section-title" label="当前工段：">
          <el-select-v2
            v-model="queryTaksParams.deptId"
            :options="deptList"
            placeholder="请选择工段"
            style="width: 120px"
            @change="handleDeptChange()"
          />
        </el-form-item>
        <el-form-item style="float: inline-end">
          <el-button type="primary" style="background-color: #409eff;" v-if="!loading && dataList.length>0 && detailInfo.status !=2" @click="handleInventory"
            >一键盘点
          </el-button>
        </el-form-item>
      </el-form>
      <div class="el-table-container">
        <div class="el-table-inner-container">
          <el-table
            ref="tableRef"
            v-loading="loading"
            :data="dataList"
            size="small"
            border
            height="100%"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="48" align="center" />
            <el-table-column
              label="行号"
              type="index"
              align="center"
              width="48"
            />
            <el-table-column
              label="批次号"
              prop="lotCode"
              align="center"
              width="120px"
            >
              <template #default="scope">
                <el-button
                  link
                  type="primary"
                  @click="handleColumnClick(scope.row.lotCode)"
                  ><span>{{ scope.row.lotCode }}</span></el-button
                >
              </template>
            </el-table-column>
            <el-table-column
              label="产品描述"
              align="center"
              prop="productDescription"
            />
            <el-table-column
              label="生产状态"
              prop="isProductStatus"
              width="90"
              align="center"
            >
              <template #default="scope">
                <dict-tag
                  :options="inventory_production_status"
                  :value="scope.row.isProductStatus"
                />
              </template>
            </el-table-column>
            <el-table-column
              label="工段"
              align="center"
              prop="deptName"
              width="90"
            />
            <el-table-column
              label="投入数"
              align="center"
              prop="prodNum"
              width="80"
            />
            <el-table-column
              label="盘点数量"
              align="center"
              prop="taksStockNum"
              width="100"
            >
              <template #default="scope">
                <el-input-number
                  v-if="scope.row.editStatus"
                  v-model="scope.row.taksStockNum"
                  controls-position="right"
                  style="width: 100px"
                  :min="0"
                  :precision="0"
                  :max="99999"
                  @input="
                    (val) => {
                      handleChangeTaksStockNum(val, scope.row, scope.$index);
                    }
                  "
                />
                <div v-else>{{ scope.row.taksStockNum }}</div>
              </template>
            </el-table-column>
            <el-table-column label="标识" width="300" 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.fromLotId != 0"
                  class="spacing"
                  type="warning"
                  >{{ "分批" }}</el-tag
                >
                <el-tag
                  v-if="scope.row.isSuperaddition == 1"
                  class="spacing"
                  type="info"
                  >{{ "追增" }}</el-tag
                >
              </template>
            </el-table-column>
            <el-table-column
              label="盘点状态"
              prop="isTaksStock"
              width="200"
              align="center"
            >
              <template #default="scope">
                <el-select
                  v-model="scope.row.isTaksStock"
                  placeholder="请选择盘点状态"
                  style="width: 160px"
                  v-if="scope.row.editStatus"
                  @change="
                    (val) => {
                      handleChangeTaksStock(val, scope.row, scope.$index);
                    }
                  "
                >
                  <el-option
                    v-for="dict in is_taks_stock"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
                <div v-else>
                  <dict-tag
                    :options="is_taks_stock"
                    :value="scope.row.isTaksStock"
                  />
                </div>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              width="160"
              align="center"
              v-if="detailInfo.status != 2"
            >
              <template #default="scope">
                <el-button
                  link
                  icon="Check"
                  v-if="scope.row.editStatus"
                  type="success"
                  @click="handleSave(scope.row)"
                  >保存</el-button
                >
                <el-button
                  link
                  icon="Edit"
                  v-else
                  type="warning"
                  @click="handleEdit(scope.row, scope.$index)"
                  v-hasPermi="['business:inventoryCheck:editDetail']"
                  >编辑</el-button
                >
                <el-button
                  link
                  icon="Close"
                  v-if="scope.row.editStatus"
                  type="danger"
                  @click="handleCancel(scope.row, scope.$index)"
                  >取消</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
  </el-drawer>
</template>
<script setup>
import {
  getProductionPlanDetail,
  getNotTaksLot,
  getLotNumber,
  singleInventoryCheck,
  multiplyInventoryCheck
} from "@/api/business/taksStockLot";
import { ref } from "vue";
import router from "@/router";
import { ElMessageBox } from "element-plus";
const emit = defineEmits(["handleSaveSuccess"]);
const { proxy } = getCurrentInstance();
/** 字典 */
const { is_identification } = proxy.useDict("is_identification");
const { is_taks_stock } = proxy.useDict("is_taks_stock");
const { inventory_production_status } = proxy.useDict("inventory_production_status");
/** 表单抽屉 页变量 */
const loading = ref(false);
const visible = ref(false);
const detailInfo = ref({});
const dataList = ref([]);
const productionPlanDetaiList = ref([]);
const tableRef = ref(null);
const isInventoryMode = ref(true);
const deptList = ref([]);
const selections = ref([]);
/** 查询对象 */
const queryTaksParams = ref({
  productionPlanDetailId: null,
  deptId: null,
});

/****************************  方法区  ****************************/
/** 打开抽屉 */
const open = (row) => {
  reset();
  detailInfo.value = proxy.deepClone(row);
  console.log(row);
  let dept = row.deptList.filter((item) => {
    return item.value != 0;
  });
  deptList.value = dept;
  queryTaksParams.value.deptId = row.deptId;
  queryTaksParams.value.takeStockPeriodId = row.takeStockPeriodId;
  visible.value = true;
  getProductionPlanDetailList();
};
function getProductionPlanDetailList() {
  getProductionPlanDetail(queryTaksParams.value).then((res) => {
    if (res.data.length > 0) {
      productionPlanDetaiList.value = res.data;
      queryTaksParams.value.productionPlanDetailId = res.data[0].value;
      getList();
    } else {
      productionPlanDetaiList.value = [];
      queryTaksParams.value.productionPlanDetailId = null;
      dataList.value = [];
      proxy.$modal.msgError("当前工段无未生产的批次");
      return;
    }
  });
}
function handleColumnClick(lotCode) {
  // 拼接 URL
  const url = "/reviseBath/lotFormParticulars/" + lotCode;
  // 在新标签页打开 URL
  window.open(url, '_blank');
}
function handleSelectionChange(selection) {
  if (isInventoryMode.value) {
    selections.value = selection;
    console.log(selections.value);
  }
}
function handleChangeTaksStockNum(value, row, index) {
  if (value != 0) {
    dataList.value[index].isTaksStock = "1"
  }
}
//一键盘点
function handleInventory() {
  //判断是否选择了
  if (!selections.value.length > 0) {
    console.log("999",loading.value);
    isInventoryMode.value = false;
    //判断走保存
    //查询当前计划生产子计划投产数量和已经盘点的数量
    getLotNumber(queryTaksParams.value).then((res) => {
      dataList.value.forEach((row) => {
        tableRef.value.toggleRowSelection(row, true);
      });
      // 延迟移除标志，确保所有行选中后再处理
      setTimeout(() => {
        isInventoryMode.value = true;
        handleSelectionChange(dataList.value);
        //判断
        let selectedLot = selections.value.filter((item) => {
          return (
            item.isWasteRecycling == 0 &&
            item.fromLotId == 0 &&
            item.isSuperaddition == 0
          );
        });
        let allowLotNum = res.data.allowLotNum
        let selectedNum = selectedLot ? selectedLot.length : 0;
        if (allowLotNum < selectedNum) {
          const message = `
    当前选择常规未生产批次数量多于可盘点批次数量，
    当前最多可勾选 <span style="color: red;">${allowLotNum}</span> 个常规批次进行一键盘点，
    当前已勾选 <span style="color: red;">${selectedNum}</span> 个。
    <br>常规批次为标识列为空或标识列仅有工艺修改字样。
  `;
          ElMessageBox.alert(message, "提示", {
            confirmButtonText: "确定",
            dangerouslyUseHTMLString: true, // 启用 HTML 解析
          }).then(() => {
  // 用户点击了确定按钮，执行的代码
          }).catch(() => {
            // 用户点击了取消按钮或关闭了弹窗，不执行任何操作或者执行一些清理工作
          });
        }else{
          //保存
          multiplyInventoryCheck(selections.value).then(res =>{
            if(res.code == 200) {
              proxy.$modal.msgSuccess("盘点成功");
              if(res.data){
              getList()
              }else{
                //重新查计划单
                getProductionPlanDetailList()
              }
            }
          })
        }
      }, 300);
    });
  } else {
    //查询当前计划生产子计划投产数量和已经盘点的数量
    getLotNumber(queryTaksParams.value).then((res) => {

      let selectedLot = selections.value.filter((item) => {
        return (
          item.isWasteRecycling == 0 &&
          item.fromLotId == 0 &&
          item.isSuperaddition == 0
        );
      });
      let selectedNum = selectedLot ? selectedLot.length : 0;
      let allowLotNum = res.data.allowLotNum
      if (allowLotNum < selectedNum) {
        const message = `
            当前选择常规未生产批次数量多于可盘点批次数量，
            当前最多可勾选 <span style="color: red;">${allowLotNum}</span> 个常规批次进行一键盘点,
            当前已勾选 <span style="color: red;">${selectedNum}</span> 个。
            <br>常规批次为标识列为空或标识列仅有工艺修改字样。
          `;

        ElMessageBox.alert(message, "提示", {
          confirmButtonText: "确定",
          dangerouslyUseHTMLString: true, // 启用 HTML 解析
        }).then(() => {
  // 用户点击了确定按钮，执行的代码
          }).catch(() => {
            // 用户点击了取消按钮或关闭了弹窗，不执行任何操作或者执行一些清理工作
          });
      }else{
         //保存
         multiplyInventoryCheck(selections.value).then(res =>{
            if(res.code == 200) {
              proxy.$modal.msgSuccess("盘点成功");
              if(res.data){
              getList()
              }else{
                //重新查计划单
                getProductionPlanDetailList()
              }
            }
          })
      }
    });
  }
}
function getList() {
  loading.value = true;
  getNotTaksLot(queryTaksParams.value).then((res) => {
    res.data.forEach(element => {
      element.isTaksStock = element.isTaksStock + ""
      element.taksStockNum = Number(element.taksStockNum)
    });
    dataList.value = res.data;
    loading.value = false;
  });
}
function handleProductionPlanChange() {
  proxy.$refs.tableRef.clearSelection();
  getList();
}
//编辑
function handleEdit(row, index) {
  //判断是否能编辑
  //分批，废品回用，增批不算在允许盘点的个数内
  if(row.isWasteRecycling == 1 || row.fromLotId !=0 || row.isSuperaddition == 1){
    row.editStatus = true;
        row.taksStockNum = row.prodNum;
        row.isTaksStock = "1"
  }else{
  getLotNumber(queryTaksParams.value).then((res) => {
    if(res.data.allowLotNum >0) {
      row.editStatus = true;
        console.log(row);
        row.taksStockNum = row.prodNum;
        row.isTaksStock = "1"
        console.log(row);
    }else{
      proxy.$modal.msgError("当前常规未生产批次数量多于可盘点批次数量，不可编辑！");
      return;
    }
  })
  }
}
//取消编辑
function handleCancel(row, index) {
  dataList.value[index].editStatus = false;
  getList();
}
//保存
function handleSave(row) {
  singleInventoryCheck(row).then((res) => {
    if (res.code == 200) {
      proxy.$modal.msgSuccess("盘点成功");
      if(res.data){
          getList()
          }else{
            //重新查计划单
            getProductionPlanDetailList()
          }
    }
  });
}
function handleDeptChange() {
  proxy.$refs.tableRef.clearSelection();
  console.log(queryTaksParams.value);
  getProductionPlanDetailList();
}

/** 取消按钮 */
const cancel = () => {
  visible.value = false;
  reset();
  emit("handleSaveSuccess");
};

/** 表单重置 */
const reset = () => {
  queryTaksParams.value.productionPlanDetailId = null;
  queryTaksParams.value.deptId = null;
};

/** 暴露给父组件的方法 */
defineExpose({
  open,
});
</script>
<style scoped>
.el-message-box {
  max-width: none !important;
  width: 420px;
}
</style>
