<!-- 条码 -->
<template>
    <div class="table-box">
        <ListBtns :selectionList="datas.selectionList" @handleParentCallback="handleParentCallback" :ruleForm="datas.ruleForm" />
        <ProTable
            ref="proTable"
            :formData="datas.formData"
            :columns="datas.columns"
            :request-api="getListApi"
            :init-param="datas.initParam"
            @selectionChange="selectionChange"
            :orgCode="datas.ruleForm.orgCode"
        >
            <template #operation="scope">
                <el-button
                    type="primary"
                    size="small"
                    @click="handlerPrintBarCode(scope.row)"
                    v-if="scope.row.generateComplete === '已完成' ? true : false"
                    >打印条码</el-button
                >
            </template>
        </ProTable>
        <!-- 生成条码 -->
        <el-dialog
            v-model="datas.generateCodeVisible"
            title="生成条码"
            width="1480px"
            :before-close="handleBeforeClose"
            @close="handleCloseGenerateCode"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            destroy-on-close
            :z-index="20"
        >
            <div style="padding-bottom: 12px" class="flx-justify-between">
                <el-button type="primary" @click="handleAdd">新增行</el-button>
                <div>
                    <el-button type="primary" @click="handleCommit">确认</el-button>
                    <el-tooltip effect="dark" content="(确认生成条码成功, 列表页面将在3秒后刷新)" placement="top">
                        <el-icon style="cursor: pointer"><QuestionFilled /></el-icon>
                    </el-tooltip>
                </div>
            </div>
            <FormTable
                :columns="datas.generateCodeColumns"
                :tableData="datas.generateCodeTableData"
                @handleRemoteClickValue="handleRemoteClickValue"
                @getRemoteData="getRemoteData"
                @verificationInput="verificationInput"
                @handleClear="handleClear"
                @handleCheckEmit="handleCheckEmit"
                :loading="datas.loading"
            >
                <template #operation="scope">
                    <el-button
                        type="primary"
                        size="small"
                        @click="handleDelete(scope)"
                        v-if="datas.generateCodeTableData.length > 1"
                        >删除</el-button
                    >
                </template>
            </FormTable>
        </el-dialog>
        <!-- 打印条码 -->
        <el-dialog
            v-model="datas.printCodeVisible"
            title="打印条码"
            width="1480px"
            :close-on-press-escape="false"
            :close-on-click-modal="false"
            :distinguish-cancel-and-close="true"
            destroy-on-close
            :z-index="20"
        >
            <div style="display: flex">
                <div v-if="isShowBtns.isAllPrint">
                    <el-dropdown trigger="click" class="triangle-box" :max-height="300" @command="handleAllPrint">
                        <el-button type="primary">
                            全部打印<el-icon class="el-icon--right"> <i-ep-arrow-down /> </el-icon>
                        </el-button>
                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item
                                    v-for="(it, index) in datas.allPrintBtn"
                                    :key="index"
                                    :command="it.value"
                                    :value="it.label"
                                >
                                    {{ it.label }}
                                </el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                </div>
                <div style="margin-left: 20px" v-if="isShowBtns.isPrint">
                    <el-dropdown trigger="click" class="triangle-box" :max-height="300" @command="handlePrint">
                        <el-button type="primary">
                            选择打印<el-icon class="el-icon--right"> <i-ep-arrow-down /> </el-icon>
                        </el-button>
                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item
                                    v-for="(it, index) in datas.selectPrintBtn"
                                    :key="index"
                                    :command="it.value"
                                    :value="it.label"
                                >
                                    {{ it.label }}
                                </el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                </div>
                <div style="margin-left: 20px" v-if="isShowBtns.isDown">
                    <el-button @click="handleDown">下载</el-button>
                </div>
                <div style="margin-left: 20px" v-if="isShowBtns.isGGZH">
                    <el-button @click="handleGGShow">规格转换</el-button>
                </div>
            </div>
            <el-divider style="margin-top: 12px; margin-bottom: 12px" />
            <ProTable
                ref="printCodeTable"
                :request-api="getCodeListApi"
                :formData="datas.printCodeFormData"
                :columns="datas.printCodeColumns"
                :init-param="datas.printCodeRuleFormData"
                @selectionChange="codePrintSelection"
                :orgCode="datas.printCodeRuleFormData.orgCode"
                :isBoxClass="false"
                :pageSizes="[50, 100, 150, 200, 300, 500]"
                :tableRowClassName="tableRowClassName"
            >
            </ProTable>
            <!--   :request-api="" -->
            <!-- 规格型号转换弹窗 -->
            <el-dialog
                v-model="datas.specificationVisible"
                title="选择转换后的规格型号"
                width="500"
                :before-close="handleSpecificationClose"
            >
                <div style="margin-bottom: 8px; margin-left: 45px">规格型号</div>
                <el-select
                    placeholder="请输入关键字"
                    filterable
                    remote
                    clearable
                    style="width: 280px; margin-left: 45px"
                    v-model.trim="datas.specificationValue"
                    class="m-2 select"
                    remote-show-suffix
                    :loading="datas.loading1"
                    @clear="handleRemoteClear"
                    :remote-method="(query:any)=>{
                        remoteMethod(query)
                    }"
                >
                    <!-- idConvertBar -->
                    <el-option
                        v-for="option in datas.specificationList"
                        :key="option.materialNumber"
                        :label="option.specifications"
                        :value="option.idConvertBar"
                        @click="handleRemoteClick(option)"
                    />
                </el-select>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="handleSpecificationClose">取消</el-button>
                        <el-button type="primary" @click="handleSpecificationConfirm"> 确认 </el-button>
                    </div>
                </template>
            </el-dialog>
        </el-dialog>
        <!-- 批产条码 -->
        <el-dialog v-model="datas.generatesCodeVisible" title="导入生成条码信息" width="600" :before-close="handleFilesClose">
            <div class="flx-justify-between">
                <div style="padding-right: 32px; padding-left: 8px">
                    <!-- 下载模板 -->
                    <div style="margin: 12px 0">
                        <div style="">
                            <span style="color: red">*</span>
                            请按照数据模板格式导入数据
                        </div>
                        <div style="display: flex; align-items: center; margin-top: 10px; margin-left: 20px">
                            <a :href="datas.downFileUrl" style="margin-right: 8px">下载模板</a>
                            <img src="@/assets/images/excel.png" width="40" height="40" />
                        </div>
                    </div>
                    <!-- 上传文件 -->
                    <div style="display: flex">
                        <div style="width: 300px">
                            <!-- 导入模板 -->
                            <div>
                                <el-upload
                                    class="upload-demo"
                                    drag
                                    action="#"
                                    :auto-upload="false"
                                    accept=".xls,.xlsx"
                                    :on-remove="handleRemoveFiles"
                                    :on-change="handleFilesChange"
                                    :limit="1"
                                    ref="uploadRef"
                                >
                                    <el-icon class="el-icon--upload" :style="datas.isUpload ? 'color: #eeeeee' : 'color: #0000ee'"
                                        ><upload-filled
                                    /></el-icon>
                                    <div class="el-upload__text">
                                        <span style="color: red">*</span>将文件拖到此处,或<span style="color: #0000ee"
                                            >点击上传</span
                                        >
                                    </div>
                                    <div
                                        style="
                                            position: absolute;
                                            top: 0;
                                            left: 0;
                                            z-index: 1000;
                                            width: 300px;
                                            height: 184px;
                                            background-color: rgb(0 0 0 / 0%);
                                        "
                                        @click.stop=""
                                        v-if="datas.isUpload"
                                    ></div>
                                </el-upload>

                                <el-progress
                                    :percentage="datas.uploadProgress"
                                    :duration="5"
                                    :stroke-width="2"
                                    v-if="datas.uploadProgress"
                                ></el-progress>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- padding: 0 0 40px 20px -->
                <div style="position: absolute; top: 157px; right: 20px">
                    <div style="margin-bottom: 10px"><span style="color: red">*</span>导入注意事项</div>
                    <div style="margin-bottom: 10px">1: 支持文件类型:XLS,XLSX</div>
                    <div style="margin-bottom: 10px">2: 支持文件大小:1MB以内</div>
                    <div style="margin-bottom: 10px">3: 导入成功的数据,会显示在列表</div>
                    <div>4: 只支持单个文件上传</div>
                </div>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleFilesClose">取消</el-button>
                    <el-button type="primary" @click="handleGeneratesCodeConfirm"> 确认 </el-button>
                </div>
            </template>
        </el-dialog>
        <div id="barcode-box2" v-show="false">
            <svg id="barcode2" xmlns="http://www.w3.org/2000/svg"></svg>
        </div>
        <div id="barcode-box3" v-show="false">
            <svg id="barcode3"></svg>
        </div>
        <div id="barcode-box4" v-show="false">
            <svg id="barcode4"></svg>
        </div>
    </div>
