<template>
    <div class="templateBox">
        <div style="flex: 1">
            <!-- @mouseenter="enter" @mouseleave="out" -->
            <!-- <div v-show="flag" :style="!editShow ? ' visibility: hidden;' : ''">
        <div id="menu" v-show="menusStyle">
          <div class="menu__item" @click="unitBinding">绑定参数单位</div>
          <div class="menu__item" @click="binding">绑定参数指标</div>
        </div>
      </div> -->

            <!-- <div id="cascader" class="cascader" :style="cascader?' visibility: hidden;':''"> 123</div>   height: ${vh - 55}px; -->
            <div class="box" :style="'height:' + vh + 'px;'">
                <div class="elButton pd10">
                    <!-- <el-button @click="getData">获取数据</el-button> -->
                    <el-upload
                        name="file"
                        ref="upload"
                        action=" "
                        :limit="1"
                        accept=".doc,.docx,.xls,.xlsx,.pdf,.txt"
                        :file-list="fileList"
                        :before-upload="beforeUpload"
                    >
                        <el-button slot="trigger" icon="el-icon-upload2" size="small" type="primary">
                            导入excel
                        </el-button>
                    </el-upload>
                    <el-button
                        @click="downloadExcel"
                        class="buttons"
                        size="small"
                        type="primary"
                        icon="el-icon-download"
                    >
                        导出excel
                    </el-button>

                    <el-button
                        v-if="!flag"
                        slot="trigger"
                        size="small"
                        type="primary"
                        style="margin-left: auto"
                        @click="$emit('close')"
                    >
                        <svg-icon class="error" icon-class="back" />
                        返回
                    </el-button>
                </div>

                <div
                    id="luckysheet"
                    style="width: 100%; padding: 0; margin: 0"
                    :style="`height:95%;cursor: pointer`"
                ></div>
            </div>
        </div>
        <div v-if="flag" class="templateRight">
            <el-button
                slot="trigger"
                size="small"
                type="primary"
                style="margin-left: 220px; margin-bottom: 10px"
                @click="dialogFormVisible = true"
                icon="el-icon-check"
            >
                保存
            </el-button>
            <el-button slot="trigger" size="small" type="primary" @click="$emit('close')">
                <svg-icon class="error" icon-class="back" />
                返回
            </el-button>
            <!-- <el-form label-width="100px"> -->
            <!-- <el-form-item label="选择模板:">
          <el-select
            v-show="editShow"
            @change="Templates"
            v-model="Template"
            placeholder="请选择模板"
          >
            <el-option
              v-for="item in TemplateList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item> -->
            <!-- <el-form-item label="Sheet名称:">
          <el-input
            v-show="editShow"
            placeholder="请输入表格名称"
            v-model.trim="input"
            clearable
            @blur="blur"
            @keyup.enter.native="keyup"
          >
          </el-input>
        </el-form-item> -->
            <!-- <el-form-item label="绑定单位:"> -->

            <!-- :show-all-levels="false" -->
            <!-- </el-form-item>
        <el-form-item label="绑定指标:"> -->

            <!-- :show-all-levels="false" -->
            <!-- </el-form-item> -->
            <!-- </el-form> -->
            <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
                <el-tab-pane label="数据单位" name="first">
                    <el-form label-width="100px" :model="formdata">
                        <el-form-item label="绑定数据单位:">
                            <el-cascader
                                style="width: 100%"
                                :popper-append-to-body="false"
                                ref="cascaderUnit"
                                placeholder="请选择数据单位"
                                v-model="value1"
                                :options="unitList"
                                filterable
                                @change="unitHandleChange"
                                :props="{
                                    value: 'code',
                                    label: 'name'
                                }"
                            ></el-cascader>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
                <el-tab-pane label="数据指标" name="second">
                    <el-form label-width="100px">
                        <el-form-item label="绑定数据指标:">
                            <el-cascader
                                style="width: 100%"
                                :popper-append-to-body="false"
                                ref="cascaderUnit"
                                placeholder="请选择数据指标"
                                v-model="value"
                                :options="options"
                                filterable
                                @change="handleChange"
                                :props="{
                                    value: 'name',
                                    label: 'showName'
                                }"
                            ></el-cascader>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
                <el-tab-pane label="合格率判定" name="third">
                    <el-form label-width="100px">
                        <el-form-item label="绑定合格率:">
                            <el-cascader
                                style="width: 100%"
                                :popper-append-to-body="false"
                                ref="cascaderhgl"
                                placeholder="请选择数据合格率"
                                v-model="valuehgl"
                                :options="optionshgl"
                                filterable
                                @change="handleChangehgl"
                                :props="{
                                    value: 'name',
                                    label: 'showName'
                                }"
                            ></el-cascader>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
                <el-tab-pane label="监测点台账指标" name="fourth">
                    <el-form label-width="100px">
                        <el-form-item label="绑定监测点:">
                            <el-cascader
                                style="width: 100%"
                                :popper-append-to-body="false"
                                ref="cascaderjcd"
                                placeholder="请选择监测点台账"
                                v-model="valuejcd"
                                :options="optionsjcd"
                                filterable
                                @change="handleChangejcd"
                                :props="{
                                    value: 'name',
                                    label: 'showName'
                                }"
                            ></el-cascader>
                        </el-form-item>
                        <!-- <el-form-item label="绑定国标限值:">
              <el-cascader  style="width:100%"
                :popper-append-to-body="false"
                ref="cascaderxz"
                placeholder="请选择国标限值"

                v-model="valuexz"
                :options="optionsxz"
                filterable

                :props="{
                  value: 'name',
                  label: 'showName',
                }"
              ></el-cascader>
           </el-form-item> -->
                    </el-form>
                </el-tab-pane>
            </el-tabs>
        </div>
        <el-dialog
            :close-on-click-modal="false"
            :title="title"
            :visible.sync="dialogFormVisible"
            width="30%"
            :before-close="closeDialog"
        >
            <el-row :gutter="10">
                <el-form :model="formdata" label-width="100px" :rules="rules" ref="ruleForm">
                    <el-form-item label="模板名称:" prop="templateName" style="margin-bottom: 20px">
                        <el-input placeholder="模板名称" v-model="formdata.templateName" style="width: 100%"></el-input>
                    </el-form-item>
                    <el-form-item
                        class="top"
                        label="部门:"
                        prop="valueTitle"
                        v-if="title != '修改报表模板'"
                        style="margin-bottom: 20px"
                    >
                        <el-cascader
                            placeholder="请选择部门"
                            style="width: 100%"
                            v-model="formdata.valueTitle"
                            :options="formdata.options"
                            :show-all-levels="false"
                            collapse-tags
                            :props="{
                                multiple: true,
                                value: 'id',
                                label: 'name'
                            }"
                        ></el-cascader>
                    </el-form-item>

                    <el-form-item class="top" label="模板类型:" prop="reportType" style="margin-bottom: 20px">
                        <el-select style="width: 100%" v-model="formdata.reportType" placeholder="请选择模板类型">
                            <el-option
                                v-for="item in classificationData"
                                :key="item.id"
                                :label="item.label"
                                :value="item.id"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item class="top" label="报表类型:" prop="reportForm" style="margin-bottom: 20px">
                        <el-select style="width: 100%" v-model="formdata.reportForm" placeholder="请选择报表类型">
                            <el-option
                                v-for="item in reportFormList"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            ></el-option>
                        </el-select>
                    </el-form-item>

                    <el-row></el-row>
                </el-form>
            </el-row>
            <span slot="footer" class="dialog-footer">
                <el-button @click="closeDialog()">取 消</el-button>
                <el-button type="primary" @click="preservation('ruleForm')">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
