<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=[];
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();

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

    },
    /** 下拉选和页面luckysheet绑定 */
    handleOptionChange() {
      this.selectedRule='';
      this.disableNextButton = this.selectedRule === '';
      //根据选中的下拉选项值获取相应的信息
      getSuppliesTemplate(this.selectedOption).then(response => {
        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() {
      //刷新下拉选框内容
      this.selectedOption='';
      this.disableNextButton='';
      this.selectedRule='';
      fileName="新建XLSX工作表";
      //刷新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
          }
          console.log("导入数据的规则是:"+rule);
          //获取物料转换的规则
          let sysRulez = JSON.parse(rule[0].detailContent);
          //获取物料转换的sheet表
          let data=window.luckysheet.transToData(exportJson.sheets[sysRulez[0].se].celldata);
          let map=new Map();
          //let key_i=data[sysRulez[0].re][sysRulez[0].ce].m;
          let key_i=sysRulez[0].ce;
          //获取物料转换的数据
          let value=[];
          let sysRules = JSON.parse(rule[1].detailContent);
          for (let i=0;i<sysRules.length;i++){
            //value.push(data[sysRules[i].re][sysRules[i].ce].m);
            value.push(sysRules[i].ce);
          }
          console.log("value的值为:"+value);
          let smallMat=[];
          for(let i=2;i<data.length;i++){
            if(data[i][key_i]!=null){
              let num=data[i][key_i].m;
              smallMat.push(num);
            }else{
              smallMat.push(null);
            }
          }
          console.log(smallMat);
          materialConvert(smallMat).then(response => {
            let array = response.rows;
            console.log(array);
            //luckysheet.setCellValue(12, 1, {bg:"#FF0000"})
            for (let i =2; 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);
                  values.push(a);
                }
              }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(values[i] + oldValues[i]).toFixed(2));
                }
                map.set(key, values);
              } else {
                map.set(key, values);
              }
            }
            //循环得到汇总结果
            console.log(map);
            let rowws;
            for(let i=0;i<sysRules.length;i++){
              map.forEach((value, key) => {
                rowws=luckysheet.find(key)[0].row;
                luckysheet.setCellValue(rowws, sysRules[i].ct,value[i]);
                luckysheet.setCellValue(rowws, sysRules[i].ct,{"ct": {
                    "fa": "General",
                    "t": "n"
                  }});
              });
            }
          }).catch(() => {
            // 处理错误逻辑，这里是一个空的错误处理函数
            console.log("走到这了,物料转换后续处理出问题了!!");
            this.$message.error('文件导入失败!发生未知错误,请重试!!');
          });
          //切换到想要的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>