</template>

<script setup lang="ts" name="barCode">
import ListBtns from "@/components/ListBtns/index.vue";
import ProTable from "@/components/ProTable/index.vue";
import FormTable from "@/components/FormTable/index.vue";
import { read, utils } from "xlsx";
import { useAuthStore } from "@/stores/modules/auth";
import { UploadFilled } from "@element-plus/icons-vue";
import $Bus from "@/utils/mittBus";
import { QuestionFilled } from "@element-plus/icons-vue";
import { ref, reactive } from "vue";
import { commitInitMsg, ElMessageBoxConfirm, handleBtnClick, printParam, printParamAll } from "./init/list/index";
// 列表页面搜索条件和表格配置项
import { RULE_FORM, FORM_DATA, COLUMNS } from "./constant/list/index";
// 消息提示
import { useMsg } from "@/hooks/useMsg";
// 打印条码页面打印按钮
import { ALL_PRINT_BTN, SELECT_PRINT_BTN, SELECT_PRINT_BTN1, ALL_PRINT_BTN1 } from "./constant/list/printBtns";
// 生成条码页面配置项
import { GENERATE_CODE_COLUMNS, GENERATE_CODE_FORM, GENERATE_CODE_FORM_INIT } from "./constant/generateCode/index";
// 打印弹窗搜索条件配置项
import { PRINT_CODE_FORM_DATA, PRINT_CODE_RULE_FORM_DATA, PRINT_CODE_FORM_COLUMNS } from "./constant/printCode/index";
// 接口
import {
    getCodeListApi,
    // getCodeList1Api,
    getSerialNumberDownLoadApi,
    getPrintListCodeApi,
    getListApi,
    generateBarCodeApi,
    getUpdateMaterialApi
} from "@/api/modules/barCode";
// 远程搜索接口
import { getMaterialListApi } from "@/api/modules/boxMark";
// 表格TS
import { ProTableInstance } from "@/components/ProTable/interface";
// 验证
import { integerNumber } from "@/utils/regexp/integerNumber";
import { useUserStore } from "@/stores/modules/user";
// 打印序列码
import { barCOdePrintFunctionObj } from "@/utils/print/barCode/index.js";
// 深拷贝方法
import { cloneDeep } from "lodash-es";
// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref<ProTableInstance>();
const printCodeTable = ref<any>();
// 获取用户信息(组织id)
const userStore: any = useUserStore();
const authStore = useAuthStore();
// 按钮权限
const SHOW_BTBS: any = authStore.btnsAuthList;
const isShowBtns = reactive<any>({
    isAllPrint: false,
    isPrint: false,
    isDown: false,
    isGGZH: false
});
if (SHOW_BTBS["barCode"] && SHOW_BTBS["barCode"].length) {
    isShowBtns.isAllPrint = SHOW_BTBS["barCode"].includes("barCodeAllPrint") || false;
    isShowBtns.isPrint = SHOW_BTBS["barCode"].includes("barCodePrint") || false;
    isShowBtns.isDown = SHOW_BTBS["barCode"].includes("barCodeDow") || false;
    isShowBtns.isGGZH = SHOW_BTBS["barCode"].includes("barCodeGGZH") || false;
}
// 数据源
const datas = reactive<any>({
    loading: false,
    loading1: false,
    columns: COLUMNS, //列表配置项
    initParam: cloneDeep(RULE_FORM), // 初始化搜索条件|重置搜索条件
    ruleForm: cloneDeep(RULE_FORM), // 搜索条件
    formData: FORM_DATA, //搜索配置项
    generatesCodeVisible: false, //批产条码窗口控制
    downFileUrl: "https://wmstestfile.f2b211.com/批量生成条码模板.xlsx", //批产条码模板下载地址
    selectionList: [], //表格选择后的数据
    printCodeVisible: false, //控制打印条码的弹窗
    specificationVisible: false, //控制规格型号转换的弹窗
    specificationValue: "", //转换规格箱号value
    specificationList: [], //规格型号转换搜索出来的数据
    generateCodeVisible: false, //控制生成条码弹窗
    generateCodeColumns: cloneDeep(GENERATE_CODE_COLUMNS), //生成条码配置项
    generateCodeTableData: cloneDeep(GENERATE_CODE_FORM), //生成条码数据
    codePrintSelectionList: [], //打印条码列表选择的数据
    printCodeFormData: cloneDeep(PRINT_CODE_FORM_DATA), //打印条码弹窗搜索配置项
    printCodeRuleFormData: cloneDeep(PRINT_CODE_RULE_FORM_DATA), //打印条码弹窗搜索结果
    printCodeColumns: cloneDeep(PRINT_CODE_FORM_COLUMNS), //打印条码弹窗表格配置项
    remoteSelectItem: {}, //转换规格的选中的数据
    isSave: false, //生成条码保存按钮状态
    // isDownLoad: false,
    generateComplete: "", //条码生成状态,生成中的不可打印
    jsonData: [], //批产条码数据
    generateRecordId: null, //生成记录id
    isUpload: false, //控制文件上传是否禁止,如 有已经上传文件了禁止上传
    fliesName: "",
    uploadProgress: "", //批产条码进度条
    selectPrintBtn: cloneDeep(SELECT_PRINT_BTN), //ALL_PRINT_BTN, SELECT_PRINT_BTN, SELECT_PRINT_BTN1, ALL_PRINT_BTN1
    allPrintBtn: cloneDeep(ALL_PRINT_BTN)
});
// 批产条码上传组件ref
let uploadRef: any = ref(null);

