<template>
    <div class="app-container">
            <el-form  ref="queryForm" size="small" :inline="true"  :rules="rules"  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="roleid">
                    <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.roleName" :value="iem.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="时间" prop="date">
                    <el-date-picker
                        v-model="from.date"
                        type="month"
                        placeholder="选择月">
                    </el-date-picker>
                </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" @click="rulesdate">导入</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 {selectActSuppliesHistorydata ,addActSuppliesSixMinesSummaryTable} from "@/api/Actsupplies/cleaning_rule";
import { getSuppliesTemplate, listSuppliesTemplate,roleList,materialConvert,roleListid,materialList} from "@/api/ruoyi-myLuckyexcel/myluckyexcel";
import {addInsert}from "@/api/system/historydata"
/*import luckysheet from 'luckysheet'*/
import LuckyExcel from 'luckyexcel'
//导入库export.js 这个文件是es6的，不能在普通的HTML文件直接引入js文件（虽然都是js文件，但是有区别，具体请百度es6与es5）！需要把es6转es5才可以直接引入使用！
/*import {materialList} from "@/api/ruoyi-myLuckyexcel/myluckyexcel";*/
import { exportExcel } from '../../../../public/exportExcel';
import { v4 as uuidv4 } from 'uuid';

var fileName="新建XLSX工作表"; //定义表名
var rule=[];
var tempId;
var roleId;
var uuid1;
var trueORfalse=false;
var modify=false;
export default {
    name: "Mymodule",
    data() {
        return {
            showMask:false,
            uuid:'',
            //弹出页面的表名
            from_name : "",
            // 是否显示弹出层
            dialogVisible : false,
            selectedOption:'',
            selectedRule:'',
            luckysheetData: '',
            fileList:[],
            disableNextButton: true,
            luckyrule:[],
            depss:[],
            // 表单参数
            from: {},
            froms: {
                hId : "",
                projectId : "",
                projectName : "",
                departmentName : "",
                number  : "",
                nuitPrice : "",
                money : "",
                createBy  : "",
                date : null

            },
            dfrom:{},
            // 查询参数
            queryParams: {
                status:0
            },

        };
    },
    created() {
//刷新页面时进行的操作
        this.getList();
    },
    mounted() {

        this.init();
        fileName="新建XLSX工作表";
    },
    methods:{

        /** 判断是否选择时间*/
        rulesdate(){

            if (this.from.date==''||this.from.date==null){
                this.$message.error('请选择时间日期！');
            }

        },

        /** 页面刷新时展示的数据*/
        getList() {
            listSuppliesTemplate(this.queryParams).then(response => {
                this.depss = response.rows;
            });

        },
        /** 下拉选和页面luckysheet绑定 */
        handleOptionChange() {
            this.selectedRule='';
            this.disableNextButton = this.selectedRule === '';
            //根据选中的下拉选项值获取相应的信息
            getSuppliesTemplate(this.selectedOption).then(response => {
                if(this.selectedOption===7){
                    trueORfalse=true;
                }else{
                    trueORfalse=false;
                }
                modify=false;
                tempId= this.selectedOption;
                uuid1=this.uuid=uuidv4().substring(0,8);

                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);
                roleList(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 === '';
            roleListid(this.selectedRule).then(response => {
                roleId=this.selectedRule;
                rule=response.rows;
            });
            if(tempId===7){
                getSuppliesTemplate(7).then(response => {
                    uuid1=this.uuid=uuidv4().substring(0,8);

                    // 通过遍历this.luckyrule找到对应的iem.roleName
                    for (let i = 0; i < this.luckyrule.length; i++) {
                        if (this.luckyrule[i].id === this.selectedRule) {
                            let name = this.luckyrule[i].roleName;
                            fileName=name.slice(0,-2);
                            break;
                        }
                    }
                    modify=false;
                    const sysSupplies = response.rows;
                    this.luckysheetData = sysSupplies[0].templateContent;
                    let json_data = JSON.parse(sysSupplies[0].templateContent);
                    //luckysheet.destroy()
                    luckysheet.create({
                        container: "luckysheet", // Luckysheet 的容器元素 ID
                        title: fileName, // Excel 文件名
                        data: json_data, // Excel 数据
                        showinfobar: false, //是否显示顶部名称栏
                        lang:'zh',
                    });
                }).catch(() => {
                    // 处理错误逻辑，这里是一个空的错误处理函数
                    this.$message.error('查询失败,发生未知错误!');
                });
            }


        },
        /** 回车事件和保存提交绑定 */
        /*handleEnter(event) {
            if (event.keyCode === 13) {
                event.preventDefault(); // 阻止默认的回车事件
                // 触发确定操作
                this.submit_from();
            }
        },*/
        /** 重置按钮操作 */
        resetQuery() {
            //刷新下拉选框内容
            fileName="新建XLSX工作表";
            this.selectedOption='';
            this.disableNextButton='';
            this.selectedRule='';
            this.luckyrule=[];
            trueORfalse=false;
            modify=false;
            uuid1='';
            //刷新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":{}, //工作表保护
                        },
                    },
                    /*{
                      "name": "Sheet2",
                      "color": "",
                      "index": 1,
                      "status": 0,
                      "order": 1,
                      "celldata": [],
                      "config": {}
                    },
                    {
                      "name": "Sheet3",
                      "color": "",
                      "index": 2,
                      "status": 0,
                      "order": 2,
                      "celldata": [],
                      "config": {},
                    }*/
                ]

            }
            luckysheet.create(options);

        },
        /** 导入事件*/
        async handleFileChange(evt) {
            debugger
            if(modify){
                this.$confirm('再次导入将会清空表内数据,是否继续操作？', '注意!!!', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(async () => {
                    // 确认继续后刷新页面返回模板
                    getSuppliesTemplate(7).then(response => {
                        const sysSupplies = response.rows;
                        this.luckysheetData = sysSupplies[0].templateContent;
                        let json_data = JSON.parse(sysSupplies[0].templateContent);
                        //luckysheet.destroy()
                        luckysheet.create({
                            container: "luckysheet", // Luckysheet 的容器元素 ID
                            title: fileName, // Excel 文件名
                            data: json_data, // Excel 数据
                            showinfobar: false, //是否显示顶部名称栏
                            lang:'zh',
                        });
                        modify=false;
                    }).then(async ()=>{
                        //将导入数据替换保存
                        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);

                            //this.submit(exportJson);
                        } catch (Error) {
                            this.$message({
                                message: Error.message,
                                type: "error"
                            });

                        } finally {
                            // 导入完成后关闭遮罩层
                            this.showMask = false;
                        }

                    }).catch(() => {
                        // 处理错误逻辑，这里是一个空的错误处理函数
                        this.$message.error('查询失败,模板未找到,请联系管理员进行处理!');
                    });
                }).catch(() => {
                    // 用户点击了取消按钮
                    //this.$message({type: 'info', message: '操作已取消'});
                });
            }else{
                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);

                    this.submit(exportJson);

                } catch (Error) {
                    this.$message({
                        message: Error.message,
                        type: "error"});

                }finally {
                    // 导入完成后关闭遮罩层
                    this.showMask = false;}
            }

        },
        /** 物料转换汇总到页面*/
        summary(exportJson){
            let sysRulez;
            let sysRules;
            let sysConver;
            let value=[];
            let data;
            //获取规则  sysRulez是物料转换  sysRules是数据汇总规则  13
            for(let i=0;i<rule.length;i++){
                if (rule[i].convertStatus==1){
                    sysRulez = JSON.parse(rule[i].detailContent);
                }
                if(rule[i].convertStatus==2){
                    if (parseInt(rule[i].detailYS)===1){
                        sysConver = JSON.parse(rule[i].detailContent)
                    }else {
                        sysRules = JSON.parse(rule[i].detailContent);
                    }
                }
            }
            try {
                //获取物料转换的sheet表
                data=window.luckysheet.transToData(exportJson.sheets[sysRulez[0].se].celldata);
            }
            catch (err){
                throw new Error("导入失败,所选文件或规则有误");
            }
            //获取物料转换中导入表的列,用来获取物料名
            let key_i=parseInt(sysRulez[0].ce);
            //获取物料转换的数据
            for (let i=0;i<sysRules.length;i++){
                //value.push(data[sysRules[i].re][sysRules[i].ce].m);
                value.push(sysRules[i].ce);
            }

            return new Promise((resolve, reject) => {
                const asyncTasks = [];
                switch (tempId) {
                    case 2:
                    {
                        let departmentMap = new Map();
                        let departments = [];
                        departmentMap.set('原煤', ['综一队', '综二队', '综三队', '开一区', '开二区', '准备一区', '准备二区', '掘进一区', '掘进二区', '掘进三区', '开拓项目部', '巷修区', '井运区', '通风区', '机电运转中心', '皮带运输中心']);
                        departmentMap.set('风选煤', '洗煤厂');
                        departmentMap.set('制造费用', ['机电检修中心', '地测科', '设备管理科', '旧品利用中心', '机修加工中心', '网络安全与信息通讯中心', '保卫科', '煤质管理科', '迁建科', '综合服务中心']);
                        departmentMap.set('管理费用', ['财务部', '综合办公室', '纪委监察科', '工会', '团委', '安全管理部', '经营管理部', '党委组织部（人力资源部）', '党委宣传部', '生产技术部', '机电运输部', '科协', '节能环保法律办公室', '党委组织部', '人力资源部']);
                        try{
                            for (let i = parseFloat(sysRulez[0].re) + 1; i < data.length; i++) {
                                let n = parseInt(sysRules[0].ce) + 2;
                                if (data[i][key_i] != null && data[i][n] != null) {
                                    let num = data[i][n].m;
                                    //根据得到的num,找到对应的key
                                    let keyy = getKeyByValue(departmentMap, num);
                                    departments.push(keyy);
                                } else {
                                    departments.push(null);
                                }
                            }

                        }catch(err){
                            throw new Error("导入失败,导入文件与模板规则不匹");
                        }
                        for (let key of departmentMap.keys()) {

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

                            try {
                                for (let i = parseFloat(sysRulez[0].re) + 1; i < data.length; i++) {

                                    if (data[i][key_i] != null && departments[i - 1] === key) {
                                        let num = data[i][key_i].m;
                                        smallMat.push(num);
                                    } else {
                                        smallMat.push(null);
                                    }
                                }
                            }catch(err){
                                throw new Error("导入失败,导入文件与模板规则不匹");
                            }

                            asyncTasks.push(
                                new Promise((innerResolve, innerReject) => {
                                    const allNull = smallMat.every(item =>item===null);
                                    if (allNull ) {
                                        throw new Error("导入失败,导入文件错误,所选文件与模板规则不匹");
                                    }
                            materialConvert(smallMat)
                                .then(response => {
                                    let array = response.rows;

                                    //luckysheet.setCellValue(12, 1, {bg:"#FF0000"})
                                    for (let i = parseFloat(sysRulez[0].re) + 1; i < data.length; i++) {
                                        let values = [];
                                        if (data[i][13] != null && departments[i - 1] === key && data[i][key_i] != null) {
                                            for (let j = 0; j < value.length; j++) {
                                                try{
                                                    let a = parseFloat(data[i][value[j]].v);
                                                    values.push(a);
                                                }catch (err){
                                                    throw new Error("导入失败,导入文件不匹");
                                                }

                                            }
                                            //插入多个value的值
                                            let index = smallMat.indexOf(data[i][key_i].m);
                                            let key = array[index];
                                            if (map.has(key)) {
                                                let oldValues = map.get(key);
                                                for (let i = 0; i < values.length; i++) {
                                                    values[i] = parseFloat(parseFloat(values[i] + oldValues[i]).toFixed(2));
                                                }
                                                map.set(key, values);
                                            } else {
                                                map.set(key, values);
                                            }
                                        }
                                    }
                                    //循环得到汇总结果

                                    if (map.size === 0) {
                                        throw new Error("导入失败,导入文件错误");
                                    }
                                    let cells;
                                    let warn;
                                    let rowss = luckysheet.find(key);
                                    if (rowss.length != 0) {
                                        for (let i = 0; i < sysRules.length; i++) {
                                            map.forEach((value, key) => {
                                                let searchResult = luckysheet.find(key);
                                                if (searchResult.length != 0 && key != null) {
                                                    cells = searchResult[0].column;
                                                    luckysheet.setCellValue(rowss[0].row, cells, value[i]);
                                                    luckysheet.setCellValue(rowss[0].row, cells, {
                                                        "ct": {
                                                            "fa": "General",
                                                            "t": "n"
                                                        }
                                                    });
                                                }else{
                                                    warn++;
                                                }
                                            });
                                        }
                                    }
                                    if (warn / sysRules.length === map.size) {
                                        throw new Error("导入文件与所选模板规则不匹配");
                                    } else if (warn > 0) {
                                        this.$message({
                                            message: "还有"+warn/sysRules.length+"条大类未能匹配到",
                                            type: "warning"});
                                    }
                                    resolve(response.rows);
                                    innerResolve(); // 标记当前异步任务完成

                                }).catch(Error => {

                                //必须加,不能删除
                                innerReject(Error); // 异步请求出错
                            });
                                }));
                        }
                    }
                        break;
                    case 6: {
                        let deps = [];
                        let exps = [];
                        let map = new Map();
                        let smallMat = [];
                        try{
                            for (let i = parseFloat(sysRulez[0].re) + 1; i < data.length; i++) {
                                if (data[i][key_i] != null) {
                                    let num = data[i][key_i].m;
                                    let dep = data[i][1].m;
                                    let exp = data[i][14].m;
                                    smallMat.push(num);
                                    deps.push(dep);
                                    exps.push(exp);
                                } else {
                                    smallMat.push(null);
                                    deps.push(null);
                                    exps.push(null);
                                }
                            }
                        }catch(err){
                            throw new Error("导入失败,导入文件与模板规则不匹");
                        }

                        asyncTasks.push(
                            new Promise((innerResolve, innerReject) => {
                                const allNull = smallMat.every(item =>item===null);
                                const allNull1 = deps.every(item =>item===null);
                                const allNull2 = exps.every(item =>item===null);
                                if (allNull || allNull1 ||allNull2) {
                                    throw new Error("导入失败,导入文件错误,所选文件与模板规则不匹");
                                }

                        materialConvert(smallMat)
                            .then(response => {

                            let array = response.rows;
                            //luckysheet.setCellValue(12, 1, {bg:"#FF0000"})
                            for (let i = parseFloat(sysRulez[0].re) + 1, k = 0; i < data.length; i++, k++) {
                                let values = [];
                                if (data[i][key_i] != null) {
                                    for (let j = 0; j < value.length; j++) {
                                        try{
                                            let a = parseFloat(data[i][value[j]].v);
                                            values.push(a);
                                        }catch(err){
                                            throw new Error("导入失败,导入文件不匹");
                                        }

                                    }
                                    //插入多个value的值
                                    let key = exps[k] + '/' + deps[k] + '/' + array[k];
                                    if (map.has(key)) {
                                        let oldValues = map.get(key);
                                        for (let i = 0; i < values.length; i++) {
                                            values[i] = parseFloat(parseFloat(values[i] + oldValues[i]).toFixed(2));
                                        }
                                        map.set(key, values);
                                    } else {
                                        map.set(key, values);
                                    }
                                }

                            }
                            //循环得到汇总结果

                                if (map.size === 0) {
                                    throw new Error("导入失败,导入文件错误");
                                }
                            //循环得到汇总结果
                            let cells;
                            let rowws;
                            let con=0;
                            let warn=0;
                            for (let i = 0; i < sysRules.length; i++) {
                                map.forEach((value, key) => {
                                    const suffixArr = key.split('/'), mat = suffixArr[2], depp = suffixArr[1],
                                        expp = suffixArr[0];

                                    let searchResult = luckysheet.find(expp);
                                    if (searchResult.length !== 0 ) {
                                        rowws = searchResult[0].row;
                                        for (let i = 1; i < 10000000000000000000000000; i++) {
                                            let n = rowws + i;
                                            let gg = luckysheet.getCellValue(n, 0);
                                            if (gg!==null) {
                                                con = rowws + i;
                                                break;
                                            }
                                        }
                                        searchResult= luckysheet.find(depp);
                                        if(searchResult.length !== 0 ){

                                            let k=0;
                                            let r;
                                            for(let i=0;i<searchResult.length;i++){
                                                r = searchResult[i].row;

                                                if(r<con&&r>=rowws){
                                                    k=1;
                                                    break;
                                                }
                                            }
                                            if(k===1){
                                                let matResult = luckysheet.find(mat);
                                                if (matResult.length !== 0 && mat != null) {
                                                    cells = matResult[0].column;
                                                    luckysheet.setCellValue(r, cells, value[i]);
                                                    luckysheet.setCellValue(r, cells, {
                                                        "ct": {
                                                            "fa": "General",
                                                            "t": "n"
                                                        }
                                                    });
                                                }else{
                                                    warn++;
                                                }
                                            }else{
                                                warn++;
                                            }
                                        }

                                    }else{
                                        warn++;
                                    }
                                });
                                if (warn / sysRules.length === map.size) {
                                    throw new Error("导入文件与所选模板规则不匹配");
                                } else if (warn > 0) {
                                    this.$message({
                                        message: "还有"+warn/sysRules.length+"条大类未能匹配到",
                                        type: "warning"});
                                }
                                resolve(response.rows);
                                innerResolve(); // 标记当前异步任务完成
                            }

                        }).catch(Error => {

                            //必须加,不能删除
                            innerReject(Error); // 异步请求出错
                        });
                            }));

                    }
                        break;
                    case 1: {
                        let map = new Map();
                        let smallMat = [];
                        try{
                            for (let i = parseInt(sysRulez[0].re) + 1; i < data.length; i++) {
                                if (data[i][key_i] != null) {
                                    let num = data[i][key_i].m;
                                    smallMat.push(num);
                                } else {
                                    smallMat.push(null);
                                }
                            }
                            for (let j = 0; j < value.length; j++) {
                                if (data[sysRulez[0].re][value[j]] != null) {
                                    let num = data[sysRulez[0].re][value[j]].m;
                                    smallMat.push(num);
                                } else {
                                    smallMat.push(null);
                                }
                            }
                        }catch(err){
                            throw new Error("导入失败,导入文件与模板规则不匹");
                        }

                        asyncTasks.push(
                            new Promise((innerResolve, innerReject) => {
                                const allNull = smallMat.every(item =>item===null);
                                if (allNull ) {
                                    throw new Error("导入失败,导入文件错误,所选文件与模板规则不匹");
                                }
                        materialConvert(smallMat)
                            .then(response => {
                            let array = response.rows;

                            //luckysheet.setCellValue(12, 1, {bg:"#FF0000"})
                            for (let i = parseInt(sysRulez[0].re) + 1; i < data.length; i++) {
                                let values = [];
                                if (data[i][key_i] != null) {
                                    for (let j = 0; j < value.length; j++) {
                                        try{
                                            let a = parseFloat(data[i][value[j]].v);
                                            if (isNaN(a)) {
                                                a = 0;
                                            }
                                            values.push(a);
                                        }catch (err){
                                            throw new Error("导入失败,导入文件不匹");
                                        }
                                    }
                                } else {
                                    break;
                                }
                                //插入多个value的值
                                let index = smallMat.indexOf(data[i][key_i].m);
                                let key = array[index];
                                if (map.has(key)) {
                                    let oldValues = map.get(key);
                                    for (let i = 0; i < values.length; i++) {
                                        values[i] = parseFloat(parseFloat(parseFloat(values[i]) + parseFloat(oldValues[i])).toFixed(2));
                                    }
                                    map.set(key, values);
                                } else {
                                    map.set(key, values);
                                }
                            }
                                if (map.size === 0) {
                                    throw new Error("导入失败,导入文件错误");
                                }
                            //循环得到汇总结果
                            let row;
                            let con;
                            let warn=0;

                            map.forEach((value,key)=>{
                                let searchResult;
                                searchResult= luckysheet.find(key);
                                if( searchResult==undefined ||searchResult.length === 0 || key === null){
                                    warn++;
                                }
                            })
                                if (warn  === map.size) {
                                    throw new Error("导入文件与所选模板规则不匹配");
                                }
                            for (let i = 0; i < sysRules.length; i++) {
                                map.forEach((value, key) => {

                                    let matchingCells = [];
                                    let name = data[sysRules[i].re][sysRules[i].ce].m
                                    if (name.includes("洗煤")) {
                                        row = sysRules[i].rt;
                                        con = parseInt(sysRules[i].rt) + 10;
                                    } else {
                                        row = sysRules[i].rt;
                                        con = 54;
                                    }
                                    for (; row <= con; row++) {
                                        let cellValue = luckysheet.getCellValue(row, parseInt(sysRulez[0].ct));
                                        if (cellValue === null) {
                                        } else {
                                            if (cellValue.includes(key)) {
                                                luckysheet.setCellValue(row, sysRules[i].ct, value[i]);
                                                luckysheet.setCellValue(row, sysRules[i].ct, {
                                                    "ct": {
                                                        "fa": "General",
                                                        "t": "n"
                                                    }
                                                });
                                                break;
                                            }else{
                                            }
                                        }
                                    }
                                });
                            }
                            let value2 = [];
                            let map2 = new Map;
                            for (let i = 0; i < sysConver.length; i++) {
                                //value.push(data[sysRules[i].re][sysRules[i].ce].m);
                                value2.push(sysConver[i].ce);
                            }
                            for (let i = parseInt(sysRulez[0].re) + 1; i < data.length; i++) {
                                let values2 = [];
                                if (data[i][key_i] != null) {
                                    for (let j = 0; j < value2.length; j++) {
                                        try{
                                            let a = parseFloat(data[i][value2[j]].v);
                                            if (isNaN(a)) {
                                                a = 0;
                                            }
                                            values2.push(a);
                                        }catch (err){
                                            throw new Error("导入失败,导入文件不匹");
                                        }
                                    }
                                } else {
                                    break;
                                }
                                //插入多个value的值
                                let key = data[sysConver[0].re][sysConver[0].ce].v;
                                if (map2.has(key)) {
                                    let oldValues = map2.get(key);
                                    for (let i = 0; i < values2.length; i++) {
                                        values2[i] = parseFloat(parseFloat(parseFloat(values2[i]) + parseFloat(oldValues[i])).toFixed(2));
                                    }
                                    map2.set(key, values2);
                                } else {
                                    map2.set(key, values2);
                                }
                            }
                                if (map2.size === 0) {
                                    throw new Error("导入失败,导入文件错误");
                                }

                            map2.forEach((value, key) => {
                                let searchResult;
                                searchResult= luckysheet.find(key);
                                if( searchResult!==undefined && searchResult.length !== 0 || key !== null){
                                    for (let i = 0; i < value.length; i++) {
                                        luckysheet.setCellValue(searchResult[0].row, sysConver[i].ct, value[i]);
                                        luckysheet.setCellValue(searchResult[0].row, sysConver[i].ct, {
                                            "ct": {
                                                "fa": "General",
                                                "t": "n"
                                            }
                                        });
                                    }
                                }else{
                                    warn++;
                                }
                            })
                                if (warn  === map.size+map2.size) {
                                    throw new Error("导入文件与所选模板规则不匹配");
                                } else if (warn > 0) {
                                    this.$message({
                                        message: "还有"+warn+"条大类未能匹配到",
                                        type: "warning"});
                                }
                                resolve(response.rows);
                                innerResolve(); // 标记当前异步任务完成
                        }).catch(Error => {

                            //必须加,不能删除
                            innerReject(Error); // 异步请求出错
                        });
                            }));
                    }
                        break;
                    case 7: {

                        let map = new Map();
                        let smallMat = [];
                        let deps = [];
                        try {
                            for (let i = parseFloat(sysRulez[0].re) + 1; i < data.length; i++) {

                                if (data[i][sysRulez[1].ce] != null && data[i][key_i] != null) {
                                    let num = data[i][key_i].m;
                                    let dep = data[i][sysRulez[1].ce].m;
                                        smallMat.push(num);
                                        deps.push(dep);
                                } else {
                                    smallMat.push(null);
                                    deps.push(null);
                                }
                            }
                        }catch(err){
                            throw new Error("导入失败,导入文件与模板规则不匹");
                        }
                        asyncTasks.push(
                            new Promise((innerResolve, innerReject) => {
                                const allNull = smallMat.every(item =>item===null);
                                if (allNull ) {
                                    throw new Error("导入失败,导入文件错误,所选文件与模板规则不匹");
                                }




                        materialConvert(smallMat)
                            .then(response => {
                            let array = response.rows;
                            for (let i = parseFloat(sysRulez[0].re) + 1, k = 0; i < data.length; i++, k++) {
                                let values = [];
                                if (data[i][key_i] != null) {
                                    for (let j = 0; j < value.length; j++) {
                                        try{
                                            let a = parseFloat(data[i][value[j]].v);
                                            values.push(a);
                                        }catch (err){
                                            this.$message({
                                                message: "导入失败,导入文件不匹",
                                                type: "error"
                                            });
                                            innerReject(error); // 异步请求出错
                                        }

                                    }
                                    //插入多个value的值
                                    //此方法只适用于一对一唯一值
                                    /*let index = smallMat.indexOf(data[i][key_i].m);
                                let key = array[index];*/
                                    let key = array[k] + '/' + deps[k];
                                    if (map.has(key)) {
                                        let oldValues = map.get(key);
                                        for (let i = 0; i < values.length; i++) {
                                            values[i] = parseFloat(parseFloat(values[i] + oldValues[i]).toFixed(2));
                                        }
                                        map.set(key, values);
                                    } else {
                                        map.set(key, values);
                                    }
                                }

                            }
                            //循环得到汇总结果


                                if (map.size === 0) {
                                    throw new Error("导入失败,导入文件错误");
                                }
                            //返回单元格第二行的数据
                            //let celn=luckysheet.getcellvalue(1);
                            //返回当前工作表第1列数据
                            //let cown=luckysheet.getcellvalue(null,0);
                            let rowws;
                            let config;
                            let bord = {
                                "rangeType": "range",
                                "borderType": "border-all",
                                "style": "1",
                                "color": "#000000",
                                "range": [{
                                    "row": [0, 0],
                                    "column": [0, 0]
                                }]
                            }
                            let warn=0;
                            map.forEach((value, key) => {
                                const suffixArr = key.split('/'), mat = suffixArr[0], depp = suffixArr[1];

                                let searchResult = luckysheet.find(mat);
                                if (searchResult.length != 0 && key != null) {
                                    rowws = searchResult[0].row;
                                    luckysheet.insertRow(rowws + 1);
                                    let vll1=luckysheet.getCellValue(rowws,sysRulez[0].ct);
                                    luckysheet.setCellValue(rowws+1, sysRulez[0].ct, {
                                        "ct": {
                                            "fa": "@",
                                            "t": "n"
                                        }
                                    });
                                    luckysheet.setCellValue(rowws + 1, sysRulez[0].ct, vll1);
                                    let vll2=luckysheet.getCellValue(rowws,parseInt(sysRulez[0].ct)+1);
                                    luckysheet.setCellValue(rowws + 1, parseInt(sysRulez[0].ct)+1, vll2);
                                    //输出部门数量金额



                                    luckysheet.setCellValue(rowws + 1, sysRulez[1].ct, depp);
                                    for (let i = 0; i < sysRules.length; i++) {
                                        luckysheet.setCellValue(rowws + 1, sysRules[i].ct, value[i]);
                                        //修改单元格样式
                                        /*luckysheet.setCellValue(rowws+g, sysRules[i].ct, {
                                        "ct": {
                                            "fa": "General",
                                            "t": "n"
                                        }
                                    });*/
                                    }
                                    //输出单价
                                    luckysheet.setCellValue(rowws + 1, parseInt(sysRules[0].ct) + 1, value[1] / value[0]);
                                    //修改单价样式
                                    /*luckysheet.setCellValue(rowws+g,parseInt(sysRules[0].ct)+1,{
                                    "ct": {
                                        "fa": "0.0000",
                                        "t": "n"
                                    }
                                });*/
                                    config = luckysheet.getConfig(0);
                                    bord.range[0].row = [rowws + 1, rowws + 1];
                                    bord.range[0].column = [0, parseInt(sysRules[sysRules.length - 1].ct)];
                                    config.borderInfo.push(bord);
                                    luckysheet.setConfig(config);
                                    modify=true;
                                } else{
                                    warn++;
                                }
                            });

                                if (warn === map.size) {
                                    throw new Error("导入文件与所选模板规则不匹配");
                                } else if (warn > 0) {
                                    this.$message({
                                        message: "还有"+warn+"条大类未能匹配到",
                                        type: "warning"});
                                }
                                resolve(response.rows);
                                innerResolve(); // 标记当前异步任务完成
                            /*let find1 = luckysheet.find("合计");
                        let number = parseInt(find1[0].row)-1;
                        luckysheet.setCellValue(find1[0].row, sysRules[sysRules.length-1].ct, "=SUM(F2:F"+number+")")*/
                        }).catch(Error => {

                            //必须加,不能删除
                            innerReject(Error); // 异步请求出错
                        });
                            }));

                    }
                        break;
                    default :
                    {
                        let map = new Map();
                        let smallMat = [];
                        try{
                        for (let i = parseFloat(sysRulez[0].re) + 1; i < data.length; i++) {
                            if (data[i][key_i] != null) {
                                let num = data[i][key_i].m;
                                smallMat.push(num);
                            } else {
                                smallMat.push(null);
                            }
                        }
                        } catch(err){
                                throw new Error("导入失败,导入文件与模板规则不匹");
                            }
                        asyncTasks.push(
                            new Promise((innerResolve, innerReject) => {
                                const allNull = smallMat.every(item =>item===null);
                                if (allNull ) {
                                    throw new Error("导入失败,导入文件错误,所选文件与模板规则不匹");
                                }
                                materialConvert(smallMat)
                                    .then(response => {
                                        let array = response.rows;
                                        for (let i = parseFloat(sysRulez[0].re) + 1; i < data.length; i++) {
                                            let values = [];
                                            let index;
                                            if (data[i][key_i] != null) {
                                                for (let j = 0; j < value.length; j++) {
                                                    try{
                                                        let a = parseFloat(data[i][value[j]].v);
                                                        values.push(a);
                                                    }catch (err){
                                                        throw new Error("导入失败,导入文件不匹");
                                                    }

                                                }
                                                //插入多个value的值
                                                     index = smallMat.indexOf(data[i][key_i].m);
                                                let key = array[index];
                                                if (map.has(key)) {
                                                    let oldValues = map.get(key);
                                                    for (let i = 0; i < values.length; i++) {
                                                        values[i] = parseFloat(parseFloat(values[i] + oldValues[i]).toFixed(2));
                                                    }
                                                    map.set(key, values);
                                                } else {
                                                    map.set(key, values);
                                                }
                                            }

                                        }
                                        //循环得到汇总结果

                                        if (map.size === 0) {
                                            throw new Error("导入失败,导入文件错误");
                                        }
                                        let rowws;
                                        let warn = 0;
                                        for (let i = 0; i < sysRules.length; i++) {
                                            map.forEach((value, key) => {
                                                let searchResult;
                                                    searchResult= luckysheet.find(key);
                                                if (searchResult!==undefined && searchResult.length !== 0 && key != null) {
                                                    rowws = searchResult[0].row;
                                                    luckysheet.setCellValue(rowws, sysRules[i].ct, value[i]);
                                                    luckysheet.setCellValue(rowws, sysRules[i].ct, {
                                                        "ct": {
                                                            "fa": "General",
                                                            "t": "n"
                                                        }
                                                    });
                                                } else {
                                                    warn++;
                                                }
                                            });
                                        }
                                        if (warn / sysRules.length === map.size) {
                                            throw new Error("导入文件与所选模板规则不匹配");
                                        } else if (warn > 0) {
                                            this.$message({
                                                message: "还有"+warn/sysRules.length+"条大类未能匹配到",
                                                type: "warning"});
                                        }
                                        resolve(response.rows);
                                        innerResolve(); // 标记当前异步任务完成
                                    }).catch(Error => {

                                        //必须加,不能删除
                                    innerReject(Error); // 异步请求出错
                                });
                            }));
                    }
                        break;
                }
                //切换到想要的sheet
                luckysheet.setSheetActive(0);
                Promise.all(asyncTasks)
                    .then(() => {
                        resolve(); // 所有异步请求执行完成
                    })
                    .catch(Error => {

                        reject(Error); // 异步请求出错
                    });
            });
        },
        /** 保存导入文件和生成文件 */
        submit(contents){

            const name = contents.info.name;
            const obj=contents.sheets;
            let list=[];
            //导入文件内容转json
            let str = JSON.stringify(obj)// 对象转化为字符串
            let objsheet = luckysheet.getAllSheets() // 得到表的数据
            //生成文件转json
            let strsheet = JSON.stringify(objsheet)// 对象转化为字符串
            this.from.templateId=this.dfrom.templateId=tempId;
            this.from.importUuid=this.dfrom.importUuid=uuid1;
            this.from.roleId=this.dfrom.roleId=roleId;
            this.dfrom.historyName=name+'(导入文件)';
            this.dfrom.historyContent=str;
            this.dfrom.identifyingCode=0;

            let date = new Date(this.from.date);

            let fullYear = date.getFullYear();
            let month = ("0" + (date.getMonth() + 1)).slice(-2);
            let datastr = fullYear +"-"+ month;
            let date1 = new Date(datastr);
            this.dfrom.date = date1
            this.from.status=this.dfrom.status=0;
            list.push(this.dfrom);
            this.from.historyName=fileName+'(生成文件)';
            this.from.historyContent=strsheet;
            this.from.identifyingCode=1;
            this.from.date = date1;
            list.push(this.from);

            addInsert(list).then(response=>{
                if(response.code==200){
                    this.$message({
                        message: '保存成功', type: 'success'
                    })
                }
            });


        },
        /** 导出设置 */
        handleExport: debounce(function() {
            // 处理点击事件
            exportExcel(luckysheet.getAllSheets(),fileName,trueORfalse);

            // 清洗数据
            selectActSuppliesHistorydata().then(response => {

                var  data = response.data;

                for (let i = 0; i < data.length; i++) {
                    if(data[i].identifyingCode == 1){
                        /*生成表*/
                        let jsonDataa = JSON.parse(data[i].historyContent);
                        for (let j = 0; j < jsonDataa.length; j++) {
                            let  dataa=window.luckysheet.transToData(jsonDataa[j].celldata);
                            for (let k = 2; k < dataa.length; k++) {
                                if(dataa[k][1] == null){
                                    break;
                                }
                                let a0;
                                let a1;
                                let a3;
                                let a4;
                                let a5;
                                let a6;

                                if(dataa[k][0] != null){
                                    a0= dataa[k][0].v;
                                    if(a0 == undefined){
                                        a0="";
                                    }
                                }

                                if(dataa[k][1] != null){
                                    a1= dataa[k][1].v;
                                    if(a1 == undefined){
                                        a1="";
                                    }
                                }

                                if(dataa[k][3] != null){
                                    a3= dataa[k][3].v;
                                    if(a3 == undefined){
                                        a3="";
                                    }
                                }

                                if(dataa[k][4] != null){
                                    a4= dataa[k][4].v;
                                    if(a4 == undefined){
                                        a4="";
                                    }
                                }

                                if(dataa[k][5] != null){
                                    a5= dataa[k][5].v;
                                    if(a5 == undefined){
                                        a5="";
                                    }
                                }

                                if(dataa[k][6] != null){
                                    a6= dataa[k][6].v;
                                    if(a6 == undefined){
                                        a6="";
                                    }
                                }

                                if(data[i].id != null){
                                    this.froms.hId = data[i].id;
                                    this.froms.projectId =a0;
                                    this.froms.projectName =a1;
                                    this.froms.departmentName =a3;
                                    this.froms.number =a4;
                                    this.froms.nuitPrice =a5;
                                    this.froms.money =a6;
                                    this.froms.createBy = data[i].createBy;
                                    this.froms.date = data[i].date;
                                    addActSuppliesSixMinesSummaryTable(this.froms).then(response => {});
                                }
                            }
                        }
                    }else {
                        /*导入表*/
                        /*let jsonDatab = JSON.parse(data[i].historyContent);
                        for (let j = 0; j < jsonDatab.length; j++) {
                            let  datab=window.luckysheet.transToData(jsonDatab[j].celldata);
                        }*/
                    }
                }
            });

        }, 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;
        }
    }
}
function generateUUID() {
    let array = new Uint32Array(4);
    window.crypto.getRandomValues(array);
    return array.join("-");
}
</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>
