<template>
  <div class="cqcy-content" style="margin: 0;height: calc(100% - 70px);">
    <breadcrumb-view :breadcrumbList="breadcrumbList" :show-index="false"></breadcrumb-view>
    <el-select class="cy-nav-sx" v-model="searchValue" placeholder="筛选报表" @change="changeReportTypeEvent">
      <el-option
          v-for="item in reportOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value">
      </el-option>
    </el-select>
    <el-button type="primary" class="cy-nav-btn" icon="el-icon-menu" size="mini" @click="addReportEvent">新增</el-button>
    <el-divider></el-divider>
    <div class="cy-main">
      <div class="cy-main-left" v-if="!showMainView">
        <div class="cy-list">
          <ul>
            <li v-for="item in reportDataList">
              <i class="el-icon-error"
                 style="float: right; margin-top: -10px; margin-right: -10px; cursor: pointer;"
                 @click="removeReportItem(item)"></i>
              <div class="cy-item-name" @click="handleReportNodeClick(item)">{{ item.reportTableName }}</div>
              <div style="display: flex; float: left; cursor: pointer;" @click="setUserGroupEvent(item)">
                <i v-if="item.userGroupId" class="el-icon-user-solid"></i>
                <i v-else class="el-icon-user"></i>
              </div>
              <div style="display: flex; float: right;">
                <div class="cy-item-val" style="width: 60px;">自动报表</div>
                <el-switch :value="item.isAutoReport == '1'" active-color="#13ce66"
                           @change="switchChangeEvent($event, item)"></el-switch>
              </div>
            </li>
          </ul>
        </div>
        <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="reportPage"
            :page-size="reportLimit"
            layout="total, prev, pager, next"
            :total="reportTotal">
        </el-pagination>
      </div>
      <div class="cy-main-right" :style="showMainView ? '' : 'display: none;'">
        <el-row v-if="btnType == 'add'" style="margin: 10px 20px;">
          <el-button type="primary" size="mini" icon="el-icon-document" @click="saveReportInfo">保存报表</el-button>
          <el-button type="danger" size="mini" icon="el-icon-circle-close" @click="cancelSaveReport">取消</el-button>
        </el-row>
        <el-row v-if="btnType == 'show'" style="margin: 10px 20px;">
          <el-button type="primary" size="mini" icon="el-icon-download" @click="downloadReport">下载</el-button>
          <el-button type="warning" size="mini" icon="el-icon-printer" @click="printExcel">打印</el-button>
          <el-button type="danger" size="mini" icon="el-icon-circle-close" @click="cancelSaveReport">取消</el-button>
        </el-row>
        <div id="luckysheet"
             style="margin:0px;padding:0px;position:relative;height:100%;width:100%;left: 20px;top: 0px;bottom:0px;">
        </div>
      </div>
    </div>

    <!-- 报表模板选择 -->
    <el-dialog
        title="选择报表模板"
        width="80%"
        top="10vh"
        center
        :before-close="dialogClose"
        :visible.sync="dialogReportTemplateVisible"
        :close-on-click-modal="false"
        :append-to-body="true">
      <el-form ref="reportForm" :model="reportForm" :rules="reportRules" label-width="80px" label-position="top">
        <el-form-item label="报表模板" prop="reportTemplate">
          <el-select v-model="reportForm.reportTemplate" filterable placeholder="请选择报表模板" style="width: 100%;">
            <el-option
                v-for="item in reportTemplateList"
                :key="item.id"
                :label="item.templateName"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="取值方式" prop="reportValueFormat">
          <el-radio v-model="reportForm.reportValueFormat" label="0">时段数据</el-radio>
        </el-form-item>
        <el-form-item style="text-align: center;">
          <el-button type="primary" @click="chooseReportEvent" style="margin-top: 20px;">确定</el-button>
          <el-button @click="dialogClose" style="margin-top: 20px;">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 用户组选择 -->
    <el-dialog
        title="选择用户组"
        width="80%"
        top="10vh"
        center
        :before-close="dialogClose"
        :visible.sync="dialogUserGroupVisible"
        :close-on-click-modal="false"
        :append-to-body="true">
      <el-form label-width="80px">
        <el-form-item label="用户组">
          <el-select v-model="userGroupInfo" filterable placeholder="请选择用户组" style="width: 100%;">
            <el-option
                v-for="item in userGroupList"
                :key="item.id"
                :label="item.userGroupName"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item style="text-align: center;">
          <el-button type="primary" @click="chooseUserGroupEvent" style="margin-top: 20px;">确定</el-button>
          <el-button @click="dialogClose" style="margin-top: 20px;">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 自动报表CRON定时表达式 -->
    <el-dialog
        title="请输入定时任务表达式"
        width="80%"
        top="10vh"
        center
        :before-close="dialogClose"
        :visible.sync="dialogAutoReportVisible"
        :close-on-click-modal="false"
        :append-to-body="true">
      <el-form label-width="80px">
        <el-form-item label="表达式">
          <el-input type="text" placeholder="请输入定时任务表达式" v-model="cronVal" maxlength="50"></el-input>
        </el-form-item>
        <div>
          <label>常用定时任务表达式例子</label>
          <ul>
            <li v-for="(item, i) in cronList" style="margin-bottom: 5px;">
              <span class="cron-txt" @click="cronNodeEvent(item)">{{ item.value }}</span>
              <span class="cron-txt-desc">{{ item.label }}</span>
            </li>
          </ul>
        </div>
        <el-form-item style="text-align: center;">
          <el-button type="primary" @click="chooseCronEvent" style="margin-top: 20px;">确定</el-button>
          <el-button @click="dialogClose" style="margin-top: 20px;">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 报表下载类型选择 -->
    <el-dialog
        title="选择下载类型"
        width="500px"
        center
        :before-close="dialogClose"
        :visible.sync="dialogDownloadReportTypeVisible"
        :close-on-click-modal="false"
        :append-to-body="true">
      <div style="text-align: center;">
        <el-radio v-model="downloadType" label="1">Excel</el-radio>
        <el-radio v-model="downloadType" label="2" disabled>PDF</el-radio>
      </div>
      <div style="text-align: center; margin-top: 40px;">
        <el-button type="primary" @click="downloadReportEvent">确定</el-button>
      </div>
    </el-dialog>

    <div id="print-area" style="display: none;position: absolute;z-index: 0;top: 0;width: 100%;height: 100vh;overflow: hidden;">
      <div id="print-html" ref="printPayFeeNew"></div>
    </div>

  </div>
