<template>
  <div>
    <el-row v-show="isShow">
      <el-col :span="5">
        <div class="box">
          <el-scrollbar>
            <basic-container>
              <avue-tree :option="treeOption" :data="customTypeData" @node-click="nodeClick">
                <template slot="addBtn">
                  <el-tooltip class="item" effect="dark" content="新建分类" placement="top">
                    <i class="el-icon-setting" style="font-size:18px;line-height: 30px;width: 20px;padding: 0 10px;"
                      @click="corpTypeVisible = true"></i>
                  </el-tooltip>
                </template>
              </avue-tree>
            </basic-container>
          </el-scrollbar>
        </div>
      </el-col>
      <el-col :span="19">
        <basic-container class="page-crad">
          <!-- :on-change="handleChange" -->
          <avue-crud :option="option" :table-loading="loading" :data="data" :page.sync="page" :permission="permissionList"
            id="out-table" :header-cell-class-name="headerClassName" :search.sync="query" :before-open="beforeOpen"
            v-model="form" ref="crud" @row-update="rowUpdate" @row-save="rowSave" @row-del="rowDel"
            @search-change="searchChange" @search-reset="searchReset" @selection-change="selectionChange"
            @current-change="currentChange" @size-change="sizeChange" @refresh-change="refreshChange"
            @resetColumn="resetColumnTwo('crud', 'option', 'optionBack', 304)"
            @saveColumn="saveColumnTwo('crud', 'option', 'optionBack', 304)" @on-load="onLoad">
            <template slot="cnName" slot-scope="scope">
                <div style="color: #1e9fff;cursor: pointer;" @click.stop="editOpen(scope.row)">
                    {{scope.row.cnName}}
                </div>
            </template>
              <template slot="status" slot-scope="scope">
                  <div v-for="(item,index) of ifInvoiceData" :key="index" v-if="scope.row.status == item.dictKey"
                       class="statusClass" :style="'background:' + item.colour">{{item.dictValue}}</div>
              </template>

            <template slot="menuLeft">
              <el-button type="warning" size="small" icon="el-icon-printer" @click="excelBox = true">导入
              </el-button>
              <el-button type="success" size="small" @click="handleExport" icon="el-icon-printer">导出</el-button>
              <!--<el-button type="success" size="small" @click="handleReportDesigner" icon="el-icon-printer">设计报表</el-button>-->
              <!--<el-button type="success" size="small" @click="handleReportPreview" icon="el-icon-printer">预览报表</el-button>-->
            </template>
            <template slot-scope="{ row, index }" slot="menu">
              <el-button icon="el-icon-edit" type="text" size="small" @click.stop="editOpen(row)">
                编辑
              </el-button>
              <el-button icon="el-icon-delete" type="text" size="small" @click.stop="rowDel(row, index)">
                删除
              </el-button>
                <el-button icon="el-icon-turn-off" v-if="row.status == 1" type="text" style="color: #85e967" size="small"
                           @click.stop="statusfun(row.id,0)">
                    启用
                </el-button>
                <el-button icon="el-icon-turn-off" v-if="row.status == 0" type="text" style="color: #e83c3a" size="small"
                           @click.stop="statusfun(row.id,1)">
                    停用
                </el-button>
            </template>
          </avue-crud>
        </basic-container>
      </el-col>
    </el-row>

    <reportContainer ref="reportContainer"></reportContainer>

    <detailPage v-if="!isShow" ref="detail" @goBack="goBack" @copyOrder="copyOrder" :detailData="detailData"></detailPage>

    <!--类别弹窗-->
    <el-dialog title="类别" v-dialogdrag :visible.sync="corpTypeVisible" append-to-body width="60%" :before-close="corpTypeClose">
      <div>
        <bcorpstypedefine></bcorpstypedefine>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="corpTypeVisible = false">取 消</el-button>
        <el-button type="primary" @click="corpTypeVisible = false">确 定</el-button>
      </span>
    </el-dialog>


    <el-dialog title="导入往来单位" append-to-body :visible.sync="excelBox" width="555px" :close-on-click-modal="false"
      v-dialog-drag>
      <avue-form :option="excelOption" v-model="excelForm" :table-loading="excelLoading" :upload-before="uploadBefore"
        :upload-after="onSuccess">
        <template slot="excelTemplate">
          <el-button type="primary" @click="handleGet">
            点击下载<i class="el-icon-download el-icon--right"></i>
          </el-button>
        </template>
      </avue-form>
      <p style="text-align: center;color: #DC0505">
        温馨提示 第一次导入时请先下载模板
      </p>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/util/auth";
