<template>
  <div class="page-container row-container">
    <section class="list-part-container" style="flex: 2">
      <!-- 搜索区域 -->
      <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.lotCode" @keydown.enter.prevent clearable
            style="width: 200px" />
        </el-form-item>
        <el-form-item label="产品描述：">
          <el-input placeholder="请输入产品描述" v-model.trim="queryParams.productDescription" @keydown.enter.prevent clearable
            style="width: 200px" />
        </el-form-item>
        <el-form-item label="炉号：">
          <el-input placeholder="请输入炉号" v-model.trim="queryParams.furnaceNumber" @keydown.enter.prevent clearable
            style="width: 200px" />
        </el-form-item>
        <el-form-item label="包装线：">
          <el-select placeholder="请选择包装线" v-model.trim="queryParams.packageResourceGroupId" @keydown.enter.prevent
            clearable style="width: 200px">
            <el-option v-for="item in packageLineList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">搜索</el-button>
          <el-button type="primary" :disabled="selections.length == 0" @click="handleExport">导出</el-button>
          <!-- <el-button type="primary" @click="getInfoFromP2">拉取包装信息</el-button> -->
        </el-form-item>
      </el-form>
      <!-- 列表区域 -->
      <div class="el-table-container">
        <div class="el-table-inner-container">
          <el-table ref="certificateTable" v-loading="loading" row-key="id" @row-click="handleRow"
            :data="certificateList" height="100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />"
            <el-table-column label="行号" type="index" width="80" align="center" />
            <el-table-column label="批次号" prop="lotCode" align="center" width="120"/>
            <el-table-column label="产品描述" prop="productDescription" align="center" width="250" />
            <el-table-column label="炉号" prop="certificate.furnaceNumber" align="center" width="230" >
              <template #default="scope">
                <el-input disabled v-model="scope.row.certificate.furnaceNumber" placeholder="" style="width: 210px"> <template #append>
                    <el-button :disabled="scope.row.certificate.generateTime != null" icon="Edit"
                      @click="showFurnaceNumberDialog(scope.row)"></el-button>
                  </template></el-input>
              </template>
            </el-table-column>
            <el-table-column label="生产工段" prop="certificate.deptName" align="center" width="170" >
              <template #default="scope">
                <el-input readonly :disabled="scope.row.certificate.generateTime != null" v-model="scope.row.certificate.deptName" placeholder=""
                  style="width: 150px">
                  <template #append>
                    <el-button :disabled="scope.row.certificategenerateTime != null" icon="Search"
                      @click="showDeptChoiceDialog(scope.row)"></el-button>
                  </template>
                </el-input>
              </template>
            </el-table-column>
            <el-table-column label="包装线号" prop="certificate.packageLineNo" align="center" width="110" >
              <template #default="scope">
                <el-input readonly :disabled="scope.row.certificate.generateTime != null" v-model="scope.row.certificate.packageLineNo" placeholder=""
                  style="width: 100px">
                  <template #append>
                    <el-button :disabled="scope.row.certificate.generateTime != null" icon="Search"
                      @click="showLineChoiceDialog(scope.row)"></el-button>
                  </template>
                </el-input>
              </template>
            </el-table-column>
            <el-table-column label="包装箱号" prop="certificate.packageNo" align="center" width="130" >
              <template #default="scope">
                <el-input readonly :disabled="scope.row.certificate.generateTime != null" v-model="scope.row.certificate.packageNo" placeholder=""
                  style="width:120px">
                  <template #append>
                    <el-button :disabled="scope.row.certificate.generateTime != null" icon="Search"
                      @click="showPackageChoiceDialog(scope.row)"></el-button>
                  </template>
                </el-input>
              </template>
            </el-table-column>
            <el-table-column label="包装数量" prop="certificate.number" align="center" width="100" >
              <template #header>
      <div style="display: flex; align-items: center; justify-content: center;">
        包装数量
        <el-tooltip
          style="margin-left: 10px;"
          effect="dark"
          content="包装数量=批次数量+零取数量-零存数量"
          placement="top"
        >
          <el-icon>
            <InfoFilled />
          </el-icon>
        </el-tooltip>
      </div>
    </template>
            </el-table-column>
            <el-table-column label="标签数量" prop="certificate.labelNumber" align="center" width="110" >
              <template #default="scope">
                <el-input-number :disabled="scope.row.certificate.generateTime != null" v-model="scope.row.certificate.labelNumber" :step="1"
                  step-strictly :controls="false" @change="handleLabelNumberChange(scope.row)" style="width: 100px" />
              </template>
            </el-table-column>
            <el-table-column label="打印份数" prop="certificate.printPages" align="center" width="110" >
              <template #default="scope">
                <el-input :disabled="scope.row.certificate.generateTime != null" v-model="scope.row.certificate.printPages" style="width: 100px" />
              </template>
            </el-table-column>
            <el-table-column label="包装日期" prop="certificate.printDate" align="center" width="170" >
              <template #default="scope">
                <el-date-picker :disabled="scope.row.certificate.generateTime != null" v-model="scope.row.certificate.printDate" value-format="YYYY-MM-DD"
                style="width: 150px" :clearable="false" />
              </template>
            </el-table-column>
            <el-table-column label="客户简称" prop="certificate.companyName" align="center" width="230" >
              <template #default="scope">
                <el-input disabled v-model="scope.row.certificate.companyName" placeholder="" style="width: 210px"> <template #append>
                    <el-button :disabled="scope.row.certificate.generateTime != null" icon="Edit"
                      @click="showCompanyNameDialog(scope.row)"></el-button>
                  </template></el-input>
              </template>
            </el-table-column>
            <el-table-column label="采购订单号" prop="certificate.purchaseOrderNo" align="center" width="150" >
              <template #default="scope">
                <el-input :disabled="scope.row.certificate.generateTime != null" v-model="scope.row.certificate.purchaseOrderNo" style="width: 130px" />
              </template>
            </el-table-column>

            <el-table-column label="包装尺寸" prop="certificate.packageStandard" align="center" width="150" >
            </el-table-column>
            <el-table-column label="包装形式码" prop="certificate.packageTypeCode" align="center" width="150" >
            </el-table-column>        
            <el-table-column label="创建时间" prop="submitTime" align="center" width="150" />
            <el-table-column label="打印次数" prop="printCount" align="center" />
            <el-table-column label="操作" fixed="right" align="center" width="250">
              <template #default="scope">
                <el-button type="primary" :disabled="scope.row.certificate.generateTime != null" @click="handleGenerate(scope.row)">保存并生成</el-button>
                <el-button type="primary" @click="handleHistory(scope.row)">历史记录</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </section>
    <DeptChoiceDialog ref="deptChoiceDialogRef" @handleSelectBelongingDept="handleDeptChoice" />
    <PackageLineChoiceDialog ref="packageLineChoiceDialogRef" @singleChoice="handlePackageLineChoice" />
    <PackageTypeChoiceDialog ref="packageTypeChoiceDialogRef" @singleChoice="handlePackageTypeChoice" />
    <DialogFurnaceNoInfo ref="dialogFurnaceNoInfoRef" @singleChoice="handleFurnaceNoInfo" />
    <companyDialog ref="companyDialogRef" @inputSuccess="handleCompanySuccess" />
    <HistoryDialog ref="historyDialogRef" />
  </div>