datas.ruleForm.createUser = userStore.userInfo.nickname;
datas.initParam.createUser = userStore.userInfo.nickname;

// 按钮回调(生成条码|下载|刷新)
const handleParentCallback = (result?: Record<string, any>) => {
    handleBtnClick(result, datas, proTable);
};

// 条码录入列表表格选择事件
const selectionChange = (selection: any) => {
    datas.selectionList = selection;
};

// 打印条码表格选择事件
const codePrintSelection = (selection: any) => {
    datas.codePrintSelectionList = selection;
};

// 点击打印条码按钮进行赋值
const handlerPrintBarCode = (row: any) => {
    datas.codePrintSelectionList = [];
    resetVisibleGroups();
    datas.printCodeRuleFormData.isDownLoad = false;
    if (row.id) {
        datas.printCodeRuleFormData.orgCode = userStore.orgCode;
        datas.printCodeRuleFormData.generateRecordId = row.id;
        datas.generateComplete = row.generateComplete;
        datas.printCodeVisible = true;
        datas.selectPrintBtn = row.isTwo > 1 ? cloneDeep(SELECT_PRINT_BTN) : cloneDeep(SELECT_PRINT_BTN1);
        datas.allPrintBtn = row.isTwo > 1 ? cloneDeep(ALL_PRINT_BTN) : cloneDeep(ALL_PRINT_BTN1);
    }
};
// 全局组ID注册表（在组件生命周期内持久化）
// 用于记录所有组的唯一ID，确保跨筛选/刷新保持一致
const globalGroupRegistry = new Map<string, number>();
let globalNextGroupId = 0;

