<template>
    <div class="app-container">
        <el-form ref="queryForm" size="small" :inline="true" label-width="68px">
            <el-form-item label="模板" prop="name">
                <el-select v-model="selectedOption" ref="mySelect" size="mini" @change="handleOptionChange" filterable
                           placeholder="请选择您要查看的模板">
                    <!--  <el-option label="自设的模板名" value="使用空白模板"></el-option>-->
                    <el-option
                        v-for="item in depss" :key="item.id" :label="item.templateName" :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="规则" prop="rule">
                <el-select v-model="selectedRule" ref="mySelect" size="mini" @change="handleRuleChange" filterable
                           placeholder="请选择您要查看的规则">
                    <el-option
                        v-for="iem in luckyrule" :key="iem.id" :label="iem.name" :value="iem.id">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                    type="warning"
                    plain
                    icon="el-icon-upload2"
                    size="mini"
                    @click="handleExport"
                >导出
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-upload
                    type="file"
                    name="file"
                    ref="upload"
                    :before-upload="handleFileChange"
                    action=''
                    accept='.xlsx'
                    :limit="1"
                    :file-list="fileList"
                    :disabled="disableNextButton"
                    :show-file-list=false
                >
                    <el-button plain size="mini" icon="el-icon-download" type="primary" :disabled="disableNextButton">
                        导入
                    </el-button>
                </el-upload>
            </el-col>
        </el-row>

        <!-- luckysheet容器 -->
        <div
            id="luckysheet"
            style="margin: 0px; padding: 0px; position: absolute; width: 100%; height:80vh; z-index: 0"
        >
        </div>
        <div v-if="showMask" class="mask">
            <div class="loading-spinner"></div>
        </div>

    </div>
</template>


<script>

import {getSuppliesTemplate, listSuppliesTemplate} from "@/api/ruoyi-myLuckyexcel/myluckyexcel";
import {convertRoleList, convertRoleListid} from "@/api/ActSuppliesConvert/convert"
/*import luckysheet from 'luckysheet'*/
import LuckyExcel from 'luckyexcel'
//导入库export.js 这个文件是es6的，不能在普通的HTML文件直接引入js文件（虽然都是js文件，但是有区别，具体请百度es6与es5）！需要把es6转es5才可以直接引入使用！
import {exportExcel} from '../../../../public/exportExcel';
import {v4 as uuidv4} from 'uuid';

