<template>
  <div class="fullheight">
    <ht-table
      @load="loadData"
      :data="data"
      :pageResult="pageResult"
      :selection="true"
      :show-export="false"
      :show-custom-column="false"
      quick-search-props="name"
      :default-sorter="[{direction: 'DESC', property: 'updateTime'}]"
      ref="htTable"
      @row-click="rowClick"
      @selection-change="handleSelectionChanges"
    >
      <template v-slot:toolbar>
        <!-- <el-button-group> -->
        <el-button
          size="small"
          @click="showDialog()"
          icon="el-icon-plus"
          type="primary"
          >添加</el-button
        >
        <el-button
          icon="el-icon-back"
          @click="handleCommand({command: 'import'})"
          >导入</el-button
        >
        <el-button
          icon="el-icon-right"
          @click="handleCommand({command: 'export'})"
          :disabled="isDisabled"
          >导出</el-button
        >
        <ht-delete-button
          :url="'${portal}/sys/sysSignet/v1/remove?tenantId=' + tenantId"
          :disabled="isDisabled"
          :htTable="$refs.htTable"
          style="margin-left:10;"
          >删除</ht-delete-button
        >
        <!-- </el-button-group> -->
      </template>
      <template>
        <ht-table-column type="index" width="50" align="center" label="序号" />
        <ht-table-column prop="id" label="主键" hidden />
        <ht-table-column
          prop="name"
          width="250"
          label="印章名称"
          :sortable="true"
        />
        <ht-table-column
          prop="alias"
          width="250"
          label="印章别名"
          :sortable="true"
        />
        <ht-table-column label="印章标识符">
          <template v-slot="{row}">
            {{ signStart }}#signet_{{ row.alias }}{{ signEnd }}
          </template>
        </ht-table-column>
        <ht-table-column prop="desc" label="印章说明" />
        <ht-table-column label="操作">
          <template v-slot="{row}">
            <el-button
              type="text"
              @click="handleCommand({row: row, command: 'edit'})"
              >编辑</el-button
            >
          </template>
        </ht-table-column>
      </template>
    </ht-table>

    <ht-sidebar-dialog
      width="32%"
      :title="(model.id ? '编辑' : '添加') + '印章标识'"
      :visible="dialogVisible"
      :append-to-body="true"
      :before-close="handleClose"
    >
      <el-form v-model="model" data-vv-scope="editModelForm">
        <ht-form-item label="印章名称" label-width="120px">
          <ht-input
            v-model="model.name"
            autocomplete="off"
            :validate="{required: true}"
            placeholder="请输入印章名称"
            :maxlength="50"
            :showWordLimit="true"
          ></ht-input>
        </ht-form-item>
        <ht-form-item label="印章别名" label-width="120px">
          <ht-input
            v-model="model.alias"
            autocomplete="off"
            :disabled="model.id ? true : false"
            :validate="{required: true, alpha_dash: true}"
            placeholder="请输入印章别名"
            :maxlength="50"
            :showWordLimit="true"
          ></ht-input>
        </ht-form-item>
        <ht-form-item label="印章说明" label-width="120px">
          <ht-input
            type="textarea"
            v-model="model.desc"
            placeholder="请输入印章说明"
            :maxlength="300"
            :showWordLimit="true"
          />
        </ht-form-item>
        <ht-form-item label="印章图片" label-width="120px" required>
          <HtViewer v-if="signetShow" v-model="model.fileId" />
        </ht-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose()">{{
          $t('eip.common.cancel')
        }}</el-button>
        <ht-submit-button
          :url="'/sys/sysSignet/v1/save?tenantId=' + tenantId"
          context="portal"
          :model="model"
          :is-submit="isSubmit"
          scope-name="editModelForm"
          @before-save-data="beforeSaveData"
          @after-save-data="afterSaveData"
          >{{ $t('eip.common.save') }}</ht-submit-button
        >
      </div>
    </ht-sidebar-dialog>
    <el-dialog
      title="上传文件"
      :visible="uploadDialogVisible"
      :before-close="beforeClose"
      name="uploadDialog"
      top="30vh"
      width="40%"
      custom-class="upload-dialog"
      append-to-body
    >
      <el-upload
        :action="uploadUrl"
        :on-exceed="onExceed"
        :http-request="handleImport"
        accept=".zip"
        :file-list="fileList"
        :limit="1"
        :auto-upload="false"
        ref="elUpload"
        class="upload-dialog__content"
      >
        <el-button size="small" icon="el-icon-upload">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">只能上传zip文件</div>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="uploadSubmit">上传</el-button>
        <el-button type="default" @click="beforeClose">取消</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="温馨提示"
      :visible="myDialogVisible"
      :before-close="beforeClose2"
      name="myDialogVisible"
      width="30%"
      custom-class="upload-dialog"
      top="30vh"
    >
      <span>部分印章已存在，请确认重复项的导入操作！</span>
      <span slot="footer" class="dialog-footer">
        <el-button type="default" @click="beforeClose2">取消</el-button>
        <el-button type="primary" @click="confirmSubmit('jump')"
          >跳过重复项</el-button
        >
        <el-button type="primary" @click="confirmSubmit('cover')"
          >覆盖更新</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import portalApi from '@/api/portal.js'
