<template>
    <div class="app-container">
        <el-form  ref="queryForm" size="small" :inline="true" >
            <el-form-item>
                <el-checkbox v-model="numm">是否只比较数值</el-checkbox>
            </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                    v-if="isluckysheet"
                    type="warning"
                    plain
                    icon="el-icon-upload2"
                    size="mini"
                    @click="handleExport"
                >导出</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button v-if="isluckysheet" icon="el-icon-s-opportunity" size="mini" @click="addToMap">生成</el-button>
            </el-col>
            <el-button type="primary" v-if="isDivVisible" @click="uploadFolder">上传旗舰文件夹</el-button>
            <input ref="folderInput" type="file" style="display: none;"  multiple @change="handleFolderSelect">

            <el-button type="primary" v-if="isDivVisible" @click="uploadFolder2">上传浪潮文件夹</el-button>
            <input ref="folderInput2" type="file" style="display: none;"  multiple @change="handleFolderSelect2">

            <el-button type="primary" @click="testdb">开始对比</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery" class="right-float">重置</el-button>
        </el-row>
        <!-- luckysheet容器 -->
        <div
            id="luckysheet" v-if="isluckysheet"
            style="margin: 0px; padding: 0px; position: absolute; width: 100%;left: 0px; top: 105px; height: 75vh; z-index: 0"
        ></div>
        <div v-if="isDivVisible" style="display: flex;">

            <el-table :data="fileName1" style="flex-basis: 50%;">
                <el-table-column prop="name"  label="旗舰版文件名称" width="300">
                    <template slot-scope="scope">
                        <div>{{ scope.row.name }}</div>
                        <div>
                            <el-button type="text" @click="moveUp(scope.$index)" :disabled="scope.$index === 0">上移</el-button>
                            <el-button type="text" @click="moveDown(scope.$index)" :disabled="scope.$index === fileName1.length - 1">下移</el-button>
                            <el-button type="text" @click="duplicate(scope.$index)">复制</el-button>
                            <el-button type="text" @click="deleteFile(scope.$index)">删除</el-button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
            <el-table :data="fileName2" style="flex-basis: 50%;">
                <el-table-column prop="name" label="旗舰版文件名称" width="300">
                    <template slot-scope="scope">
                        <div>{{ scope.row.name }}</div>
                        <div>
                            <el-button type="text" @click="moveUp2(scope.$index)" :disabled="scope.$index === 0">上移</el-button>
                            <el-button type="text" @click="moveDown2(scope.$index)" :disabled="scope.$index === fileName2.length - 1">下移</el-button>
                            <el-button type="text" @click="duplicate2(scope.$index)">复制</el-button>
                            <el-button type="text" @click="deleteFile2(scope.$index)">删除</el-button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
        </div>

    </div>
</template>

<style>
.right-float {
    float: right;
}
</style>
<script>

/*import luckysheet from 'luckysheet'*/
import LuckyExcel from 'luckyexcel'
//导入库export.js 这个文件是es6的，不能在普通的HTML文件直接引入js文件（虽然都是js文件，但是有区别，具体请百度es6与es5）！需要把es6转es5才可以直接引入使用！
import { exportExcel } from '../../../../public/exportExcel';
import {vueScript} from "@/utils/generator/html";