</template>

<script setup name="Equipment">
import { getBatchCertificateList, generateQrCode,exportCertificate } from "@/api/business/certificate";
import { listGroup } from "@/api/business/packageResourceGroup";
import {
  getP2Accessories,
  getP2CompanyProductPackage,
  setP2Certificate
} from "@/api/business/p2.js";
import { getToken } from "@/utils/auth";
import DeptChoiceDialog from "./DeptChoiceDialog.vue";
import PackageLineChoiceDialog from "./PackageLineChoiceDialog.vue";
import PackageTypeChoiceDialog from "./PackageTypeChoiceDialog.vue";
import DialogFurnaceNoInfo from "./DialogFurnaceNoInfo.vue";
import companyDialog from "./companyDialog.vue";
import HistoryDialog from "./HistoryDialog.vue";
import { ElLoading } from "element-plus";
import useSettingsStore from "@/store/modules/settings";
const dataSource = useSettingsStore().dataSource;
const { proxy } = getCurrentInstance();
/**字典数组 */
/** 设备档案管理 */
const selections = ref([]);
const certificateTable = ref(null);
const total = ref(0);
const sealItem = ref({});
const certificateList = ref([]);
const loading = ref(false);
const ids = ref([]);
const historyDialogRef = ref(null);
const packageLineList = ref([]);
const deptChoiceDialogRef = ref(null);
const packageLineChoiceDialogRef = ref(null);
const packageTypeChoiceDialogRef = ref(null);
/** 设备档案 查询对象 */
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
});
const form = ref({});
const formLoading = ref(false);
let previousDeptId = 0;

