<template>
  <div class="height100" style="width:100%;">
    <!-- 工具栏 -->
    <input
      name="file"
      type="file"
      accept=".txt"
      multiple="multiple"
      @change="ruleFileChange"
      class="none"
      ref="selectFile"
    />
    <ts-table
      :source="source"
      width="100%"
      height="100%"
      style="background:#fff;"
      ref="userDefinedForm"
      v-if="!isFromPreview"
    >
      <ts-radio
        v-model="appType"
        :data="appTypeSource"
        type="group"
        :isDefaultFirst="true"
        class="mrgl5"
        slot="filterBoxLeftLast"
        width="240px"
        @change="designFn"
      ></ts-radio>
      <div slot="filterRightSlot">
        <tsButton icon="iconfont icon-Group-13" @click="add">普通模式</tsButton>
        <tsButton
          icon="iconfont icon-Group-13"
          class="mrgl5"
          @click="addSelfAnalysis"
          v-if="appType==1"
        >自助分析</tsButton>
        <!-- <tsButton icon="iconfont icon-Group-13" class="mrgl5" @click="addBig" v-if="appType==1">大屏模式</tsButton> -->
        <tsButton icon="iconfont icon-daochu" class="mrgl5" @click="exportForm">批量导出</tsButton>
        <tsButton icon="iconfont icon-Group-7" class="mrgl5" @click="importForm">导入</tsButton>
        <!-- <tsButton icon="iconfont icon-daochu" class="mrgl5" @click="batchExportForm">批量导出</tsButton>
        <tsButton icon="iconfont icon-Group-7" class="mrgl5" @click="batchImportForm">批量导入</tsButton>-->
      </div>
    </ts-table>
    <!-- 弹窗新增 -->
    <diaLog
      v-for="(item,index) of dialogEditors"
      :key="index"
      class="editor_dialog"
      :source="{title:item.designName?'设计器(' + item.designName + ')':'设计器',closeBtn:true}"
      ref="userDefinedDialog"
      width="100%"
      height="100%"
      @beforeHideMethod="beforeHideMethod"
      @hide="closeEditorDialog"
    >
      <user-defined-editor
        :isAdd="isAdd"
        :oldData="oldDataList[index]"
        :biModel="biModel"
        @refreshDefinedFormTable="refreshDefinedFormTable"
      />
    </diaLog>
    <diaLog
      v-if="isFromPreview"
      class="editor_dialog"
      :source="layObj"
      ref="targetInfoDialog"
      :width="layObj.key=='infoTable'?'100%':'40%'"
      height="100%"
      type="right"
    >
      <biTargetInfo :target="layObj.target" v-if="layObj.key=='info'"></biTargetInfo>
      <biTargetInfoTable :target="layObj.target" v-if="layObj.key=='infoTable'"></biTargetInfoTable>
    </diaLog>

    <diaLog
      :source="layObj"
      ref="userDefinedRightDialog"
      class="userDefinedRightDialog_con"
      :type="layObj.type||'right'"
      :width="layObj.width||'40%'"
      height="100%"
      @close="closeDialog"
    >
      <biPreviewForm
        v-if="dialogType==='previewReport'"
        ref="biPreview"
        :paramId="layObj.paramId"
        :isFromPreview="true"
        :isFromList="true"
        :versionCode="layObj.versionCode"
        :displayMode="layObj.displayMode"
      ></biPreviewForm>
      <div v-if="dialogType==='relateReport'" style="height:calc(100% - 12px);padding:6px">
        <ts-table :source="relateSource" width="100%" height="100%" ref="relateReportTable"></ts-table>
      </div>
      <bi-menu-merge
        v-if="dialogType==='biMenuMerge'"
        ref="biMenuMerge"
        :menuName="menuName"
        @submitClick="submitClick"
        :key="new Date()+''"
      />
      <bi-menu-add
        v-if="dialogType==='biMenuAdd'"
        ref="biMenuAdd"
        :menuName="menuName"
        @submitClick="submitClick"
        :row="other"
        :key="new Date()+''"
      />
      <bi-save
        ref="biMenuSort"
        @saveClick="sortModify"
        v-if="dialogType==='biMenuSort'"
        :oldData="clickItem"
        :biModel="clickItem.displayMode == 0?'custom':'bigScreen'"
        saveType="form"
        :key="new Date()+''"
      ></bi-save>
      <bi-menu-copy
        v-if="dialogType==='biMenuCopy'"
        ref="biMenuCopy"
        @submitClick="copyModify"
        :copyData="copyData"
        :key="copyData.id"
      />
      <pivot-table-editor
        v-if="dialogType==='pivotTable'"
        ref="pivotTableEditor"
        :isAdd_="isAdd"
        :oldData_="oldData"
        @refreshDefinedFormTable="refreshDefinedFormTable"
      />
    </diaLog>
  </div>