var fileName="新建XLSX工作表"; //定义表名
var data1;
var name1;
var datast;
var namest;
var map=new Map();
var maper=new Map();
export default {
    name: "Mymodule",
    data() {
        return {
            fileName1:[],
            fileName2:[],
            isDivVisible:true,
            isluckysheet:false,
            row:1,
            numm:false,
            //弹出页面的表名
            // 是否显示弹出层
            fileList:[],
            disableNextButton: true,
            // 查询参数
            queryParams: {
                status:0
            },
        };
    },
    created() {

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

        uploadFolder() {
            this.$refs.folderInput.value = ''; // 清空文件选择框的值
            this.$refs.folderInput.click();
        },
        handleFolderSelect(event) {
            const files = event.target.files;
            for(let i = 0; i < files.length; i++){
                this.fileName1.push({name: files[i].name, data: files[i]});
            }
        },
        moveUp(index) {
            if (index > 0) {
                const temp = this.fileName1[index];
                this.fileName1.splice(index, 1);
                this.fileName1.splice(index - 1, 0, temp);
            }
        },
        moveDown(index) {
            if (index < this.fileName1.length - 1) {
                const temp = this.fileName1[index];
                this.fileName1.splice(index, 1);
                this.fileName1.splice(index + 1, 0, temp);
            }
        },
        deleteFile(index) {
            this.fileName1.splice(index, 1);
        },
        isFileNameExists(name) {
            return this.fileName1.some(item => item.name === name);
        },
        // 复制
        duplicate(index) {
            const item = Object.assign({}, this.fileName1[index]);
            const originalName = item.name;
            let newName = originalName;
            let count = 1;

            // 检查是否存在同名文件，如果存在则进行递增命名
            while (this.isFileNameExists(newName)) {
                const dotIndex = originalName.lastIndexOf('.');
                if (dotIndex !== -1) {
                    newName = originalName.slice(0, dotIndex) + ` (${count})` + originalName.slice(dotIndex);
                } else {
                    newName = originalName + ` (${count})`;
                }
                count++;
            }
            item.name = newName;
            this.fileName1.splice(index + 1, 0, item);
            this.fileName1[index+1].copy =`(${count-1})`;
            if (!this.fileName1[index+1].hasOwnProperty('oldname')) {
                let suffixArr = originalName.split('.');
                suffixArr.pop(); // 删除数组中的最后一项，即 '.xlsx'
                const newname = suffixArr.join('.'); // 将数组中剩下的部分通过 . 连接起来
                this.fileName1[index+1].oldname = newname;
            }
        },
        uploadFolder2() {
            this.$refs.folderInput2.value = ''; // 清空文件选择框的值
            this.$refs.folderInput2.click();
        },
        handleFolderSelect2(event) {
            const files = event.target.files;
            for(let i = 0; i < files.length; i++){
                this.fileName2.push({name: files[i].name, data: files[i]});
            }
        },
        moveUp2(index) {
            if (index > 0) {
                const temp = this.fileName2[index];
                this.fileName2.splice(index, 1);
                this.fileName2.splice(index - 1, 0, temp);
            }
        },
        moveDown2(index) {
            if (index < this.fileName2.length - 1) {
                const temp = this.fileName2[index];
                this.fileName2.splice(index, 1);
                this.fileName2.splice(index + 1, 0, temp);
            }
        },
        deleteFile2(index) {
            this.fileName2.splice(index, 1);
        },
        isFileNameExists2(name) {
            return this.fileName2.some(item => item.name === name);
        },
        duplicate2(index) {
            const item = Object.assign({}, this.fileName2[index]);
            const originalName = item.name;
            let newName = originalName;
            let count = 1;
            // 检查是否存在同名文件，如果存在则进行递增命名
            while (this.isFileNameExists2(newName)) {
                const dotIndex = originalName.lastIndexOf('.');
                if (dotIndex !== -1) {
                    newName = originalName.slice(0, dotIndex) + ` (${count})` + originalName.slice(dotIndex);
                } else {
                    newName = originalName + ` (${count})`;
                }
                count++;
            }
            item.name = newName;
            this.fileName2.splice(index + 1, 0, item);
        },
        /** 回车事件和保存提交绑定 */
        handleEnter(event) {
            if (event.keyCode === 13) {
                event.preventDefault(); // 阻止默认的回车事件
                // 触发确定操作
                this.testdb();
            }
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.isDivVisible = true;
            luckysheet.destroy();
            this.isluckysheet = false;
            fileName="新建XLSX工作表";
            this.disableNextButton='';
            this.fileName1=[];
            this.fileName2=[];
            this.row=1;
            datast='';
            namest='';
            map.clear();
            maper.clear();
            this.numm=false;
            this.$refs.folderInput.value = ''; // 清空文件选择框的值
            this.$refs.folderInput2.value = ''; // 清空文件选择框的值
        },
        /** 生成标签*/
        addToMap(){
            map.forEach((value,key)=>{
                for(let i=0;i<value.length;i++){
                    let row=parseInt(value[i][0])-1;
                    let cell=this.stringTonum(value[i][1])-1;
                    //let row=value[i][0]-1,cell=value[i][1]-1;
                    let sd=luckysheet.getCellValue(row,cell,{type:"bg"});
                    //用批注进行比较的时候把下面的!==判断去掉
                    //let sd=luckysheet.getCellValue(row,cell,{type:"ps"});
                    if(sd===null || sd!=="#e85f61"){
                        luckysheet.setCellValue(row, cell, {bg: "#e85f61"})
                        luckysheet.setCellValue(row, cell, {bg: "#e85f61"})

                        /*  luckysheet.setCellValue(row, cell, {
                               ps: { //批注
                                   "left": 92, //批注框左边距
                                   "top": 10, //批注框上边距
                                   "width": 91, //批注框宽度
                                   "height": 48, //批注框高度
                                   "value": key+"表有误", //批准内容
                                   "isshow": false //批注框为显示状态
                               }
                        })*/

                        maper.set("("+(row+1)+","+value[i][1]+")",1);
                    }else{
                        //let sd=luckysheet.getCellValue(row,cell,{type:"ps"}).value;
                        /*luckysheet.setCellValue(row, cell, {
                            ps: { //批注
                                "left": 92, //批注框左边距
                                "top": 10, //批注框上边距
                                "width": 91, //批注框宽度
                                "height": 48, //批注框高度
                                "value": sd+'\n；'+key+"表有误", //批准内容
                                "isshow": false //批注框为显示状态
                            }
                        })*/
                        maper.set("("+(row+1)+","+value[i][1]+")",maper.get("("+(row+1)+","+value[i][1]+")")+1);
                    }
                }

            })
            let row;
            let num=luckysheet.getSheet().data.length;
            let data=luckysheet.getSheet().data;
            for(let i=0;i<num;i++){
                if(data[i][0]===null){
                    row=i;
                    break;
                }
            }
            if (row === undefined){
                row = num;
            }
            //生成多少条数据添加多少行
            let asd=maper.size+map.size;
            if(row+asd>=num){
                for (let i=0;i<=row+asd-num;i++){
                    luckysheet.insertRow(row + 1);
                }
                luckysheet.insertRow(row + 1);
            }
            row=row+1;
            let k=0;
            for (let [key,value] of map.entries()) {

                let a="("+value.join("),(")+")";
                luckysheet.setCellValue(row+k,0,key);
                luckysheet.setCellValue(row+k,1 ,a);
                k++
            }
            let froms = Array.from(maper);
            froms.sort((a, b) => {
                return b[1] - a[1];
            });
            for (let i=0;i<froms.length;i++){
                luckysheet.setCellValue(row+k,0,froms[i][0]);
                luckysheet.setCellValue(row+k,1 ,froms[i][1]);
                k++;
            }
        },
        /** 开始对比功能 */
        async testdb(){
            if(this.fileName1.length!==0 && this.fileName2.length!==0){
                if ( this.fileName1.length === this.fileName2.length ){
                    this.isDivVisible=false;
                    this.isluckysheet = true;
                    for (let i =0;i<this.fileName1.length;i++){
                        let sda=this.fileName1;
                        const name = this.fileName1[i].name;//ACCOUNT通用 (1) (1).xlsx
                        let suffixArr = name.split('.');
                        suffixArr.pop(); // 删除数组中的最后一项，即 '.xlsx'
                        const newname = suffixArr.join('.'); // 将数组中剩下的部分通过 . 连接起来
                        const oldname = this.fileName1[i].oldname;//ACCOUNT通用.xlsx
                        let extraPart
                        if(oldname!==undefined){
                            extraPart = newname.replace(oldname, '').trim(); // 去掉前后空格
                        }
                        //const newcode = extraPart ? extraPart : '没有多余的部分';
                        await this.handleFileChange(this.fileName1[i].data,extraPart);
                        await this.handleFileChange1(this.fileName2[i].data);
                    }
                    luckysheet.create({
                        container: 'luckysheet', //luckysheet is the container id
                        title: namest,
                        lang: 'zh', // 设定表格语言
                        showinfobar: false,
                        data: datast,
                    });
                    luckysheet.setSheetName(name1);
                }else {
                    this.msgError("旗舰版文件与浪潮文件数量不匹配，请检查后在对比");
                }
            }else{
                this.msgError("请先上传对比文件!!!");
            }

        },
        /** 导入事件*/
         handleFileChange(evt,copy) {
            this.disableNextButton=false;
            let name = evt.name
            let suffixArr = name.split('.'),
                suffix = suffixArr[suffixArr.length - 1]
            if (suffix !== 'xlsx') {
                this.$message({
                    message: "上传格式不正确，请上传xlsx格式文件",
                    type: "warning"});
                return
            }
            let exx;
            return new Promise((resolve, reject) => {
            LuckyExcel.transformExcelToLucky(
                evt,
                (exportJson)=> {
                    if (exportJson.sheets === null || exportJson.sheets.length === 0) {
                        this.$message({
                            message: "导入失败，请检查上传的文件是否正确",
                            type: "warning"
                        });
                        return
                    }
                    data1=exportJson.sheets[0];
                    if(copy!=undefined){
                        name1=exportJson.sheets[0].name+copy;
                    }else{
                        name1=exportJson.sheets[0].name;
                    }
                    //console.log(name1);
                    datast=exportJson.sheets;
                    namest=exportJson.info.name;
                    let suffixArr = exportJson.info.name.split('.');
                    fileName = suffixArr[0];
                    exx=exportJson.sheets;
                    resolve(exx);
                })
            });

        },

        handleFileChange1(evt) {
            let name = evt.name
            let suffixArr = name.split('.'),
                suffix = suffixArr[suffixArr.length - 1];
            name=suffixArr[0]
            if (suffix !== 'xlsx') {
                this.$message({
                    message: "上传格式不正确，请上传xlsx格式文件",
                    type: "warning"});
                return
            }
            return  new Promise((resolve, reject) => {
                LuckyExcel.transformExcelToLucky(
                    evt,
                    (exportJson) => {
                        if (exportJson.sheets === null || exportJson.sheets.length === 0) {
                            this.$message({
                                message: "导入失败，请检查上传的文件是否正确",
                                type: "warning"
                            });
                            return
                        }
                        let ddd = data1;
                        let as = 0;
                        let d1 = window.luckysheet.transToData(ddd.celldata);
                        let d2 = window.luckysheet.transToData(exportJson.sheets[0].celldata);
                        let r1 = d1.length, r2 = d2.length, c1 = d1[0].length, c2 = d2[0].length;
                        let row = (r1 <= r2) ? r1 : r2;
                        let cell = (c1 <= c2) ? c1 : c2;
                        let array = [];
                        let r = this.row - 1;
                        try{


                        for (let i = r; i < row; i++) {
                            for (let j = 0; j < cell; j++) {
                                //第一个表的单元格为null直接跳出
                                if(d1[i][j]==null ){
                                    continue
                                }
                                //第二个表的单元格为null直接跳出
                                if(d2[i][j]==null ){
                                    continue
                                }
                                //第一个表内数据为0 且 第二个表只有样式内部为空
                                if(d2[i][j].v==0 && d1[i][j].v==undefined ){
                                    continue
                                }
                                //第一个表内数据为0 且 第二个表只有样式内部为空
                                if( d1[i][j].v==0 && d2[i][j].v==undefined ){
                                    continue
                                }
                                // 第一个表内数据为string型 且 第二个表只有样式内部为空
                                /*if((typeof(d1[i][j].v)=="string" && d2[i][j].v==undefined)){
                                    continue
                                }*/
                                //第一个表为合并单元格 且第二个内没有值
                                if(d1[i][j].mc!=undefined &&d2[i][j].v==undefined){
                                    continue
                                }
                                //第二个表为合并单元格 且第一个内没有值
                                if(d2[i][j].mc!=undefined &&d1[i][j].v==undefined){
                                    continue
                                }
                                if((isNaN(d1[i][j].v) && d2[i][j].v==undefined)){

                                }
                                // 第二个表内数据为string型 且 第一个表只有样式内部为空
                                if(isNaN(d2[i][j].v)&& d1[i][j].v==undefined){

                                }
                                // 没有选只比较数值 且 第一个表内数据为string型 且 第二个表内数据位string型
                                if(this.numm!=false &&(isNaN(d1[i][j].v)&&isNaN(d2[i][j].v))){
                                    continue;
                                }
                                // 两个表的值都是0
                                if(d1[i][j].v==0 && d2[i][j].v==0 ){
                                    continue
                                }
                                // 两个表都是只有样式没有数据
                                if (d1[i][j].v == undefined && d2[i][j].v == undefined) {

                                } else if (d1[i][j].v == undefined || d2[i][j].v == undefined) {
                                    as++
                                    let s = this.numToString(j + 1);
                                    array.push([i + 1, s]);
                                    //array.push([i+1,j+1]);
                                } else {
                                    if (d1[i][j].v != d2[i][j].v) {

                                        as++
                                        let s = this.numToString(j + 1);
                                        array.push([i + 1, s]);
                                    }
                                }
                            }
                        }
                        map.set(name1, array);
                        if (as > 0) {
                            this.$message({
                                message: "导入完成,本次导入共发现" + as + "条不同数据",
                                type: "warning"
                            });
                        } else {
                            this.$message({
                                message: "导入完成,本次导入未发现不同数据",
                                type: "success"
                            });
                        }
                        }catch (err){
                            this.$message({
                                message: "导入失败,导入文件与对比文件有所不匹",
                                type: "error"});
                        }
                        data1 = '';
                        ddd = '';
                        resolve(data1);
                    })
            });
        },
        /** 导出设置 */
        handleExport: debounce(function() {
            // 处理点击事件
            exportExcel(luckysheet.getSheet(),fileName+"(对比后数据)")
        }, 500), // 设置延迟时间，单位为毫秒
        numToString(numm){
            let char=[];
            char.length = 0;
            let numToStringAction = function(nnum){
                let num = nnum - 1;
                let a = parseInt(num / 26);
                let b = num % 26;
                char.push(String.fromCharCode(64 + parseInt(b+1)));
                if(a>0){
                    numToStringAction(a);
                }
            }
            numToStringAction(numm);
            return char.reverse().join("");
        },
        stringTonum(a) {
            var str = a.toLowerCase().split("");
            var num = 0;
            var al = str.length;
            var getCharNumber = function (charx) {
                return charx.charCodeAt() - 96;
            };
            var numout = 0;
            var charnum = 0;
            for (var i = 0; i < al; i++) {
                charnum = getCharNumber(str[i]);
                numout += charnum * Math.pow(26, al - i - 1);
            }
            return numout;
        },

    }
// 配置项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);
    };
}
</script>
