<template>
  <el-container class="fullheight" style="border: 1px solid #eee">
    <ht-aside-tree cat-id="15" @node-click="handleNodeClick" @check="check" />
    <el-container>
      <el-main>
        <ht-table
          @load="loadData"
          :data="rows"
          :pageResult="pageResult"
          :selection="true"
          quick-search-props="name,alias"
          :default-sorter="[{direction: 'DESC', property: 'createTime'}]"
          :show-export="false"
          :show-custom-column="false"
          ref="htTable"
          :header-cell-class-name="headerCellClassName"
          @selection-change="handleSelectionChange"
        >
          <template v-slot:toolbar>
            <!-- <el-button-group> -->
            <el-button
              size="small"
              @click="showDialog()"
              icon="el-icon-plus"
              type="primary"
              >添加</el-button
            >

            <ht-import-button 
              name="连接" 
              cat-id="15" 
              :uploadUrl="uploadUrl" 
              :confirmUrl="confirmUrl" 
              :htTable="$refs.htTable" />

            <el-button
              icon="el-icon-right"
              @click="handleExport"
              >导出</el-button
            >

            <ht-delete-button
              url="${portal}/portal/portalConnectionManager/v1/remove"
              :htTable="$refs.htTable"
              :disabled="isDisabled"
              >删除</ht-delete-button
            >
            <el-button size="small" @click="initConnection()">
              <el-tooltip
                content="连接列表中自动初始化本地数据源以及portal、uc、bpm_model、bpm_runtime、form五个微服务的连接，不允许编辑和删除"
              >
                <i
                  class="icon-question"
                  style="margin-right: 8px"
                /> </el-tooltip
              >初始化默认连接
            </el-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}">
                <span v-if="row.initFlag == 1">
                  {{ row.name }}
                </span>
                <el-link
                  v-else
                  type="primary"
                  @click="showDialog(row.id)"
                  title="查看详情"
                  >{{ row.name }}</el-link
                >
              </template>
            </ht-table-column>
            <ht-table-column
              prop="alias"
              label="连接别名"
              :sortable="true"
              :show-overflow-tooltip="true"
            >
            </ht-table-column>
            <ht-table-column
              prop="connectionType"
              label="连接类型"
              :render-header="renderHeaderMethod"
              :filters="[
                {text: '数据源', value: 'dataSource'},
                {text: 'restful接口', value: 'restful'}
              ]"
            >
              <template v-slot="{row}">
                <el-tag type="info" v-if="row.connectionType == 'dataSource'"
                  >数据源</el-tag
                >
                <el-tag type="success" v-if="row.connectionType == 'restful'"
                  >restful接口</el-tag
                >
              </template>
            </ht-table-column>
            <ht-table-column
              prop="status"
              label="状态"
              :render-header="renderHeaderMethod"
              :filters="[
                {text: '启用', value: '1'},
                {text: '停用', value: '0'}
              ]"
            >
              <template v-slot="{row}">
                <el-tag type="success" v-if="row.status == '1'">启用</el-tag>
                <el-tag type="danger" v-if="row.status == '0'">停用</el-tag>
                <!-- <el-switch
                :width="38"
                v-model="row.status"
                active-value="1"
                inactive-value="0"
                @change="(status)=>handleSwitch(row,status)"
                >
              </el-switch>
              <span
                class="status_text"
                :class="{'primary':row.status == '1'}"
                >{{row.status == '1'?'启用':'停用'}}
              </span> -->
              </template>
            </ht-table-column>
            <ht-table-column
              prop="typeName"
              label="所属分类"
              :sortable="true"
              :show-overflow-tooltip="true"
            >
            </ht-table-column>
            <ht-table-column width="150" label="操作" align="left">
              <template v-slot="{row}">
                <el-button
                  v-if="row.initFlag == 1"
                  type="text"
                  @click="showDialog(row.id)"
                  >预览</el-button
                >
                <el-button
                  v-if="row.initFlag != 1 && row.status == '1'"
                  type="text"
                  @click="handleCommand({row: row, command: 'stop'})"
                  class="delete-drop-item"
                  >停用</el-button
                >
                <el-button
                  v-if="row.initFlag != 1 && row.status == '0'"
                  type="text"
                  @click="handleCommand({row: row, command: 'start'})"
                  >启用</el-button
                >
                <!-- <el-dropdown
                  size="mini"
                  split-button
                  @command="handleCommand"
                  @click="handleCommand({row: row, command: 'testConnect'})"
                >
                  <span> <i class="el-icon-tickets"></i>测试连接 </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item
                      icon="el-icon-menu"
                      :command="{row: row, command: 'stop'}"
                      v-if="row.status == '1'"
                      >停用</el-dropdown-item
                    >
                    <el-dropdown-item
                      icon="el-icon-menu"
                      :command="{row: row, command: 'start'}"
                      v-if="row.status == '0'"
                      >启用</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </el-dropdown> -->
              </template>
            </ht-table-column>
          </template>
        </ht-table>
      </el-main>
      <PortalConnectionManager-manager-edit
        ref="PortalConnectionManagerManagerEdit"
        @reloadList="reloadList"
      ></PortalConnectionManager-manager-edit>
    </el-container>
  </el-container>