// 临时组跟踪（仅用于当前渲染批次，记录可见组的顺序）
let visibleGroupOrder: string[] = [];

// 重置临时跟踪（筛选/分页时调用，保留全局注册表）
const resetVisibleGroups = () => {
    visibleGroupOrder = [];
    globalNextGroupId = 0;
};
// // 生成组标识（与之前相同）
const getGroupKey = (row: any) => {
    return JSON.stringify([row.serialNumber, row.twoSerialNumber].sort());
};

// 关键改进：跨筛选/刷新保持颜色交替的行样式函数
const tableRowClassName = ({ row }: { row: any }) => {
    // 排除不需要着色的行
    if (row.isTwo === 1) return "";

    // 验证必要字段
    if (!row.serialNumber || !row.twoSerialNumber) return "";

    const groupKey = getGroupKey(row);

    // 1. 全局注册组ID（首次出现时分配，永久不变）
    if (!globalGroupRegistry.has(groupKey)) {
        globalGroupRegistry.set(groupKey, globalNextGroupId);
        globalNextGroupId++;
    }
    globalGroupRegistry.get(groupKey)!;

    // 2. 跟踪当前可见组的出现顺序
    if (!visibleGroupOrder.includes(groupKey)) {
        visibleGroupOrder.push(groupKey);
    }
    const visibleIndex = visibleGroupOrder.indexOf(groupKey);

    // 3. 基于可见顺序的索引分配颜色（确保当前视图内严格交替）
    return visibleIndex % 2 === 0 ? "warning-row" : "success-row";
};
// // 新增：分组缓存管理
// const groupCache = new Map<string, { groupIndex: number; colorClass: string }>();
// let groupCounter = 0;