import LuckyExcel from 'luckyexcel'
import { dicData } from '@/assets/commjs/dictypeData'
import jquery from 'jquery'
import { exportExcel } from '@/views/components/luckyexcel/export'
import { getExcel, getIndex, codeDicTree } from '@/api/luckyexcel.js'

import {
    addTemplate,
    dateTemplateup,
    getCustomReportTemplateById,
    viewCustomReportTemplateById,
    targetLimitChooseTree,
    terminalChooseTree
} from '@/api/templateConfiguration'
import { pvTree } from '@/api/AccountOperation'
export default {
    components: {},
    props: ['title', 'id', 'valList'],
    data() {
        return {
            activeName: 'first',
            zoom: '', //图表焦点校验
            flag: true,
            classificationData: [
                {
                    label: '电能质量报表类型',
                    id: '1'
                },
                {
                    label: '用能报表类型',
                    id: '2'
                }
            ],
            unitList: [],
            options: [],
            valuehgl: '',
            optionshgl: [],
            valuejcd: '',
            optionsjcd: [],
            valuexz: '',
            optionsxz: [],
            formdata: {
                value: '',
                props: '',
                valueTitle: '',
                accordion: false,
                defaultExpandedKey: [],
                reportType: '',
                reportForm: '',
                //区域
                options: [],
                valuehgl: '',
                optionshgl: [],
                valuejcd: '',
                optionsjcd: [],
                valuexz: '',
                optionsxz: [],
                default: {
                    value: 'id',
                    children: 'children',
                    label: 'name'
                },
                templateName: ''
            },
            reportFormList: [
                {
                    value: '1',
                    label: '分析报表'
                },
                {
                    value: '2',
                    label: '统计报表'
                },
                {
                    value: '3',
                    label: '自定义报表'
                }
            ],
            rules: {
                valueTitle: [
                    {
                        required: true,
                        message: '内容不能为空',
                        trigger: 'blur'
                    }
                ],

                templateName: [
                    {
                        required: true,
                        message: '内容不能为空',
                        trigger: 'blur'
                    }
                ],
                reportType: [
                    {
                        required: true,
                        message: '内容不能为空',
                        trigger: 'change'
                    }
                ],
                reportForm: [
                    {
                        required: true,
                        message: '内容不能为空',
                        trigger: 'change'
                    }
                ]
            },
            currentYearProportion: '',
            vh: undefined,
            fileList: [],
            activeName: 'first',
            menusStyle: false,
            cascader: true,
            unit: true,
            options: [],
            dialogFormVisible: false,
            Template: '', //模板数据
            zoom: null,
            TemplateList: [
                {
                    value: '选项1',
                    label: '模板1'
                },
                {
                    value: '选项2',
                    label: '模板2'
                },
                {
                    value: '选项3',
                    label: '模板3'
                }
            ],
            name: '', //表格查询数据
            editShow: true, //编辑控制按钮
            value: [],
            value1: [],
            input: '', //自定义表格头
            showtoolbar: true, //富文本框头部显示
            cellRightClickConfig: {
                copy: true, // 复制
                copyAs: true, // 复制为
                paste: true, // 粘贴
                insertRow: true, // 插入行
                insertColumn: true, // 插入列
                deleteRow: true, // 删除选中行
                deleteColumn: true, // 删除选中列
                deleteCell: true, // 删除单元格
                hideRow: true, // 隐藏选中行和显示选中行
                hideColumn: true, // 隐藏选中列和显示选中列
                rowHeight: true, // 行高
                columnWidth: true, // 列宽
                clear: true, // 清除内容
                matrix: true, // 矩阵操作选区
                sort: true, // 排序选区
                filter: true, // 筛选选区
                chart: true, // 图表生成
                image: true, // 插入图片
                link: true, // 插入链接
                data: true, // 数据验证
                cellFormat: true // 设置单元格格式
            }, //控制右键菜单
            list: [
                {
                    name: 'Cell',
                    index: 0,
                    defaultRowHeight: 27,
                    defaultColWidth: 105,
                    chart: [] //图表配置
                }
            ],
            replace: []
        }
    },
    created() {
        this.getIndexs()
        this.gettreedata()
        this.getdievs()
        this.getclassificationData()
    },

    mounted() {
        this.zoom = 1 / document.body.style.zoom
        window.addEventListener('resize', () => {
            this.zoom = 1 / document.body.style.zoom
        })

        document.getElementsByClassName('el-cascader-panel')[0].style.maxHeight = '400px'
        this.currentYearProportion = this.$route.params
        // console.log(this.currentYearProportion instanceof Array,this.currentYearProportion,'this.currentYearProportion')
        // if(this.currentYearProportion instanceof Array){
        //  this.edit()
        // }

        for (const key in this.currentYearProportion) {
            if (key == 'currentYearProportion') {
                this.edit()
            }
        }
        this.getExcels()
        let _this = this
        this.setHeight()
        window.addEventListener('resize', this.setHeight)

        // 右击
        window.oncontextmenu = function (e) {
            //取消默认的浏览器自带右键
            e.preventDefault()
            //获取我们自定义的右键菜单
            let menu = document.getElementById('menu')
            let menuItem = document.getElementById('luckysheet-cols-rows-data').clientWidth
            let menus = document.getElementById('luckysheet-rightclick-menu')

            //根据事件对象中鼠标点击的位置,进行定位
            menu.style.left = menus.offsetLeft - 209 + 'px'
            menu.style.top = menus.offsetTop - 8 + 'px'
            menu.style.width = menuItem + 'px'
            let res = document.getElementById('luckysheet-rightclick-menu').style.display
            if (res == 'block') {
                _this.menusStyle = true
            } else {
                _this.menusStyle = false
            }
        }
        // 左击
        jquery(document).ready(function () {
            if (document.getElementById('luckysheet-rightclick-menu') != null) {
                jquery(document).click(function () {
                    // let res = document.getElementById("luckysheet-rightclick-menu").style.display;

                    // if (res == "block") {
                    //   _this.menusStyle = true;
                    //   _this.binding()
                    //   _this.unitBinding()

                    // } else {
                    //   _this.menusStyle = false;
                    //   _this.binding()
                    //   _this.unitBinding()
                    // }

                    if (_this.activeName == 'first') {
                        _this.unitBinding()
                    }
                    if (_this.activeName == 'second') {
                        _this.binding()
                    }
                })
            } else {
                jquery(document).click(function () {
                    if (_this.activeName == 'first') {
                        _this.unitBinding()
                    }
                    if (_this.activeName == 'second') {
                        _this.binding()
                    }
                })
            }
        })
        window.addEventListener('dblclick', function () {
            // alert('双击了')
            var donm = document.getElementsByClassName('luckysheet-input-box')
            //donm.style.border = 'red 2px solid'
            // console.log('+++++++++++++++',donm)
        })
    },
    beforeDestroy() {
        window.removeEventListener('resize', this.setHeight)
    },
    methods: {
        setHeight() {
            this.vh = window.sessionStorage.getItem('appheight') - 20
        },
        closeDialog() {
            this.dialogFormVisible = false
            this.resetForm()
        },
        // 表单重置
        resetForm() {
            if (this.$refs['ruleForm']) {
                this.$refs['ruleForm'].resetFields()
            }
        },
        handleClick(tab, event) {
            //console.log(tab, event);
            this.activeName = tab.name
        },
        // 获取指标参数
        async getIndexs() {
            codeDicTree({
                code: 'Device_Unit'
            }).then(res => {
                this.unitList = this.getTreeData(res.data)
            })
            let { data } = await getIndex()
            //  console.log(data, "aaaa");
            // data[50].children[47].children[0].name='AAA1'
            this.options = data
            pvTree().then(res => {
                // console.log(res);
                if (res.code == 'A0000') {
                    this.formdata.options = this.getTreeData(res.data)
                }
            })
        },
        async gettreedata() {
            let { data } = await targetLimitChooseTree()
            this.optionshgl = data
        },
        async getdievs() {
            let { data } = await terminalChooseTree()
            this.optionsjcd = data
        },
        getTreeData(data) {
            // 循环遍历json数据
            for (var i = 0; i < data.length; i++) {
                if (data[i].children.length < 1) {
                    // children若为空数组，则将children设为undefined
                    data[i].children = undefined
                } else {
                    this.getTreeData(data[i].children)
                }
            }
            return data
        },

        // 获取 数据
        async getExcels() {
            let _this = this
            if (this.title == '修改报表模板') {
                const { data } = await getCustomReportTemplateById({ id: this.id })
                // await jquery.getJSON(data.content, null, function (list) {
                //   _this.list = list;
                // });
                viewCustomReportTemplateById({ id: this.id }).then(Response => {
                    _this.list = Response
                    this.edit()
                })
                // eval(data.valueTitle).forEach((item) => {
                //   console.log(123, item[item.length - 1] == this.valList.deptId);
                //   if (item[item.length - 1] == this.valList.deptId)

                //     this.formdata.valueTitle = [item];
                //   return;
                // });

                this.formdata.templateName = data.name
                this.formdata.createby = data.createby
                this.formdata.deptId = data.deptId
                this.formdata.reportType = data.reportType
                this.formdata.reportForm = data.reportForm
                this.formdata.valueTitle = eval(data.valueTitle)
            } else if (this.title == '模板内容') {
                this.flag = false
                this.showtoolbar = false
                this.cellRightClickConfig = {
                    copy: false, // 复制
                    copyAs: false, // 复制为
                    paste: false, // 粘贴
                    insertRow: false, // 插入行
                    insertColumn: false, // 插入列
                    deleteRow: false, // 删除选中行
                    deleteColumn: false, // 删除选中列
                    deleteCell: false, // 删除单元格
                    hideRow: false, // 隐藏选中行和显示选中行
                    hideColumn: false, // 隐藏选中列和显示选中列
                    rowHeight: false, // 行高
                    columnWidth: false, // 列宽
                    clear: false, // 清除内容
                    matrix: false, // 矩阵操作选区
                    sort: false, // 排序选区
                    filter: false, // 筛选选区
                    chart: false, // 图表生成
                    image: false, // 插入图片
                    link: false, // 插入链接
                    data: false, // 数据验证
                    cellFormat: false // 设置单元格格式
                }
                // const { data } = await getCustomReportTemplateById({ id: this.id });
                // await jquery.getJSON(data.content, null, function (list) {
                //   _this.list = list;
                // });
                viewCustomReportTemplateById({ id: this.id }).then(Response => {
                    _this.list = Response
                    this.edit()
                })
            }
            setTimeout(() => {
                // this.init();
                this.edit()
            }, 0)
        },
        // 初始化插件
        init() {
            let options = {
                container: 'luckysheet', //luckysheet为容器id
                title: '',
                lang: 'zh',
                showinfobar: false,
                cellRightClickConfig: this.cellRightClickConfig,
                showtoolbar: this.showtoolbar,
                // column:8,
                // row:7,
                showtoolbarConfig: {
                    textRotateMode: false // '文本旋转方式'
                },

                data: this.list
            }
            luckysheet.create(options)
        },

        beforeUpload(file) {
            //console.log("file", file);
            let _this = this
            // //   let suffix = this.getSuffix(file.name);
            //   if (suffix !== "xlsx") {
            //     this.$message.error("文件格式只能是.xlsx");
            //     return false;
            //   }
            luckysheet.destroy() // 先销毁当前容器
            LuckyExcel.transformExcelToLucky(file, function (exportJson, luckysheetfile) {
                if (exportJson.sheets == null || exportJson.sheets.length == 0) {
                    this.$message.warning('读取excel文件内容失败,目前不支持xls文件!')
                    return
                }
                exportJson.sheets.forEach(item => {
                    // item.celldata = []
                    // item.data = []
                    item.celldata.forEach(k => {
                        k.v.ct.s ? (k.v.v = k.v.ct.s[0].v) : ''
                        k.v.ct.s ? (k.v.m = k.v.ct.s[0].v) : ''
                    })
                })
                let options = exportJson.sheets
                //  console.log(`000`, exportJson.sheets);
                luckysheet.create({
                    // container: "luckysheet", //luckysheet is the container id
                    // showinfobar: false,
                    // data: exportJson.sheets,
                    // title: exportJson.info.name,
                    // userInfo: exportJson.info.name.creator,
                    container: 'luckysheet', //luckysheet为容器id
                    title: exportJson.info.name,
                    lang: 'zh',
                    showinfobar: false,
                    cellRightClickConfig: _this.cellRightClickConfig,
                    showtoolbar: _this.showtoolbar,
                    // column:8,
                    // row:7,
                    showtoolbarConfig: {
                        textRotateMode: false // '文本旋转方式'
                    },

                    data: options //exportJson.sheets,
                })
            })
        },

        getFlie() {
            //请求接口  获取参数
            downloadPDF({ filePath: 'xxxx-7388ec99358e.xlsx' }).then(res => {
                //这里需要将获取到的base64 转成 file
                let filetext = this.changefile(res.data, 'spling.xlsx')
                // console.log(filetext);

                //主要功能代码
                luckysheet.destroy() // 先销毁当前容器
                LuckyExcel.transformExcelToLucky(filetext, function (exportJson, luckysheetfile) {
                    if (exportJson.sheets == null || exportJson.sheets.length == 0) {
                        this.$message.warning('读取excel文件内容失败,目前不支持xls文件!')
                        return
                    }

                    luckysheet.create({
                        container: 'luckysheet', //luckysheet is the container id
                        showinfobar: false,
                        data: exportJson.sheets,
                        title: exportJson.info.name,
                        userInfo: exportJson.info.name.creator
                    })
                })
            })
        },
        changefile(dataurl, filename) {
            var bstr = window.atob(dataurl)
            var n = bstr.length

            var u8arr = new Uint8Array(n)
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n)
            }
            return new File([u8arr], filename, {
                type: 'application/vnd.ms-excel'
            })
        },
        // 获取当前表格信息
        getData() {
            //  luckysheet.setWorkbookName('测试' )
            // luckysheet.setRangeShow({row:[3,4]})
            // 获取表格显示数据
            // console.log(luckysheet.getAllSheets());
            // console.log(JSON.stringify(luckysheet.getAllSheets()));
        },
        // 下载表格
        downloadExcel() {
            // const value = this.selected;;
            //console.log("数据对比", JSON.stringify(luckysheet.getAllSheets()))
            exportExcel(luckysheet.getAllSheets(), '下载')
            // testaaa();
        },
        // 绑定参数指标
        binding() {
            // children
            this.cascader = false
            this.menusStyle = false
            this.unit = true
            this.value1 = []
            let data = luckysheet.getRange()

            if (luckysheet.getRangeValue(data[0].column[0], data[0].row[0])[0][0] == null) {
                // console.log("cesi");
            } else {
                if ('tr' in luckysheet.getRangeValue(data[0].column[0], data[0].row[0])[0][0]) {
                    let x = data[0].column[0]
                    let y = data[0].row[0]
                    // console.log(`==`,luckysheet.getRangeValue(x, y));
                    this.value = luckysheet.getRangeValue(x, y)[0][0].tr
                } else {
                }
            }
        },
        // 绑定单位
        unitBinding() {
            this.cascader = true
            this.unit = false
            this.value = []
            let data = luckysheet.getRange()
            if (luckysheet.getRangeValue(data[0].column[0], data[0].row[0])[0][0] == null) {
                // console.log("cesi");
            } else {
                if ('tr' in luckysheet.getRangeValue(data[0].column[0], data[0].row[0])[0][0]) {
                    let x = data[0].column[0]
                    let y = data[0].row[0]
                    // console.log(`==`,luckysheet.getRangeValue(x, y));
                    this.value1 = luckysheet.getRangeValue(x, y)[0][0].tr
                }
            }
        },
        // 自定义表头
        blur() {
            if (this.input == '') {
                return
            } else {
                luckysheet.setSheetName(this.input)
                // this.input = "";
            }
        },
        keyup() {
            if (this.input == '') {
                return
            } else {
                luckysheet.setSheetName(this.input)
                this.input = ''
            }
        },
        //编辑 表格
        edit() {
            luckysheet.destroy() // 先销毁当前容器
            this.editShow = true
            //   this.cellRightClickConfig = {};
            this.init()
        },
        Templates() {
            luckysheet.destroy() // 先销毁当前容器
            this.editShow = true
            //   this.cellRightClickConfig = {};
            this.getExcels()
        },
        // 切换选项
        handleNodeClick(data) {
            this.formdata.deptId = data.id
            this.$refs.selectTree1.blur()
            this.formdata.valueTitle = data.name
            this.formdata.defaultExpandedKey = []
        },
        // //表格保存
        preservation(formName) {
            // let userStr = JSON.stringify(luckysheet.getAllSheets());
            // let blob = new Blob([userStr], {
            //   type: "application/json;charset=UTF-8",
            // });

            // var files = new window.File([blob], "content.json", {
            //   type: "application/json;charset=UTF-8",
            // });
            // var params = new FormData();

            // params.append("fileContent", files);
            // params.append("name", this.formdata.templateName);
            // params.append("reportType", this.formdata.reportType);
            console.log('🚀 ~ preservation ~ luckysheet.getAllSheets():', luckysheet.getAllSheets())

            this.$refs[formName].validate(valid => {
                if (valid) {
                    let data = luckysheet.getAllSheets()

                    let list = []
                    console.log("🚀 ~ preservation ~ this.formdata.valueTitle:", this.formdata.valueTitle)

                    if (this.formdata.valueTitle) {
                        this.formdata.valueTitle.forEach(item => {
                            list.push(item[item.length - 1])
                        })
                    }

                    //console.log('保存存入格式',JSON.stringify(data));
                    let userStr = JSON.stringify(luckysheet.getAllSheets())
                    let blob = new Blob([userStr], {
                        type: 'application/json;charset=UTF-8'
                    })
                    const files = new window.File([blob], 'content.json', {
                        type: 'application/json;charset=UTF-8'
                    })
                    let params = new FormData()

                    params.append('fileContent', files)
                    params.append('deptId', list)
                    params.append('name', this.formdata.templateName)
                    params.append('reportType', this.formdata.reportType)
                    params.append('reportForm', this.formdata.reportForm)
                    params.append('valueTitle', this.arrToStr(this.formdata.valueTitle))

                    // let params = {
                    //   deptId: list,
                    //   content: files,
                    //   name: this.formdata.templateName,
                    //   reportType: this.formdata.reportType,

                    //   valueTitle: this.arrToStr(this.formdata.valueTitle),
                    // };
                    if (this.title == '新增报表模板') {
                        addTemplate(params).then(res => {
                            if (res != undefined && res.code == 'A0000') {
                                this.$message({
                                    message: res.message,
                                    type: 'success'
                                })
                                this.$emit('close')
                            }
                        })
                    } else if (this.title == '修改报表模板') {
                        params.append('id', this.id)
                        dateTemplateup(params).then(res => {
                            if (res != undefined && res.code == 'A0000') {
                                this.$emit('close')
                                this.$message({
                                    message: res.message,
                                    type: 'success'
                                })
                            }
                        })
                    }
                } else {
                    // console.log("error submit!!");
                    return false
                }
            })
        },
        // 二维数组转换
        arrToStr(objarr) {
            var typeNO = objarr.length
            var tree = '['
            for (var i = 0; i < typeNO; i++) {
                tree += '['
                for (let v = 0; v < objarr[i].length; v++) {
                    tree += "'" + objarr[i][v] + "',"
                }

                tree += ']'
                if (i < typeNO - 1) {
                    tree += ','
                }
            }
            tree += ']'
            return tree
        },
        // 鼠标经过
        enter() {
            this.cascader = false
            let menu = document.getElementById('cascader')
            let menus = document.getElementById('luckysheet-rightclick-menu')

            //根据事件对象中鼠标点击的位置,进行定位
            menu.style.left = menus.offsetLeft - 50 + 'px'
            menu.style.top = menus.offsetTop + 475 + 'px'
        },
        // 鼠标离开
        out() {
            this.cascader = true
        },
        handleChange(e) {
            // console.log(`12213===123`, this.options);
            let flag = null
            this.options.forEach(item => {
                if (item.name == e[0]) {
                    flag = item.flag
                }
            })
            this.cascader = true
            const checkedNodes = this.$refs['cascaderUnit'].getCheckedNodes()
            // console.log(checkedNodes, "checknode");
            // console.log(checkedNodes[0].data.value); // 获取当前点击的节点
            // console.log(checkedNodes[0].data.label); // 获取当前点击的节点的label
            // console.log(checkedNodes[0].pathLabels); // 获取由 label 组成的数组
            let data = luckysheet.getRange()
            let value = luckysheet.getCellValue(data[0].column[0], data[0].row[0])
            let list = ''
            for (let i = 1; i < e.length - 1; i++) {
                list = list + e[i] + '#'
            }

            if (flag == 1) {
                list = '$' + list + e[e.length - 1] + '$'
            } else {
                list = '$' + e[0] + '#' + list + e[e.length - 1] + '$'
            }

            luckysheet.setCellValue(
                data[0].row[0],
                data[0].column[0],
                {
                    v: e[e.length - 1],
                    tr: e
                }
                //  checkedNodes[0].data.label
            )

            // console.log(luckysheet.getAllSheets()[0]);
            this.value = []
        },
        unitHandleChange(e) {
            // console.log(`12213===123`, this.options);
            let flag = null
            this.options.forEach(item => {
                if (item.name == e[0]) {
                    flag = item.flag
                }
            })
            this.unit = true
            const checkedNodes = this.$refs['cascaderUnit'].getCheckedNodes()
            // console.log(checkedNodes, "checknode");
            // console.log(checkedNodes[0].data.value); // 获取当前点击的节点
            // console.log(checkedNodes[0].data.label); // 获取当前点击的节点的label
            // console.log(checkedNodes[0].pathLabels); // 获取由 label 组成的数组
            let data = luckysheet.getRange()

            let list = ''
            for (let i = 1; i < e.length - 1; i++) {
                list = list + e[i] + '#'
            }

            if (flag == 1) {
                list = '@' + list + e[e.length - 1] + '@'
            } else {
                list = '@' + e[0] + '#' + list + e[e.length - 1] + '@'
            }

            luckysheet.setCellValue(
                data[0].row[0],
                data[0].column[0],
                {
                    v: e[e.length - 1],
                    tr: e
                }
                //  checkedNodes[0].data.label
            )

            // console.log(luckysheet.getAllSheets()[0]);
            this.value1 = []
        },

        handleChangehgl(e) {
            // console.log(`12213===123`, this.options);
            let flag = null
            this.optionshgl.forEach(item => {
                if (item.name == e[0]) {
                    flag = item.flag
                }
            })
            this.cascader = true
            const checkedNodes = this.$refs['cascaderhgl'].getCheckedNodes()
            // console.log(checkedNodes, "checknode");
            // console.log(checkedNodes[0].data.value); // 获取当前点击的节点
            // console.log(checkedNodes[0].data.label); // 获取当前点击的节点的label
            // console.log(checkedNodes[0].pathLabels); // 获取由 label 组成的数组
            let data = luckysheet.getRange()
            let value = luckysheet.getCellValue(data[0].column[0], data[0].row[0])
            let list = ''
            for (let i = 1; i < e.length - 1; i++) {
                list = list + e[i] + '#'
            }

            if (flag == 1) {
                list = '$' + list + e[e.length - 1] + '$'
            } else {
                list = '$' + e[0] + '#' + list + e[e.length - 1] + '$'
            }

            luckysheet.setCellValue(
                data[0].row[0],
                data[0].column[0],
                {
                    v: e[e.length - 1],
                    tr: e
                }
                //  checkedNodes[0].data.label
            )

            // console.log(luckysheet.getAllSheets()[0]);
            this.valuehgl = ''
        },
        handleChangejcd(e) {
            // console.log(`12213===123`, this.options);
            let flag = null
            this.optionsjcd.forEach(item => {
                if (item.name == e[0]) {
                    flag = item.flag
                }
            })
            this.cascader = true
            const checkedNodes = this.$refs['cascaderjcd'].getCheckedNodes()
            // console.log(checkedNodes, "checknode");
            // console.log(checkedNodes[0].data.value); // 获取当前点击的节点
            // console.log(checkedNodes[0].data.label); // 获取当前点击的节点的label
            // console.log(checkedNodes[0].pathLabels); // 获取由 label 组成的数组
            let data = luckysheet.getRange()
            let value = luckysheet.getCellValue(data[0].column[0], data[0].row[0])
            let list = ''
            for (let i = 1; i < e.length - 1; i++) {
                list = list + e[i] + '#'
            }

            if (flag == 1) {
                list = '$' + list + e[e.length - 1] + '$'
            } else {
                list = '$' + e[0] + '#' + list + e[e.length - 1] + '$'
            }

            luckysheet.setCellValue(
                data[0].row[0],
                data[0].column[0],
                {
                    v: e[e.length - 1],
                    tr: e
                }
                //  checkedNodes[0].data.label
            )

            // console.log(luckysheet.getAllSheets()[0]);
            this.valuejcd = []
        },
        //获取统计类型
        getclassificationData() {
            // var code = "Report_Type";
            // this.classificationData = dicData(code, ["Load_Type"]);
            // console.log(`123`, this.classificationData);
        }
    },
    watch: {
        // menusStyle(e) {
        //     if (e == "block") {
        //       this.menusStyleShow = false;
        //     } else {
        //       this.menusStyleShow = true;
        //     }
        // },
    },
    beforeDestroy() {
        window.luckysheet.destroy()
    }
}
</script>
<style lang="less" scoped>
@import url('../../styles/comStyle.less');
::v-deep .el-cascader-menu__list {
    max-height: 500px;
}
::v-deep .el-table .cell {
    text-align: center;
}

