<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="handleDownOpen(scope)"
                    v-if="scope.row.generateComplete === '已完成' ? true : false"
                    >下载防伪码</el-button
                >
            </template>
        </ProTable>

        <el-dialog v-model="datas.dialogFormVisible" title="生成防伪码" width="500px" @close="handleCloseGenerateCode">
            <el-form
                ref="ruleFormRef"
                style="width: 300px"
                :model="datas.numberRuleForm"
                :rules="datas.numberRules"
                class="demo-ruleForm"
                label-width="80px"
                :z-index="20"
            >
                <el-form-item label="数量: " prop="number" style="width: 360px">
                    <el-input v-model="datas.numberRuleForm.number" style="width: 224px" @input="valueVerify" :maxlength="6" />
                    <el-tooltip effect="dark" content="最大防伪码生成数量为999999" placement="top">
                        <el-icon style="cursor: pointer"><QuestionFilled /></el-icon>
                    </el-tooltip>
                </el-form-item>
                <el-form-item label="规格型号: " prop="specifications" style="margin-top: 20px">
                    <el-select
                        v-model="datas.numberRuleForm.specifications"
                        placeholder="请输入规格型号"
                        clearable
                        remote
                        :loading="datas.loading"
                        filterable
                        remote-show-suffix
                        @clear="handleClear"
                        :remote-method="(query:any) => {remoteMethod1(query)}"
                        style="width: 224px"
                    >
                        <el-option
                            :label="option.specifications"
                            :value="option.materialNumber"
                            v-for="option in datas.options"
                            :key="option.materialNumber"
                        />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm(ruleFormRef)"> 确认 </el-button>
                    <el-button @click="resetForm(ruleFormRef)">取消</el-button>
                </div>
            </template>
        </el-dialog>
        <div class="down-dialog-box">
            <el-dialog
                v-model="datas.downVisible"
                title="防伪码详情"
                width="1020px"
                :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; padding-top: 16px">
                    <el-button type="primary" @click="handleAllDown" v-if="isShowBtns.isAllDown">全部下载</el-button>
                    <el-button type="primary" @click="handleDown" v-if="isShowBtns.isNoAllDown">下载</el-button>
                </div>
                <el-divider style="margin: 16px 0" />
                <ProTable
                    ref="downProTable"
                    :formData="datas.downFormData"
                    :columns="datas.downColumns"
                    :request-api="getDownListApi"
                    :init-param="datas.initDownParam"
                    @selectionChange="downSelectionChange"
                    :orgCode="datas.ruleForm.orgCode"
                    :isBoxClass="false"
                >
                </ProTable>
            </el-dialog>
        </div>
    </div>
</template>

<script setup lang="ts" name="antiCode">
import ListBtns from "@/components/ListBtns/index.vue";
import ProTable from "@/components/ProTable/index.vue";
import $Bus from "@/utils/mittBus";
import { QuestionFilled } from "@element-plus/icons-vue";
import { useMsg } from "@/hooks/useMsg";
import type { FormInstance } from "element-plus";
import { getMaterialListApi } from "@/api/modules/boxMark";

import { useAuthStore } from "@/stores/modules/auth";

import {
    RULE_FORM,
    FORM_DATA,
    COLUMNS,
    NUM_RULES,
    NUM_RULE_FORM,
    DOWN_FORM_DATA,
    DOWN_RULE_FORM,
    DOWN_COLUMNS
} from "./constant/list/index";
import { getListApi, getGenerateSecurityNumberApi, getDownListApi, getDownApi, getDownAllApi } from "@/api/modules/antiCode";
//表格TS
import { ProTableInstance } from "@/components/ProTable/interface";
import { useUserStore } from "@/stores/modules/user";
import { integerRexg } from "@/utils/regexp/index";
//深拷贝方法
import { cloneDeep } from "lodash-es";
// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref<ProTableInstance>();
const ruleFormRef = ref<FormInstance>();
const downProTable = ref<any>();
const authStore = useAuthStore();
const SHOW_BTBS: any = authStore.btnsAuthList;

const isShowBtns = reactive<any>({
    isAllDown: false,
    isNoAllDown: false
});
if (SHOW_BTBS["antiCode"] && SHOW_BTBS["antiCode"].length) {
    isShowBtns.isAllDown = SHOW_BTBS["antiCode"].includes("antiCodeAllDow") || false;
    isShowBtns.isNoAllDown = SHOW_BTBS["antiCode"].includes("antiCodeNoAllDow") || false;
}

// 获取用户信息(组织id)
const userStore: any = useUserStore();