// // // 重置分组缓存（在表格数据变化时调用）
// const resetGroupCache = () => {
//     groupCache.clear();
//     groupCounter = 0;
// };
// const tableRowClassName = ({ row }: { row: any }) => {
//     // 当isTwo为1时不应用颜色
//     if (row.isTwo === 1) {
//         return "";
//     }

//     // 确保serialNumber和twoSerialNumber存在
//     if (!row.serialNumber || !row.twoSerialNumber) {
//         return "";
//     }

//     // 生成唯一组标识（排序后拼接，确保A-B和B-A属于同一组）
//     const groupKey = [row.serialNumber, row.twoSerialNumber].sort().join("-");

//     // 如果该组已处理过，直接使用缓存的颜色
//     if (groupCache.has(groupKey)) {
//         return groupCache.get(groupKey)!.colorClass;
//     }

//     // 新组：分配组索引并确定颜色（偶数组红色，奇数组绿色）
//     const groupIndex = groupCounter++;
//     const colorClass = groupIndex % 2 === 0 ? "warning-row" : "success-row";

//     // // 缓存该组信息
//     groupCache.set(groupKey, { groupIndex, colorClass });

//     return colorClass;

//     // if (row.isTwo == 1) {
//     //     return "";
//     // }
//     // console.log(row, "============>");
//     // // 计算当前行所在的组（每组2行）
//     // let groupIndex = Math.floor(rowIndex / 2);

//     // // 根据组索引的奇偶性决定使用哪种颜色
//     // if (groupIndex % 2 === 0) {
//     //     return "warning-row";
//     // } else {
//     //     return "success-row";
//     // }
//     // return "";
// };
// 删除文件
const handleRemoveFiles = () => {
    datas.uploadProgress = "";
    datas.isUpload = false;
    datas.fliesName = "";
    datas.jsonData = [];
};

// 取消
const handleFilesClose = () => {
    uploadRef.value.clearFiles();
    datas.generatesCodeVisible = false;
    datas.isUpload = false;
    datas.fliesName = "";
    datas.uploadProgress = "";
    datas.jsonData = [];
};

// 文件上传改变
const handleFilesChange = (file: any) => {
    //文件上传的大小限制(1MB)
    const maxSize = 1 * 1024 * 1024;
    const fileSize = file.size;

    //判断上传的文件是否大于1MB,大于则提示并且不进行上传操作
    if (fileSize > maxSize) {
        uploadRef.value.clearFiles();
        datas.isUpload = false;
        useMsg("warning", "支持文件大小:1MB以内 ！");
        return;
    }
    datas.fliesName = file.name;
    //将表格的数据读取出来转换成可用的数组
    const reader = new FileReader();
    const totalChunks = 1; // 模拟将文件读取解析过程分为1个阶段
    let processedChunks = 0;
    reader.onload = (e: any) => {
        const data: any = new Uint8Array(e.target.result);
        const workbook: any = read(data, { type: "array" });
        const sheetName: any = workbook.SheetNames[0];
        const worksheet: any = workbook.Sheets[sheetName];
        const jsonData: any = utils.sheet_to_json(worksheet);
        datas.jsonData = jsonData;
        if (!datas.jsonData.length) {
            return;
        }
        //大于1000只能是1000
        datas.jsonData.forEach((item: any) => {
            if (item["生成数量*"] > 1000) {
                item["生成数量*"] = 1000;
            }
        });
        //过滤为0的
        datas.jsonData = datas.jsonData.filter((item: any) => {
            return item["生成数量*"] > 0;
        });
    };

    //进度条(假的,产品要进度条!),将文件上传到本地是很快的
    reader.onprogress = (e: any) => {
        if (e.lengthComputable) {
            processedChunks++;
            const percent = ((processedChunks / totalChunks) * 100).toFixed(2);
            datas.uploadProgress = parseFloat(percent);
        }
    };
    reader.readAsArrayBuffer(file.raw);
    //判断是否已上传,上传则禁用
    if (datas.fliesName) {
        datas.isUpload = true;
    }
};

