<template>
  <div class="tool-datasource-list" style="height:100%">
    <div class="my-menu">
      <el-form inline size="mini">
        <el-form-item label="数据库类型">
          <el-select v-model="type" size="mini" style="width: 120px" @change="changeType">
            <el-option :value="-1" label="全部类型"></el-option>
            <el-option :value="0" label="mysql"></el-option>
            <el-option :value="1" label="oracle"></el-option>
            <el-option :value="2" label="sqlserver"></el-option>
            <el-option :value="3" label="postgresql"></el-option>
            <el-option :value="4" label="clickhouse"></el-option>
            <el-option :value="5" label="kingbase"></el-option>
            <el-option :value="6" label="dameng"></el-option>
            <el-option :value="7" label="uxdb"></el-option>
            <el-option :value="8" label="xugu"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数据库名">
          <el-input v-model="name" clearable placeholder="输入数据库名" size="mini" style="width: 160px"></el-input>
        </el-form-item>
        <el-button icon="el-icon-search" size="mini" type="primary" @click="getData">查询</el-button>
      </el-form>
      <el-button icon="el-icon-plus" plain size="mini" type="primary" @click="onDsAdd">添加数据源</el-button>
    </div>
    <el-table :data="list" border height="calc(100% - 115px)" size="mini" :header-cell-style="{color:APP_CONFIG.TABLE_DOMINANT_COLOR}"
              :cell-style="{color:APP_CONFIG.TABLE_ASSISTANT_COLOR}">
      <el-table-column label="数据库名" prop="dsDb"></el-table-column>
      <el-table-column label="数据库类型">
        <template v-slot="{row}">{{ typeMap[row.dsType] }}</template>
      </el-table-column>
      <el-table-column label="IP地址" prop="dsIp"></el-table-column>
      <el-table-column label="端口" prop="dsPort"></el-table-column>
      <el-table-column label="连接用户" prop="dsUser"></el-table-column>
      <el-table-column label="负责人">
        <template v-slot="{row}">{{ row.responsiblePersonName || '-' }}</template>
      </el-table-column>
      <el-table-column label="描述" prop="remark"></el-table-column>
      <el-table-column label="操作" width="140px">
        <template v-slot="{row}">
          <el-button size="mini" type="text" @click="onDsEdit(row)">编辑</el-button>
          <el-button size="mini" type="text" @click="onGoDetail(row)">查看</el-button>
          <el-button size="mini" type="text" @click="onDsDel(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="mydiv">
      <el-pagination
        :current-page.sync="page.current" :page-size="page.size" :page-sizes="[10, 20, 50, 100]" :total="page.total"
        class="my-paging" layout="sizes,total, prev, pager, next" @size-change="sizeChange"
        @current-change="getData"
      ></el-pagination>
    </div>
    <el-dialog :visible.sync="showEdit" append-to-body title="编辑数据源" width="600px">
      <el-form ref="form" :model="dsForm" :rules="rules" label-width="115px" size="mini">
        <el-form-item label="数据源类型">
          <el-select v-model="dsForm.dsType" @change="changeType">
            <el-option :value="0" label="mysql"></el-option>
            <el-option :value="1" label="oracle"></el-option>
            <el-option :value="2" label="sqlserver"></el-option>
            <el-option :value="3" label="postgresql"></el-option>
            <el-option :value="4" label="clickhouse"></el-option>
            <el-option :value="5" label="kingbase"></el-option>
            <el-option :value="6" label="dameng"></el-option>
            <el-option :value="7" label="uxdb(优炫数据库)"></el-option>
            <el-option :value="8" label="xugu(虚谷数据库)"></el-option>
          </el-select>
          <el-tooltip
            class="item" content="某些版本的oracle数据库，用户名需要大写才可查询，请自行检查" effect="dark"
            placement="right"
          >
            <el-button icon="el-icon-info" plain size="mini" style="margin-left: 20px" type="warning">提示</el-button>
          </el-tooltip>
        </el-form-item>
        <template v-if="dsForm.dsType === 3 || dsForm.dsType === 1 || dsForm.dsType === 2 || dsForm.dsType === 5 || dsForm.dsType === 6">
          <el-form-item label="模式(schema)" prop="dbSchema">
            <el-input v-model="dsForm.dbSchema" clearable></el-input>
          </el-form-item>
        </template>
        <el-form-item label="中文名" prop="remark">
          <el-input v-model="dsForm.remark" clearable></el-input>
        </el-form-item>
        <el-form-item label="数据库名" prop="dsDb">
          <el-input v-model="dsForm.dsDb" clearable></el-input>
        </el-form-item>
        <el-form-item label="IP地址" prop="dsIp">
          <el-input v-model="dsForm.dsIp" clearable></el-input>
        </el-form-item>
        <el-form-item label="端口" prop="dsPort">
          <el-input v-model="dsForm.dsPort" clearable></el-input>
        </el-form-item>
        <el-form-item label="连接用户" prop="dsUser">
          <el-input v-model="dsForm.dsUser" autocomplete="new-password" clearable></el-input>
        </el-form-item>
        <el-form-item label="连接密码" prop="dsPassword">
          <el-input v-model="dsForm.dsPassword" autocomplete="new-password" clearable show-password></el-input>
        </el-form-item>