// 数据源
const datas = reactive<any>({
    downVisible: false,
    columns: COLUMNS, //列表配置项
    initParam: cloneDeep(RULE_FORM), // 初始化搜索条件|重置搜索条件
    ruleForm: cloneDeep(RULE_FORM), // 搜索条件
    formData: FORM_DATA, //搜索配置项
    dialogFormVisible: false,
    options: [], //规格型号
    numberRuleForm: cloneDeep(NUM_RULE_FORM), //生成防伪码
    numberRules: NUM_RULES, //生成防伪码rule规则
    selectionList: [], //选中表格的行
    loading: false,
    downFormData: cloneDeep(DOWN_FORM_DATA), //
    downColumns: DOWN_COLUMNS, //
    initDownParam: cloneDeep(DOWN_RULE_FORM), //
    downSelectionList: [] //防伪码下载列表选中
});

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

// input输入验证
const valueVerify = () => {
    datas.numberRuleForm.number = integerRexg(datas.numberRuleForm.number);
};
// 按钮回调(生成条码|下载|刷新)
const handleParentCallback = (result?: any) => {
    const { type } = result;
    //生成条码
    if (type === "Generate") {
        datas.dialogFormVisible = true;
    }
    if (type === "Refresh") {
        proTable.value!.getTableList();
    }
};
// 表格选择事件
const selectionChange = (selection: any) => {
    datas.selectionList = selection;
};
// 防伪码详情选中数据
const downSelectionChange = (selection: any) => {
    datas.downSelectionList = selection;
};
// 规格型号
const remoteMethod1 = async (query: any) => {
    datas.loading = true;
    if (!query) {
        datas.loading = false;
        return;
    }
    let valClone = query.replace(/^\s*|\s*$/g, "");
    if (!valClone.length) {
        datas.loading = false;
        return;
    }
    const result = await getMaterialListApi(valClone);
    if (result.status === 200) {
        const { data } = result;
        datas.options = data;
    }
    datas.loading = false;
};
const handleClear = () => {
    datas.options = [];
};
//生成防伪码接口
const getGenerateSecurityNumber = async () => {
    const { specifications, number } = datas.numberRuleForm;
    const result = await getGenerateSecurityNumberApi({
        materialNumber: specifications,
        number,
        orgCode: userStore.orgCode
    });
    if (result.status === 200) {
        useMsg("success", "防伪码生成成功 ！");
        datas.dialogFormVisible = false;
        //这里应该调用重置接口,如果调用列表接口页面还会保留上次的搜索条件
        proTable.value!.getTableList();
        //proTable.value!.getTableList();
    }
};
// 生成箱码提交
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            getGenerateSecurityNumber();
        } else {
            console.log("error submit!", fields);
        }
    });
};
const generateSecurityNumberInit = () => {
    datas.numberRuleForm = cloneDeep(NUM_RULE_FORM); //生成防伪码
    datas.dialogFormVisible = false;
    datas.options = [];
};
// 生成箱码取消
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.resetFields();
    generateSecurityNumberInit();
};
const handleCloseGenerateCode = () => {
    ruleFormRef.value!.resetFields();
    generateSecurityNumberInit();
};
// 防伪码下载弹窗
const handleDownOpen = (scope: any) => {
    datas.downVisible = true;
    datas.initDownParam.generateRecordId = scope.row.id;
};
// 防伪码下载
const handleDown = async () => {
    if (!datas.downSelectionList.length) {
        useMsg("warning", "请勾选需要下载的数据 ！");
        return;
    }
    let securityNumbers: any[] = [];
    proTable.value!.searchParam;
    datas.downSelectionList.forEach((item: any) => {
        securityNumbers.push(item.securityNumber);
    });
    const { generateRecordId } = datas.initDownParam;
    const params: any = {
        generateRecordId,
        orgCode: userStore.orgCode,
        securityNumbers: securityNumbers
    };
    const result = await getDownApi(params);
    if (result.status === 200 && result.isSuccess) {
        useMsg("success", "导出成功请前往导出列表中进行下载 ！");
        setTimeout(() => {
            downProTable!.value.getTableList();
        }, 500);
    } else {
        useMsg("error", "导出失败,请稍后重试 ！");
    }
};
const handleAllDown = async () => {
    const { pageable, searchParam } = downProTable.value;
    const { pageNo, pageSize } = pageable;
    const { generateRecordId } = datas.initDownParam;
    const result = await getDownAllApi({
        pageNo,
        pageSize,
        generateRecordId,
        orgCode: userStore.orgCode,
        ...searchParam
    });
    if (result.status === 200 && result.isSuccess) {
        useMsg("success", "导出成功请前往导出列表中进行下载 ！");
        downProTable!.value.getTableList();
    } else {
        useMsg("error", "导出失败,请稍后重试 ！");
    }
};

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

onMounted(() => {
    $Bus.on("clearBoxAntiCodeCreator", () => {
        datas.ruleForm.createUser = "";
        datas.initParam.createUser = "";
        console.log("123232");
    });

    $Bus.on("setAntiCodeInputCreateUser", (params: any) => {
        const { createUser } = params;
        datas.ruleForm.createUser = createUser;
        datas.initParam.createUser = createUser;
        console.log("1232323");
    });
});
</script>

<style scope lang="scss">
.down-dialog-box {
    .el-dialog__body {
        padding: 0 16px 40px;
    }
}
</style>