</template>
<script>
import portal from '@/api/portal.js'
const htAsideTree = () => import('@/components/common/HtAsideTree.vue')
import PortalConnectionManagerManagerEdit from './PortalConnectionManagerManagerEdit.vue'
import HtImportButton from '@/components/common/HtImportButton.vue'
import tableHeaderFilter from '@/mixins/tableHeaderFilter.js'
export default {
  components: {
    htAsideTree,
    PortalConnectionManagerManagerEdit,
    HtImportButton
  },
  mixins: [tableHeaderFilter],
  data() {
    return {
      dialogVisible: false,
      rows: [],
      pageResult: {
        page: 1,
        pageSize: 50,
        total: 0
      },
      PortalConnectionManager: {},
      formData: {},
      formRow: {},
      saveMethod: 'POST',
      typeIdQuery: null,
      isDisabled: true, //按钮的禁用
      selectedList: [],
      listRestfulVo: [
        {
          alias: 'form',
          name: 'form服务',
          baseUrl: window.context.form
        },
        {
          alias: 'portal',
          name: 'portal服务',
          baseUrl: window.context.portal
        },
        {
          alias: 'bpmRunTime',
          name: 'bpmRunTime服务',
          baseUrl: window.context.bpmRunTime
        },
        {
          alias: 'bpmModel',
          name: 'bpmModel服务',
          baseUrl: window.context.bpmModel
        },
        {
          alias: 'uc',
          name: 'uc服务',
          baseUrl: window.context.uc
        },
        {
          alias: 'auth',
          name: 'auth服务',
          baseUrl: window.context.auth
        }
      ],
      uploadUrl:window.context.portal +'/portal/portalConnectionManager/v1/import?typeId=',
      confirmUrl: window.context.portal + '/portal/portalConnectionManager/v1/importData?unZipFilePath='
    }
  },
  watch: {
    // 监听选中下
    selectedList: {
      handler(val) {
        this.isDisabled = val.length < 1 ? true : false
        if (val.length > 0) {
          for (var i = 0; i < val.length; i++) {
            if (val[i]['initFlag'] == 1) {
              this.isDisabled = true
              break
            }
          }
        }
      },
      deep: true
    }
  },
  mounted() {
    this.$validator = this.$root.$validator
  },
  methods: {
    handleExport() {
      let allSelection = this.$refs.htTable.$refs.htTable.selection

      let selection = allSelection.filter(s=> s.initFlag != 1)

      if (selection && selection.length == 0) {
        this.$message.warning('请选择至少一个非默认连接')
        return
      }
      let ids = selection.map(item => item.id)
      let url = `${window.context.portal}/portal/portalConnectionManager/v1/export?ids=${ids}`
      this.$http.download(url)
    },
    initConnection() {
      this.$confirm('确定初始化吗？')
        .then(() => {
          this.authLoading = this.$loading({
            lock: true,
            text: '初始化中',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          let initConnectionVo={
            initDatabase: window.context.combine==undefined?true:window.context.combine,
            restfulVoList: this.listRestfulVo
          }
          portal.initConnection(initConnectionVo).then(resp => {
            if (this.authLoading) this.authLoading.close()
            if (resp.data.state) {
              this.$message({message: resp.data.message, type: 'success'})
              this.$refs.htTable.load()
            } else {
              this.$message({message: resp.data.message, type: 'error'})
            }
          })
        })
        .catch(() => {
          this.$message({message: '操作失败！', type: 'error'})
        })
    },
    handleSelectionChange(selection) {
      this.selectedList = selection
    },
    showDialog(id) {
      this.$refs.PortalConnectionManagerManagerEdit.showDialog(id)
    },
    handleNodeClick(node) {
      if (node.typeKey == 'CONNECT_TYPE') {
        this.typeIdQuery = null
      } else {
        this.formData.typeName = node.name
        this.formData.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) {
      if (!param.querys) {
        param.querys = []
      }
      let _param = {}
      _param = {..._param, ...param}
      if (this.typeIdQuery) {
        _param.querys.push(this.typeIdQuery)
      }
      portal
        .getConnectManageList(_param || {})
        .then(resp => {
          let response = resp.data
          this.rows = response.rows
          this.pageResult = {
            page: response.page,
            pageSize: response.pageSize,
            total: response.total
          }
          // this.$loading().close()
        })
        .finally(() => cb && cb())
    },
    handleCommand(params) {
      this.formRow = params.row
      switch (params.command) {
        case 'edit':
          this.$refs.PortalConnectionManagerManagerEdit.showDialog(
            params.row.id
          )
          break
        case 'testConnect':
          break
        case 'stop':
          this.$confirm('是否停用?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(() => {
              portal.changeConnectStatus(params.row.id, '0').then(resp => {
                if (resp.state) {
                  this.$message({
                    type: 'success',
                    message: resp.message
                  })
                  this.$refs.htTable.load()
                } else {
                  this.$message({
                    type: 'error',
                    message: resp.message
                  })
                }
              })
            })
            .catch(() => {})
          break
        case 'start':
          this.$confirm('是否启用?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(() => {
              portal.changeConnectStatus(params.row.id, '1').then(resp => {
                if (resp.state) {
                  this.$message({
                    type: 'success',
                    message: resp.message
                  })
                  this.$refs.htTable.load()
                } else {
                  this.$message({
                    type: 'error',
                    message: resp.message
                  })
                }
              })
            })
            .catch(() => {})
          break
        case 'copy':
          break
        default:
          break
      }
    },
    //导入
    handleImport() {},
    //导出
    handExport() {},
    reloadList() {
      this.$refs.htTable.load()
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep {
  .cell > .el-table__column-filter-trigger {
    display: none;
  }
}
.fullheight {
}
.sp-manager__dialog /deep/ .el-dialog > .el-dialog__body {
  height: calc(100% - 170px);
}
.form-version__dialog /deep/ .el-dialog > .el-dialog__body {
  padding: 0 10px;
}
</style>