</template>

<script>
import userDefinedEditor from './components/userDefinedEditor'
import biMenuMerge from './components/biDialog/biMenuMerge'
import biMenuAdd from './components/biDialog/biMenuAdd'
import BiMenuCopy from './components/biDialog/biMenuCopy'
import biSave from './components/biDialog/biSave'
import biTargetInfo from './components/uiElement/biTargetInfo'
import biTargetInfoTable from './components/uiElement/biTargetInfoTable'
import pivotTableEditor from './pivotTable/pivotTableEditor'
import biUtils from './utils/biUtils'
// import biPreviewForm from './biPreviewForm'
export default {
  name: 'biEditor',
  components: {
    userDefinedEditor,
    biMenuMerge,
    biMenuAdd,
    biSave,
    BiMenuCopy,
    biTargetInfo,
    biTargetInfoTable,
    pivotTableEditor
    // biPreviewForm
  },
  props: {
    isFromPreview: {
      // 是否从预览进入
      type: Boolean,
      default: false
    },
    formId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      isSaved: false, // 是否被保存过
      timer: '',
      menuName: '',
      sortData: '',
      dialogType: '',
      layObj: {},
      oldDataList: [], // 用于存多个oldData，避免多框时混淆
      oldData: [],
      themeClassCodes: [
        'PLAT_USER_EDITOR_REPORT',
        'PLAT_USER_EDITOR_INDEX',
        'PLAT_USER_EDITOR_BUSINESS',
        'PLAT_USER_EDITOR_FORM'
      ],
      appType: '1',
      isAdd:true,
        // this.$store.state.bi.isBIAdd[
        //   'd' + (this.$store.state.bi.dialogEditors.length - 1)
        // ] || true,
      source: this.sourceFn(),
      relateSource: this.sourceRelateFn(), // 关联报表
      biModel: 'custom',
      clickItem: {},
      copyData: {},
      dialogEditors: [], // 设计区弹框
      appTypeSource: [
        {
          value: '1',
          text: '报表'
        },
        {
          value: '2',
          text: '门户'
        },
        {
          value: '4',
          text: '表单'
        },
        {
          value: '3',
          text: '业务组件'
        }
      ]
    }
  },
  created() {
    this.isAdd =  this.$store.state.bi.isBIAdd[
          'd' + (this.$store.state.bi.dialogEditors.length - 1)
        ] || true
    console.dir(this)
  },

  mounted() {
    this.$eventBus.$on('openDesignDialog', this.openDesignDialog)
    let sysRoleCode = global.userInfo?global.userInfo.sysRoleCode:''
    if (
      sysRoleCode.indexOf(window.platSysRoleColde) > -1 ||
      sysRoleCode.indexOf(window.superSysRoleColde) > -1
    ) {
      // 系统管理员权限
      this.source.filtrate.push({
        name: 'systemReport',
        placeholder: '请选择系统报表',
        width: '120px',
        type: 'select',
        deploy: {
          dataType: 'local',
          data: [
            {
              categoryCode: '01',
              categoryName: '系统'
            },
            {
              categoryCode: '02',
              categoryName: '自定义'
            }
          ],
          code: 'categoryCode',
          text: 'categoryName'
        },
        event: this.refresh
      })
    }
  },
  methods: {
    // 列表配置
    sourceFn() {
      let self = this
      return {
        checkbox: true,
        rownumbers: true,
        url: '/ts-bi/api/BiReportDesign/list',
        method: 'get',
        colModel: this.colFn(),
        showOverflow: true,
        timeout: 20000, // 指定请求超时的毫秒数
        postData: {
          themeClassifyValue: '',
          designName: '',
          systemReport: '',
          appType: 1
        },
        filtrate: [
          {
            title: '',
            name: 'themeClassifyValue',
            placeholder: '请选择主题分类',
            width: '150px',
            type: 'select',
            deploy: {
              dataType: 'json',
              url: '/ts-system/api/dict/item/list/PLAT_USER_EDITOR_REPORT',
              method: 'get',
              data: {},
              page: 'pageNo',
              code: 'itemCode',
              text: 'itemName',
              condition: 'condition',
              isReq: true,
              value: {
                name: '',
                code: ''
              }
            },
            event: this.designFn,
            isbutton: true
          },
          {
            title: '',
            name: 'designName',
            placeholder: '请输入名称',
            width: '200px',
            type: 'text',
            isbutton: true
          }
        ]
      }
    },
    colFn() {
      let self = this
      return [
        {
          title: '操作',
          field: 'handle',
          align: 'center',
          width: 100,
          buttons: [
            {
              icon: 'iconfont icon-Group-16 font16',
              type: 'editor',
              event: this.editor,
              color: 'var(--base-acv)',
              text: '编辑'
            },
            {
              icon: 'iconfont icon-Group-25 font16',
              event: this.biMenuSort,
              text: '分类'
            },
            {
              icon: 'iconfont icon-yulan font16',
              event: this.previewForm,
              color: '#51c75b',
              text: '预览'
            },
            {
              icon: 'iconfont icon-Group-17 font16',
              event: this.delete,
              // color: '#8470FF',
              text: '删除'
            },
            {
              icon: 'iconfont icon-jianmo font16',
              event: this.biMenuCopy,
              text: '复制'
            },

            {
              icon: 'iconfont icon-bianyi font16',
              event: this.biBianYi,
              color: '#f59a23',
              text: '编译',
              visiableEvent: this.showBianYiBtn
            },
            {
              icon: 'iconfont icon-jiaohu font16',
              event: this.showRelateReport,
              color: '#f56c6c',
              text: '查看关联',
              visiableEvent: this.showBianYiBtn
            },
            {
              icon: 'iconfont icon-fenli font16',
              event: this.biMenuAdd,
              color: '#f59a23',
              text: '分配菜单',
              visiableEvent: this.showBiMenuAdd
            }
          ]
        },
        {
          title: '设计器名称',
          field: 'designName',
          width: 200,
          type: 'html',
          formatter: function({ cellValue, row, column }) {
            return (
              '<div style="color:' +
              (row.systemReport == '01' ? '#e6a23c' : '') +
              '">' +
              (cellValue || '-') +
              '</div>'
            )
          }
        },
        {
          title: '主题分类',
          field: 'themeClassifyName',
          width: 130,
          type: 'html',
          formatter: function({ cellValue, row, column }) {
            return (
              '<div style="color:' +
              (row.systemReport == '01' ? '#e6a23c' : '') +
              '">' +
              (cellValue || '-') +
              '</div>'
            )
          }
        },
        {
          title: '版本号',
          field: 'versionCode',
          width: 60,
          align: 'center',
          type: 'html',
          formatter: function({ cellValue, row, column }) {
            return (
              '<div style="color:' +
              (row.systemReport == '01' ? '#e6a23c' : '') +
              '">' +
              (cellValue || '草稿') +
              '</div>'
            )
          }
        },
        {
          title: '模式',
          field: 'displayMode',
          width: 80,
          type: 'html',
          formatter: function({ cellValue, row, column }) {
            return (
              '<div style="color:' +
              (row.systemReport == '01' ? '#e6a23c' : '') +
              '">' +
              (cellValue == 1
                ? '大屏模式'
                : cellValue == 2
                ? '自助分析'
                : '普通模式') +
              '</div>'
            )
          }
        },
        {
          title: '类别',
          field: 'systemReport',
          width: 80,
          type: 'html',
          formatter: function({ cellValue, row, column }) {
            return (
              '<div style="color:' +
              (row.systemReport == '01' ? '#e6a23c' : '') +
              '">' +
              (cellValue == '01' ? '系统' : '自定义') +
              '</div>'
            )
          }
        },

        {
          title: '创建人',
          field: 'createUserName',
          width: 130,
          type: 'html',
          formatter: function({ cellValue, row, column }) {
            return (
              '<div style="color:' +
              (row.systemReport == '01' ? '#e6a23c' : '') +
              '">' +
              (cellValue || '-') +
              '</div>'
            )
          }
        },
        {
          title: '创建日期',
          field: 'createDate',
          width: 150,
          sortable: true,
          type: 'html',
          formatter: function({ cellValue, row, column }) {
            return (
              '<div style="color:' +
              (row.systemReport == '01' ? '#e6a23c' : '') +
              '">' +
              (cellValue || '-') +
              '</div>'
            )
          }
        },
        {
          title: '更新人',
          field: 'updateUserName',
          width: 130,
          type: 'html',
          formatter: function({ cellValue, row, column }) {
            return (
              '<div style="color:' +
              (row.systemReport == '01' ? '#e6a23c' : '') +
              '">' +
              (cellValue || '-') +
              '</div>'
            )
          }
        },
        {
          title: '更新时间',
          field: 'updateDate',
          width: 150,
          sortable: true,
          type: 'html',
          formatter: function({ cellValue, row, column }) {
            return (
              '<div style="color:' +
              (row.systemReport == '01' ? '#e6a23c' : '') +
              '">' +
              (cellValue || '-') +
              '</div>'
            )
          }
        }
      ]
    },
    sourceRelateFn() {
      let self = this
      return {
        rownumbers: true,
        url: '/ts-bi/api/BiReportDesign/selectRelationReport',
        method: 'post',
        colModel: this.colFn().splice(1),
        showOverflow: true,
        contentType: 'application/x-www-form-urlencoded',
        postData: {
          id: ''
        }
      }
    },
    // 删除
    delete(d) {
      const _this = this
      this.$mModal.confirm('您确定要删除吗？').then(type => {
        if (type == 'confirm') {
          this.$api({
            url: '/ts-bi/api/BiReportDesign/delete/' + d.id,
            method: 'post',
            headers: {
              'Content-Type': 'application/json; charset=utf-8'
            }
          })
            .then(function(response) {
              // 请求成功
              if (response.success) {
                _this.refreshDefinedFormTable()
                _this.$utils.msg(_this, '删除成功', 'success')
              } else {
                _this.$utils.msg(_this, response.message, 'error')
              }
            })
            .catch(function(error) {
              // 请求失败
              _this.$utils.msg(_this, error.message, 'error')
            })
        }
      })
    },
    showBiMenuAdd(row) {
      if (row.appType == '3' || !row.versionCode) {
        // 业务组件
        return false
      }
      return true
    },
    // 编译
    showBianYiBtn(row) {
      if (row.appType == '3') {
        // 业务组件
        return true
      }
      return false
    },
    // 切换类型
    designFn(row) {
      this.source.postData.themeClassifyValue = row.value
      this.$nextTick(() => {
        this.source.postData.appType = this.appType
        this.source.filtrate[0].deploy.url =
          '/ts-system/api/dict/item/list/' +
          this.themeClassCodes[Number(this.appType) - 1]
        this.$refs.userDefinedForm.refresh()
      })
    },
    refresh() {
      this.$refs.userDefinedForm.refresh()
    },
    // 详情
    add() {
      this.dialogEditors = [{}]
      this.biModel = 'custom'
      this.other = {}
      this.oldData = []
      this.oldDataList.push([]) // 用于存多个oldData，避免多框时混淆
      this.$nextTick(() => {
        this.$store.commit('setBIAdd', true)
        this.$store.commit('setSelectData', {})
        this.$store.commit('setNatureArr', [])
        // this.$store.commit('setAllBiPreviewMap', {})
        this.$refs.userDefinedDialog[0].open()
      })
    },
    // 增加自助分析
    addSelfAnalysis() {
      this.layObj = this.layObjFn('pivotTable')
      this.isAdd = true
      this.layObj.title = '新增自助分析设计'
      this.layObj.closeBtn = true
      this.$refs.userDefinedRightDialog.open()
    },
    // 查看关联
    showRelateReport(row) {
      this.relateSource.postData.id = row.id
      this.layObj = this.layObjFn('relateReport')
      this.layObj.title = '查看关联'
      this.$refs.userDefinedRightDialog.open()
    },
    // 打开指标项窗体
    openTargetItemDialog(row, key) {
      this.layObj = {
        key: key,
        title: row.targetName,
        closeBtn: true,
        target: row
      }
      this.$nextTick(() => {
        if (this.$refs.targetInfoDialog) {
          this.$refs.targetInfoDialog.open()
        }
      })
    },
    // 编译
    biBianYi(row) {
      const _this = this
      this.$mModal
        .confirm('是否需要对所有使用该业务组件的报表，进行全量更新覆盖？')
        .then(type => {
          if (type == 'confirm') {
            this.$api({
              url:
                '/ts-bi/api/BiReportDesign/compileRelationBusinessComponent/' +
                row.id,
              method: 'get',
              headers: {
                'Content-Type': 'application/json; charset=utf-8'
              }
            })
              .then(function(response) {
                // 请求成功
                if (response.success) {
                  _this.$utils.msg(
                    _this,
                    response.message || '编译成功！',
                    'success'
                  )
                } else {
                  _this.$utils.msg(
                    _this,
                    response.message || '编译失败！',
                    'error'
                  )
                }
              })
              .catch(function(error) {
                // 请求失败
                _this.$utils.msg(_this, error.message, 'error')
              })
          }
        })
    },
    // 大屏模式
    addBig() {
      this.dialogEditors = [{}]
      this.biModel = 'bigScreen'
      this.other = {}
      this.oldData = []
      this.$store.commit('setBIAdd', true)
      this.$store.commit('setSelectData', {})
      this.$store.commit('setNatureArr', [])
      this.$nextTick(() => {
        this.$refs.userDefinedDialog[0].open()
      })
    },
    //导入
    importForm() {
      this.$refs.selectFile.click()
    },
    ruleFileChange(e) {
      const files = e.target.files
      e.target.value = ''
      let postUrl = []
      if (files.length > 0) {
        for (let file of files) {
          postUrl.push(this.ruleFileUpload(file))
        }
        Promise.all(postUrl)
          .then(res => {
            // this.$utils.msg(this, '上传成功！', 'success')
          })
          .catch(res => {})
      }
    },
    // upload
    ruleFileUpload(file) {
      const _this = this
      let data = new FormData()
      data.append('file', file)
      this.$api({
        url: '/ts-bi/api/BiReportDesign/importReport',
        method: 'post',
        data: data,
        processData: false,
        contentType: false,
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        onUploadProgress(res) {},
        cancel(c) {}
      })
        .then(function(response) {
          // 请求成功
          if (response.success) {
            _this.$refs.userDefinedForm.refresh()
          } else {
            _this.$utils.msg(_this, '上传失败！', 'error')
          }
        })
        .catch(function(error) {
          _this.$utils.msg(_this, '上传失败！', 'error')
        })
    },
    //导出
    exportForm() {
      let rows = this.$refs.userDefinedForm.getCheckboxRecords()
      if (!rows || rows.length == 0) {
        this.$utils.msg(this, '请至少选择一条数据进行操作！', 'warning')
        return false
      }
      let ds = []
      for (let item of rows) {
        ds.push(item.id)
      }
      const _this = this
      this.$api({
        url: '/ts-bi/api/BiReportDesign/exportReport',
        method: 'post',
        data: { id: ds.join(',') }, //data,
        responseType: 'blob'
      })
        .then(function(res) {
          let filename = res.headers['content-disposition']
            .split(';')[1]
            .split('fileName=')[1]
          if (filename) {
            filename = JSON.parse(filename)
          } else {
            filename = new Date().getTime() + '.zip'
          }
          // 请求成功
          let blob = res.data
          if (blob.size > 0) {
            let reader = new FileReader()
            reader.readAsDataURL(blob) // 转换为base64，可以直接放入a标签href
            reader.onload = function(e) {
              // 转换完成，创建一个a标签用于下载
              let a = document.createElement('a')
              a.download = filename
              a.href = e.target.result
              document.body.appendChild(a)
              a.click()
              a.remove()
            }
          }
        })
        .catch(function(error) {
          // 请求失败
        })
    },
    //  批量导出
    // batchExportForm() {
    //   if (!this.datasetCodeList) {
    //     this.$utils.msg(this, '至少选择一条需要导出的数据', 'error')
    //     return
    //   }
    //   let url = '/ts-bi/api/BiReportDesign/exportReport'
    // },
    // //批量导入
    // batchImportForm() {
    //   this.$refs.selectFile.click()
    // },
    //合并菜单
    biMenuMerge() {
      this.other = {}
      this.layObj = this.layObjFn('biMenuMerge')
      this.$refs.userDefinedRightDialog.open()
    },
    // 隐藏之前
    async beforeHideMethod(callback) {
      let isNoEidt = true
      if (
        !this.$store.state.bi.isBIAdd[
          'd' + (this.$store.state.bi.dialogEditors.length - 1)
        ] // 非新增
      ) {
        let oldNatureArr =
          (this.oldDataList &&
          this.oldDataList[this.dialogEditors.length - 1] &&
          this.oldDataList[this.dialogEditors.length - 1].length > 0
            ? this.oldDataList[this.dialogEditors.length - 1][0].other
            : '{}') || '{}'
        let newNatureArr = this.$store.state.bi.natureArr[
          'd' + (this.dialogEditors.length - 1)
        ]
        isNoEidt =
          JSON.stringify(JSON.parse(oldNatureArr).natureArr) ==
          JSON.stringify(newNatureArr) // 判断是否修改过
      } else {
        // 新增
        let newNatureArr = this.$store.state.bi.natureArr[
          'd' + (this.dialogEditors.length - 1)
        ]
        isNoEidt = !newNatureArr || newNatureArr.length == 0
      }
      if (isNoEidt || this.isSaved) {
        // 未修改过或已经保存过
        callback({
          val: true
        })
        // this.closeEditorDialog()
      } else {
        callback({
          showBeforeHideDialog: true,
          beforeHideDialogText: '您已进行过修改，确定要退出吗？',
          val: false
        })
      }
    },
    closeDialog() {
      if (this.isFromPreview) {
        // 来自预览，恢复编辑器显示
        this.$parent.isShowPivotTableEditor = true
      }
    },
    //关闭编辑弹框
    closeEditorDialog() {
      let natureArr = { ...this.$store.state.bi.natureArr }
      delete natureArr['d' + (this.dialogEditors.length - 1)]
      this.$store.commit('setNatureArr', { ...natureArr })
      let biPreviewMap = { ...this.$store.state.bi.biPreviewMap }
      delete biPreviewMap['d' + (this.dialogEditors.length - 1)]
      this.$store.commit('setAllBiPreviewMap', { ...biPreviewMap })
      let biAdds = { ...this.$store.state.bi.isBIAdd }
      delete biAdds['d' + (this.dialogEditors.length - 1)]
      this.$store.commit('setBIAdd', { ...biAdds })
      this.oldDataList.pop()
      this.dialogEditors.pop()
      if (this.biModel == 'bigScreen') {
        this.$store.commit('setCurComponent', { component: null, zIndex: null })
        this.$store.commit('setBigScreenNature', { natureArr: [] })
      }
      this.$store.commit('setSelectData', {})
      if (!this.$store.state.bi.isBIAdd && this.dialogType !== 'editor') {
        this.$refs.userDefinedForm.refresh() //提交成功后刷新页面
      }
    },
    //分类
    biMenuSort(d) {
      this.clickItem = _.cloneDeep(d)
      this.layObj = this.layObjFn('biMenuSort')
      this.$refs.userDefinedRightDialog.open()
    },
    //复制
    biMenuCopy(d) {
      this.copyData.id = _.cloneDeep(d).id
      this.copyData.newDesignName = ''
      this.layObj = this.layObjFn('biMenuCopy')
      this.$refs.userDefinedRightDialog.open()
    },

    // 菜单分配
    biMenuAdd(d) {
      this.other = d
      this.menuName = d.designName
      this.layObj = this.layObjFn('biMenuAdd')
      this.$refs.userDefinedRightDialog.open()
    },
    //编辑
    editor(d) {
      const _this = this
      this.biModel = d.displayMode == '1' ? 'bigScreen' : 'custom'
      if (d.displayMode && d.versionCode && d.versionCode != '草稿') {
        // 列表进入或者非草稿
        this.$api({
          url: '/ts-bi/api/BiReportDesign/' + d.id,
          method: 'get',
          headers: {
            'Content-Type': 'application/json; charset=utf-8'
          }
        })
          .then(function(response) {
            // 请求成功
            if (response.success && response.object) {
              let oldData = response.object
              _this.setOtherData(d, oldData)
            } else {
              _this.$utils.msg(
                _this,
                response.message || '获取信息失败',
                'error'
              )
            }
          })
          .catch(function(error) {
            // 请求失败
            _this.$utils.msg(_this, error.message || '系统异常', 'error')
          })
      } else {
        let url =
          d.versionCode && d.versionCode != '草稿'
            ? '/ts-version/api/version/data?versionCode=' + d.versionCode
            : '/ts-version/api/version/data?type=3&systemName=平台应用&moduleName=自定义报表&name=' +
              d.id +
              '&copyFlag=1'
        this.$api({
          url: url,
          method: 'get',
          contentType: 'application/x-www-form-urlencoded; charset=utf-8'
        })
          .then(function(res) {
            if (res.success) {
              let oldData = []
              d.other = _this.$utils.escape2Html(res.object)
              oldData.push(d) //包装到oldData
              _this.setOtherData(d, oldData)
            } else {
              _this.$utils.msg(_this, '加载失败，请联系管理员', 'error')
            }
          })
          .catch(function(error) {
            console.warn(error)
            // 请求失败
            _this.$utils.msg(_this, '加载失败，请联系管理员', 'error')
          })
      }
    },
    // 设置其他信息
    setOtherData(d, oldData) {
      const _this = this
      if (d.displayMode == 2) {
        // 透视表
        this.layObj = this.layObjFn('pivotTable')
        this.oldData = oldData
        this.isAdd = false
        this.layObj.title = '自助分析设计(' + d.designName + ')'
        this.layObj.closeBtn = true
        this.$refs.userDefinedRightDialog.open()
        this.$parent.isShowPivotTableEditor = false // 打开设计区，暂时隐藏透视表
      } else {
        _this.layObj = _this.layObjFn('editor', d)
        _this.dialogEditors.push({ designName: d.designName })
        _this.oldDataList.push(oldData)
        _this.$nextTick(() => {
          _this.$store.commit('setBIAdd', false)
          if (this.$refs.userDefinedDialog) {
            _this.$refs.userDefinedDialog[_this.dialogEditors.length - 1].open()
          }
        })
      }
    },
    // 弹窗属性
    layObjFn(type, row) {
      let d = {
        title: '', // 标题
        closeBtn: false // 关闭按钮区域，boolean 默认：false
      }
      this.dialogType = type
      if (type === 'biMenuMerge') {
        d.title = '分配菜单'
        d.buttons = [{ text: '确认', event: this.biMenuMergeAffirm }]
      } else if (type === 'biMenuAdd') {
        d.title = '分配菜单'
        d.buttons = [{ text: '确认', event: this.biMenuAddAffirm }]
      } else if (type === 'biMenuSort') {
        d.title = '分类'
        d.buttons = [
          {
            text: '确认',
            event: this.biMenuSortAffirm,
            icon: 'iconfont icon-baocun1'
          }
        ]
      } else if (type === 'biMenuCopy') {
        d.title = '复制'
        d.buttons = [
          {
            text: '确认',
            event: this.biMenuCopyAffirm,
            icon: 'iconfont icon-baocun1'
          }
        ]
      } else if (type == 'previewReport' || type == 'pivotTable') {
        d.title = row ? row.designName : ''
        d.type = 'noRight'
        d.width = '100%'
        d.height = '100%'
      }
      return d
    },
    //复制确认框
    biMenuCopyAffirm() {
      this.$refs.biMenuCopy.$refs.xForm.submit()
      // this.$refs.biMenuCopy.$refs.submit.$el.click()
    },
    // 分类确认框
    biMenuSortAffirm() {
      this.$refs.biMenuSort.$refs.xForm.submit()
      // this.$refs.biMenuSort.$refs.submit.$el.click()
    },
    //菜单分配确认框
    biMenuAddAffirm() {
      this.$refs.biMenuAdd.$refs.xForm.submit()
      // this.$refs.biMenuAdd.$refs.submit.$el.click()
    },
    //合并菜单分配
    biMenuMergeAffirm() {
      this.$refs.biMenuMerge.$refs.xForm.submit()
      // this.$refs.biMenuMerge.$refs.submit.$el.click()
    },
    //提交复制
    copyModify(row) {
      const _this = this
      this.$api({
        url: '/ts-bi/api/BiReportDesign/copy',
        data: {
          id: row.formData.id,
          newDesignName: row.formData.newDesignName
        },
        method: 'post',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      })
        .then(function(response) {
          // 请求成功
          if (response.success) {
            _this.refreshDefinedFormTable()
            _this.$refs.userDefinedRightDialog.close() //提交成功后关闭弹窗
            _this.$utils.msg(_this, '复制成功', 'success')
          } else {
            _this.$utils.msg(_this, response.message, 'error')
          }
        })
        .catch(function(error) {
          // 请求失败
          _this.$utils.msg(_this, error.message, 'error')
        })
    },
    //提交分类
    sortModify(sortData) {
      const _this = this
      let sortDatas = { ...sortData }.formData
      // delete sortDatas.other
      sortDatas = {
        saveType:
          sortDatas.versionCode && sortDatas.versionCode != '草稿' ? '2' : '1',
        datas: [sortDatas],
        otherSave: 1
      }
      this.$api({
        url: '/ts-bi/api/BiReportDesign/update',
        method: 'post',
        data: JSON.stringify(sortDatas),
        headers: {
          'Content-Type': 'application/json; charset=utf-8'
        }
      })
        .then(function(response) {
          // 请求成功
          if (response.success) {
            _this.$utils.msg(_this, '修改成功！', 'success')
            _this.$refs.userDefinedRightDialog.close() //提交成功后关闭弹窗
            _this.$refs.userDefinedForm.refresh() //提交成功后刷新页面
          } else {
            _this.$utils.msg(
              _this,
              response.message || '保存失败，请检查页面',
              'error'
            )
          }
        })
        .catch(function(error) {
          // 请求失败
          _this.$utils.msg(_this, error.message, 'error')
        })
    },

    //提交菜单分配
    submitClick(param) {
      const _this = this
      let data = { ...param }.formData
      data.menutype = 0
      data.id = this.$utils.uuid(32)
      data.sort = '99'
      data.menulevel = Number(data.menulevel) + 1
      data.alink =
        '/bi/biPreview_' + this.other.id + '?mid=' + this.$utils.uuid(16)
      this.$api({
        url: '/ts-system/sysmenu/publish',
        method: 'post',
        data: JSON.stringify(data),
        headers: {
          'Content-Type': 'application/json; charset=utf-8'
        }
      })
        .then(function(response) {
          // 请求成功
          if (response.success) {
            _this.$refs.userDefinedRightDialog.close()
            _this.$utils.msg(
              _this,
              '分配成功，如需查看，请先刷新页面',
              'success'
            )
          } else {
            _this.$utils.msg(_this, response.message || '操作失败', 'error')
          }
        })
        .catch(function(error) {
          // 请求失败
          _this.$utils.msg(_this, error.message || '操作失败', 'error')
        })
    },
    // 刷新自定义报表
    refreshDefinedFormTable(param) {
      this.$nextTick(() => {
        this.isSaved = (param && param.isSaved) || false
        if (param?.biModel == 'pivot') {
          this.$refs.userDefinedRightDialog.close()
        }
        if (this.dialogEditors.length > 0 && this.$refs.userDefinedDialog) {
          this.$refs.userDefinedDialog[this.dialogEditors.length - 1].close()
        }
        if (!this.isFromPreview) {
          // 非外部预览
          this.$refs.userDefinedForm.refresh()
        } else {
          location.reload()
          this.$eventBus.$emit('refreshPreview')
        }
      })
    },
    // 打开设计区
    openDesignDialog(param) {
      this.$store.commit('setSelectData', {})
      let newParam = {
        id: param.bid,
        designName: param.bTitle,
        versionCode: param.versionCode
      }
      if (param.displayMode) {
        newParam.displayMode = param.displayMode
      }
      this.editor(newParam)
    },
    //列表预览
    previewForm(d) {
      this.layObj = this.layObjFn('previewReport', d)
      this.layObj.closeBtn = true
      this.layObj.paramId = d.id
      this.layObj.versionCode = d.versionCode || '草稿'
      this.layObj.displayMode = d.displayMode
      this.$refs.userDefinedRightDialog.open()
    }
  },
  watch: {
    dialogEditors: {
      handler(n, o) {
        this.$store.commit('setDialogEditors', n)
      },
      deep: true
    },
    formId: {
      handler(n, o) {
        // 监听指标项详情
        this.$eventBus.$on(
          'openTargetItemDialog' + n,
          this.openTargetItemDialog
        )
      }
    }
  },
  activated() {
    // this.$eventBus.$on('openDesignDialog', this.openDesignDialog)
  },
  destroyed() {
    this.$eventBus.$off('openDesignDialog', this.openDesignDialog)
  },
  deactivated() {
    this.$eventBus.$off(
      'openTargetItemDialog' + this.formId,
      this.openTargetItemDialog
    )
    //防止切换tab签后 打不来设计器
    // this.$eventBus.$off('openDesignDialog', this.openDesignDialog)
    this.$store.commit('setRoleTreeList', [])
  }
}
</script>
<style lang="less" scoped>
.sysManageSystemDepartment__editor {
  height: calc(100% - 14px);
}
/deep/.vxe-radio-button.size--mini .vxe-radio--label {
  line-height: 23px !important;
}
.userDefinedRightDialog_con {
  /deep/.layer-con__con {
    margin: 0;
    background-color: var(--light-back-grey);
  }
}
</style>
