<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.roleName" :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"
          v-hasPermi="['ruoyi-myexcel:myexcel:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-upload
          type="file"
          name="file"
          ref="upload"
          :before-upload="handleFileChange"
          action=''
          :limit="1"
          :file-list="fileList"
          :disabled="disableNextButton"
        >
          <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%;left: 0px; top: 110px; height: 1000px; z-index: 0"
    >
    </div>

  </div>
</template>


<script>

import { getSuppliesTemplate, listSuppliesTemplate,roleList,materialConvert,roleListid} from "@/api/ruoyi-myLuckyexcel/myluckyexcel";

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


var fileName="新建XLSX工作表"; //定义表名
var rule=[];
var tempId;
export default {
  name: "Mymodule",
  data() {
    return {
      //弹出页面的表名
      from_name : "",
      // 是否显示弹出层
      dialogVisible : false,
      selectedOption:'',
      selectedRule:'',
      luckysheetData: '',
      fileList:[],
      disableNextButton: true,
      luckyrule:[],
      depss:[],
      // 表单参数
      form: {},
      // 查询参数
      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;
        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 => {
        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":{}, //工作表保护
            },
          },
          /*{
            "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);

    },

    /** 导入事件*/
    handleFileChange(evt) {
      if (this.disableNextButton) {
        this.$message.warning("请先选择模板再进行导入!");
        return false; // 如果按钮被禁用，提前返回，避免执行下一步操作
      }
      let name = evt.name
      let suffixArr = name.split('.'),
        suffix = suffixArr[suffixArr.length - 1]
      if (suffix !== 'xlsx') {
        this.$message({
          message: "上传格式不正确，请上传xlsx格式文件",
          type: "warning"});
        return
      }
      LuckyExcel.transformExcelToLucky(
          evt,
            function(exportJson) {
              if (exportJson.sheets === null || exportJson.sheets.length === 0) {
                  this.$message({
                      message: "导入失败，请检查上传的文件是否正确",
                      type: "warning"
                  });
                  return
                }
                let sysRulez;
                let sysRules;
                let value=[];
                let map=new Map();
                //获取物料转换的规则
                //
                for(let i=0;i<rule.length;i++){
                    if (rule[i].convertStatus===1){
                        sysRulez = JSON.parse(rule[i].detailContent);
                    }
                    if(rule[i].convertStatus===2){
                        sysRules = JSON.parse(rule[i].detailContent);
                    }
                }
                //获取物料转换的sheet表
                let data=window.luckysheet.transToData(exportJson.sheets[sysRulez[0].se].celldata);
                window.luckysheet.set
                let key_i=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);
                }

                let smallMat=[];
                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);
                    }
                }

                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++) {
                                let a = parseFloat(data[i][value[j]].v);
                                if (isNaN(a)){
                                    a=0;
                                }
                                values.push(a);
                            }
                        }else{
                            break;
                        }
                        //插入多个value的值
                        let index = smallMat.indexOf(data[i][key_i].m);
                        let key = array[index];
                        key = key+"-"+data[i][sysRulez[1].ce].m
                        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);
                        }
                    }
                    //循环得到汇总结果
                    let row;
                        map.forEach((value, key) => {
                            let splitElement = key.split("-");
                            row = luckysheet.find(splitElement[0])[0].row
                            if (splitElement[1] !== 'undefined') {

                                let find = luckysheet.find(splitElement[1])[0];
                                if (find != null && luckysheet.getCellValue(find.row, 0) === 0) {
                                    // for (let i =0;i<value.length;i++) {
                                    //     luckysheet.setCellValue(sysConver[i].rt, sysConver[i].ct, value[i]);
                                    //     luckysheet.setCellValue(sysConver[i].rt, sysConver[i].ct, {
                                    //         "ct": {
                                    //             "fa": "General",
                                    //             "t": "n"
                                    //         }
                                    //     });
                                    // }
                                } else {

                                    let rowindex;
                                    let colindex;
                                    let config;

                                    // let bord={
                                    //     "rangeType": "cell",
                                    //     "value": {
                                    //         "row_index": 0,
                                    //         "col_index": 0,
                                    //         "l": {
                                    //             "style": 1,
                                    //             "color": "#000000"
                                    //         },
                                    //         "r": {
                                    //             "style": 1,
                                    //             "color": "#000000"
                                    //         },
                                    //         "t": {
                                    //             "style": 1,
                                    //             "color": "#000000"
                                    //         },
                                    //         "b": {
                                    //             "style": 1,
                                    //             "color": "#000000"
                                    //         }
                                    //     }
                                    // };

                                    let bord = {
                                        "rangeType": "range",
                                        "borderType": "border-all",
                                        "style": "1",
                                        "color": "#000000",
                                        "range": [{
                                            "row": [0, 0],
                                            "column": [0, 0]
                                        }]
                                    }


                                    let cellValue = luckysheet.getcellvalue(row);
                                    luckysheet.insertRow(row + 1)
                                    luckysheet.setCellValue(row + 1, sysRulez[0].ct, splitElement[0]);
                                    luckysheet.setCellValue(row + 1, sysRulez[0].ct, cellValue[0]);

                                    // config = luckysheet.getConfig(0);
                                    // bord.value.row_index = row+1;
                                    // bord.value.col_index = parseInt(sysRulez[0].ct);
                                    // config.borderInfo.push(bord);
                                    // luckysheet.setConfig(config);
                                    //
                                    // config = luckysheet.getConfig(0);
                                    // bord.value.row_index = row+1;
                                    // bord.value.col_index = parseInt(sysRulez[0].ct)+1;
                                    // config.borderInfo.push(bord);
                                    // luckysheet.setConfig(config);

                                    luckysheet.setCellValue(row + 1, sysRulez[1].ct, splitElement[1]);
                                    luckysheet.setCellValue(row + 1, sysRulez[1].ct, cellValue[2]);

                                    // config = luckysheet.getConfig(0);
                                    // bord.value.row_index = row+1;
                                    // bord.value.col_index = parseInt(sysRulez[1].ct);
                                    // config.borderInfo.push(bord);
                                    // luckysheet.setConfig(config);
                                    if (value[0]===0){
                                        luckysheet.setCellValue(row + 1, parseInt(sysRules[0].ct) + 1, 0);
                                        luckysheet.setCellValue(row + 1, parseInt(sysRules[0].ct) + 1, cellValue[4]);
                                    }else {
                                        luckysheet.setCellValue(row + 1, parseInt(sysRules[0].ct) + 1, value[1] / value[0]);
                                        luckysheet.setCellValue(row + 1, parseInt(sysRules[0].ct) + 1, cellValue[4]);
                                    }
                                    // config = luckysheet.getConfig(0);
                                    // bord.value.row_index = row+1;
                                    // bord.value.col_index = parseInt(sysRules[0].ct)+1;
                                    // config.borderInfo.push(bord);
                                    // luckysheet.setConfig(config);

                                    for (let i = 0; i < value.length; i++) {
                                        luckysheet.setCellValue(row + 1, sysRules[i].ct, value[i]);
                                        luckysheet.setCellValue(row + 1, sysRules[i].ct, {
                                            "ct": {
                                                "fa": "General",
                                                "t": "n"
                                            }
                                        });
                                        luckysheet.setCellValue(row + 1, sysRules[i].ct, cellValue[3]);
                                        // config = luckysheet.getConfig(0);
                                        // bord.value.row_index = row+1;
                                        // bord.value.col_index = parseInt(sysRules[i].ct);
                                        // config.borderInfo.push(bord);
                                        // luckysheet.setConfig(config);
                                    }

                                    config = luckysheet.getConfig(0);
                                    bord.range[0].row = [row + 1, row + 1];
                                    bord.range[0].column = [sysRulez[0].ct, sysRules[sysRules.length - 1].ct];
                                    config.borderInfo.push(bord);
                                    luckysheet.setConfig(config);

                                }
                            }else {
                                luckysheet.setCellValue(row, parseInt(sysRulez[1].ct), "无");
                                if (value[0]===0){
                                    luckysheet.setCellValue(row, parseInt(sysRules[0].ct) + 1, 0);
                                }else {
                                    luckysheet.setCellValue(row, parseInt(sysRules[0].ct) + 1, value[1] / value[0]);
                                }
                                for (let i = 0; i < value.length; i++) {
                                    luckysheet.setCellValue(row, sysRules[i].ct, value[i]);
                                    // config = luckysheet.getConfig(0);
                                    // bord.value.row_index = row+1;
                                    // bord.value.col_index = parseInt(sysRules[i].ct);
                                    // config.borderInfo.push(bord);
                                    // luckysheet.setConfig(config);
                                }

                            }
                        });
                    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(() => {
                    // 处理错误逻辑，这里是一个空的错误处理函数
                    console.log("走到这了,物料转换后续处理出问题了!!");

                });
                //切换到想要的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);
  };
}
</script>

