<template>
  <el-container class="custom-query-list fullheight" form-manager>
    <ht-aside-tree cat-id="16" @node-click="handleNodeClick" @check="check" />
    <el-container>
      <el-main>
        <!-- 关联查询数据 -->
        <ht-table
          @load="loadData"
          :data="data"
          :pageResult="pageResult"
          quick-search-props="name,alias"
          :defaultSorter="[{property: 'CREATE_TIME_', direction: 'DESC'}]"
          :show-export="false"
          ref="htTable"
          @row-click="rowClick"
          :header-cell-class-name="headerCellClassName"
          @selection-change="handleSelectionChange"
        >
          <template v-slot:toolbar>
            <el-button
              size="small"
              @click="showDialog('add')"
              icon="el-icon-plus"
              type="primary"
              >添加</el-button
            >
            <el-button
              size="small"
              @click="uploadDialogVisible = true"
              icon="el-icon-back"
              >导入</el-button
            >
            <el-button
              size="small"
              @click="handleExport"
              icon="el-icon-right"
              :disabled="isDisabled"
              >导出</el-button
            >

            <ht-delete-button
              :url="deleteUrl"
              :htTable="$refs.htTable"
              style="margin-left:10;"
              :checkRight="true"
              :disabled="isDisabled"
              >删除</ht-delete-button
            >
            <el-button
              @click="openTypeSetDialog()"
              icon="icon-shezhifenlei"
              :disabled="isDisabled"
              >设置分类</el-button
            >
          </template>
          <template>
            <ht-table-column
              type="index"
              width="50"
              align="center"
              label="序号"
            />
            <ht-table-column
              label="名称"
              prop="name"
              :sortable="true"
              :show-overflow-tooltip="true"
            >
              <template v-slot="{row}">
                <el-link
                  v-if="$checkRight(row, '3')"
                  @click="showDialog('edit', row.id)"
                  type="primary"
                  title="编辑详情"
                  >{{ row.name }}</el-link
                >
                <template v-else>{{ row.name }}</template>
              </template>
            </ht-table-column>
            <ht-table-column prop="alias" label="别名" :sortable="true" />
            <ht-table-column
              prop="dsType"
              label="数据来源"
              :render-header="renderHeaderMethod"
              :filters="[
                {text: '数据源', value: 'dataSource'},
                {text: 'REST接口', value: 'restful'},
                {text: '选择接口', value: 'selectedApi'}
              ]"
            >
              <template v-slot="{row}">
                <el-tag type="info" v-if="row.dsType == 'dataSource'"
                  >数据源</el-tag
                >
                <el-tag type="success" v-if="row.dsType == 'restful'"
                  >REST接口</el-tag
                >
                <el-tag v-if="row.dsType == 'selectedApi'">选择接口</el-tag>
              </template>
            </ht-table-column>
            <ht-table-column prop="objName" label="对象名称" :sortable="true" />
            <ht-table-column
              prop="dsalias"
              label="数据源的别名"
              :sortable="true"
            />
            <ht-table-column prop="typeName" label="分类" :sortable="true" />
            <ht-table-column width="200" label="操作" align="left">
              <template v-slot="{row}">
                <el-button
                  type="text"
                  @click="handleCommond({row: row, command: 'preview'})"
                  >预览</el-button
                >
                <el-button
                  type="text"
                  @click="handleCommond({row: row, command: 'dialog'})"
                  >添加为对话框</el-button
                >
                <!-- <el-dropdown
                  size="mini"
                  split-button
                  @command="handleCommond"
                  @click="handleCommond({row: row, command: 'preview'})"
                >
                  <span> <i class="el-icon-view"></i>预览 </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item
                      icon="el-icon-plus"
                      :command="{row: row, command: 'dialog'}"
                      >添加为对话框</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </el-dropdown> -->
              </template>
            </ht-table-column>
          </template>
        </ht-table>
      </el-main>
    </el-container>
    <!-- 关联查询新增、编辑 -->
    <custom-query-dialog
      ref="customQueryDialog"
      @afterSaveCustomDialog="dialogClose"
    />
    <!-- 关联查询预览 -->
    <custom-query-show ref="customQueryShow" />
    <!--导入功能上传-->
    <el-dialog
      title="上传文件"
      :visible="uploadDialogVisible"
      :before-close="beforeClose"
      name="uploadDialog"
      width="40%"
      custom-class="upload-dialog"
      top="30vh"
    >
      <eip-sys-type-selector
        placeholder="请选择分类"
        type-key="Query_TYPE"
        v-model="formTypeSelectorCatName"
        :sys-type-id.sync="formTypeSelectorCatId"
        :validate="{required: true}"
      />
      <br />
      <br />
      <el-upload
        :action="uploadUrl"
        :http-request="handleImport"
        accept=".zip"
        :file-list="fileList"
        :limit="1"
        :on-exceed="onExceed"
        :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>
    <eip-sys-type-dialog
      ref="typeSetDialog"
      name="typeSetDialog"
      cat-id="16"
      @onConfirm="sysTypeDialogOnConfirm"
      style="height:500px"
    />
    <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>
  </el-container>
