<template>
  <div class="page-container column-container">
    <section class="list-part-container column-container" style="flex: 1">
      <!-- 搜索区 -->
      <el-form class="list-search-container" :model="queryParams" ref="queryRef" :inline="true">
        <el-form-item class="section-title" label="生产计划" />
        <el-form-item label="生产计划单号：">
          <el-input placeholder="请输入生产计划单号" v-model.trim="queryParams.productionPlanNo"
            @keyup.enter="handleQueryProductionPlanDetail" @keydown.enter.prevent clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="产品描述：">
          <el-input placeholder="请输入产品描述" v-model.trim="queryParams.keywords"
            @keyup.enter="handleQueryProductionPlanDetail" @keydown.enter.prevent clearable style="width: 200px" />
        </el-form-item>

        <el-form-item>
          <el-button type="info" icon="Search" @click="handleQueryProductionPlanDetail">
            搜索
          </el-button>
        </el-form-item>
        <el-form-item class="section-title" label="请选择当前工段：">
          <el-select-v2 v-model="queryParams.deptId" filterable :options="deptList" placeholder="请选择工段"
            style="width: 100%" @change="handleDeptChange" />
        </el-form-item>
      </el-form>
      <div class="el-table-container">
        <div class="el-table-inner-container">
          <el-table ref="planDetailTable" :data="detailPlanList" v-loading="detailLoading" highlight-current-row
            height="100%" @current-change="handlePlanDetailCurrentChange">
            <el-table-column label="客户简称" prop="companyAlias" width="120" align="center" />
            <el-table-column label="生产计划单号" prop="productionPlanNo" width="110" align="center" />
            <el-table-column label="序号" width="60" prop="lineNumber" align="center" />
            <el-table-column label="产品描述" prop="productDescription" align="center" />
            <el-table-column label="图纸版本" prop="technologyVersion" width="70" align="center" />
            <el-table-column label="总投产量" prop="productionQuantity" width="80" align="center" />
            <el-table-column label="总批数" prop="totalLotNumber" width="70" align="center" />
            <el-table-column label="单批量" prop="oneLotQuantity" width="80" align="center" />
            <el-table-column label="尾批量" prop="lastLotQuantity" width="80" align="center" />
            <el-table-column label="追增批数" prop="superadditionTotalNumber" width="80" align="center" />
            <el-table-column label="批号状态" prop="lotCodeStatusCode" width="100" align="center">
              <template #default="scope">
                <dict-tag :options="lot_code_status_code" :value="scope.row.lotCodeStatusCode" />
              </template>
            </el-table-column>
            <el-table-column label="累计投产量" prop="pickUpQuantity" width="80" align="center" />
            <el-table-column label="累计投产批数" prop="lotTotalNumber" width="90" align="center" />
            <!-- <el-table-column label="库位" prop="storageLocation" width="80" align="center" /> -->
            <el-table-column label="领料部门" prop="requisitionDepartmentName" width="100" align="center">
              <template #default="scope">
                <span>{{ scope.row.requisitionDepartmentName }}</span>
              </template>
            </el-table-column>
            <el-table-column label="下达日期" prop="issueDate" width="100" align="center" />
            <el-table-column label="操作" width="240" align="center" fixed="right">
              <template #default="scope">
                <el-button link type="success" icon="View" @click="handleCheckMarterialInfo(scope.row)">领料信息
                </el-button>
                <el-button :disabled="!(
          queryParams.deptId == scope.row.requisitionDepartmentId
        ) || scope.row.totalLotNumber == scope.row.lotTotalNumber
        " link type="primary" icon="Postcard" @click="handleAddSubDetail(scope.row)"
                  v-hasPermi="['business:productionBatch:add']">投产
                </el-button>
                <el-button v-if="scope.row.lotTotalNumber && scope.row.lotTotalNumber >0"  v-hasPermi="['business:productionBatch:check']" link type="warning" icon="Search" @click="handleCheckLotInfo(scope.row)">批次信息
                </el-button>
                <!-- <el-button
                  icon="edit"
                  link
                  type="warning"
                  @click="handleUpdateProduction(scope.row)"
                  >编辑</el-button
                > -->
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </section>
    <!-- 分页 -->
    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getProductionPlanDetail" />

    <section class="list-part-container row-container" style="flex: 1">
      <section class="list-part-container" style="flex: 4">
        <!-- 下边页面开始 -->
        <!-- 搜索区 -->
        <el-form class="list-search-container" :inline="true">
          <el-form-item class="section-title" label="生产子计划" />
        </el-form>
        <div class="el-table-container">
          <div class="el-table-inner-container">
            <el-table ref="subDetailsTable" v-loading="subDetailsLoading" :data="subList" highlight-current-row
              height="100%">
              <el-table-column type="index" label="行号" width="50" align="center" />
              <el-table-column label="生产计划单号" prop="productionPlanNo" width="110" align="center" />
              <el-table-column label="产品描述" prop="productDescription" align="center" />
              <el-table-column label="首序投产量" prop="productionQuantity" width="80" align="center" />
              <el-table-column label="首序投产批数" prop="lotNumber" width="100" align="center">
                <template #default="scope">
                  <el-input-number v-if="scope.row.editStatus" v-model="scope.row.lotNumber" placeholder="当前投产批数"
                    :controls="false" :precision="0" :min="0" :max="scope.row.totalLotNumber" align="center" />
                  <span v-else>{{ scope.row.lotNumber }}</span>
                </template>
              </el-table-column>
              <el-table-column label="下达日期" prop="issuanceDate" width="120" align="center">
                <template #default="scope">
                  <el-date-picker v-if="scope.row.editStatus" clearable v-model="scope.row.issuanceDate" type="date"
                    value-format="YYYY-MM-DD" placeholder="请选择实际开始 时间" />
                  <span v-else>{{ scope.row.issuanceDate }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="150" align="center" v-if="flag">
                <template #default="scope">
                  <el-button v-if="!scope.row.editStatus" icon="edit" link type="warning"
                    @click="handleShowSubDetailDialog(scope.row)" v-hasPermi="['business:productionBatch:edit']">编辑
                  </el-button>
                  <el-button v-if="!scope.row.editStatus" icon="delete" link type="danger"
                    @click="handleDelSubDetail(scope.row)" v-hasPermi="['business:productionBatch:remove']">删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </section>
    </section>
    <!-- 投产表单 -->
    <production-lot-form ref="productionRef" @handleSaveSuccess="handleFresh()" />
    <!-- 领料信息弹窗 -->
    <check-material ref="checkMaterialRef" />
    <lot-info ref="lotInfoRef" @handleSaveSuccess="handleFresh()" />
    <!-- 工艺版本变更弹窗
    <production-dialog
      ref="productionDetailRef"
      @handleUpdateSuccess="handleFresh()"
    /> -->
  </div>
</template>
<script setup name="ProductionBatch">
import { ref } from "vue";
import { listProductionPlanDetail } from "@/api/business/productionPlanDetail.js";
import {isTakeStock} from "@/api/business/takeStockPeriod.js"
import {
  listPlanDetailSubDetail,
  delPlanDetailSubDetail,
  getDeptList,
  getLastLotStatus,
} from "@/api/business/planDetailSubDetail.js";
import { updateLotCodeStatus } from "@/api/business/productionPlanDetail.js";
import checkMaterial from "./DialogCheckMaterial";
import productionLotForm from "./form";
import lotInfo from "./lotInfoForm.vue"
// import productionDialog from "./DialogProduction";
const { proxy } = getCurrentInstance();
/** 字典数组区 */
const { lot_code_status_code } = proxy.useDict("lot_code_status_code");
/** 生产计划 */
const currentPlanDetail = ref({});
const detailPlanList = ref([]);
const detailLoading = ref(false);
const total = ref(0);
/** 工段 */
const loading = ref(false);
const deptList = ref([]);
/** 生产子计划 */
const subList = ref([]);
const flag = ref(false);
const isDispatch = ref(false);
const subDetailsLoading = ref(false);
/** 查询对象 */
const queryParams = ref({
  deptId: "",
  keywords: "",
  pageNum: 1,
  pageSize: 10,
});

/***********************  方法区  ****************************/
/***********************  工段  ****************************/
/**
查询工段
 *
 */
function getList() {
  loading.value = true;
  getDeptList().then((response) => {
        deptList.value = response.data.rows;
        isDispatch.value = response.data.others.isDispatch;
        loading.value = false;
        if (isDispatch.value) {
            deptList.value.unshift({ label: "全部", value: "0" });
        } 
        queryParams.value.deptId = deptList.value[0].value;
        getProductionPlanDetail();
    });
  loading.value = false;
}
/**工段下拉框change事件 */
function handleDeptChange() {
  handlePlanDetailCurrentChange(currentPlanDetail.value);
}
/***********************  生产计划  ****************************/

/** 生产子计划进行修改时，对生产计划进行重新查询并选中*/
function handleFresh() {
  detailLoading.value = true;
  listProductionPlanDetail(queryParams.value).then((res) => {
    detailPlanList.value = res.rows;
    total.value = res.total;
    detailLoading.value = false;
    //生产子计划点击
    if (detailPlanList.value.length > 0) {
      for (var i = 0; i < detailPlanList.value.length; i++) {
        if (detailPlanList.value[i].id == currentPlanDetail.value.id) {
          var index = i;
          break;
        }
      }
    }
    proxy.$refs.planDetailTable.setCurrentRow(detailPlanList.value[index]);
    currentPlanDetail.value = detailPlanList.value[index];
  });
}
/**查询计划明细 */
function getProductionPlanDetail() {
  detailLoading.value = true;
  listProductionPlanDetail(queryParams.value).then((res) => {
    detailPlanList.value = res.rows;
    total.value = res.total;
    detailLoading.value = false;
    //生产子计划点击
    if (detailPlanList.value.length > 0) {
      proxy.$refs.planDetailTable.setCurrentRow(detailPlanList.value[0]);
    }
  });
}
/** 生产计划搜索按钮操作 */
function handleQueryProductionPlanDetail() {
  queryParams.value.pageNum = 1;
  getProductionPlanDetail();
}
// //打开修改生产计划的版本弹窗
// function handleUpdateProduction(row) {
//   proxy.$refs.productionDetailRef.open(row);
// }
//查询生产计划单的领料信息
function handleCheckMarterialInfo(row) {
  proxy.$refs.checkMaterialRef.open(row);
}
/** 生产计划明细 current-change 事件 */
function handlePlanDetailCurrentChange(row) {
  if (row) {
    currentPlanDetail.value = row;
    //领料部门是当前工段时，有操作列进行修改删除
    if (
      currentPlanDetail.value.requisitionDepartmentId ==
      queryParams.value.deptId
    ) {
      flag.value = true;
    } else {
      flag.value = false;
    }
    subDetailsLoading.value = true;
    listPlanDetailSubDetail({
      productionPlanDetailId: row.id,
      deptId: queryParams.value.deptId,
    }).then((res) => {
      subList.value = res.rows;
      subDetailsLoading.value = false;
    });
  } else {
    subList.value = [];
  }
}
/***********************  生产子计划  ****************************/
/**新增按钮生产子计划 */
function handleAddSubDetail(row) {
  isTakeStock().then(res =>{
    if(res.data) {
      proxy.$modal.msgError('正在盘点，不能投产')
    }else{
  /**创建一个空的对象，将生产计划中的数据赋值给子计划数据 */
  const newDetail = {};
  newDetail.productionPlanId = row.productionPlanId;
  newDetail.productionPlanDetailId = row.id;
  newDetail.productionPlanNo = row.productionPlanNo;
  newDetail.lineNumber = row.lineNumber
  //生产计划总投产量
  newDetail.productionQuantityTotal = row.productionQuantity;
  newDetail.productId = row.productId;
  newDetail.productDescription = row.productDescription;
  //生产计划单批量
  newDetail.oneLotQuantity = row.oneLotQuantity;
  newDetail.deptId = queryParams.value.deptId;
  //生产计划总批数
  newDetail.totalLotNumber = row.totalLotNumber;
  newDetail.technologicalProcessId = row.technologicalProcessId;
  newDetail.technologyVersion = row.technologyVersion;
  //子计划累计投产量
  newDetail.pickUpQuantity = row.pickUpQuantity;
  //子计划累计投产批数
  newDetail.lotTotalNumber = row.lotTotalNumber;
  //生产计划尾批数
  newDetail.lastLotQuantity = row.lastLotQuantity;
  //已投产的常规批次
  newDetail.regularTotalNumber = row.regularTotalNumber;
  //新增尾批状态默认为否
  newDetail.lastLotStatus = 0;
  //新增状态
  newDetail.status = false;
  //新增时查询生产子计划数据
  getLastLotStatus(row.id).then((response) => {
    if (response.code == 200) {
      //如果为true，生产子计划已有尾批
      newDetail.lastLot = response.data;
      proxy.$refs.productionRef.open(newDetail);
    }
  });
    }
  })

}

/** 修改 生产子计划 事件 */
function handleShowSubDetailDialog(row) {
  //生产计划单批量
  row.oneLotQuantity = currentPlanDetail.value.oneLotQuantity;
  //子计划累计投产量
  row.pickUpQuantity = currentPlanDetail.value.pickUpQuantity;
  //子计划累计投产批数
  row.lotTotalNumber = currentPlanDetail.value.lotTotalNumber;
  //生产计划总投产量
  row.productionQuantityTotal = currentPlanDetail.value.productionQuantity;
  //生产计划总批数
  row.totalLotNumber = currentPlanDetail.value.totalLotNumber;
  //生产计划尾批数
  row.lastLotQuantity = currentPlanDetail.value.lastLotQuantity;
  //已投产的常规批次
  row.regularTotalNumber = currentPlanDetail.value.regularTotalNumber;
  //当前修改的生产子计划的投产批数最低值
  let otherList = subList.value.filter(item =>item.id !=row.id);
  let otherLotNum = 0
  if(otherList.length > 0) {
    otherList.forEach(item =>{
      otherLotNum += item.lotNumber
    })
    row.minLotNumber = row.regularTotalNumber - otherLotNum
  }else{
    row.minLotNumber = row.regularTotalNumber
  }
  //生产计划id
  row.productionPlanDetailId = currentPlanDetail.value.id;
  //编辑状态
  row.status = true;
  console.log(row)
  //判断已投产的生产子计划是否包含尾批
  getLastLotStatus(currentPlanDetail.value.id).then((response) => {
    if (response.code == 200) {
      //如果为true，生产子计划已有尾批
      row.lastLot = response.data;
      proxy.$refs.productionRef.open(row);
    }
  });
}
//查看计划单批次
function handleCheckLotInfo(row) {
  proxy.$refs.lotInfoRef.open(row)
}

/** 删除子计划事件 */
function handleDelSubDetail(row) {
  const _ids = row.id;
  var subInfo = subList.value.filter((item) => !item.id.includes(_ids));
  proxy.$modal
    .confirm("是否确认删除选中的数据项？")
    .then(function () {
      return delPlanDetailSubDetail(_ids);
    })
    .then(() => {
      //如果该生产计划没有生产子计划了，改变生产计划的批号状态
      if (subInfo.length == 0) {
        updateLotCodeStatus({
          id: currentPlanDetail.value.id,
          lotCodeStatusCode: "NA",
        }).then((res) => { });
      }
      handleFresh();
      proxy.$modal.msgSuccess("删除成功！");
    })
    .catch(() => { });
}
onMounted(() => {
  // getProductionPlanDetail();
  getList();
});
</script>
<style scoped>
.list-search-container-child .el-form-item {
  /* 修改样式 */
  margin-right: 10px;
}
</style>