// 批产提交
const handleGeneratesCodeConfirm = async () => {
    if (!datas.fliesName) {
        useMsg("warning", "请上传需要导入的数据 ！");
        return false;
    }
    const KEY = ["生成数量*", "规格型号*", "采购订单号*"];
    //提交后端的数据
    let params: any = {
        details: [],
        orgCode: datas.ruleForm.orgCode
    };
    if (datas.jsonData.length) {
        datas.jsonData.forEach((item: any) => {
            if (item[KEY[0]] && item[KEY[1]] && item[KEY[2]]) {
                let obj = {
                    number: item[KEY[0]],
                    specifications: item[KEY[1]],
                    purchaseBillNo: item[KEY[2]]
                };
                params.details.push(obj);
            }
        });
    }

    if (!params.details.length) {
        useMsg("warning", " 表格数据为空, 请重新上传数据！");
        uploadRef.value.clearFiles();
        datas.isUpload = false;
        datas.jsonData = [];
        datas.fliesName = "";
        datas.uploadProgress = "";
        return;
    }
    //根据下标提示表格空数据的行数
    let result = await generateBarCodeApi(params);
    if (result.status === 200 && result.isSuccess) {
        useMsg("success", "操作成功 ！");
        datas.generatesCodeVisible = false;
        handleFilesClose();
        setTimeout(() => {
            proTable.value!.reset();
        }, 3000);
    } else {
        useMsg("error", "操作失败 ！");
    }
};

// 规格转换按钮点击事件
const handleGGShow = () => {
    if (!datas.codePrintSelectionList.length) {
        useMsg("warning", "请选择需要转换规格的数据 ! ");
        return;
    }
    //判断用户是否选择了已经使用的序列号
    let isSome = datas.codePrintSelectionList.some((item: any) => {
        return item.isUse;
    });
    if (isSome) {
        useMsg("warning", "序列号已使用, 不允许转换规格型号 ! ");
        return;
    }
    datas.specificationVisible = true;
};

// 生成条码弹窗新增行按钮事件
const handleAdd = () => {
    datas.generateCodeTableData.push(cloneDeep(GENERATE_CODE_FORM_INIT));
};

// 生成条码弹窗删除行按钮事件
const handleDelete = (scope: any) => {
    const { $index } = scope;
    datas.generateCodeTableData.splice($index, 1);
};

// 生成条码弹窗确认按钮事件
const handleCommit = async () => {
    await commitInitMsg(datas, proTable);
};

// 远程搜索点x清空值
const handleClear = (params: any) => {
    const { index } = params;
    datas.generateCodeTableData[index] = {};
    datas.generateCodeColumns[0].options[index] = [];
    datas.loading = false;
};

// 规格型号转换弹窗里的搜索与getRemoteData的区分一下,避免修改老代码出错
const remoteMethod = async (query: any) => {
    datas.loading1 = true;
    if (!query) {
        datas.loading1 = false;
        return;
    }
    let valClone = query.replace(/^\s*|\s*$/g, "");
    if (!valClone.length) {
        datas.loading1 = false;
        return;
    }
    const result = await getMaterialListApi(valClone);
    if (result.status === 200) {
        const { data } = result;
        //规格型号下拉框设置数据
        datas.specificationList = data;
    }
    datas.loading1 = false;
};

// 生成条码弹窗远程操作赋值
const getRemoteData = async (query: any) => {
    datas.loading = true;
    const { val, index } = query;
    if (!val) {
        datas.loading = false;
        return;
    }
    //清除空格
    let valClone = val.replace(/^\s*|\s*$/g, "");
    if (!valClone) {
        datas.loading = false;
        return;
    }
    const result = await getMaterialListApi(valClone);
    if (result.status === 200) {
        const { data } = result;
        //规格型号下拉框设置数据
        datas.generateCodeColumns[0].options[index] = data;
        if (datas.generateCodeColumns[0].options[index].length) {
            datas.generateCodeColumns[0].options[index].forEach((item: any) => {
                item.idConvertBar = item.idConvertBar + "&" + item.specifications;
            });
        }
    }
    datas.loading = false;
};

// 规格型号转换option点击事件
const handleRemoteClick = (item: any) => {
    datas.remoteSelectItem = item;
};

// 规格型号转换清空
const handleRemoteClear = () => {
    datas.specificationValue = "";
    datas.loading1 = false;
};