var fileName = "新建XLSX工作表"; //定义表名
var rule = [];
var tempId;
var roleId;
export default {
    name: "Mymodule",
    data() {
        return {
            showMask: false,
            uuid: '',
            //弹出页面的表名
            from_name: "",
            // 是否显示弹出层
            dialogVisible: false,
            selectedOption: '',
            selectedRule: '',
            luckysheetData: '',
            fileList: [],
            disableNextButton: true,
            luckyrule: [],
            depss: [],
            // 表单参数
            from: {},
            dfrom: {},
            // 查询参数
            queryParams: {
                status: 0
            },
        };
    },
    created() {
        this.getList();
    },
    mounted() {
        this.init();
        fileName = "新建XLSX工作表";
    },
    methods: {
        /** 页面刷新时展示的数据*/
        getList() {
            listSuppliesTemplate(this.queryParams).then(response => {
                this.depss = response.rows;
            });
        },
        /** 下拉选和页面luckysheet绑定 */
        handleOptionChange() {
            this.selectedRule = '';
            this.disableNextButton = this.selectedRule === '';
            //根据选中的下拉选项值获取相应的信息
            getSuppliesTemplate(this.selectedOption).then(response => {
                tempId = this.selectedOption;
                console.log(this.uuid);
                const sysSupplies = response.rows;
                this.luckysheetData = sysSupplies[0].templateContent;
                //将接收到的json存到json_data中
                //const json_data = response.data;
                var json_data = JSON.parse(sysSupplies[0].templateContent);
                convertRoleList(this.selectedOption).then(response => {
                    this.luckyrule = response.rows;
                });
                let suffixArr = sysSupplies[0].templateName.split('.');
                fileName = suffixArr[0];
                //luckysheet.destroy()
                luckysheet.create({
                    container: "luckysheet", // Luckysheet 的容器元素 ID
                    title: fileName, // Excel 文件名
                    data: json_data, // Excel 数据
                    showinfobar: false, //是否显示顶部名称栏
                    lang: 'zh',
                });
            }).catch(() => {
                // 处理错误逻辑，这里是一个空的错误处理函数
                this.$message.error('查询失败,发生未知错误!');
            });
        },
        /** 规则下拉选 调佣后端的方法*/
        handleRuleChange() {
            if (this.selectedOption === '') {
                this.selectedRule = '';
                this.$message.warning("选择规则前请先选择模板!");
                return; // 如果按钮被禁用，提前返回，避免执行下一步操作
            }
            this.disableNextButton = this.selectedRule === '';
            convertRoleListid(this.selectedRule).then(response => {
                roleId = this.selectedRule;
                rule = response.rows;
            });
        },
        /** 回车事件和保存提交绑定 */
        handleEnter(event) {
            if (event.keyCode === 13) {
                event.preventDefault(); // 阻止默认的回车事件
                // 触发确定操作
                this.submit_from();
            }
        },
        /** 重置按钮操作 */
        resetQuery() {
            //刷新下拉选框内容
            fileName = "新建XLSX工作表";
            this.selectedOption = '';
            this.disableNextButton = '';
            this.selectedRule = '';
            this.luckyrule = [];
            //刷新luckysheet表格
            this.init();
        },
        /** Luckyexcel文档 */
        init() {
            let options = {
                container: 'luckysheet', //luckysheet为容器id
                title: '',
                lang: 'zh',
                showinfobar: false,
                data: [
                    {
                        "name": "sheet1", //工作表名称
                        "color": "", //工作表颜色
                        "index": 0, //工作表索引
                        "status": 1, //激活状态
                        "order": 0, //工作表的下标
                        "hide": 0,//是否隐藏
                        "row": 8, //行数
                        "column": 10, //列数
                        "defaultRowHeight": 19, //自定义行高
                        "defaultColWidth": 73, //自定义列宽
                        "celldata": [], //初始化使用的单元格数据
                        "config": {
                            "merge": {}, //合并单元格
                            "rowlen": {}, //表格行高
                            "columnlen": {}, //表格列宽
                            "rowhidden": {}, //隐藏行
                            "colhidden": {}, //隐藏列
                            "borderInfo": {}, //边框
                            "authority": {}, //工作表保护
                        },
                    },
                ]

            }
            luckysheet.create(options);

        },
        /** 导入事件*/
        async handleFileChange(evt) {
            let exx;
            this.showMask = true;
            const cons = new Promise((resolve, reject) => {
                LuckyExcel.transformExcelToLucky(evt, exportJson => {
                    exx = exportJson;
                    resolve(exx);
                });
            });

            try {
                const exportJson = await cons;
                await this.summary(exportJson);
                //console.log('summary 执行完毕');
            } catch (Error) {
                this.$message({
                    message: Error.message,
                    type: "error"
                });
                console.log(Error.message);
                console.log("这里是最外面的地方");
            } finally {
                // 导入完成后关闭遮罩层
                this.showMask = false;
            }
        },
        /** 物料转换汇总到页面*/
        summary(exportJson) {
            let sysRules;
            let value = [];
            let data;
            //获取规则  sysRulez是物料转换  sysRules是数据汇总规则  13
            for (let i = 0; i < rule.length; i++) {
                sysRules = JSON.parse(rule[i].content);
            }
            try {
                //获取物料转换的sheet表
                data = window.luckysheet.transToData(exportJson.sheets[0].celldata);
            } catch (err) {
                throw new Error("导入失败,所选文件或规则有误");
            }

            let map = new Map();
            let smallMat = [];
            let deps = [];

            for (let i =0;i<sysRules.length;i++){
                debugger
                //判断运算方法/0无运算方法/1加法/2减法/3乘法/4除法/5平均值/6最大值/7最小值
                if (sysRules[i].ys ==0){
                    //判断导入表行列单元格/1行/2列/3单元格
                    if (sysRules[i].ze==1){
                        //判断模板表行列单元格/1行/2列/3单元格
                        if (sysRules[i].zt==1){
                            for (let j=parseInt(sysRules[i].ce),x=parseInt(sysRules[i].ct);j<parseInt(sysRules[i].le)+parseInt(sysRules[i].ce);j++,x++){
                                luckysheet.setCellValue(parseInt(sysRules[i].rt),x,data[parseInt(sysRules[i].re)][j].v)
                            }
                        }else if (sysRules[i].zt==2){
                            for (let j=parseInt(sysRules[i].ce),x=parseInt(sysRules[i].rt);j<parseInt(sysRules[i].le)+parseInt(sysRules[i].ce);j++,x++){
                                luckysheet.setCellValue(x,parseInt(sysRules[i].ct),data[parseInt(sysRules[i].re)][j].v)
                            }
                        }
                    }else if (sysRules[i].ze==2){
                        if (sysRules[i].zt==1){
                            for (let j=parseInt(sysRules[i].re),x=parseInt(sysRules[i].ct);j<parseInt(sysRules[i].le)+parseInt(sysRules[i].re);j++,x++){
                                luckysheet.setCellValue(parseInt(sysRules[i].rt),x,data[j][parseInt(sysRules[i].ce)].v)
                            }
                        }else if (sysRules[i].zt==2){
                            for (let j=parseInt(sysRules[i].re),x=parseInt(sysRules[i].rt);j<parseInt(sysRules[i].le)+parseInt(sysRules[i].re);j++,x++){
                                luckysheet.setCellValue(x,parseInt(sysRules[i].ct),data[j][parseInt(sysRules[i].ce)].v)
                            }
                        }
                    }else if (sysRules[i].ze==3){
                        if (sysRules[i].zt==1){
                            for (let x=parseInt(sysRules[i].ct);x<parseInt(sysRules[i].lt)+parseInt(sysRules[i].ct);x++){
                                luckysheet.setCellValue(parseInt(sysRules[i].rt),x,data[parseInt(sysRules[i].re)][parseInt(sysRules[i].ce)].v)
                            }
                        }else if (sysRules[i].zt==2){
                            for (let x=parseInt(sysRules[i].rt);x<parseInt(sysRules[i].lt)+parseInt(sysRules[i].rt);x++){
                                luckysheet.setCellValue(x,parseInt(sysRules[i].ct),data[parseInt(sysRules[i].re)][parseInt(sysRules[i].ce)].v)
                            }
                        }else if (sysRules[i].zt==3){
                            luckysheet.setCellValue(parseInt(sysRules[i].rt),parseInt(sysRules[i].ct),data[parseInt(sysRules[i].re)][parseInt(sysRules[i].ce)].v)
                        }
                    }

                }else if (sysRules[i].ys ==2){//减法

                    if (sysRules[i].ze==1){
                        if (sysRules[i].zt==3){
                            let sum=parseInt(data[parseInt(sysRules[i].re)][parseInt(sysRules[i].ce)].v);
                            for (let j=parseInt(sysRules[i].ce)+1;j<parseInt(sysRules[i].le)+parseInt(sysRules[i].ce);j++){

                                sum-=parseInt(data[parseInt(sysRules[i].re)][j].v);

                            }
                            luckysheet.setCellValue(parseInt(sysRules[i].rt),parseInt(sysRules[i].ct),sum);
                        }
                    }else if (sysRules[i].ze==2){
                        if (sysRules[i].zt==3){
                            let sum=parseInt(data[parseInt(sysRules[i].re)][parseInt(sysRules[i].ce)].v);
                            for (let j=parseInt(sysRules[i].re)+1;j<parseInt(sysRules[i].le)+parseInt(sysRules[i].re);j++){

                                sum-=parseInt(data[j][parseInt(sysRules[i].ce)].v);

                            }
                            luckysheet.setCellValue(parseInt(sysRules[i].rt),parseInt(sysRules[i].ct),sum);
                        }
                    }
                }else if (sysRules[i].ys ==3){//乘法

                    if (sysRules[i].ze==1){
                        if (sysRules[i].zt==3){
                            let sum=parseInt(data[parseInt(sysRules[i].re)][parseInt(sysRules[i].ce)].v);
                            for (let j=parseInt(sysRules[i].ce)+1;j<parseInt(sysRules[i].le)+parseInt(sysRules[i].ce);j++){

                                sum*=parseInt(data[parseInt(sysRules[i].re)][j].v);

                            }
                            luckysheet.setCellValue(parseInt(sysRules[i].rt),parseInt(sysRules[i].ct),sum);
                        }
                    }else if (sysRules[i].ze==2){
                        if (sysRules[i].zt==3){
                            let sum=parseInt(data[parseInt(sysRules[i].re)][parseInt(sysRules[i].ce)].v);
                            for (let j=parseInt(sysRules[i].re)+1;j<parseInt(sysRules[i].le)+parseInt(sysRules[i].re);j++){

                                sum*=parseInt(data[j][parseInt(sysRules[i].ce)].v);

                            }
                            luckysheet.setCellValue(parseInt(sysRules[i].rt),parseInt(sysRules[i].ct),sum);
                        }
                    }

                }else if (sysRules[i].ys ==4){//除法

                    if (sysRules[i].ze==1){
                        if (sysRules[i].zt==3){
                            let sum=parseInt(data[parseInt(sysRules[i].re)][parseInt(sysRules[i].ce)].v);
                            for (let j=parseInt(sysRules[i].ce)+1;j<parseInt(sysRules[i].le)+parseInt(sysRules[i].ce);j++){

                                sum/=parseInt(data[parseInt(sysRules[i].re)][j].v);

                            }
                            luckysheet.setCellValue(parseInt(sysRules[i].rt),parseInt(sysRules[i].ct),sum);
                        }
                    }else if (sysRules[i].ze==2){
                        if (sysRules[i].zt==3){
                            let sum=parseInt(data[parseInt(sysRules[i].re)][parseInt(sysRules[i].ce)].v);
                            for (let j=parseInt(sysRules[i].re)+1;j<parseInt(sysRules[i].le)+parseInt(sysRules[i].re);j++){

                                sum/=parseInt(data[j][parseInt(sysRules[i].ce)].v);

                            }
                            luckysheet.setCellValue(parseInt(sysRules[i].rt),parseInt(sysRules[i].ct),sum);
                        }
                    }

                }else if (sysRules[i].ys ==1){//和
                    if (sysRules[i].ze==1){
                        if (sysRules[i].zt==3){
                            debugger
                            let sum=parseInt(data[parseInt(sysRules[i].re)][parseInt(sysRules[i].ce)].v);
                            for (let j=parseInt(sysRules[i].ce)+1;j<parseInt(sysRules[i].le)+parseInt(sysRules[i].ce);j++){

                                sum+=parseInt(data[parseInt(sysRules[i].re)][j].v);

                            }
                            luckysheet.setCellValue(parseInt(sysRules[i].rt),parseInt(sysRules[i].ct),sum);
                        }
                    }else if (sysRules[i].ze==2){
                        if (sysRules[i].zt==3){
                            let sum=parseInt(data[parseInt(sysRules[i].re)][parseInt(sysRules[i].ce)].v);
                            for (let j=parseInt(sysRules[i].re)+1;j<parseInt(sysRules[i].le)+parseInt(sysRules[i].re);j++){

                                sum+=parseInt(data[j][parseInt(sysRules[i].ce)].v);

                            }
                            luckysheet.setCellValue(parseInt(sysRules[i].rt),parseInt(sysRules[i].ct),sum);
                        }
                    }

                }else if (sysRules[i].ys==5){//平均值

                    if (sysRules[i].ze==1){
                        if (sysRules[i].zt==3){
                            debugger
                            let sum=parseInt(data[parseInt(sysRules[i].re)][parseInt(sysRules[i].ce)].v);
                            for (let j=parseInt(sysRules[i].ce)+1;j<parseInt(sysRules[i].le)+parseInt(sysRules[i].ce);j++){

                                sum+=parseInt(data[parseInt(sysRules[i].re)][j].v);

                            }
                            luckysheet.setCellValue(parseInt(sysRules[i].rt),parseInt(sysRules[i].ct),sum/parseInt(sysRules[i].le));
                        }
                    }else if (sysRules[i].ze==2){
                        if (sysRules[i].zt==3){
                            let sum=parseInt(data[parseInt(sysRules[i].re)][parseInt(sysRules[i].ce)].v);
                            for (let j=parseInt(sysRules[i].re)+1;j<parseInt(sysRules[i].le)+parseInt(sysRules[i].re);j++){

                                sum+=parseInt(data[j][parseInt(sysRules[i].ce)].v);

                            }
                            luckysheet.setCellValue(parseInt(sysRules[i].rt),parseInt(sysRules[i].ct),sum/parseInt(sysRules[i].le));
                        }
                    }

                }else if (sysRules[i].ys==6){//最大值

                    if (sysRules[i].ze==1){
                        if (sysRules[i].zt==3){
                            debugger
                            let sum=parseInt(data[parseInt(sysRules[i].re)][parseInt(sysRules[i].ce)].v);
                            for (let j=parseInt(sysRules[i].ce)+1;j<parseInt(sysRules[i].le)+parseInt(sysRules[i].ce);j++){

                                if (sum<parseInt(data[parseInt(sysRules[i].re)][j].v)){
                                    sum = parseInt(data[parseInt(sysRules[i].re)][j].v);
                                }

                            }
                            luckysheet.setCellValue(parseInt(sysRules[i].rt),parseInt(sysRules[i].ct),sum);
                        }
                    }else if (sysRules[i].ze==2){
                        if (sysRules[i].zt==3){
                            let sum=parseInt(data[parseInt(sysRules[i].re)][parseInt(sysRules[i].ce)].v);
                            for (let j=parseInt(sysRules[i].re)+1;j<parseInt(sysRules[i].le)+parseInt(sysRules[i].re);j++){

                                if (sum<parseInt(data[j][parseInt(sysRules[i].ce)].v)){
                                    sum = parseInt(data[j][parseInt(sysRules[i].ce)].v);
                                }

                            }
                            luckysheet.setCellValue(parseInt(sysRules[i].rt),parseInt(sysRules[i].ct),sum);
                        }
                    }

                }else if (sysRules[i].ys==7){//最小值

                    if (sysRules[i].ze==1){
                        if (sysRules[i].zt==3){
                            debugger
                            let sum=parseInt(data[parseInt(sysRules[i].re)][parseInt(sysRules[i].ce)].v);
                            for (let j=parseInt(sysRules[i].ce)+1;j<parseInt(sysRules[i].le)+parseInt(sysRules[i].ce);j++){

                                if (sum<parseInt(data[parseInt(sysRules[i].re)][j].v)){
                                    sum = parseInt(data[parseInt(sysRules[i].re)][j].v);
                                }

                            }
                            luckysheet.setCellValue(parseInt(sysRules[i].rt),parseInt(sysRules[i].ct),sum);
                        }
                    }else if (sysRules[i].ze==2){
                        if (sysRules[i].zt==3){
                            let sum=parseInt(data[parseInt(sysRules[i].re)][parseInt(sysRules[i].ce)].v);
                            for (let j=parseInt(sysRules[i].re)+1;j<parseInt(sysRules[i].le)+parseInt(sysRules[i].re);j++){

                                if (sum<parseInt(data[j][parseInt(sysRules[i].ce)].v)){
                                    sum = parseInt(data[j][parseInt(sysRules[i].ce)].v);
                                }

                            }
                            luckysheet.setCellValue(parseInt(sysRules[i].rt),parseInt(sysRules[i].ct),sum);
                        }
                    }

                }

            }

            //切换到想要的sheet
            luckysheet.setSheetActive(0);

        },

        /** 导出设置 */
        handleExport: debounce(function () {
            // 处理点击事件
            exportExcel(luckysheet.getAllSheets(), fileName)
        }, 500), // 设置延迟时间，单位为毫秒
    }
// 配置项111
};

// debounce函数定义
function debounce(func, delay) {
    let timer;
    return function () {
        const context = this;
        const args = arguments;
        clearTimeout(timer);
        timer = setTimeout(function () {
            func.apply(context, args);
        }, delay);
    };
}

function getKeyByValue(map, value) {
    for (let [key, val] of map) {
        if (val === value) {
            return key;
        }
        if (Array.isArray(val) && val.includes(value)) {
            return key;
        }
    }
}

</script>
<style>
.mask {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
}

.loading-spinner {
    /* 添加你的加载动画样式 */
    width: 40px;
    height: 40px;
    border-radius: 50%;
    border: 4px solid #f3f3f3;
    border-top: 4px solid #3498db;
    animation: spin 1s linear infinite;
}

@keyframes spin {
    0% {
        transform: rotate(0deg);
    }
    100% {
        transform: rotate(360deg);
    }
}
</style>