<!--        <el-form-item label="负责人" prop="responsiblePersonId">-->
<!--          <el-cascader-->
<!--            v-model="dsForm.responsiblePersonId" :options="userList"-->
<!--            :props="{expandTrigger: 'hover',emitPath: false,label: 'title',value: 'id',}" :show-all-levels="false"-->
<!--            clearable-->
<!--            filterable size="mini"-->
<!--            @change="onSelectUser"-->
<!--          ></el-cascader>-->
<!--        </el-form-item>-->
      </el-form>
      <div style="margin-top: 30px;display: flex;justify-content: flex-end">
        <el-button size="small" style="width:80px" @click="showEdit=false">取消</el-button>
        <el-button v-debounce="2000" size="small" style="width:80px" type="primary" @click="onDsEditConfirm">
          确定
        </el-button>
        <el-button v-debounce="2000" plain size="small" type="danger" @click="onDsTest">
          测试连接
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  reportdatasourcePage,
  reportdatasourceSave,
  reportdatasourceTestDs,
  reportdatasourceRemove,
  reportdatasourceUpdate,
  listViewsByDataSource,
  dsAuthList,
  dsAuthSave,getDeptTree,getUserList
} from "@/api/report/report";
import APP_CONFIG from "../../../public/config";
import { mapState } from "vuex";
export default {
  computed: {
    APP_CONFIG() {
      return APP_CONFIG
    },
    ...mapState(['user'])
  },
  data() {
    return {
      page: {size: 20, current: 1, total: 0},
      name: '',
      type: -1,
      list: [],
      showEdit: false,
      dsForm: {
        dbSchema: ''
      },
      editType: 'add',
      typeMap: {0: 'mysql', 1: 'oracle', 2: 'sqlserver', 3: 'postgresql', 4: 'clickhouse', 5: 'kingbase', 6: 'dameng',7:'uxdb',8:'xugu'},
      showAuth: false,
      nowDs: {}, //当前数据源
      tableList: [], //数据源表列表
      tableListSearched: [], //数据源表列表
      authList: [], //数据源所用权限列表
      nowAuth: {dataPermId: 0, dataPermName: '', datasourceId: 0, tableNames: []}, //当前权限组
      tableKey: '',
      rules: {
        dsDb: [
          {required: true, message: '请输入数据库名', trigger: 'blur'},
        ],
        dsIp: [
          {required: true, message: '请输入IP地址', trigger: 'blur'}
        ],
        dbSchema: [
          {required: true, message: '请输入模式(schema)', trigger: 'blur'}
        ],
        dsPort: [
          {required: true, message: '请输入端口号', trigger: 'blur'}
        ],
        dsUser: [
          {required: true, message: '请输入连接用户', trigger: 'blur'}
        ],
        dsPassword: [
          {required: true, message: '请输入连接密码', trigger: 'blur'}
        ],
        responsiblePersonId: [
          {required: true, message: '请选择负责人', trigger: 'blur'}
        ],
        remark: [
          {required: true, message: '请输入中文名', trigger: 'blur'}
        ],
      },
      userList: []
    };
  },
  created() {
    this.getData();
    // this.getUserList();
  },
  methods: {
    onSelectUser(val) {
      let allUser = this.userList.reduce((r, i) => r.concat(i.children), []);
      this.dsForm.responsiblePersonName = allUser.find(i => i.id == val).title;
    },
    getChildren(arr, nodes) {
      if (!nodes) return;
      arr.push(...nodes);
      nodes.forEach((item) => {
        this.getChildren(arr, item.children);
      });
    },
    // 获取用户列表
    getUserList() {
      getDeptTree().then((res) => {
        let parents = [];
        this.getChildren(parents, res.data);
        getUserList(1, 10000).then((res) => {
          let users = res.data.records;
          parents.forEach((item) => {
            item.children = users.filter((i) => i.deptId.includes(item.id));
            item.children.forEach((i) => {
              i.title = i.name;
              i.disabled = false;
            });
          });
          this.userList = parents.filter((i) => i.children.length);
        });
      });
    },
    onAuthSave() {
      let {dataPermId, tableNames} = this.nowAuth;
      dsAuthSave({dataPermId, tableNames: JSON.stringify(tableNames), datasourceId: this.nowDs.id}).then(res => {
        this.$message({type: 'success', message: '已保存'});
        this.getAuthList();
      });
    },
    onAuthAdd(id, name) {
      if (this.authList.find(i => i.dataPermId == id)) {
        return this.$message({type: 'warning', message: '此权限组已使用过'});
      }
      let newAuth = {dataPermId: id, dataPermName: name, datasourceId: this.nowDs.id, tableNames: []};
      this.authList.push(newAuth);
      this.nowAuth = newAuth;
    },
    onSetAuth(ds) {
      this.nowDs = ds;
      this.tableKey = '';
      listViewsByDataSource({datasourceId: this.nowDs.id, current: 1, size: 10000}).then(res => {
        this.tableList = res.data.records;
        this.tableListSearched = [...this.tableList];
      });
      this.getAuthList();
      this.showAuth = true;
    },
    getAuthList() {
      dsAuthList({datasourceId: this.nowDs.id}).then(res => {
        let data = res.data;
        data.forEach(i => i.tableNames = JSON.parse(i.tableNames || '[]'));
        this.authList = data;
        if (data.length) {
          this.nowAuth = data[0];
        }
      });
    },
    onSearchTable(key) {
      this.tableListSearched = this.tableList.filter(i => {
        return (i.tableComments && i.tableComments.includes(key)) || i.tableViewName.includes(key);
      });
    },
    onAllAdd() {
      this.tableListSearched.forEach(i => {
        if (!this.nowAuth.tableNames.includes(i.tableViewName)) {
          this.nowAuth.tableNames.push(i.tableViewName);
        }
      });
    },
    onAllDel() {
      this.nowAuth.tableNames = [];
    },
    onDsTest() {
      let data = {...this.dsForm};
      if (data.driverClassName) delete data.driverClassName;
      if (data.url) delete data.url;
      reportdatasourceTestDs(data).then((res) => {
        if (res.data.code == 200) {
          this.$message({message: "连接成功", type: "success",});
        } else {
          this.$message.error("连接错误");
        }
      });
    },
    onDsDel(ds) {
      this.$confirm("确定删除此数据源?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        reportdatasourceRemove(ds.id).then(res => {
          this.$message({type: 'success', message: '已删除'});
          this.getData();
        });
      });
    },
    // 确认编辑数据源
    onDsEditConfirm() {
      this.$refs.form.validate((valid) => {
        if (!valid) return;
        let data = {...this.dsForm};
        if (this.editType == 'add') {
          reportdatasourceSave(data).then(res => {
            this.$message({type: 'success', message: '已提交'});
            this.showEdit = false;
            this.getData();
          });
        } else if (this.editType == 'edit') {
          reportdatasourceUpdate(data).then(res => {
            this.$message({type: 'success', message: '已提交'});
            this.showEdit = false;
            this.getData();
          });
        }
      });
    },
    onGoDetail(ds) {
      this.$router.push({path: "/apimngr/datasourcelist", query: {id: ds.id},});
    },
    // 编辑数据源
    onDsEdit(ds) {
      this.editType = 'edit';
      this.dsForm = {...ds};
      this.showEdit = true;
    },
    // 添加数据源
    onDsAdd() {
      this.showEdit = true;
      this.editType = 'add';
      this.dsForm = {
        "dsDb": "", // 数据库名
        "dbSchema": 'public', // 数据库schema
        "dsIp": "", // ip地址
        "dsPort": 0, // 端口
        "dsUser": "", // 连接用户名
        "dsPassword": "", // 连接密码
        "dsType": 0, // 数据源类型 0-mysql 1-oracle 2-sqlserver 3-postgresql 4-clickhouse 5-kingbase 6-dameng 7-uxdb 8-xugu
        "remark": "", // 描述
        responsiblePersonId: this.user.userId,
        responsiblePersonName: this.user.name,
      };
    },
    changeType(e){
      if (this.dsForm.id) return
      if (e == 1) {
        this.dsForm.dbSchema = '';
      }else if (e == 2){
        this.dsForm.dbSchema = 'dbo';
      }else{
        this.dsForm.dbSchema = 'public';
      }
    },
    getData() {
      let {current, size} = this.page;
      let data = {current, size};
      if (this.name) data.dsDb = this.name;
      if (this.type != -1) data.dsType = this.type;
      reportdatasourcePage(data).then(res => {
        let {total, records} = res.data;
        this.page.total = total;
        this.list = records;
      });
    },
    sizeChange(size) {
      this.page.size = size;
      this.getData();
    }
  }
};
</script>
<style lang="scss" scoped>
.my-menu {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: justify;
  -ms-flex-pack: justify;
  justify-content: space-between;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  margin-bottom: 5px;
  margin-right: -8px;
}
.tool-datasource-list {
  .my-menu {
    .el-form-item {
      margin-bottom: 0;
    }
  }
}
.datasource-auth {
  .el-dialog__body {
    height: 800px;
    overflow-y: hidden;
    padding-top: 0;
    .top {
      .item {
        line-height: 30px;
      }
    }
    .btns {
      text-align: right;
    }
    .wrapper {
      height: 680px;
      display: flex;
      margin-top: 10px;
      .left {
        flex: 0 0 200px;
        margin-right: 10px;
        overflow-y: auto;
        .item {
          margin: 15px 0;
          line-height: 22px;
          font-size: 14px;
          cursor: pointer;
          &.active {
            color: #409eff;
          }
        }
      }
      .right {
        flex: 1;
        overflow-y: auto;
        border: 1px solid #ccc;
        padding: 10px;
        .el-checkbox {
          margin: 5px;
        }
      }
    }
  }
}
.mydiv {
  float: right;
  margin-top: 10px;
  margin-right: 10px;
}
</style>