// 规格型号转换确认
const handleSpecificationConfirm = async () => {
    let params: any = {
        generateRecordId: datas.printCodeRuleFormData.generateRecordId,
        serialNumbers: [],
        materialNumber: datas.remoteSelectItem.materialNumber,
        specifications: []
    };
    //判断一下是否是相同的物料编码进行转换
    let isMaterialNumberSome = datas.codePrintSelectionList.some((item: any) => {
        return item.specifications === datas.remoteSelectItem.specifications;
    });
    if (isMaterialNumberSome) {
        useMsg("warning", "请选择不同的规格型号进行转换 ! ");
        return;
    }
    datas.codePrintSelectionList.forEach((item: any) => {
        params.serialNumbers.push(item.serialNumber);
        params.specifications.push({
            serialNumber: item.serialNumber,
            old_Specification: item.specifications
        });
    });

    //接口
    const result = await getUpdateMaterialApi(params);
    if (result.status === 200) {
        if (result.isSuccess) {
            useMsg("success", "规格转换成功 ！");
            resetVisibleGroups();
            printCodeTable.value.getTableList();
            datas.specificationVisible = false;
            handleSpecificationClose();
        } else {
            useMsg("error", "规格转换失败 ！");
        }
    } else {
        useMsg("error", result.message);
    }
};

// 规格型号弹窗关闭钩子
const handleSpecificationClose = () => {
    datas.specificationVisible = false;
    datas.loading1 = false;
    datas.specificationList = [];
    datas.specificationValue = "";
    datas.remoteSelectItem = {};
    datas.isDownLoad = false;
};

// 生成条码弹窗远程操作赋值(规格型号点击选择)
const handleRemoteClickValue = (params: any) => {
    const { item, index } = params;
    let items = datas.generateCodeColumns[0].options[index];
    let idConvertBar = datas.generateCodeTableData[index][item.prop];
    let result: any = [];
    if (items.length > 1) {
        result = items.filter((it: any) => {
            return it.idConvertBar == idConvertBar;
        });
    }
    if (items.length === 1) {
        result = items;
    }
    datas.generateCodeTableData[index] = { ...datas.generateCodeTableData[index], ...result[0] };
};

// 偶数验证
const integerNumber2 = (value: any, vNumber: number): any => {
    if (!value) {
        return;
    }
    let valueClone = Number(cloneDeep(value));
    if (typeof valueClone === "number" && !isNaN(valueClone) && valueClone % vNumber === 0) {
        return true;
    }
    return false;
};
const isTowNumber = (index: any) => {
    let number = datas.generateCodeTableData[index]["number"];
    if (number && !integerNumber2(number, 2)) {
        useMsg("warning", "两件装产品,数量需填双数!");
    }
};
const handleCheckEmit = (params: Record<string, any>) => {
    const { index } = params;
    let isTwoClone = datas.generateCodeTableData[index]["isTwoClone"];
    if (isTwoClone == 2) {
        isTowNumber(index);
    }
};
// 表单验证
const verificationInput = (params: Record<string, any>) => {
    const { prop, index } = params;
    if (prop !== "number") {
        return;
    }
    if (datas.generateCodeTableData[index]["number"] == 0) {
        datas.generateCodeTableData[index]["number"] = "";
    }
    let isTwoClone = datas.generateCodeTableData[index]["isTwoClone"];
    if (isTwoClone == 2) {
        isTowNumber(index);
    } else {
        datas.generateCodeTableData[index]["number"] = integerNumber(datas.generateCodeTableData[index]["number"]);
    }

    if (datas.generateCodeTableData[index]["number"] > 1000) {
        datas.generateCodeTableData[index]["number"] = 1000;
    }
};

// 生成条码关闭弹窗前需要做的事情
const handleBeforeClose = () => {
    ElMessageBoxConfirm(datas);
};

// 生成条码关闭弹窗需要做的事情
const handleCloseGenerateCode = () => {
    //重置条码表格数据
    datas.generateCodeColumns = cloneDeep(GENERATE_CODE_COLUMNS);
    datas.generateCodeTableData = cloneDeep(GENERATE_CODE_FORM);
    datas.isSave = false;
};

