import { useMsg } from "@/hooks/useMsg";
import { ElMessageBox } from "element-plus";
import { generateBarCodeApi } from "@/api/modules/barCode";
import { getCodeListApi } from "@/api/modules/barCode";

/**
 * 提取字符串中&符号前面的部分，无&则返回空字符串，包含完善的容错处理
 * @param {string} str - 待处理的原始字符串
 * @returns {string} 有&返回前面部分，无&/输入异常返回空字符串
 */
const getStrBeforeAmpersand = (str: any) => {
    // 容错处理1：非字符串转字符串，null/undefined转空字符串
    const inputStr = String(str ?? "");

    // 容错处理2：去除首尾空格
    const trimmedStr = inputStr.trim();

    // 容错处理3：空字符串直接返回''
    if (!trimmedStr) {
        return "";
    }

    // 找到&符号的位置
    const ampersandIndex = trimmedStr.indexOf("&");

    // 核心修正：无&符号直接返回''，而非原字符串
    if (ampersandIndex === -1) {
        return "";
    }

    // 提取&前部分并去空格（即使&在开头，也会返回''）
    return trimmedStr.substring(0, ampersandIndex).trim();
};

//生成条码接口
const generateBarCode = async (datas: any, proTable: any) => {
    let params: any = {
        details: [],
        orgCode: datas.ruleForm.orgCode
    };

    datas.generateCodeTableData.forEach((item: any) => {
        params.details.push({
            idConvertBar: getStrBeforeAmpersand(item.idConvertBar),
            materialNumber: item.materialNumber,
            number: item.number,
            purchaseBillNo: item.purchaseBillNo,
            specifications: item.specifications,
            isTwo: item.isTwoClone ? item.isTwoClone : 1
        });
    });
    console.log(params, "=params=");
    const result = await generateBarCodeApi(params);
    if (result.status === 200 && result.isSuccess) {
        useMsg("success", "操作成功 ！");
        datas.isSave = true;
        datas.generateCodeVisible = false;
        setTimeout(() => {
            //getTableList reset
            proTable.value!.getTableList();
        }, 3000);
    } else {
        useMsg("error", "操作失败 ！");
    }
};

//生成条码弹窗确认按钮点击后的判断必填项空值判断
export const commitInitMsg = (datas: any, proTable: any) => {
    let isSpecifications = datas.generateCodeTableData.some((item: any) => {
        return !item.specifications;
    });
    let isNumber = datas.generateCodeTableData.some((item: any) => {
        return !item.number;
    });
    let isPurchaseBillNo = datas.generateCodeTableData.some((item: any) => {
        return !item.purchaseBillNo;
    });

    //是否有选择了两件装的产品但是数量又不是偶数的
    let isTwoNumber = datas.generateCodeTableData.some((item: any) => {
        if (item.isTwoClone === 2) {
            return Number(item.number) % 2 == 0;
        } else {
            return true;
        }
    });

    if (!isTwoNumber) {
        return useMsg("warning", "两件装产品,数量需填双数!");
    }
    if (isSpecifications) {
        return useMsg("warning", "请输入规格型号 ！");
    }
    if (isNumber) {
        return useMsg("warning", "请输入生成数量 ！");
    }
    if (isPurchaseBillNo) {
        return useMsg("warning", "请输入采购订单号 ！");
    }

    generateBarCode(datas, proTable);
};
//生成条码窗口有数据的时候需要进行提示让用户确认关闭
export const ElMessageBoxConfirm = (datas: any) => {
    let isValue = datas.generateCodeTableData.some((item: any) => {
        return item.specifications;
    });
    if (isValue && !datas.isSave) {
        ElMessageBox.confirm("您已编辑数据确认要进行关闭操作(关闭后,已编辑的数据将不会保存)?", "提示", {
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            type: "warning"
        })
            .then(() => {
                datas.generateCodeVisible = false;
            })
            .catch(() => {});
    } else {
        datas.generateCodeVisible = false;
    }
};
//初始化组织信息
export const initRuleForm = (datas: any) => {
    datas.ruleForm.orgCode = 1;
};

//顶部按钮事件
export const handleBtnClick = (result: any, datas: any, proTable: any) => {
    const { type } = result;
    console.log(type, "============>");
    //生成条码
    if (type === "Generate") {
        datas.generateCodeVisible = true;
    }
    if (type === "Refresh" || type === "Convert") {
        proTable!.value.getTableList();
    }
    if (type === "Generates") {
        datas.generatesCodeVisible = true;
    }
};
//打印条码下载参数过滤
export const getSerialNumberDownLoadFilter = (printCodeTable: any) => {
    let pageable = {
        pageNo: printCodeTable.value!.pageable.pageNo,
        pageSize: printCodeTable.value!.pageable.pageSize
    };
    let searchParam: any = {};
    for (let key in printCodeTable.value!.searchParam) {
        if (key !== "Time" && key !== "Time1") {
            searchParam[key] = printCodeTable.value!.searchParam[key];
        }
    }
    return {
        searchParam,
        pageable
    };
};
//打印条码部分打印
export const printParam = (datas: any) => {
    let generateRecordIds: any[] = [];
    let serialNumbers: any[] = [];
    //获取打印条码列表id
    datas.codePrintSelectionList.forEach((item: any) => {
        serialNumbers.push(item.serialNumber);
    });
    let generateRecordId = datas.printCodeRuleFormData.generateRecordId;
    //获取生成列表id
    generateRecordIds.push(generateRecordId);
    return {
        serialNumbers,
        generateRecordIds
    };
};
//打印条码列表接口(这里因为有个全部打印,需要获取全部条码,所以需要传全部条码的id)
const getCodeList = async (datas: any, printCodeTable: any) => {
    let generateRecordId = datas.printCodeRuleFormData.generateRecordId;
    let orgCode = datas.printCodeRuleFormData.orgCode;
    const result = await getCodeListApi({
        pageNo: 1,
        pageSize: 1000,
        orgCode,
        generateRecordId,
        ...printCodeTable.value!.searchParam
    });
    if (result.status === 200) {
        const { data } = result;
        return data;
    }
};
export const printParamAll = async (datas: any, printCodeTable: any) => {
    let list: any = await getCodeList(datas, printCodeTable);
    let serialNumbers: any = [];
    let generateRecordIds: any = [];
    list.forEach((item: any) => {
        serialNumbers.push(item.serialNumber);
    });
    let generateRecordId = datas.printCodeRuleFormData.generateRecordId;
    generateRecordIds.push(generateRecordId);
    return {
        generateRecordIds,
        serialNumbers,
        list
    };
};