onMounted(() => {
  getList();
  getPackageLine();
  getInfoFromP2();
});

const getPackageLine = () => {
  listGroup({}).then((res) => {
    if (res.code == 200) {
      packageLineList.value = res.rows;
    }
  });
};

/** 获取设备档案列表 */
const getList = () => {
  loading.value = true
  getBatchCertificateList(queryParams.value).then((res) => {
    if (res.code == 200) {
      certificateList.value = res.rows;
      if (certificateList.value.length > 0) {
        handleRow(certificateList.value[0]);
      }
      total.value = res.total;
    }
    loading.value = false
  }).catch(e => {
    loading.value = false
  });
};

function handleRow(row) {
  sealItem.value = row;
}
function showDeptChoiceDialog(row) {
  previousDeptId = row.certificate.deptId;
  deptChoiceDialogRef.value.open();
}
function showLineChoiceDialog(row) {
  if (row.certificate.deptId) {
    packageLineChoiceDialogRef.value.open({ deptId: row.certificate.deptId });
  } else {
    proxy.$modal.msgError("请先选择生产工段");
  }
}
function showPackageChoiceDialog(row) {
  packageTypeChoiceDialogRef.value.open({
    productId: row.certificate.productId,
    companyId:row.certificate.companyId,
  });
}
function handleLabelNumberChange(row) {
 row.certificate.printPages =
    Number.isNaN(row.certificate.number) || Number.isNaN(row.certificate.labelNumber)
      ? 0
      : Math.floor(row.certificate.number / row.certificate.labelNumber);
}
function showCompanyNameDialog(row) {
  proxy.$refs.companyDialogRef.open(row.certificate.companyName);
}
function showFurnaceNumberDialog(row){
  proxy.$refs.dialogFurnaceNoInfoRef.open({productionPlanNo:row.productionPlanNo,lineNumber:row.lineNumber})
}
function handleFurnaceNoInfo(item){
  let index = certificateList.value.findIndex(item=>item.id == sealItem.value.id)
  certificateList.value[index].certificate.furnaceNumber = item.furnaceNumber;
}
function handleDeptChoice(item) {
  let index = certificateList.value.findIndex(item=>item.id == sealItem.value.id)
  certificateList.value[index].certificate.deptName = item.deptName;
  certificateList.value[index].certificate.deptId = item.deptId;
  if (previousDeptId != certificateList.value[index].certificate.deptId) {
    certificateList.value[index].certificate.deptNo = null;
    certificateList.value[index].certificate.packageLineNo = null;
    certificateList.value[index].certificate.year = null;
    certificateList.value[index].certificate.packageResourceGroupId = null;
    certificateList.value[index].certificate.packageResourceGroupName = null;
  }
}
function handlePackageLineChoice(item) {
  let index = certificateList.value.findIndex(item=>item.id == sealItem.value.id)
  certificateList.value[index].certificate.deptNo = item.deptNo;
  certificateList.value[index].certificate.packageLineNo = item.packageLineNo;
  certificateList.value[index].certificate.year = item.year;
  certificateList.value[index].certificate.packageResourceGroupId = item.id;
  certificateList.value[index].certificate.packageResourceGroupName = item.name;
}
function handlePackageTypeChoice(item) {
  let index = certificateList.value.findIndex(item=>item.id == sealItem.value.id)
  certificateList.value[index].certificate.packageCode = item.packageCode;
  certificateList.value[index].certificate.packageNo = item.packageNo;
  certificateList.value[index].certificate.packageStandard = item.packageStandard;
  certificateList.value[index].certificate.packageId = item.accessoriesId;
  certificateList.value[index].certificate.packageTypeCode = item.packageTypeCode;
}
function handleCompanySuccess(data) {
  let index = certificateList.value.findIndex(item=>item.id == sealItem.value.id)
  certificateList.value[index].certificate.companyName = data;
}
/**
 * 列表checkbox列选择 事件
 */