.box {
    //   border: 1px solid #000;
    box-shadow: 0 2px 4px 0 rgb(0 0 0 / 12%), 0 0 6px 0 rgb(0 0 0 / 4%);
    .elButton {
        display: flex;
    }
    cursor: pointer;
}

#menu {
    position: absolute;
    z-index: 999999999;
    padding: 1px 6em 1px 20px;
    padding-right: 10px;
    padding-left: 8px;
    margin: 0;
    color: #333;
    text-align: left;
    white-space: nowrap;
    vertical-align: middle;
    list-style: none;
    cursor: pointer;
    background-color: #fff;
    user-select: none;
}
.menu__item {
    position: relative;
    padding: 6px 15px 6px 20px;
    margin: 0;
    font-size: 13px;
    color: #333;
    white-space: nowrap;
    list-style: none;
    cursor: pointer;
    user-select: none;
}
.menu__item:hover {
    background: #efefef;
}
.cascader {
    position: absolute;
    z-index: 9999;
    width: 200px;
    height: 100px;
    background-color: #fff;
    box-shadow: 0 2px 4px rgb(0 0 0 / 20%);
}
.input {
    width: 200px;
    margin-right: 15px;
    margin-left: 15px;
}
.buttons {
    margin-right: 15px;
    margin-left: 15px;
}
::v-deepinput::-webkit-input-placeholder {
    color: #353535;
}
.templateBox {
    display: flex;
    .templateRight {
        width: 400px;
        padding: 0 10px;
    }
}
.el-scrollbar .el-scrollbar__view .el-select-dropdown__item {
    height: auto;
    max-height: 1000px;
    padding: 0;
    overflow: hidden;
    overflow-y: hidden;
}

.el-select-dropdown__item.selected {
    font-weight: normal;
    // border: #333 2px solid;
}

// ::v-deep .luckysheet-input-box {
//   z-index: 0 !important;

// }
</style>