</template>

<script>
import {mapState} from 'vuex'
import {Message} from 'element-ui'
import req from '@/request.js'
const htAsideTree = () => import('@/components/common/HtAsideTree.vue')
const CustomQueryDialog = () =>
  import('@/views/form/customquery/CustomQueryDialog.vue')
const customQueryShow = () =>
  import('@/views/form/customquery/CustomQueryShow.vue')
const VariablesSelector = () =>
  import('@/components/common/VariablesSelector.vue')
const eipScriptDialog = () => import('@/components/dialog/EipScriptDialog.vue')
import form from '@/api/form.js'
import tableHeaderFilter from '@/mixins/tableHeaderFilter.js'
const EipSysTypeSelector = () =>
  import('@/components/selector/EipSysTypeSelector.vue')
const eipSysTypeDialog = () =>
  import('@/components/dialog/EipSysTypeDialog.vue')
export default {
  components: {
    CustomQueryDialog,
    customQueryShow,
    htAsideTree,
    EipSysTypeSelector,
    eipSysTypeDialog
  },
  computed: {
    ...mapState({
      currentUser: state => state.login.currentUser,
      formDeleteUrl: function() {
        return `${window.context.form}/form/form/v1/remove`
      },
      imporCheckUrl: function(mapState) {
        return (
          window.context.form +
          '/form/customQuery/v1/import?typeId=' +
          this.formTypeSelectorCatId
        )
      }
    }),
    //删除关联查询数据的URL
    deleteUrl: function() {
      return window.context.form + '/form/customQuery/v1/removes'
    }
  },
  mixins: [tableHeaderFilter],
  data() {
    return {
      formTypeSelectorCatId: '',
      formTypeSelectorCatName: '',
      data: [],
      typeIdQuery: null,
      treeSidebarData: {
        diySql: ''
      }, //关联查询的新增修改数据
      pageResult: {
        page: 1,
        pageSize: 20,
        total: 0
      },
      uploadAddress: '',
      uploadDialogVisible: false,
      myDialogVisible: false,
      fileList: [],
      uploadUrl: window.context.form + '/form/customQuery/v1/import',
      innerValidation: true,
      isDisabled: true,
      selectedList: []
    }
  },
  watch: {
    selectedList: {
      handler(val) {
        this.isDisabled = val.length < 1 ? true : false
      },
      deep: true
    }
  },
  methods: {
    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()
    },
    getHasRightIds(alertMessage = true, right = '3') {
      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, right)) {
          ids.push(item['id'])
        } else {
          notRightNames.push(item.name)
        }
      }
      if (notRightNames.length > 0) {
        if (alertMessage || notRightNames.length == selection.length) {
          this.$message.error(
            '以下数据无权限' +
              (right == '3' ? '更新' : '删除') +
              ',已跳过：[' +
              notRightNames.join(',') +
              ']'
          )
        }

        if (notRightNames.length == selection.length) {
          return null
        }
      }
      return ids
    },
    //设置分类
    openTypeSetDialog() {
      let selection = this.$refs.htTable.$refs.htTable.selection
      if (!selection || selection.length == 0) {
        this.$message({type: 'warning', message: '请先选择需要设置分类的数据'})
        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()
            }, 2000)

            return
          }
          this_.$message.error(resp.data.message)
        })
    },
    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()
    },
    // 选中点击按钮
    handleSelectionChange(selection) {
      this.selectedList = selection
    },
    //鼠标选中行改变复选框
    rowClick(row, column, event) {
      this.$refs.htTable.$refs.htTable.toggleRowSelection(row)
    },
    //添加为对话框
    saveDialogByQuery(id) {
      this.$confirm('确认添加为对话框？')
        .then(_ => {
          this.getDialogById(id, 'add')
        })
        .catch(_ => {})
    },
    //预览
    preview(row) {
      if (!row || !row.alias) {
        this.$message.error(`所要预览的关联查询为空或其别名不存在`)
        return
      }
      const title = `${row.name} - 关联查询预览`
      this.$refs.customQueryShow.showDialog(row.alias, title) //显示自定义对话框列表预览弹框
    },
    showDialog(action, id) {
      this.$refs.customQueryDialog.showDialog(action, id)
    },
    dialogClose() {
      this.$refs.htTable.load() //重新加载列表数据
    },
    confirmSubmit(arg) {
      const this_ = this
      let url =
        window.context.form +
        '/form/customQuery/v1/importData?unZipFilePath=' +
        this.uploadAddress +
        '&status=' +
        arg +
        '&typeId=' +
        this.formTypeSelectorCatId
      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_.beforeClose()
      })
    },
    //根据关联查询信息ID查询关联查询所有信息
    getDialogById(id, action) {
      const this_ = this
      if (!id) return
      let url = window.context.form + '/form/customQuery/v1/' + id
      req.get(url).then(function(data) {
        data = data.data
        this_.treeSidebarData = data
        this_.treeSidebarData.resultfield = JSON.parse(data.resultfield)
        this_.treeSidebarData.sortfield = JSON.parse(data.sortfield)
        this_.treeSidebarData.conditionfield = JSON.parse(data.conditionfield)

        //添加为对话框
        if (action && action == 'add') {
          if (this_.treeSidebarData.needPage == 0) {
            this_.treeSidebarData.needPage = false
          } else {
            this_.treeSidebarData.needPage = true
          }
          for (let i = 0; i < this_.treeSidebarData.resultfield.length; i++) {
            this_.treeSidebarData.resultfield[i].idKey = '0'
            this_.treeSidebarData.resultfield[i].AggFuncOp = '' //合计函数运算符
          }
          let url =
            window.context.form + '/form/customQuery/v1/saveDialogByQuery'
          req.post(url, this_.treeSidebarData).then(function(rep) {
            rep = rep.data
            if (rep && rep.state) {
              Message.success(rep.message)
            }
          })
        }
      })
    },
    //页面加载显示数据
    loadData(param, cb) {
      let _param = {querys: []}
      _param = {..._param, ...param}
      if (this.typeIdQuery && this.typeIdQuery.value != '16') {
        const typeIdObj = _param.querys.find(item => item.property === 'typeId')
        if (typeIdObj) {
          _param.querys = _param.querys.filter(
            item => item.property !== 'typeId'
          )
        }
        _param.querys.push(this.typeIdQuery)
      } else {
        _param.querys = _param.querys.filter(item => item.property !== 'typeId')
      }
      this.$addRightMarkIntoFilter(_param)
      req
        .post(window.context.form + '/form/customQuery/v1/list', _param)
        .then(response => {
          this.data = response.data.rows
          this.pageResult = {
            page: response.data.page,
            pageSize: response.data.pageSize,
            total: response.data.total
          }
        })
        .finally(() => cb())
    },
    handleCommond(param) {
      switch (param.command) {
        case 'preview':
          this.preview(param.row)
          break
        case 'dialog':
          this.saveDialogByQuery(param.row.id)
          break
      }
    },
    handleExport() {
      let selection = this.$refs.htTable.$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.form + '/form/customQuery/v1/export?ids=' + ids.join(',')
      )
    },
    //上传对话框关闭
    beforeClose() {
      this.fileList = []
      this.uploadDialogVisible = false
    },
    beforeClose2() {
      this.myDialogVisible = false
    },
    handleImport(param) {
      let formData = new FormData()
      formData.append('file', param.file)
      formData.append('typeId', this.formTypeSelectorCatId)
      form.importCustomQuery(formData).then(resp => {
        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.beforeClose()
            this.$refs.htTable.load() //重新加载列表数据
          }
        } else {
          this.beforeClose()
        }
      })
    },
    uploadSubmit() {
      if (this.$refs.elUpload.uploadFiles.length == 0) {
        this.$message({type: 'warning', message: '请上传文件'})
      }
      this.$refs.elUpload.submit()
    },
    onExceed() {
      this.$message.warning('只能选择一个zip文件!')
    }
  },
  mounted() {
    this.$validator = this.$root.$validator
  }
}
</script>
<style lang="scss" scoped>
::v-deep {
  .cell > .el-table__column-filter-trigger {
    display: none;
  }
}