function handleSelectionChange(selection) {
  selections.value = selection
  ids.value = selections.value.map((item) => item.certificate.id);
}
async function handleExport(){
  let index = selections.value.findIndex(item=>item.certificate.generateTime == null)
  if(index != -1){
    proxy.$modal.msgError("批次"+selections.value[index].certificate.lotCode+"未保存并生成条码")
    return
  }
  console.log(selections.value)
  await exportCertificate({ ids: ids.value });
        proxy.$modal.msgSuccess("导出成功");
        getList();
}
function handleHistory(row) {
  historyDialogRef.value.open({ dayworkId: row.id });
}

function handleQuery() {
  getList();
}
function handleGenerate(row){
  if(row.certificate.generateTime != null){
    return
  }
  let index = certificateList.value.findIndex(item=>item.id == row.id)
  // 生成判断
  if (row.certificate.deptId == null) {
    proxy.$modal.msgError("请先选择生产工段");
    return;
  }
  if (row.certificate.packageLineNo == null) {
    proxy.$modal.msgError("请先选择包装线号");
    return;
  }
  if (row.certificate.labelNumber == null) {
    proxy.$modal.msgError("请填写标签数量");
    return;
  }
  if (row.certificate.printPages == null || row.certificate.printPages == 0) {
    proxy.$modal.msgError("请填写打印份数");
    return;
  }
  if (row.certificate.packageId == null) {
    proxy.$modal.msgError("请先选择包装");
    return;
  }
  const loading = ElLoading.service({
    lock: true,
  });
  generateQrCode(row.certificate).then((res) => {
    loading.close();
    if (res.code === 200) {
      certificateList.value[index].certificate = res.data;
      proxy.$modal.msgSuccess("生成成功");
      //向P2保存
      if(!dataSource){
      setP2Certificate({ id:res.data.id });
      }else{
        console.log("切换数据源")
      }
    } else {
      proxy.$modal.msgError("生成失败");
    }
  });
  console.log("保存");
}

function getInfoFromP2() {
  proxy.$modal.loading("正在拉取数据，请稍后...");
  if(!dataSource){
  getP2Accessories()
    .then((res) => {
      if (res.code === 200) {
        getP2CompanyProductPackage()
          .then((res) => {
            if (res.code === 200) {
              proxy.$modal.closeLoading();
              // proxy.$modal.msgSuccess("拉取成功")
            } else {
              proxy.$modal.closeLoading();
              // proxy.$modal.msgError("拉取失败")
            }
          })
          .catch((err) => {
            proxy.$modal.closeLoading();
            // proxy.$modal.msgError("拉取失败")
          });
      } else {
        proxy.$modal.closeLoading();
        // proxy.$modal.msgError("拉取失败")
      }
    })
    .catch((err) => {
      proxy.$modal.closeLoading();
      // proxy.$modal.msgError("拉取失败")
    });
  }else{
    console.log("切换数据源")

  }
}
</script>
<style scoped>
:deep(.el-tree-node__label) {
  font-size: 14px !important;
  display: inline-block;
  width: 100%;
}

:deep(.el-tree-node__content) {
  height: 40px;
  border-bottom: 1px solid #ebeef5;
  padding: 8px 0;
  line-height: 23px;
}

.move-handle {
  cursor: move;
  background-color: #eee;
}
</style>