// 条码列表下载
const getSerialNumberDownLoad = async () => {
    datas.printCodeRuleFormData.isDownLoad = true;
    if (!datas.codePrintSelectionList.length) {
        useMsg("warning", "请选择需要下载的数据 ！");
        return;
    }

    let serialNumbers: any[] = [];
    let isTwo = datas.codePrintSelectionList[0].isTwo;
    datas.codePrintSelectionList.forEach((item: any) => {
        serialNumbers.push(item.serialNumber);
    });
    const { orgCode } = datas.printCodeRuleFormData;
    const { generateRecordId } = datas.printCodeRuleFormData;
    const result = await getSerialNumberDownLoadApi({
        orgCode,
        serialNumbers,
        generateRecordId,
        isTwo
    });
    if (result.status === 200 && result.isSuccess) {
        useMsg("success", "导出成功请前往导出列表中进行下载 ！");
        resetVisibleGroups();
        printCodeTable.value.getTableList();
        datas.printCodeRuleFormData.isDownLoad = false;
    } else {
        useMsg("warning", "导出失败,请稍后重试 ！");
        datas.printCodeRuleFormData.isDownLoad = false;
    }
};

// 打印条码下载
const handleDown = () => {
    getSerialNumberDownLoad();
};

// 打印记录接口
const getPrintListCode = async (params: any) => {
    datas.printCodeRuleFormData.isDownLoad = false;
    const result = await getPrintListCodeApi(params);
    if (result.status === 200) {
        printCodeTable!.value.getTableList();
    }
};

// 是否在WMS系统使用过的序列号
const isWMSSerialNumber = (list: any) => {
    let length = list.length;
    let listClone = [];
    let listFilter = [];
    for (let i = 0; i < length; i++) {
        let item = list[i];
        if (item.isEnablePrint) {
            listClone.push(item);
        } else {
            listFilter.push(item);
        }
    }
    if (listFilter.length) {
        let str = "";
        let listFilterLength = listFilter.length;
        let listFilterSerialNumber = [];
        for (let i = 0; i < listFilterLength; i++) {
            listFilterSerialNumber.push(listFilter[i].serialNumber);
        }
        str = listFilterSerialNumber.join(",");
        useMsg("warning", `打印时过滤WMS系统已使用的序列码"${str}" ！`);
    }
    let serialNumbers = [];
    let listCloneLength = listClone.length;
    for (let i = 0; i < listCloneLength; i++) {
        let item = listClone[i];
        serialNumbers.push(item.serialNumber);
    }

    return {
        listClone,
        serialNumbers
    };
};

// 打印全部条码
const handleAllPrint = async (val: number) => {
    if (datas.generateComplete === "生成中") {
        useMsg("warning", "请选择已生成完成的条码进行打印 ！");
        return;
    }
    const prams = await printParamAll(datas, printCodeTable);
    const { generateRecordIds, list } = prams;
    const { listClone, serialNumbers } = await isWMSSerialNumber(list);

    if (!listClone.length) {
        return;
    }
    await barCOdePrintFunctionObj(val, listClone, () => {
        getPrintListCode({
            generateRecordIds,
            isAll: false,
            serialNumbers
        });
    });
};

// 打印部分条码
const handlePrint = async (val: number) => {
    if (datas.generateComplete === "生成中") {
        useMsg("warning", "请选择已生成完成的条码进行打印 ！");
        return;
    }
    if (!datas.codePrintSelectionList.length) {
        useMsg("warning", "请选择需打印的数据 ！");
        return;
    }

    const prams = await printParam(datas);
    const { generateRecordIds } = prams;
    const { listClone, serialNumbers } = await isWMSSerialNumber(datas.codePrintSelectionList);
    if (!listClone.length) {
        return;
    }
    await barCOdePrintFunctionObj(val, listClone, () => {
        getPrintListCode({
            generateRecordIds,
            isAll: false,
            serialNumbers
        });
    });
};

watch(
    () => userStore.orgCode,
    newVal => {
        datas.ruleForm.orgCode = newVal;
        datas.initParam.orgCode = newVal;
    },
    {
        immediate: true,
        deep: true
    }
);

onMounted(() => {
    $Bus.on("clearBarCodeCreateUser", () => {
        resetVisibleGroups();
        datas.ruleForm.createUser = "";
        datas.initParam.createUser = "";
        datas.printCodeRuleFormData.isDownLoad = false;
    });

    $Bus.on("setBarCodeInputCreateUser", (params: any) => {
        const { createUser } = params;
        datas.ruleForm.createUser = createUser;
        datas.initParam.createUser = createUser;
    });
    $Bus.on("searchBarCodeSsDownLoad", () => {
        resetVisibleGroups();
        datas.printCodeRuleFormData.isDownLoad = false;
    });
});
</script>

<style scope lang="scss">
@import "./index.scss";
</style>