</template>

<script>
import BreadcrumbView from '@/components/BreadcrumbView'
import {getNowFormatDate, showLoading} from '@/utils/cqcy'
import {
  delReportTableById,
  getAllDataModel,
  getAllReportTable,
  getAllTableTemplate, getChartData,
  getDataModelById, getReportTableById, getTableData,
  getTableTemplateById, saveReport, tableAssignUserById, tableExchangeTypeById
} from '@/api/datasource'
import {insertEChart} from 'luckytool'
// import {insertEChart, exportExcel, packtable} from 'luckytool'
// import ExcelJS from 'exceljs'
import Print from 'print-js'
import {getUsername} from '@/utils/auth'
import {exportExcel} from '@/utils/export'
import {getAllUserGroup} from "@/api/user";

export default {
  name: "index",
  components: {
    BreadcrumbView
  },
  data() {
    return {
      breadcrumbList: ['我的报表'],
      groupProps: {
        isLeaf: 'leaf'
      },
      showMainView: false,
      chooseMyReport: null,
      dialogReportTemplateVisible: false,
      dialogDownloadReportTypeVisible: false,
      dialogAutoReportVisible: false,
      dialogUserGroupVisible: false,
      downloadType: '1',
      btnType: '',
      userGroupInfo: null,
      userGroupList: [],
      cronVal: '',
      cronList: [],
      reportId: null,
      reportTemplateList: [],
      dataModelList: [],
      chooseReportTemplate: null,
      delFlag: 0,
      reportForm: {
        reportTemplate: null,
        reportValueFormat: '0'
      },
      searchValue: null,
      reportOptions: [{
        label: '所有报表',
        value: -1
      }, {
        label: '自动报表',
        value: 1
      }, {
        label: '非自动报表',
        value: 0
      }],
      reportTotal: 0,
      reportPage: 1,
      reportLimit: 20,
      reportDataList: [],
      reportRules: {
        reportTemplate: [
          {required: true, message: '请选择报表模板', trigger: 'change'}
        ]
      }
    }
  },
  watch: {},
  beforeDestroy() {
  },
  created() {
    luckysheet.destroy()
    this.loadReport()
    this.initCronList()
  },
  methods: {
    handleSizeChange(val) {
      this.reportPage = 1
      this.reportLimit = val
      this.loadReport()
    },
    handleCurrentChange(val) {
      this.reportPage = val
      this.loadReport()
    },
    changeReportTypeEvent(val) {
      this.reportPage = 1
      this.loadReport()
    },
    validCron(value) {
      const cronParse = require('cron-parser')
      try {
        const interval = cronParse.parseExpression(value)
        console.log('cronDate:', interval.next().toDate())
        return true
      } catch (e) {
      }
      return false
    },
    chooseCronEvent() {
      if (!this.cronVal) {
        this.$message({
          message: '请输入定时任务表达式！',
          type: 'warning'
        })
        return
      }
      if (!this.validCron(this.cronVal)) {
        this.$message({
          message: '定时任务表达式格式不正确，请检查！',
          type: 'warning'
        })
        return
      }
      const loading = showLoading(this, '请稍候···')
      let params = {
        'id': this.reportId,
        'isAutoReport': '1',
        'cron': this.cronVal
      }
      tableExchangeTypeById(params).then(res => {
        loading.close()
        this.dialogClose()
        this.loadReport()
      }).catch((e) => {
        loading.close()
        this.$message({
          message: '保存失败！',
          type: 'warning'
        })
      })
    },
    switchChangeEvent(val, data) {
      if (val) {
        this.dialogAutoReportVisible = true
        this.reportId = data.id
        getReportTableById(data.id).then(res => {
          this.cronVal = res.data.cron
        }).catch((e) => {
          console.log(e)
        })
        return
      }
      const loading = showLoading(this, '请稍候···')
      let params = {
        'id': data.id,
        'isAutoReport': '0'
      }
      tableExchangeTypeById(params).then(res => {
        loading.close()
        this.loadReport()
      }).catch((e) => {
        loading.close()
        this.$message({
          message: '保存失败！',
          type: 'warning'
        })
      })
    },
    /** 新增报表 */
    addReportEvent() {
      this.getAllReportTemplate()
      this.dialogReportTemplateVisible = true
    },
    /** 模版报表选择 */
    chooseReportEvent() {
      this.$refs['reportForm'].validate((valid) => {
        if (valid) {
          const loading = showLoading(this, '数据加载中，请稍候···')
          getTableTemplateById(this.reportForm.reportTemplate).then(res => {
            if (!res.data) {
              loading.close()
              this.$message({
                message: '选择的报表模板不存在！',
                type: 'warning'
              })
              return
            }
            this.showMainView = true
            let luckyData = JSON.parse(res.data.templateData)
            this.chooseReportTemplate = luckyData
            this.drawLuckyExcel(luckyData, () => {
              loading.close()
              this.btnType = 'add'
              this.$refs.reportForm.resetFields()
              this.dialogReportTemplateVisible = false
            })
          }).catch((e) => {
            loading.close()
            console.log(e)
            this.$message({
              message: '数据查询失败！',
              type: 'warning'
            })
          })
        }
      })
    },
    /** 根据 ID 查询数据模型 */
    getDataModelById(loading, reportData) {
      if (!loading) {
        loading = showLoading(this, '数据加载中，请稍候···')
      }
      getDataModelById(this.reportForm.operationRule).then(res => {
        loading.close()
        if (!res.data) {
          this.$message({
            message: '选择的四则运算表达式不存在！',
            type: 'warning'
          })
          return
        }
        let luckyData = JSON.parse(reportData.templateData)
        this.drawLuckyExcel(luckyData)
        this.btnType = 'add'
        this.dialogReportTemplateVisible = false
      }).catch((e) => {
        loading.close()
        this.$message({
          message: '数据查询失败！',
          type: 'warning'
        })
      })
    },
    /** 绘制 Excel 表 */
    drawLuckyExcel(luckyData, callback) {
      luckysheet.destroy()
      let option = luckyData.option
      option.data = luckyData.data
      let charts = luckyData.charts
      let tables = luckyData.tables
      luckysheet.create(option)
      for (let i in charts) {
        this.insertEChartInfo(charts[i])
      }
      for (let i in tables) {
        this.insertTableInfo(tables[i])
      }
      if (callback) {
        callback()
      }
    },
    /** 获取图表数据 */
    getChartData(data, callback) {
      getChartData(data).then(res => {
        if (!res.data) {
          if (callback) callback([])
          return
        }
        if (callback) callback(res.data)
      }).catch((e) => {
        if (callback) callback([])
      })
    },
    /** 获取表格数据 */
    getTableData(data, callback) {
      getTableData(data).then(res => {
        if (!res.data) {
          if (callback) callback([])
          return
        }
        if (callback) callback(res.data)
      }).catch((e) => {
        if (callback) callback([])
      })
    },
    /** 向 Excel 插入表格 */
    insertTableInfo(tableData) {
      let params = []
      let itemList = tableData.item
      for (let i in itemList) {
        let temp = itemList[i]
        params.push({
          'itemGroupId': temp.itemGroupId,
          'itemName': temp.itemName
        })
      }
      let p = {
        'reportValueFormat': this.reportForm.reportValueFormat,
        'tableDataDtoChList': params,
        'showType': tableData.showType
      }

      this.getTableData(p, (res) => {
        // console.log('option==>', luckysheet.getAllSheets()[0])
        // console.log('table1==>', res)
        // const optionData = packtable(res, luckysheet.getAllSheets()[0])
        // console.log('table2==>', optionData)
        setTimeout(() => {
          this.drawTableData(res, p.showType, luckysheet.getAllSheets()[0])
        }, 500)
      })
    },
    drawTableData(sources, type, option) {
      option.celldata.map(item => {
        if (item.v.v) {
          item.v.v = String(item.v.v).trim();
          if (item.v.v.match(/\${([^}]+)}/g)) { // 替换${xxx}内部数据
            let currDate = getNowFormatDate('date')
            if (sources.length > 0 && sources[0].dataList.length > 0) {
              currDate = sources[0].dataList[0].dh
              currDate = currDate.substring(0, 10)
            }
            sources.forEach(source => {
              let itemName = source.itemName
              itemName = itemName.substring(itemName.lastIndexOf('.') + 1)
              let name = '${' + source.itemGroupId + '.' + itemName + '.' + type.dataId + '}'
              if (item.v.v === name) {
                let dataList = source.dataList
                // for (let i = 0; i < dataList.length; i++) {
                for (let i = 0; i < type.valLine; i++) {
                  let p_r = parseInt(item.r)
                  let p_c = parseInt(item.c)
                  if (type.valType == '2') p_r += i
                  else p_c += i
                  luckysheet.setCellValue(p_r, p_c, dataList[i].dv)
                }
              }
            })

            if (item.v.v.indexOf('${currDate}') > -1) {
              let val = item.v.v
              val = val.replace('${currDate}', currDate)
              luckysheet.setCellValue(item.r, item.c, val)
            }
            if (item.v.v.indexOf('${currDateTime}') > -1) {
              let currDateTime = getNowFormatDate('')
              let val = item.v.v
              val = val.replace('${currDateTime}', currDateTime)
              luckysheet.setCellValue(item.r, item.c, val)
            }
            if (item.v.v.indexOf('${userName}') > -1) {
              let val = item.v.v
              val = val.replace('${userName}', getUsername())
              luckysheet.setCellValue(item.r, item.c, val)
            }
            if (item.v.v.indexOf('${winUserName}') > -1) {
              let val = item.v.v
              val = val.replace('${winUserName}', process.env.VUE_APP_WINNAME)
              luckysheet.setCellValue(item.r, item.c, val)
            }
          }
        }
      })
    },
    /** 向 Excel 插入图表 */
    insertEChartInfo(chart) {
      console.log(chart)
      let info = chart.info
      let itemList = chart.item
      let groupId = null
      let itemArr = []
      for (let i in itemList) {
        let temp = itemList[i]
        if (i == 0) groupId = temp.itemGroupId
        itemArr.push({
          'id': temp.id,
          'itemName': temp.itemName,
          // 'dataModelId': temp.rule.id
        })
      }
      let params = {
        'type': info.option.series[0].type,
        'itemGroup': {
          'id': groupId,
          'itemList': itemArr
        }
      }
      this.getChartData(params, (res) => {
        let result = (res instanceof Array) ? res : []
        // 系列
        let series = info.option.series
        for (let i in series) {
          let temp = series[i]
          temp.data = []
          for (let j in result) {
            if (params.type == 'pie') {
              temp.name = result[j].name
              temp.data.push({
                'name': result[j].describe ? result[j].describe : result[j].name,
                'value': result[j].value
              })
            } else {
              temp.data = result[i].dataList ? result[i].dataList : []
            }
          }
        }
        if (params.type != 'pie') {
          // x 轴
          let xAxis = info.option.xAxis
          let legend = info.option.legend
          xAxis.data = []
          legend.data = []
          for (let i in result) {
            let name = result[i].describe ? result[i].describe : result[i].itemName
            xAxis.data.push(name)
            legend.data.push(name)
          }
        }
        console.log(params.type, info)
        setTimeout(() => {
          const sheet = luckysheet.getLuckysheetfile()[0]
          let optionData = sheet.data
          try {
            insertEChart({
              selector: '#luckysheet',
              info,
              sheet,
              optionData,
              echarts,
              luckysheet,
              $
            })
          } catch (e) {
            console.log(999, e == 'echarts is not defined')
            console.error(e)
          }
        }, 200)
      })
    },
    /** 查询所有报表信息 */
    getAllReportTemplate() {
      let params = {
        'page': 1,
        'limit': 1000
      }
      getAllTableTemplate(params).then(res => {
        if (!res.data) {
          return
        }
        this.reportTemplateList = res.data.tableTemplateList
      }).catch((e) => {
      })
    },
    /** 查询所有数据模型 */
    getAllDataModel() {
      let params = {
        'page': 1,
        'limit': 1000
      }
      getAllDataModel(params).then(res => {
        if (!res.data) {
          return
        }
        this.dataModelList = res.data.dataModelList
      }).catch((e) => {
      })
    },
    /** 查询我的报表列表 */
    loadReport() {
      let params = {
        'page': this.reportPage,
        'limit': this.reportLimit
      }
      if (this.searchValue != '-1') {
        params.isAutoReport = this.searchValue
      }
      getAllReportTable(params).then(res => {
        if (!res.data) {
          return
        }
        this.reportTotal = res.data.count
        this.reportDataList = res.data.reportTableList
      }).catch((e) => {
      })
    },
    /** 设置用户组信息 */
    setUserGroupEvent(data) {
      this.reportId = data.id
      this.dialogUserGroupVisible = true
      getAllUserGroup().then(res => {
        this.$nextTick(() => {
          this.userGroupList = res.data
          this.userGroupInfo = data.userGroupId
        })
      }).catch((e) => {
      })
    },
    chooseUserGroupEvent() {
      if (!this.userGroupInfo) {
        this.$message({
          message: '请选择用户组！',
          type: 'warning'
        })
        return
      }
      tableAssignUserById({
        'id': this.reportId,
        'groupId': this.userGroupInfo
      }).then(res => {
        this.$message({
          message: res.data,
          type: 'success'
        })
        this.dialogClose()
        this.loadReport()
      }).catch((e) => {
      })
    },
    /** 报表点击事件 */
    handleReportNodeClick(data) {
      if (data.id == -1 || this.delFlag == 1) {
        return
      }
      const loading = showLoading(this, '加载中，请稍候···')
      getReportTableById(data.id).then(res => {
        loading.close()
        if (!res.data) {
          this.$message({
            message: '选择的报表不存在！',
            type: 'warning'
          })
          return
        }
        this.showMainView = true
        this.chooseMyReport = res.data
        let reportTableData = res.data.reportTableData
        let luckyData = JSON.parse(reportTableData)
        // this.drawLuckyExcel(luckyData, () => {
        //   this.btnType = 'show'
        //   loading.close()
        // })
        luckysheet.destroy()
        let option = luckyData.option
        option.data = luckyData.data
        // 设置工作表保护
        option.data[0].config.authority = {
          sheet: 1, // 如果为 1 或 true，则该工作表受到保护；如果为 0 或 false，则该工作表不受保护。
          hintText: '该工作表受到保护，无法操作', // 弹窗提示的文字
        }
        // 关闭右键菜单
        option.cellRightClickConfig.chart = false
        option.cellRightClickConfig.columnWidth = false
        option.cellRightClickConfig.rowHeight = false
        option.cellRightClickConfig.deleteColumn = false
        option.cellRightClickConfig.deleteRow = false
        option.cellRightClickConfig.insertColumn = false
        option.cellRightClickConfig.insertRow = false
        // 关闭工具栏
        option.showtoolbar = false
        option.enableAddRow = false
        option.showtoolbarConfig = {
          bold: false,
          border: false,
          fillColor: false,
          font: false,
          fontSize: false,
          function: false,
          horizontalAlignMode: false,
          italic: false,
          mergeCell: false,
          moreFormats: false,
          paintFormat: false,
          strikethrough: false,
          textColor: false,
          underline: false,
          verticalAlignMode: false
        }
        // 钩子函数
        option.hook = {
          workbookCreateAfter() {
            option.data.forEach((data, i) => {
              data.chart.forEach((chart, j) => {
                console.log(chart.chart_id)
                let dom = document.getElementById(chart.chart_id + '_c')
                if (dom) dom.style.display = 'none'
              })
            })
          }
        }
        luckysheet.create(option)
        this.btnType = 'show'
      }).catch((e) => {
        console.log(e)
        loading.close()
        this.$message({
          message: '加载失败！',
          type: 'warning'
        })
      })
    },
    /** 报表移除 */
    removeReportItem(data) {
      this.$confirm('您确定要删除该报表吗？', '温馨提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        const loading = showLoading(this, '删除中，请稍候···')
        delReportTableById(data.id).then(res => {
          loading.close()
          let msg = res.data ? '删除成功！' : '删除失败！'
          let msgType = res.data ? 'success' : 'warning'
          this.$message({
            message: msg,
            type: msgType
          })
          this.loadReport()
          this.cancelSaveReport()
        }).catch((e) => {
          loading.close()
          this.$message({
            message: '删除失败！',
            type: 'warning'
          })
        })
      }).catch(() => {
      })
    },
    /** 获取单元格大小 */
    getCellSize(celldata, r, c, luckysheet) {
      const { cs, rs } = celldata.data[r][c].mc
      const rowhidden = celldata.config.rowhidden && Object.keys(celldata.config.rowhidden) || ''
      const rowArr = []
      for (let i = 0; i < rs; i++) {
        let rowIndex = r + i
        if (rowhidden.indexOf(String(rowIndex)) < 0) {
          rowArr.push(rowIndex)
        }
      }
      const colArr = []
      for (let j = 0; j < cs; j++) {
        colArr.push(c + j)
      }
      const totalHeight = Object.values(
          luckysheet.getRowHeight(rowArr)
      ).reduce((a, b) => a + b)
      const totalWidth = Object.values(
          luckysheet.getColumnWidth(colArr)
      ).reduce((a, b) => a + b)
      return {
        w: totalWidth,
        h: totalHeight
      }
    },
    /** 获取图片位置 */
    getImagePosition(num, arr) {
      let index = 0
      let minIndex
      let maxIndex
      for (let i = 0; i < arr.length; i++) {
        if (num < arr[i]) {
          index = i
          break
        }
      }
      if (index == 0) {
        minIndex = 0
        maxIndex = 1
      } else if (index == arr.length - 1) {
        minIndex = arr.length - 2
        maxIndex = arr.length - 1
      } else {
        minIndex = index - 1
        maxIndex = index
      }
      let min = arr[minIndex]
      let max = arr[maxIndex]
      let radio = Math.abs((num - min) / (max - min)) + index
      return radio
    },
    /** 图表转换为图片 */
    convertChart() {
      let luckyData = this.chooseReportTemplate
      const optionData = luckysheet.getLuckysheetfile()[0]
      let {
        visibledatacolumn, // 所有行的位置
        visibledatarow // 所有列的位置
      } = optionData
      // 动态图表
      if (luckyData.charts && luckyData.charts.length > 0) {
        luckyData.charts.forEach((chart, i) => {
          let myChart = echarts.init(
              document.getElementsByClassName(chart.info.className)[0]
          )
          let baseData = myChart.getConnectedDataURL({
            type: 'png',
            pixelRatio: 2,
            backgroundColor: '#ffffff'
          })
          // luckysheet.cancelRangeMerge(chart.info.pos)
          luckysheet.insertImage(baseData, {
            rowIndex: chart.info.pos[0],
            colIndex: chart.info.pos[1],
            cellSize: this.getCellSize(optionData, chart.info.pos[0], chart.info.pos[1], luckysheet),
            success: function () {
              console.log("插入成功")
            }
          })
        })
      }
      // 静态图表
      if (luckyData.data && luckyData.data.length > 0) {
        luckyData.data.forEach((data, i) => {
          if (data.chart && data.chart.length > 0) {
            data.chart.forEach((chart, j) => {
              let myChart = echarts.init(
                  document.getElementById(chart.chart_id)
              )
              myChart.setOption(chart.chartOptions);
              let baseData = myChart.getConnectedDataURL({
                type: 'png',
                pixelRatio: 2,
                backgroundColor: '#ffffff'
              })
              let col_st = this.getImagePosition(chart.left, visibledatacolumn)
              let row_st = this.getImagePosition(chart.top, visibledatarow)
              luckysheet.insertImage(baseData, {
                rowIndex: parseInt(row_st),
                colIndex: parseInt(col_st),
                cellSize: {
                  w: chart.width,
                  h: chart.height,
                },
                success: function () {
                  console.log("插入成功")
                }
              })
            })
          }
        })
      }
    },
    /** 保存报表信息 */
    saveReportInfo() {
      this.$prompt('请输入报表名称', '保存', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValidator: (val) => {
          if (!val) {
            return '报表名称不能为空'
          }
          if (val.length > 20) {
            return '报表名称必须在20字以内'
          }
        }
      }).then(({value}) => {
        if (!this.chooseReportTemplate) {
          this.$message({
            message: '请重新选择报表模版',
            type: 'warning'
          })
          return
        }
        const loading = showLoading(this, '保存中，请稍候···')
        this.convertChart()
        let data = {
          'reportTableName': value,
          'reportValueFormat': this.reportForm.reportValueFormat,
          'reportTableData': JSON.stringify(this.chooseReportTemplate)
        }
        saveReport(data).then(res => {
          loading.close()
          let msg = res.data ? '保存成功！' : '保存失败！'
          let msgType = res.data ? 'success' : 'error'
          this.$message({
            message: msg,
            type: msgType
          })
          this.showMainView = false
          this.loadReport()
          this.cancelSaveReport()
        }).catch((e) => {
          loading.close()
        })
      }).catch((e) => {
        console.log(e)
      })
    },
    /** 报表下载 */
    downloadReport() {
      this.dialogDownloadReportTypeVisible = true
    },
    /** 报表下载事件 */
    downloadReportEvent() {
      if (!this.chooseMyReport) {
        this.$message({
          message: '请选择报表',
          type: 'warning'
        })
        return
      }
      let reportName = this.chooseMyReport.reportTableName ? this.chooseMyReport.reportTableName : '统计报表'
      if (this.downloadType == '1') {
        // exportExcel(luckysheet, reportName, ExcelJS).then((res) => {
        //   console.log("result==>", res)
        //   // this.$message({
        //   //   message: res,
        //   //   type: 'success'
        //   // })
        //   this.dialogDownloadReportTypeVisible = false
        // }).catch((err) => {
        // })
        exportExcel(luckysheet.getAllSheets(), reportName)
      }
    },
    /** 打印操作 */
    printExcel() {
      const loading = showLoading(this, '请稍候···')
      let src = luckysheet.getScreenshot(); // 生成base64图片
      let $img = `<img src=${src} style="width: 100%; position: absolute; left: 0px" />`;
      document.querySelector("#print-area").style.display = "block";
      this.$nextTick(() => {
        document.querySelector("#print-html").innerHTML = $img;
        setTimeout(() => {
          Print({
            printable: 'print-html',
            type: 'html',
            documentTitle: '文档标题',
            header: '统计图',
            headerStyle: 'font-weight:400;text-align:center;',
            style: '@page {margin: 0 10mm};', // 不打印页眉和页脚
            honorColor: true, // 是否打印彩色文本
            targetStyles: ['*'] // 允许打印所有样式属性
          }) // Print.js插件
          document.querySelector("#print-area").style.display = "none";
          loading.close()
        }, 2000)
      });
    },
    /** 自定义选中区域 */
    getExcelRowColumn() {
      const sheetData = luckysheet.getSheetData();
      let objRowColumn = {
        row: [null, null], //行
        column: [null, null], //列
      };
      sheetData.forEach((item, index) => {
        //行数
        item.forEach((it, itemIndex) => {
          console.log(it)
          if (it !== null) {
            if (objRowColumn.row[0] == null) objRowColumn.row[0] = index; // row第一位
            objRowColumn.row[1] = index; //row第二位
            if (objRowColumn.column[0] == null)
              objRowColumn.column[0] = itemIndex; //column第一位
            objRowColumn.column[1] = itemIndex; //column第二位
          }
        });
      });
      return objRowColumn;
    },
    cronNodeEvent(obj) {
      this.cronVal = obj.value
    },
    initCronList() {
      this.cronList = []
      this.cronList.push({ value: '0/2 * * * * ?', label: '表示每2秒钟执行一次任务' })
      this.cronList.push({ value: '0 0/2 * * * ?', label: '表示每2分钟执行一次任务' })
      this.cronList.push({ value: '0 0 0/2 * * ?', label: '表示每2小时执行一次任务' })
      this.cronList.push({ value: '0 15 10 * * ?', label: '表示在每天上午10点15分执行一次任务' })
      this.cronList.push({ value: '0 0 10,14,16 * * ?', label: '表示在每天的上午10点、下午2点、下午4点分别执行一次任务' })
      this.cronList.push({ value: '0 0/30 9-17 * * ?', label: '表示在每天的上午9点到下午5点的范围内每30分钟执行一次任务' })
      this.cronList.push({ value: '0 0 12 ? * WED', label: '表示在每周星期三中午12点执行一次任务' })
      this.cronList.push({ value: '0 0 2 1 * ?', label: '表示在每月的1日的凌晨2点执行一次任务' })
      this.cronList.push({ value: '0 15 10 * * ? 2023', label: '表示在2023年每天上午10点15分执行一次任务' })
    },
    /** 取消保存报表 */
    cancelSaveReport() {
      luckysheet.destroy()
      this.showMainView = false
      this.btnType = ''
      if (this.$refs['reportForm']) this.$refs['reportForm'].resetFields()
    },
    /** 弹出层关闭事件 */
    dialogClose(done) {
      this.cronVal = ''
      this.reportId = null
      this.userGroupInfo = null
      if (typeof (done) === 'function') {
        done()
      } else {
        this.dialogReportTemplateVisible = false
        this.dialogDownloadReportTypeVisible = false
        this.dialogAutoReportVisible = false
        this.dialogUserGroupVisible = false
      }
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
.breadcrumb-content {
  padding-bottom: 0;
}

.cy-nav-sx {
  float: left !important;
  margin-top: -23px !important;
  margin-left: 120px !important;
}

.cy-nav-btn {
  float: right !important;
  margin-right: 20px !important;
  margin-top: -20px !important;
}

.cy-main {
  margin: 10px 20px;
  width: calc(100% - 40px);
  height: calc(100% - 100px);

  .cy-btn {
    margin-bottom: 10px;
  }

  .cy-btn .el-link {
    margin-right: 15px;
  }

  .cy-main-left {
    width: 100%;
    height: 100%;
    overflow: auto;
    //float: left;
    padding: 5px 10px;
    //border-right: 1px solid #d4d4d4;

    .cy-list {
      overflow: auto;
      height: 100%;
      height: calc(100% - 40px);

      ul {
        display: flex;
        flex-wrap: wrap;
        padding: 0;
        margin-top: 0;

        li {
          list-style-type: none;
          background: #41aed7;
          width: 23%;
          margin: 10px 1%;
          border-radius: 8px;
          height: 75px;
          padding: 15px;
          color: #ffffff;

          .cy-item-name {
            font-size: 14px;
            text-overflow: ellipsis;
            white-space: nowrap;
            overflow: hidden;
            margin-bottom: 10px;
            cursor: pointer;
          }

          .cy-item-val {
            font-size: 12px;
          }
        }
      }
    }
  }

  .cy-main-right {
    width: 100%;
    height: 100%;
    float: left;
    overflow: hidden;
  }
}

.cy-group-tree1 {
  font-size: 14px;

  .custom-tree-node1 {
    height: 28px;
    line-height: 28px;
  }
}

.cron-txt {
  color: blue;
  margin-right: 20px;
  cursor: pointer;
  font-weight: bold;
  font-size: 16px;
}

.cron-txt-desc {
}
</style>