import detailPage from "./detailsPage";
import { BcorpsList, getBcorpsDetail, addBcorps, updateBcorps, removeBcorps, downLoadBcorpsTemplate } from "@/api/iosBasicData/bcorps";
import { mapGetters } from "vuex";
import { bcorpstypedefineList } from "@/api/iosBasicData/bcorpstypedefine"
import bcorpstypedefine from "@/views/iosBasicData/bcorps/bcorpstypedefine.vue"

import reportContainer from "@/views/iosBasicData/report-container/report-container.vue"
import {getWorkDicts} from "@/api/system/dictbiz";
import {bcountrysList} from "@/api/iosBasicData/bcountrys";

export default {
  components: {
    detailPage,
    bcorpstypedefine,
    reportContainer
  },
  data() {
    return {
      headers: { "Blade-Auth": "Bearer " + getToken() },
      // 类别弹窗的开启
      corpTypeVisible: false,
      treeOption: {
        nodeKey: "id",
        lazy: true,
        treeLoad: function (node, resolve) {
          const parentId = node.level === 0 ? 0 : node.data.id;
        },
        addBtn: false,
        menu: false,
        size: "small",
        props: {
          labelText: "标题",
          label: "cnName",
          value: "id",
          children: "children"
        }
      },
      excelForm: {},
      excelLoading: false,
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: "模板下载",
            prop: "excelTemplate",
            formslot: true,
            span: 24
          },
          {
            label: "模板上传",
            prop: "excelFile",
            type: "upload",
            drag: true,
            loadText: "模板上传中，请稍等",
            span: 24,
            propsHttp: {
              res: "data"
            },
            tip: "请上传 .xls,.xlsx 标准格式文件",
            action: "/api/blade-los/bcorps/importBCorps"
          }
        ]
      },
      // 客户类别数据
      customTypeData: [],
      excelBox: false,
      form: {},
      query: {},
      detailData: {},
      isShow: true,
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
        pageSizes: [10, 20, 30, 40, 50, 100, 200, 300, 400, 500]
      },
      selectionList: [],
      option: {},
      optionBack: {
        height: 'auto',
        calcHeight: 30,
        tip: false,
        searchIcon: true,
        searchIndex: 3,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        viewBtn: true,
        selection: true,
        addBtnText: '新建往来单位',
        dialogClickModal: false,
          menuWidth: 220,
        column: [
          {
            label: "编码",
            prop: "code",
            width: "180",
            search: true,
            rules: [{
              required: true,
              message: "请输入单位编码",
              trigger: "blur"
            }],
            overHidden:true,
          },
          {
            label: "中文名称",
            prop: "cnName",
            width: "180",
            search: true,
            rules: [{
              required: true,
              message: "请输入中文名称",
              trigger: "blur"
            }],
            overHidden:true,
          },
          {
            label: "英文名称",
            prop: "enName",
            width: "180",
            search: true,
            rules: [{
              required: true,
              message: "请输入英文名称",
              trigger: "blur"
            }],
            overHidden:true,
          },
          {
            label: "统一社会信用代码",
            prop: "uscc",
            width: 160,
            rules: [{
              required: true,
              message: "请输入统一社会信用代码",
              trigger: "blur"
            }],
              overHidden:true,
          },
          // {
          //   label: "首字母",
          //   prop: "initials",
          //   rules: [{
          //     required: true,
          //     message: "请输入首字母",
          //     trigger: "blur"
          //   }]
          // },
          {
            label: "简称",
            prop: "shortName",
            width: "180",
            rules: [{
              required: true,
              message: "请输入简称",
              trigger: "blur"
            }],
              overHidden:true,
          },
          // {
          //   label: "国家代码",
          //   prop: "cntyCode",
          //   rules: [{
          //     required: true,
          //     message: "请输入国家代码",
          //     trigger: "blur"
          //   }]
          // },
          {
            label: "国家",
            prop: "cntyName",
            width: 140,
            overHidden:true,
            search: true,
            type: "select",
            filterable:true,
            remote:true,
            dicUrl: "/api/blade-los/bcountrys/list?cnName={{key}}",
            dicData:[],
            props: {
                label: 'cnName',
                value: 'cnName',
                res:"data.records"
            },
          },
          {
            label: "中文地址",
            prop: "cnAddr",
            width: "200",
            search: true,
            rules: [{
              required: true,
              message: "请输入中文地址",
              trigger: "blur"
            }],
              overHidden:true,
          },
          {
            label: "英文地址",
            prop: "enAddr",
            width: "200",
            search: true,
            rules: [{
              required: true,
              message: "请输入英文地址",
              trigger: "blur"
            }],
              overHidden:true,
          },
          {
            label: "电话",
            prop: "tel",
            width: "120",
            search: true,
            rules: [{
              required: true,
              message: "请输入电话",
              trigger: "blur"
            }],
              overHidden:true,
          },
          {
            label: "负责人姓名",
            prop: "mgrName",
            width: 100,
            rules: [{
              required: true,
              message: "请输入负责人姓名",
              trigger: "blur"
            }],
              overHidden:true,
          },
          {
            label: "联系人姓名",
            prop: "attnName",
            width: 100,
            rules: [{
              required: true,
              message: "请输入联系人姓名",
              trigger: "blur"
            }],
              overHidden:true,
          },
          {
            label: "联系人电话",
            prop: "attnTel",
            width: 100,
            rules: [{
              required: true,
              message: "请输入联系人电话",
              trigger: "blur"
            }],
              overHidden:true,
          },
          {
            label: "客户类型",
            prop: "corpTypeName",
            width: "140",
            rules: [{
              required: true,
              message: "请输入客户类型",
              trigger: "blur"
            }],
              overHidden:true,
          },
          {
            label: "分管员",
            prop: "adminProfilesName",
            width: "100",
            rules: [{
              required: true,
              message: "请输入分管员",
              trigger: "blur"
            }],
              overHidden:true,
          },
          {
            label: "状态",
            prop: "status",
            type: 'select',
            search: true,
            dicData: [{
              label: '启用',
              value: 0
            }, {
              label: '停用',
              value: 1
            }],
            rules: [{
              required: true,
              message: "请输入状态",
              trigger: "blur"
            }],
              overHidden:true,
          },
          {
            label: "备注",
            prop: "remarks",
            span: 24,
            type: 'textarea',
            width: "180",
            slot: true,
            minRows: 3,
              overHidden:true,

          },
        ],
        designer: null,
      },
      data: [],
        // 字典数据
        ifInvoiceData:[],
    };
  },
  props:{
      // 是否的弹窗状态打开
      eldialog:{
          type:Boolean,
          default:false
      }
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        // addBtn: this.vaildData(this.permission.bcorps_add, false),
        viewBtn: this.vaildData(this.permission.bcorps_view, false),
        delBtn: this.vaildData(this.permission.bcorps_delete, false),
        editBtn: this.vaildData(this.permission.bcorps_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  async created() {
    this.option = await this.getColumnData(this.getColumnName(304), this.optionBack);
    // 这个是从海运出口跳进来的
    if (this.$route.query.corpType) {
        this.isShow = false
        this.$store.commit("DOMIO_IN_CUL");
    }
    // 付费申请开户账号点击跳过来的
    if (this.$route.query.id) {
        this.detailData.id = this.$route.query.id
        this.$nextTick(()=>{
            this.$refs.detail.activeName = "yhxx" // tabs切换成银行信息
            this.$refs.detail.getBcorpsDetailfun(this.$route.query.id)
        })
        this.isShow = false
        this.$store.commit("DOMIO_IN_CUL");

    }
    this.$store.commit("DOMIO_IN_CUL");
    this.bcountrysListfun() // 获取国家数据
    this.bcorpstypedefineListfun() // 获取客户类别
    this.ifInvoiceGetWorkDictsfun() // 字典状态
  },
  activated(){
      this.$store.commit("DOMIO_OUT_CUL");
  },
  methods: {
      // 获取国家数据
      bcountrysListfun(){
          bcountrysList(1,10).then(res=>{
              this.findObject(this.option.column, "cntyName").dicData = res.data.data.records
          })
      },
      // 获取状态字典数据
      ifInvoiceGetWorkDictsfun(){
          getWorkDicts('ifInvoice').then(res=>{
              this.ifInvoiceData = res.data.data
          })
      },
      // 禁用启用按钮
      statusfun(id,status){
          this.$confirm("确定将选择数据更改状态?", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
          }).then(()=>{
              this.loading = true
              getBcorpsDetail(id).then(res => {
                  let obj = res.data.data;
                  obj.status = status
                  updateBcorps(obj).then(res=>{
                      this.onLoad(this.page);
                      this.$message({
                          type: "success",
                          message: "操作成功!"
                      });
                  })
              });
          })

      },
    // 导入
    // handleChange(file, fileLis) {
    //   console.log('daoru');
    //   // this.$Export.xlsx(file.raw)
    //   //   .then(data => {
    //   //     this.data=data.results;
    //   //   })
    // },
    // 导出
    handleExport() {
      var condition = ''
      for (const key in this.query) {
        var value = this.query[key]
        if (value) {
          condition += `&${key}=${this.query[key]}`
        }
      }

      this.$confirm('是否导出客户资料？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        window.open(
          `/api/blade-los/bcorps/exportBCorps?${this.website.tokenHeader
          }=${getToken()}${condition}`
        );
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消' //
        });
      })
    },
    // 下载模板
    handleGet() {
      window.open(
        `/api/blade-los/bcorps/exportBCorps/template?${this.website.tokenHeader
        }=${getToken()}`
      );
    },
    // 上传成功
    onSuccess(res, done, loading, column) {
      this.excelBox = false;
      this.$message.success("导入成功！");
      loading = false;
      this.onLoad(this.page);
      done();
    },
    uploadBefore(file, done, loading) {
      done();
      loading = true;
    },
    onError(err, file, fileList) {
      err += ''
      // console.log(JSON.stringify(err.match(/{(\S*)}/)[1]));
      var data = err.match(/{(\S*)}/)[1]
      this.$message.error(data.split("msg\":")[1]);
    },
    // 左侧点击回调
    nodeClick(data) {
      // var reqiestData = this.search;
      // // console.log(data, 904)
      // reqiestData.corpType = data.id
      // if (this.search.corpType == null) {
      this.query.corpType = data.id
      // } else {
      //   this.search.corpType = null
      // }
      this.onLoad(this.page, this.query);
      // this.onLoad(this.page, reqiestData);
    },
    // 获取客户类别
    bcorpstypedefineListfun() {
      bcorpstypedefineList(1,30).then(res => {
        this.customTypeData = res.data.data.records
      })
    },
    editOpen(row) {
      this.detailData = {
        id: row.id
      };
      this.isShow = false;
    },
    rowSave(row, done, loading) {
      addBcorps(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        window.console.log(error);
      });
    },
    rowUpdate(row, index, done, loading) {
      updateBcorps(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        console.log(error);
      });
    },
    rowDel(row) {
      if (row.status === 1) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return removeBcorps(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      } else {
        this.$message({
          message: '非禁用状态无法删除',
          type: 'warning'
        });
      }
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return removeBcorps(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      this.detailData = {};
      if (this.query.corpType != null) {
        this.detailData.corpType = this.query.corpType
      }
      this.isShow = false;
      // if (["edit", "view"].includes(type)) {
      //   getBcorpsDetail(this.form.id).then(res => {
      //     this.form = res.data.data;
      //   });
      // }
      // done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      if(this.eldialog){
          this.$emit('selectionChange',list)
      }else {
          this.selectionList = list;
      }
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      BcorpsList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    goBack() {
      if (JSON.stringify(this.$route.query) != "{}") {
         this.$router.$avueRouter.closeTag();
         this.$router.push({
             path: "/iosBasicData/bcorps/index"
         });
      }
      this.isShow = true;
      this.detailData = {};
      this.onLoad(this.page);
    },
    // 类别弹窗关闭
    corpTypeClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => { });
    },
    //自定义列保存
    async saveColumnTwo(ref, option, optionBack, code) {
      /**
       * 已定义全局方法，直接使用，saveColumnData保存列数据方法,参数传值(表格名称，当前表格的option数据)
       * 已定义全局方法，直接使用，getColumnName方法用来获取枚举值，参数根据自己定义的code值获取中文名
       * 一定要执行异步操作，要等接口成功返回，才能执行下一行代码
       */
      const inSave = await this.saveColumnData(this.getColumnName(code), this[option]);
      if (inSave) {
        this.$message.success("保存成功");
        //关闭窗口
        this.$refs[ref].$refs.dialogColumn.columnBox = false;
      }
    },
    //自定义列重置
    async resetColumnTwo(ref, option, optionBack, code) {
      this[option] = this[optionBack];
      const inSave = await this.delColumnData(this.getColumnName(code), this[optionBack]);
      if (inSave) {
        this.$message.success("重置成功");
        this.$refs[ref].$refs.dialogColumn.columnBox = false;
      }
    },
    // 更改表格颜色
    headerClassName(tab) {
      //颜色间隔
      let back = ""
      if (tab.columnIndex >= 0 && tab.column.level === 1) {
        if (tab.columnIndex % 2 === 0) {
          back = "back-one"
        } else if (tab.columnIndex % 2 === 1) {
          back = "back-two"
        }
      }
      return back;
    },
    // 报表加载格式和数据
    // report 报表实例
    // content 报表设计模板, data:application/zip;base64,UEsDBAoAAAAIAClHSlfgHxo4LgwDAHeJBQAPAAAAcmVwb3J0Zml...
    // data 报表数据 JSON Object
    loadReport(report, content, data){
      var mimeString = content
        .split(',')[0]
        .split(':')[1]
        .split(';')[0]
      var byteString = atob(content.split(',')[1])

      var ab = new ArrayBuffer(byteString.length)
      var ia = new Uint8Array(ab)

      for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i)
      }

      var blob = new Blob([ab])
      JSZip.loadAsync(blob).then(function(unziped) {
        unziped
          .file('reportfile.json')
          .async('string')
          .then(res => {
            report.load(res)

            if (!!data) {
              var dataSet = new Stimulsoft.System.Data.DataSet(
                'reportData'
              )
              dataSet.readJson(data)
              report.regData('reportData', 'reportData', dataSet)
            }
          })
      })

    },
    createDesignerButtons(e) {
      if (!!e) {
        try {
          this.designer.jsObject.options.menus.localizationMenu.addEventListener(
            'click',
            this.createDesignerButtons
          )
        } catch (error) {
        }
      }

      let toolBarRow =  this.designer.jsObject.options.toolBar.firstChild.tr[0]

      let customButton =  this.designer.jsObject.StatusPanelButton(
        'exitButton',
        '关闭',
        'LoginControls.Window.CloseWhite.png',
        '关闭',
        null,
        30,
        60
      )

      customButton.image.style.width = customButton.image.style.height = '16px'

      let buttonCell = document.createElement('td')

      buttonCell.className = 'stiDesignerToolButtonCell'

      buttonCell.appendChild(customButton)

      toolBarRow.appendChild(buttonCell)

      let that=this
      customButton.action = function(e) {
        let jsObject = this.jsObject

        if (jsObject.options.reportIsModified) {
          var messageForm = jsObject.MessageFormForSave()
          messageForm.changeVisibleState(true)
          messageForm.action = function(state) {
            if (state) {
              jsObject.SendCommandSaveReport()
              setTimeout(() => {
                jsObject.SendCommandCloseReport()
                jsObject.designer.invokeExit()
                if (that.$refs.reportContainer)
                  that.$refs.reportContainer.hideContainer()
                }, 250)
            } else {
              jsObject.SendCommandCloseReport()
              jsObject.designer.invokeExit()
              if (that.$refs.reportContainer)
                that.$refs.reportContainer.hideContainer()
            }
          }
        } else {
          jsObject.SendCommandCloseReport()
          jsObject.designer.invokeExit()
          if (that.$refs.reportContainer)
            that.$refs.reportContainer.hideContainer()
        }
      }
    },
    handleReportDesigner(){
      Stimulsoft.Base.StiLicense.key = '6vJhGtLLLz2GNviWmUTrhSqnOItdDwjBylQzQcAOiHn0s4gy0Fr5YoUZ9V00Y0igCSFQzwEqYBh/N77k4f0fWXTHW5rqeBNLkaurJDenJ9o97TyqHs9HfvINK18Uwzsc/bG01Rq+x3H3Rf+g7AY92gvWmp7VA2Uxa30Q97f61siWz2dE5kdBVcCnSFzC6awE74JzDcJMj8OuxplqB1CYcpoPcOjKy1PiATlC3UsBaLEXsok1xxtRMQ283r282tkh8XQitsxtTczAJBxijuJNfziYhci2jResWXK51ygOOEbVAxmpflujkJ8oEVHkOA/CjX6bGx05pNZ6oSIu9H8deF94MyqIwcdeirCe60GbIQByQtLimfxbIZnO35X3fs/94av0ODfELqrQEpLrpU6FNeHttvlMc5UVrT4K+8lPbqR8Hq0PFWmFrbVIYSi7tAVFMMe2D1C59NWyLu3AkrD3No7YhLVh7LV0Tttr/8FrcZ8xirBPcMZCIGrRIesrHxOsZH2V8t/t0GXCnLLAWX+TNvdNXkB8cF2y9ZXf1enI064yE5dwMs2fQ0yOUG/xornE'
      // Stimulsoft.Base.StiLicense.Key = '6vJhGtLLLz2GNviWmUTrhSqnOItdDwjBylQzQcAOiHkcgIvwL0jnpsDqRpWg5FI5kt2G7A0tYIcUygBh1sPs7plofUOqPB1a4HBIXJB621mau2oiAIj+ysU7gKUXfjn/D5BocmduNB+ZMiDGPxFrAp3PoD0nYNkkWh8r7gBZ1v/JZSXGE3bQDrCQCNSy6mgby+iFAMV8/PuZ1z77U+Xz3fkpbm6MYQXYp3cQooLGLUti7k1TFWrnawT0iEEDJ2iRcU9wLqn2g9UiWesEZtKwI/UmEI2T7nv5NbgV+CHguu6QU4WWzFpIgW+3LUnKCT/vCDY+ymzgycw9A9+HFSzARiPzgOaAuQYrFDpzhXV+ZeX31AxWlnzjDWqpfluygSNPtGul5gyNt2CEoJD1Yom0VN9fvRonYsMsimkFFx2AwyVpPcs+JfVBtpPbTcZscnzUdmiIvxv8Gcin6sNSibM6in/uUKFt3bVgW/XeMYa7MLGF53kvBSwi78poUDigA2n12SmghLR0AHxyEDIgZGOTbNI33GWu7ZsPBeUdGu55R8w='
      Stimulsoft.Base.Localization.StiLocalization.addLocalizationFile( '/reports/stimulsoft/Localization/zh-CHS.xml', true, 'zh-CHS')
      Stimulsoft.Base.Localization.StiLocalization.setLocalizationFile('/reports/stimulsoft/Localization/zh-CHS.xml' )

      var options = new Stimulsoft.Designer.StiDesignerOptions()
      options.appearance.fullScreenMode = true
      options.allowChangeWindowTitle = false
      options.toolbar.showSaveDialog = false

      options.toolbar.showFileMenuSave = false
      options.toolbar.showFileMenuAbout = false
      options.toolbar.showFileMenuClose = false
      options.toolbar.showFileMenuExit = false
      options.toolbar.showFileMenuInfo = false
      options.toolbar.showFileMenuHelp = false
      options.toolbar.showFileMenuNew = false

      options.appearance.showTooltips = false
      options.appearance.showDialogsHelp = false

      options.toolbar.showSetupToolboxButton = true
      options.appearance.htmlRenderMode = Stimulsoft.Report.Export.StiHtmlExportMode.Table

      let designer = new Stimulsoft.Designer.StiDesigner(
        options,
        'StiDesigner',
        false
      )

      designer.onSaveReport = (e)=>{
        console.log('onSaveReport')
        /*
        let jsObject = this.jsObject

        if (!e.report.isModified)
          return
        var jsonString = e.report.saveToJsonString()
        var zip = new JSZip()

        zip.file('reportfile.json', jsonString)
        zip.generateAsync({
          type: 'blob',
          compression: 'DEFLATE',
          compressionOptions: {
            level: 9
          }
        }).then(content => {
          var reader = new FileReader()
          reader.onload = event => {
            var reportContent = reader.result

            // 此处将报表模版保存到数据库
            // save content to database

            e.report.isModified = false
          }
          reader.readAsDataURL(content)
        })
        */
      }

      let report = new window.Stimulsoft.Report.StiReport();

      report.styles.loadFile('static/Plugins/reports/css/Styles.sts')
      report.applyStyles()

      // 加载文件
      console.log("从 url 报表");
      report.loadFile("/reports/stimulsoft/demos/SimpleList.mrt");
      // 从模版和数据加载报表
      // loadReport(report, '', {})

      designer.report = report
      this.designer=designer

      this.$refs.reportContainer.showContainer(
        ()=> {
          setTimeout(() => {
            designer.renderHtml('reportContainer')
            this.createDesignerButtons()
          }, 50)
        },
        ()=>{
        },
      )
    },
    createViewerButtons (viewer){
      viewer.jsObject.collections.images['myClose.png'] =
        'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABmJLR0QA/wD/AP+gvaeTAAAA0ElEQVQ4ja3TO05CQRQG4A8iOwAbtYWETndAaecK7NwCKmETtJZsSBNLobEz8ZFIJQ0UnOGSm3DnYviTybzO/895DQXGWGCVGQuMEqkRcwcfuMOLalziCaf4TIe9UG9nyMJmFRzNGoRK1BU4xxx9G7cfwostciGk+x8MqgySwDXe4tU53hVV+MNtTmAoX84JGv9NYgrHyR6DV8wUSW7hItZLm36ZVoVQxsFJLOMsPOrH/h7dQwR2cdxOTEn8DtUbPGc4V2H7Vb4Yqfedf/GYSGt8VUmxgyfuBAAAAABJRU5ErkJggg=='
      const closeBtn = viewer.jsObject.SmallButton(
        'closeBtn',
        '关闭',
        'myClose.png'
      )

      const toolbarTable = viewer.jsObject.controls.toolbar.firstChild.firstChild
      const buttonsTable = toolbarTable.rows[0].lastChild.lastChild
      const userButtonCell = buttonsTable.rows[0].insertCell(0)
      userButtonCell.className = 'stiJsViewerClearAllStyles'
      userButtonCell.appendChild(closeBtn)

      let that=this
      closeBtn.action = function() {
        console.log(that.$refs.ReportContainer)
        if (that.$refs.reportContainer)
          that.$refs.reportContainer.hideContainer()
      }
    },
    handleReportPreview(){
      Stimulsoft.Base.StiLicense.key = '6vJhGtLLLz2GNviWmUTrhSqnOItdDwjBylQzQcAOiHn0s4gy0Fr5YoUZ9V00Y0igCSFQzwEqYBh/N77k4f0fWXTHW5rqeBNLkaurJDenJ9o97TyqHs9HfvINK18Uwzsc/bG01Rq+x3H3Rf+g7AY92gvWmp7VA2Uxa30Q97f61siWz2dE5kdBVcCnSFzC6awE74JzDcJMj8OuxplqB1CYcpoPcOjKy1PiATlC3UsBaLEXsok1xxtRMQ283r282tkh8XQitsxtTczAJBxijuJNfziYhci2jResWXK51ygOOEbVAxmpflujkJ8oEVHkOA/CjX6bGx05pNZ6oSIu9H8deF94MyqIwcdeirCe60GbIQByQtLimfxbIZnO35X3fs/94av0ODfELqrQEpLrpU6FNeHttvlMc5UVrT4K+8lPbqR8Hq0PFWmFrbVIYSi7tAVFMMe2D1C59NWyLu3AkrD3No7YhLVh7LV0Tttr/8FrcZ8xirBPcMZCIGrRIesrHxOsZH2V8t/t0GXCnLLAWX+TNvdNXkB8cF2y9ZXf1enI064yE5dwMs2fQ0yOUG/xornE'
      // Stimulsoft.Base.StiLicense.Key = '6vJhGtLLLz2GNviWmUTrhSqnOItdDwjBylQzQcAOiHkcgIvwL0jnpsDqRpWg5FI5kt2G7A0tYIcUygBh1sPs7plofUOqPB1a4HBIXJB621mau2oiAIj+ysU7gKUXfjn/D5BocmduNB+ZMiDGPxFrAp3PoD0nYNkkWh8r7gBZ1v/JZSXGE3bQDrCQCNSy6mgby+iFAMV8/PuZ1z77U+Xz3fkpbm6MYQXYp3cQooLGLUti7k1TFWrnawT0iEEDJ2iRcU9wLqn2g9UiWesEZtKwI/UmEI2T7nv5NbgV+CHguu6QU4WWzFpIgW+3LUnKCT/vCDY+ymzgycw9A9+HFSzARiPzgOaAuQYrFDpzhXV+ZeX31AxWlnzjDWqpfluygSNPtGul5gyNt2CEoJD1Yom0VN9fvRonYsMsimkFFx2AwyVpPcs+JfVBtpPbTcZscnzUdmiIvxv8Gcin6sNSibM6in/uUKFt3bVgW/XeMYa7MLGF53kvBSwi78poUDigA2n12SmghLR0AHxyEDIgZGOTbNI33GWu7ZsPBeUdGu55R8w='
      Stimulsoft.Base.Localization.StiLocalization.addLocalizationFile( '/reports/stimulsoft/Localization/zh-CHS.xml', true, 'zh-CHS')
      Stimulsoft.Base.Localization.StiLocalization.setLocalizationFile('/reports/stimulsoft/Localization/zh-CHS.xml' )

      // 工具栏
      var options = new Stimulsoft.Viewer.StiViewerOptions()
      options.height = '100%'

      options.appearance.scrollbarsMode = true
      options.toolbar.showDesignButton = false
      options.toolbar.showAboutButton = false
      options.toolbar.showResourcesButton = false
      options.toolbar.showFullScreenButton = false
      options.toolbar.showOpenButton = false

      options.appearance.showTooltips = false
      options.appearance.showDialogsHelp = false

      options.exports.showExportToDocument = false
      options.toolbar.showParametersButton = true
      options.appearance.bookmarksPrint = true

      options.toolbar.printDestination = Stimulsoft.Viewer.StiPrintDestination.Direct

      options.appearance.htmlRenderMode = Stimulsoft.Report.Export.StiHtmlExportMode.Table

      let viewer = new Stimulsoft.Viewer.StiViewer(options, 'StiViewer', false)

      // 报表
      console.log("创建一个报表实例");
      let report = new window.Stimulsoft.Report.StiReport();

      // 加载文件
      console.log("从url加载报表");
      report.loadFile("/reports/stimulsoft/demos/SimpleList.mrt");
      // 从模版和数据加载报表
      // loadReport(report, '', {})

      viewer.report = report;

      this.$refs.reportContainer.showContainer(
        ()=> {
          setTimeout(() => {
            viewer.renderHtml('reportContainer')
            this.createViewerButtons(viewer)
          }, 50)
        },
        ()=>{
        },
      )

      console.log("加载成功完成!");
    },

  }
};
</script>

<style lang="scss" scoped>
::v-deep#out-table .back-one {
  background: #ecf5ff !important;
}

::v-deep#out-table .back-two {
  background: #ecf5ff !important;
}

::v-deep .el-input-group__append {
  padding: 0 0px !important;
}

/deep/ .el-tree-node__content>.el-tree-node__expand-icon {
  visibility: hidden;
}

/deep/ .el-col-md-8 {
  width: 24.33333%;
}
.statusClass {
    border-radius: 10px;
    color: #fff;
    text-align: center;
}
</style>
