<template>
  <el-container class="fullheight" style="border: 1px solid #eee">
    <ht-aside-tree cat-id="13" @node-click="handleNodeClick" @check="check" />
    <el-container>
      <el-main>
        <ht-table
          @row-click="rowClick"
          @load="loadData"
          :data="data"
          :pageResult="pageResult"
          :selection="true"
          quick-search-props="name,alias"
          :default-sorter="[{direction: 'DESC', property: 'updateTime'}]"
          :show-export="false"
          ref="htTable"
          @select="tableSelect"
          @select-all="tableSelect"
          :header-cell-class-name="headerCellClassName"
          @selection-change="handleSelectionChange"
        >
          <template v-slot:toolbar>
            <el-button
              size="small"
              @click="openAddDailog('')"
              icon="el-icon-plus"
              type="primary"
              >添加</el-button
            >
            <el-button
              size="small"
              @click="
                importDialogVisible = true
                importTypeSelectorCatId = ''
                importTypeSelectorCatName = ''
              "
              icon="el-icon-back"
              >导入</el-button
            >
            <el-button
              size="small"
              @click="handExport"
              icon="el-icon-right"
              :disabled="isDisabled"
              >导出</el-button
            >
            <el-button
              @click="openTypeSetDialog()"
              icon="icon-shezhifenlei"
              :disabled="isDisabled"
              >设置分类</el-button
            >
            <ht-delete-button
              :url="formDeleteUrl"
              :htTable="$refs.htTable"
              style="margin-left: 10px"
              :disabled="isDisabled"
              :checkRight="true"
              @after-delete="updateTableData = []"
              >删除</ht-delete-button
            >
          </template>
          <template>
            <ht-table-column
              type="index"
              width="50"
              align="center"
              label="序号"
            />
            <ht-table-column
              prop="name"
              label="名称"
              :sortable="true"
              :show-overflow-tooltip="true"
            >
              <template v-slot="{row}">
                <el-link v-if="$checkRight(row,'3')" @click="openAddDailog(row.id)" type="primary">{{
                  row.name
                }}</el-link>
                <template v-else>{{ row.name }}</template>
              </template>
            </ht-table-column>
            <ht-table-column
              width="150"
              prop="alias"
              label="别名"
              :sortable="true"
            />
            <ht-table-column
              width="120"
              prop="typeName"
              label="分类名称"
              :sortable="true"
            />
            <ht-table-column
              prop="printType"
              label="类型"
              width="120"
              :render-header="renderHeaderMethod"
              :filters="[
                {text: 'WORD套打', value: 'word'},
                {text: 'EXCEL套打', value: 'excel'}
              ]"
            >
              <template v-slot="{row}">
                <span v-if="row.printType == 'word'">WORD套打</span>
                <span v-if="row.printType == 'excel'">EXCEL套打</span>
              </template>
            </ht-table-column>
            <ht-table-column
              prop="dataSourceForm"
              label="数据来源"
              width="120"
              :render-header="renderHeaderMethod"
              :filters="[
                {text: 'SQL', value: 'sql'},
                {text: '数据建模', value: 'bo'}
              ]"
            >
              <template v-slot="{row}">
                <span v-if="row.dataSourceForm == 'sql'">SQL</span>
                <span v-if="row.dataSourceForm == 'bo'">数据建模</span>
              </template>
            </ht-table-column>
            <ht-table-column prop="desc" label="描述" />
          </template>
        </ht-table>
      </el-main>
    </el-container>

    <eip-sys-type-dialog
      ref="typeSetDialog"
      name="typeSetDialog"
      :cat-id="'13'"
      @onConfirm="sysTypeDialogOnConfirm"
    />

    <FormPrintTemplateConfig
      ref="formPrintTemplateConfig"
      @onSerarch="reLoad"
    />

    <el-dialog
      title="导入数据报表"
      :visible.sync="importDialogVisible"
      width="40%"
      top="30vh"
      :close-on-click-modal="false"
      v-if="importDialogVisible"
    >
      <div style="height: 150px; padding-left: 20px">
        <eip-sys-type-selector
          placeholder="请选择分类"
          type-key="PRINT_TEMPLATE"
          v-model="importTypeSelectorCatName"
          :sys-type-id.sync="importTypeSelectorCatId"
          :validate="{required: true}"
        />
        <br /><br />
        <el-upload
          style="display: inline-block"
          :action="imporCheckUrl"
          :on-success="hadleUploadResult"
          :on-error="hadleUploadResult"
          :headers="uploadHeaders"
          :on-exceed="onExceed"
          accept=".zip"
          :before-upload="beforeUpload"
          :limit="1"
          :data="{isCheck: true}"
          :auto-upload="false"
          ref="upload"
        >
          <el-button size="small" icon="el-icon-upload"
            >选择导入套打模板文件</el-button
          >
        </el-upload>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="importDialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="submitImport"
          element-loading-text="拼命导入中"
          v-loading.fullscreen.lock="fullscreenLoading"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </el-container>
