<template>
  <div class="fullheight">
    <ht-table
      @load="loadData"
      @row-click="rowClick"
      :data="data"
      :pageResult="pageResult"
      :selection="true"
      quick-search-props="name,alias"
      :show-export="false"
      :show-custom-column="false"
      ref="table"
      @selection-change="handleSelectionChange"
    >
      <template v-slot:toolbar>
        <!-- <el-button-group> -->
        <el-button
          size="small"
          @click="edit()"
          icon="el-icon-plus"
          type="primary"
          >添加</el-button
        >
        <el-button
          size="small"
          @click="dialogVisible = true"
          icon="el-icon-download"
          >导入</el-button
        >
        <el-button
          size="small"
          @click="handleExport"
          icon="el-icon-upload2"
          :disabled="isDisabled"
          >导出</el-button
        >
        <ht-delete-button
          :url="deleteUrl"
          :htTable="$refs.table"
          style="margin-left: 10px"
          :disabled="isDisabled"
          :checkRight="true"
          >删除</ht-delete-button
        >
        <!-- </el-button-group> -->
      </template>
      <ht-table-column type="index" width="50" align="center" label="序号" />
      <ht-table-column prop="name" label="名称">
        <template slot-scope="scope">
          <el-link
            @click="edit(scope.row.id)"
            v-if="$checkRight(scope.row,'3')"
            type="primary"
            >{{ scope.row.name }}</el-link
          >
          <template v-else>{{ scope.row.name }}</template>
        </template>
      </ht-table-column>
      <ht-table-column prop="alias" label="别名" :sortable="true" />
      <ht-table-column prop="dsName" label="数据源" :sortable="true" />
      <ht-table-column prop="sql" label="SQL语句" />
      <ht-table-column label="操作" width="150">
        <template slot-scope="scope">
          <el-button type="text" @click="jumpToViewList(scope.row.alias,scope.row.resourceRight)"
            >视图列表</el-button
          >
        </template>
      </ht-table-column>
    </ht-table>
    <custom-view-edit
      :id.sync="selectedId"
      ref="customChartEdit"
      @after-save="afterSave"
      @beforeClose="editBeforeClose"
    />
    <el-dialog
      title="上传文件"
      :visible="dialogVisible"
      :before-close="beforeClose"
      width="40%"
      top="30vh"
      name="uploadDialog"
      custom-class="upload-dialog"
    >
      <el-upload
        :action="uploadUrl"
        :http-request="handleImport"
        accept=".zip"
        :file-list="fileList"
        :on-change="onChange"
        :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="primary" @click="confirmSubmit()"
          >跳过重复项</el-button
        >
        <el-button type="default" @click="beforeClose2">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {Message, TableColumn} from 'element-ui'
import form from '@/api/form.js'
import req from '@/request.js'
const customViewEdit = () =>
  import('@/components/form/customView/CustomViewEdit.vue')
export default {
  components: {
    customViewEdit
  },
  data() {
    return {
      data: [],
      pageResult: {
        page: 0,
        pageSize: 50,
        total: 0
      },
      selectedId: '',
      deleteUrl: window.context.form + '/form/query/querySqldef/remove',
      dialogVisible: false,
      file: {},
      uploadUrl: window.context.form + '/form/query/querySqldef/import',
      uploadAddress: '',
      myDialogVisible: false,
      fileList: [],
      isDisabled: true,
      selectedList: []
    }
  },
  watch: {
    selectedList: {
      handler(val) {
        this.isDisabled = val.length < 1 ? true : false
      },
      deep: true
    }
  },
  methods: {
    handleSelectionChange(selection) {
      this.selectedList = selection
    },
    beforeClose2() {
      this.myDialogVisible = false
    },
    confirmSubmit() {
      const this_ = this
      let url =
        window.context.form +
        '/form/query/querySqldef/importData?unZipFilePath=' +
        this.uploadAddress
      req.post(url).then(function(rep) {
        rep = rep.data
        if (rep && rep.state) {
          Message.success(rep.message)
        } else {
          Message.error(rep.message || '保存失败')
        }
        this_.myDialogVisible = false
        this_.loadData()
        this_.dialogVisible = false
        this_.fileList = []
      })
    },
    rowClick(row, column, event) {
      this.$refs.table.$refs.htTable.toggleRowSelection(row)
    },
    loadData(param, cb) {
      param = param || {}
      this.$addRightMarkIntoFilter(param)
      form
        .getCustomViewList(param)
        .then(response => {
          this.data = response.rows
          this.pageResult = {
            page: response.page,
            pageSize: response.pageSize,
            total: response.total
          }
        })
        .finally(() => {
          cb()
        })
    },
    edit(id) {
      this.$refs.customChartEdit.handleOpen()
      if (id) {
        this.selectedId = id
      } else {
        this.selectedId = ''
      }
    },
    jumpToViewList(alias,resourceRight) {
      sessionStorage.setItem('ht_view_right_'+alias,resourceRight)
      this.$router.push({
        path: '/reportManager/viewList',
        query: {
          alias: alias
        }
      })
    },
    afterSave() {
      this.$refs.table.load()
    },
    handleExport() {
      let formIds = this.getSelectKeys('id')
      if (!formIds) {
        this.$message({
          message: '请选择至少一项记录',
          type: 'warning'
        })
        return
      }
      let url = `${window.context.form}/form/query/querySqldef/export?ids=${formIds}`
      req.download(url)
    },
    handleImport(param) {
      let formData = new FormData()
      formData.append('file', param.file)
      form.importCustomSql(formData).then(data => {
        if (data.state) {
          if (data.state) {
            if (data.message && data.message == 'confirmUpload') {
              this.uploadAddress = data.value
              this.myDialogVisible = true
              return
            } else {
              this.$message({
                type: 'success',
                message: data.message
              })
              param.onSuccess()
              this.loadData()
              this.dialogVisible = false
              this.fileList = []
            }
          }
        } else {
          param.onError()
        }
      })
    },
    getSelectKeys(key) {
      if (!this.$refs.table.$refs.htTable.selection) {
        this.$message('请选择的数据!')
        return
      }
      let ids = []
      for (
        let i = 0;
        i < this.$refs.table.$refs.htTable.selection.length;
        i++
      ) {
        ids.push(this.$refs.table.$refs.htTable.selection[i][key])
      }
      return ids.join(',')
    },
    onChange(file, fileList) {
      if (fileList.length > 0) {
        this.fileList = [fileList[fileList.length - 1]] //这一步，是 展示最后一次选择文件
      }
    },
    beforeClose() {
      this.dialogVisible = false
      this.fileList = []
    },
    editBeforeClose() {
      this.$refs.table.load()
    },
    uploadSubmit() {
      if (this.$refs.elUpload.uploadFiles.length == 0) {
        this.$message({
          type: 'warning',
          message: '请上传文件'
        })
      }
      this.$refs.elUpload.submit()
    }
  }
}
</script>

<style lang="scss" scoped>
@media (max-width: 1024px) {
  /deep/ .search-container__col {
    flex-wrap: wrap;

    .el-button-group {
      margin-top: 10px;
    }
  }
}

/deep/ .el-dialog.upload-dialog {
  .upload-dialog__content {
    height: 150px;
  }
}
</style>