.custom-query-list {
}
div >>> .el-dialog__body {
  padding: 10px 20px;
  color: #606266;
  font-size: 14px;
  word-break: break-all;
  height: calc(100% - 140px);
  overflow-y: auto;
}
.cd-column__dialog {
  /deep/.el-dialog__body {
    height: calc(100% - 100px);
  }
}
.todo-subject {
  cursor: pointer;
}

.todo-subject:hover {
  color: #2761ff;
}

.ht {
  width: 320px;
}
.cd-column__dialog /deep/ .el-dialog > .el-dialog__header {
  padding: 8px 20px;
}
.label-tooltip {
  width: 0px;
}
@media (max-width: 1024px) {
  /deep/ .search-container__col {
    flex-wrap: wrap;
    .el-button-group {
      margin-top: 10px;
    }
  }
}
/deep/.el-dialog__wrapper {
  overflow: unset !important;
}

/deep/.el-dialog {
  height: 90%;
  min-height: 400px;
}
/deep/.el-dialog__body .selector-table {
  height: 100% !important;
}
/deep/.el-dialog .el-dialog__body .select-tree-div {
  height: calc(100% - 60px);
  min-height: unset;
}
@media (max-height: 960px) {
  /deep/.el-dialog__body .el-container {
    height: 100% !important;
  }
}
/deep/ [name='uploadDialog'] {
  // height:30%;
}
/deep/ .el-dialog.upload-dialog {
  height: unset;
  /deep/.el-dialog__body {
    height: unset;
  }
  .upload-dialog__content {
    height: 150px;
  }
  min-height: unset;
}
.form-table__wrap,
.form-table__row,
.form-table__left,
.form-table__right {
  height: 100%;
}
.form-table__left,
.form-table__right {
  overflow-y: auto;
}
/deep/.CodeMirror {
  height: 100%;
}
/deep/.inputs.ht-form-inputs__inline {
  position: relative;
}
</style>