</template>
<script>
import {mapState} from 'vuex'
import form from '@/api/form.js'
import req from '@/request.js'
import utils from '@/hotent-ui-util.js'

const htAsideTree = () => import('@/components/common/HtAsideTree.vue')
const EipSysTypeSelector = () =>
  import('@/components/selector/EipSysTypeSelector.vue')
const eipSysTypeDialog = () =>
  import('@/components/dialog/EipSysTypeDialog.vue')
const FormPrintTemplateConfig = () =>
  import('@/components/form/FormPrintTemplateConfig.vue')
import tableHeaderFilter from '@/mixins/tableHeaderFilter.js'

export default {
  name: 'FormPrintTemplateListManager',
  components: {
    htAsideTree,
    EipSysTypeSelector,
    FormPrintTemplateConfig,
    eipSysTypeDialog
  },
  mixins: [tableHeaderFilter],
  data() {
    return {
      asideShow: true,
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      data: [],
      pageResult: {
        page: 1,
        pageSize: 20,
        total: 0
      },
      dialogVisible: false,
      dialogVisible2: false,
      formEditorDialogVisible: false,
      dialogSaveCopyVisible: false,
      formId: null,
      formDefId: null,
      bpmForm: {
        formKey: '',
        bos: '',
        desc: '',
        templateConf: {}
      },
      typeIdQuery: null,
      formVersionVisible: false,
      formKey: null,
      updateTableData: [],
      formRow: {},
      newForm: {id: '', name: '', formKey: '', typeId: '', typeName: ''},
      importDialogVisible: false,
      fullscreenLoading: false,
      bindData: [],
      importTypeSelectorCatName: '',
      importTypeSelectorCatId: '',
      isDisabled: true,
      selectedList: []
    }
  },
  watch: {
    formEditorDialogVisible: function(newVal, oldVal) {
      if (newVal == false && oldVal == true) {
        this.handleCloseFormEditor()
      }
    },
    selectedList: {
      handler(val) {
        this.isDisabled = val.length < 1 ? true : false
      },
      deep: true
    }
  },
  computed: {
    ...mapState({
      currentUser: state => state.login.currentUser,
      formDeleteUrl: function() {
        return `${window.context.form}/form/printTemplate/v1/removes`
      },
      uploadHeaders: function(mapState) {
        return {Authorization: 'Bearer ' + mapState.login.currentUser.token}
      },
      imporCheckUrl: function(mapState) {
        return (
          window.context.form +
          '/form/printTemplate/v1/importCheck?typeId=' +
          this.importTypeSelectorCatId
        )
      }
    })
  },
  created() {},
  mounted() {
    this.$validator = this.$root.$validator
    if (this.$route.query.formId && this.$route.query.defId) {
      let row = {
        id: this.$route.query.formId,
        defId: this.$route.query.defId
      }
      this.handleCommand({row: row, command: 'edit'})
      this.$router.push('formManager')
    }
  },
  methods: {
    handleSelectionChange(selection) {
      this.selectedList = selection
    },

    beforeUpload(file) {
      if (!file.name.endsWith('.zip')) {
        this.$message.warning('只能导入zip文件!')
        return false
      }
      this.imporActionUrl = this.imporCheckUrl
      this.fullscreenLoading = true
    },
    onExceed(file) {
      this.$message.warning('只能选择一个zip文件!')
    },
    submitImport() {
      if (
        !this.$refs.upload.uploadFiles ||
        this.$refs.upload.uploadFiles.length == 0
      ) {
        this.$message.warning('请选择要导入的套打模板文件')
        return false
      }
      if (!this.importTypeSelectorCatId) {
        this.$message.warning('请选择要导入的分类')
        return false
      }
      this.$refs.upload.submit()
    },
    hadleUploadResult(response, file, fileList) {
      var height =
        (document.documentElement.clientHeight || document.body.clientHeight) *
          0.85 +
        'px'
      this.fullscreenLoading = false
      let this_ = this
      if (response.state) {
        this_.handleImportSuccess(response.value)
      } else {
        if (response.message && response.message.indexOf('是否覆盖') > 0) {
          this.$confirm(
            '<div style="overflow-x:hidden;overflow-y:auto ;max-height:' +
              height +
              '">' +
              response.message +
              '</div>',
            '提示',
            {
              cancelButtonText: '取消',
              dangerouslyUseHTMLString: true,
              confirmButtonText: '确定',
              type: 'warning',
              closeOnClickModal: false
            }
          )
            .then(() => {
              this_.fullscreenLoading = true
              req
                .post(
                  window.context.form +
                    '/form/printTemplate/v1/importSave?cacheFileId=' +
                    response.value +
                    '&confirmImport=' +
                    true +
                    '&typeId=' +
                    this.importTypeSelectorCatId
                )
                .then(function(resp) {
                  this_.fullscreenLoading = false
                  let data = resp.data
                  if (data.state) {
                    this_.handleImportSuccess(data.value)
                  } else {
                     this.$refs.upload.clearFiles()
                    //this_.$message.error(data.message)
                  }
                })
            })
            .catch(action => {
              req.post(
                window.context.form +
                  '/form/printTemplate/v1/importSave?cacheFileId=' +
                  response.value +
                  '&confirmImport=' +
                  false
              )
              this_.importDialogVisible = false
              this.$refs.upload.clearFiles()
            })
        } else {
          this.$message.error(response.message || '套打模板文件导入失败')
        }
      }
    },
    handleImportSuccess(msg) {
      this.$alert(
        (msg?'<span style="color:red">'+msg+'</span>。':'')+'如果套打模板对应BO不存在请先导入BO及重新上传套打模板附件，套打模板才能正常使用',
        '套打模板文件导入成功',
        {
          confirmButtonText: '关闭',
          type: 'success',
          dangerouslyUseHTMLString: true,
        }
      ).then(() => {
        this.importDialogVisible = false
        this.$refs.htTable.load()
        this.$refs.upload.clearFiles()
      })
    },
    onExceed(file) {
      this.$message.warning('只能选择一个zip文件!')
    },
    beforeUpload(file) {
      if (!file.name.endsWith('.zip')) {
        this.$message.warning('只能导入zip文件!')
        return false
      }
      this.imporActionUrl = this.imporCheckUrl
      this.fullscreenLoading = true
    },
    handExport() {
      if (this.updateTableData.length == 0) {
        this.$message.warning('请选择至少一项记录')
        return
      }
      let ids = []
      for (let item of this.updateTableData) {
        ids.push(item['id'])
      }
      if (ids.length == 0) {
        this.$message.warning('请选择至少一项记录')
        return
      }
      let url = `${window.context.form}/form/printTemplate/v1/exportXml?ids=${ids}`
      req.download(url)
    },
    rowClick(row, column, event) {
      this.updateTableData.push(
        this.$refs.htTable.$refs.htTable.toggleRowSelection(row)
      )
    },
    //表格选中数据
    tableSelect(selection) {
      this.updateTableData = selection
    },
    getHasRightIds(alertMessage = true){
      let selection = this.$refs.htTable.$refs.htTable.selection
      if (selection.length == 0) {
        this.$message.warning('请选择至少一项记录')
        return
      }
      let ids = []
      let notRightNames = []
      for (let item of selection) {
        if (this.$checkRight(item,'3')) {
            ids.push(item['id'])
        }else{
            notRightNames.push(item.name)
        }
      }
      if (notRightNames.length > 0) {
          if (alertMessage || notRightNames.length == selection.length) {
            this.$message.error('以下数据无权限更新,已跳过：['+notRightNames.join(',')+']')
          }
         
          if (notRightNames.length == selection.length) {
            return null
          }
      }
      return ids;
    },
    //设置分类
    openTypeSetDialog() {
      if (this.updateTableData.length == 0) {
        this.$message({
          message: '请先选择需要设置分类的数据',
          type: 'warning'
        })
        return
      }
      var ids = this.getHasRightIds(false)
      if (!ids || ids.length == 0) {
        return;
      }
      this.$refs.typeSetDialog.showDialog({})
    },
    sysTypeDialogOnConfirm(data) {
      var id = this.getHasRightIds()
      let this_ = this
      this.$http
        .get(
          '${portal}/sys/sysType/v1/updateEntitySysType?typeID=' +
            data.id +
            '&entityIds=' +
            id.join(',')
        )
        .then(function(resp) {
          if (resp.data && resp.data.state) {
            this_.$message({message: resp.data.message, type: 'success'})
            this_.updateTableData = []
            setTimeout(function() {
              this_.dialogVisible = false
              this_.$refs.htTable.load()
            }, 3000)

            return
          }
          this_.$message.error(resp.data.message)
        })
    },
    reLoad() {
      this.$refs.htTable.load()
    },
    formAuth(formKey) {
      let param = {
        flowKey: '',
        formKey: formKey,
        nodeId: '',
        parentflowKey: '',
        type: '1'
      }
      this.$refs.flowFormAuth.showDialog(param)
    },
    handleNodeClick(node) {
      if (node.typeKey == 'FORM_TYPE') {
        this.typeIdQuery = null
      } else {
        this.bpmForm.typeName = node.name
        this.bpmForm.typeId = node.id
        this.typeIdQuery = {
          property: 'typeId',
          value: node.id,
          group: 'typeId',
          operation: 'EQUAL',
          relation: 'AND'
        }
      }
      this.$refs.htTable.load()
    },
    check(data, checkObj) {
      if (checkObj.checkedKeys.length == 0) {
        this.typeIdQuery = null
      } else {
        this.typeIdQuery = {
          property: 'typeId',
          value: checkObj.checkedKeys.join(','),
          group: 'typeId',
          operation: 'IN',
          relation: 'AND'
        }
      }
      this.$refs.htTable.load()
    },
    loadData(param, cb) {
      let _param = {querys: []}
      _param = {..._param, ...param}
      this.$addRightMarkIntoFilter(_param)
      if (this.typeIdQuery && this.typeIdQuery.value != '13') {
        _param.querys.push(this.typeIdQuery)
      }

      req
        .post('${form}/form/printTemplate/v1/getPrintList?type=word', _param)
        .then(response => {
          this.data = response.data.rows
          this.pageResult = {
            page: response.data.page,
            pageSize: response.data.pageSize,
            total: response.data.total
          }
        })
        .finally(() => cb())
    },
    handleCommand(params) {
      this.formRow = params.row
      switch (params.command) {
        case 'edit':
          this.bpmForm.bos = []
          this.formId = params.row.id
          this.formDefId = params.row.defId
          this.formEditorDialogVisible = true
          break
        case 'preview':
          if (this.currentUser && this.currentUser.account) {
            window.open(
              window.context.front +
                '/previewForm/' +
                params.row.id +
                '?token=' +
                this.currentUser.token,
              // Base64.encode(this.currentUser.account),
              '_blank'
            )
          }
          break
        case 'printForm':
          this.formKey = params.row.formKey
          this.formPrintVisible = true
          break
        default:
          break
      }
    },

    openAddDailog(id) {
      // 编辑套打
      this.$refs.formPrintTemplateConfig.handleOpen(id ? id : null)
    },
    handleCloseFormEditor() {
      this.formEditorDialogVisible = false
      this.$refs.htTable.load()
    }
  }
}
</script>

<style lang="scss" scoped>
.form-editor-dialog >>> .el-dialog__header {
  display: none;
}

.m-l-5 {
  margin-left: 5px;
}

.form-version__dialog /deep/ > .el-dialog > .el-dialog__body {
  padding: 0 10px;
}

.form-editor-dialog >>> .el-dialog__body {
  padding: 0;
  height: 100%;
}

@media (max-width: 1366px) {
  /deep/ .search-container__col {
    flex-wrap: wrap;
    .el-button-group {
      margin-top: 10px;
    }
  }
}

::v-deep {
  .cell > .el-table__column-filter-trigger {
    display: none;
  }
}
::v-deep .inputs.ht-form-inputs__inline {
  position: relative;
}
</style>