import req from '@/request.js'
import HtViewer from '@/components/common/HtViewer'
export default {
  name: 'sysSignetManager',
  components: {
    HtViewer
  },
  props: {
    tenantId: String
  },
  computed: {},
  data() {
    return {
      dialogVisible: false,
      model: {
        name: '',
        groupKey: '',
        type: 1
      },
      data: [],
      pageResult: {
        page: 1,
        pageSize: 20,
        total: 0
      },
      signStart: '{{',
      signEnd: '}}',
      isSubmit: true,
      signetShow: true,
      uploadDialogVisible: false,
      uploadUrl: window.context.portal + '/sys/sysSignet/v1/import',
      fileList: [],
      myDialogVisible: false,
      uploadAddress: '',
      // 禁用
      isDisabled: true,
      selectedList: []
    }
  },
  watch: {
    selectedList: {
      handler(val) {
        this.isDisabled = val.length < 1 ? true : false
      },
      deep: true
    }
  },

  mounted() {
    this.$validator = this.$root.$validator
  },
  methods: {
    handleSelectionChanges(selection) {
      this.selectedList = selection
    },
    rowClick(row, column, event) {
      this.$refs.htTable.$refs.htTable.toggleRowSelection(row)
    },
    handleClose() {
      this.dialogVisible = false
    },
    showDialog(row) {
      this.dialogVisible = true
      let this_ = this
      req
        .get('${portal}/sys/sysSignet/v1/getJson?id=' + (row ? row.id : ''))
        .then(response => {
          if (response.data) {
            this_.model = response.data
            this_.signetShow = false
            setTimeout(function() {
              this_.signetShow = true
            }, 100)
          }
        })
    },
    loadData(param, cb) {
      this.$http
        .post(
          '${portal}/sys/sysSignet/v1/listJson?tenantId=' + this.tenantId,
          param
        )
        .then(
          resp => {
            let response = resp.data
            if (this.tenantId) this.data = response.rows
            this.pageResult = {
              page: response.page,
              pageSize: response.pageSize,
              total: response.total
            }
          },
          error => {
            reject(error)
          }
        )
        .finally(() => {
          cb()
        })
    },
    export() {
      let selection = this.$refs.htTable.selection
      if (!selection || selection.length == 0) {
        this.$message({type: 'warning', message: '请至少选择一条记录'})
        return
      }
      let ids = []
      for (let i = 0; i < selection.length; i++) {
        ids.push(selection[i].id)
      }
      req.download(
        window.context.portal +
          '/sys/sysSignet/v1' +
          '/export?ids=' +
          ids.join(',')
      )
    },
    beforeClose() {
      this.uploadDialogVisible = false
      this.fileList = []
      this.loadData()
    },
    handleImport(param) {
      let formData = new FormData()
      formData.append('file', param.file)
      req
        .post(window.context.portal + '/sys/sysSignet/v1/import', formData)
        .then(response => {
          let resp = response.data
          if (resp.state) {
            if (resp.message && resp.message == 'confirmUpload') {
              this.uploadAddress = resp.value
              this.myDialogVisible = true
            } else {
              this.$message({type: 'success', message: resp.message})
              this.fileList = []
              this.uploadDialogVisible = false
              this.$refs.htTable.load() //重新加载列表数据
            }
          } else {
            this.beforeClose()
          }
        })
    },
    handleCommand(params) {
      switch (params.command) {
        case 'edit':
          this.showDialog(params.row)
          break
        case 'import':
          this.uploadDialogVisible = true
          break
        case 'export':
          this.export()
          break
        default:
          break
      }
    },
    uploadSubmit() {
      if (this.$refs.elUpload.uploadFiles.length == 0) {
        this.$message({type: 'warning', message: '请上传文件'})
      }
      this.$refs.elUpload.submit()
    },
    async beforeSaveData() {
      this.isSubmit = true
      if (!this.model.fileId) {
        this.$message.error('请上传印章图片')
        this.isSubmit = false
        return
      }
    },
    afterSaveData() {
      this.dialogVisible = false
      this.$refs.htTable.load()
    },
    beforeClose2() {
      this.myDialogVisible = false
    },
    confirmSubmit(arg) {
      let url =
        window.context.portal +
        '/sys/sysSignet/v1/confirmImport?unZipFilePath=' +
        this.uploadAddress +
        '&status=' +
        arg
      req.post(url).then(rep => {
        rep = rep.data
        if (rep && rep.state) {
          this.$message.success(rep.message)
        } else {
          this.$message.error(rep.message || '保存失败')
        }
        this.myDialogVisible = false
        this.beforeClose()
      })
    },
    onExceed() {
      this.$message.warning('只能选择一个zip文件!')
    }
  }
}
</script>
<style lang="scss" scoped>
div[aria-invalid='true'] >>> .el-input__inner,
div[aria-invalid='true'] >>> .el-input__inner:focus {
  border-color: #f56c6c;
}
.ht-viewer {
  margin-left: 15px;
}
.ht-tab-pane {
  width: 99.9%;
}
::v-deep {
   .el-table {
    height: calc(100% - 170px) !important;
    max-height: calc(100% - 170px) !important;
  }
  .el-table > .el-table__body-wrapper {
    height: calc(100% - 37px) !important;
    max-height: calc(100% - 37px) !important;
  }
}

</style>
