<template>
  <div class="app-container">
    <!--<el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="数据库名" prop="dataBase">
        <el-input
          v-model="queryParams.dataBase"
          placeholder="请输入数据库名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>-->

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['druid:druid:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-upload"
          size="mini"
          :disabled="single"
          @click="handleImport"
        >数据库驱动上传(本地文件)</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-upload"
          size="mini"
          :disabled="single"
          @click="handleDownload"
        >数据库驱动上传(路径)</el-button>
      </el-col>
      <!--<el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['druid:druid:edit']"
        >修改</el-button>
      </el-col>-->
      <!--<el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['druid:druid:remove']"
        >删除</el-button>
      </el-col>-->
      <!--<el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['druid:druid:export']"
        >导出</el-button>
      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="druidList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="配置名称" align="center" prop="propertyName" width="90"/>
      <el-table-column label="是否启用" align="center" prop="enabled" width="80">
        <template slot-scope="scope">
          <span v-if="scope.row.enabled == true">启用</span>
          <span v-else-if="scope.row.enabled == false">停用</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="数据库类型" align="center" prop="type" width="110"/>
      <el-table-column label="数据库版本" align="center" prop="version" >
        <template slot-scope="scope">
          <span v-if="scope.row.version === 'null'">-</span>
          <span v-else>{{scope.row.version}}</span>
        </template>
      </el-table-column>
      <el-table-column label="数据库驱动" align="center" prop="driverClass" width="320"/>
      <el-table-column label="数据库名" align="center" prop="dataBase" width="130"/>
      <el-table-column label="IP地址" align="center" prop="host" width="130"/>
      <el-table-column label="端口" align="center" prop="port" width="80"/>
      <el-table-column label="用户名" align="center" prop="user" width="90"/>
      <el-table-column label="密码" align="center" prop="password" width="100"/>
      <!--<el-table-column label="驱动名称" align="center" prop="jarName" width="220">
        <template slot-scope="scope">
          <span v-if="scope.row.jarName === 'null'">-</span>
          <span v-else>{{scope.row.jarName}}</span>
        </template>
      </el-table-column>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="scope.row.propertyName !== 'master'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['druid:druid:edit']"
          >修改</el-button>
          <el-button v-if="scope.row.propertyName !== 'master'"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['druid:druid:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改多数据源配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="配置名称" prop="propertyName">
          <el-input v-model="form.propertyName" placeholder="请输入配置名称" v-if="title === '修改多数据源配置'" disabled/>
          <el-input v-model="form.propertyName" placeholder="请输入配置名称" v-else/>
        </el-form-item>
        <el-form-item label="是否启用" prop="enabled">
          <el-select v-model="form.enabled" placeholder="请选择是否启用">
            <el-option
              v-for="item in enabled"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数据库类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择数据库类型">
            <el-option
              v-for="dict in dict.type.database_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.label"
              @click.native="typesChange(dict)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数据库版本" prop="version">
          <el-select v-model="form.version" placeholder="请选择数据库版本">
            <el-option
              v-for="dict in versionList"
              :key="dict"
              :label="dict"
              :value="dict"
              @click.native="versionChange(dict)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数据库驱动" prop="driverClass">
          <el-input v-model="form.driverClass" disabled />
        </el-form-item>
        <el-form-item label="数据库名" prop="dataBase">
          <el-input v-model="form.dataBase" placeholder="请输入数据库名" />
        </el-form-item>
        <el-form-item label="数据库IP" prop="host">
          <el-input v-model="form.host" placeholder="请输入数据库IP" />
        </el-form-item>
        <el-form-item label="端口" prop="port">
          <el-input v-model="form.port" placeholder="请输入端口" />
        </el-form-item>
        <el-form-item label="用户名" prop="user">
          <el-input v-model="form.user" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入密码" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 数据库驱动上传(本地文件)对话框 -->
    <!--<el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".jar"
        :headers="upload.headers"
        :action="upload.url + '?propertyName=' + propertyName"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          &lt;!&ndash;<div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据
          </div>&ndash;&gt;
          <span>仅允许导入jar格式文件。</span>
          &lt;!&ndash;<el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>&ndash;&gt;
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>-->

    <!-- 数据库驱动上传(路径)对话框 -->
    <!--<el-dialog :title="download.title" :visible.sync="download.open" width="400px" append-to-body>
      <el-input v-model="downloadPath" placeholder="请输入下载路径" clearable/>
      <div class="el-upload__tip text-center" slot="tip">
        <span>根据路径下载第三方数据库驱动后并上传到本地服务器。</span>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="driverClassDownload">下载</el-button>
        <el-button @click="download.open = false">取 消</el-button>
      </div>
    </el-dialog>-->
  </div>
</template>

<script>
import { listDruid, delDruid, addDruid, updateDruid, driverClassDownload } from "@/api/druid/druid";
import { getToken } from "@/utils/auth";
export default {
  name: "Druid",
  dicts: ['database_type'],
  data() {
    return {
      versionList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 多数据源配置表格数据
      druidList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      propertyName: "",
      // 数据库驱动上传参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/druidConfig/driverClassUpload"
      },
      download: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
      },
      downloadPath: "",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: null,
        version: null,
        driverClass: null,
        comment: null,
        dataBase: null,
        host: null,
        port: null,
        user: null,
        password: null,
      },
      enabled: [{
        label:'启用',
        value:true
      },{
        label:'停用',
        value:false
    }],
      MySQL: [
        'MySQL 8.0',
        'MySQL 5.7',
        'MySQL 5.6',
        'MySQL 5.5',
        'MySQL 5.1',
        'MySQL 5.0',
      ],
      SQLServer: [
        'SQLServer 2022',
        'SQLServer 2019',
        'SQLServer 2017',
        'SQLServer 2016',
        'SQLServer 2014',
        'SQLServer 2012',
        'SQLServer 2008',
        'SQLServer 2005'
      ],
      Oracle: [
        'Oracle 19c',
        'Oracle 18c',
        'Oracle 12c',
        'Oracle 11g',
        'Oracle 10g',
        'Oracle 9i',
      ],
      PostgreSQL: [
        'PostgreSQL 14',
        'PostgreSQL 13',
        'PostgreSQL 12',
        'PostgreSQL 11',
        'PostgreSQL 10',
        'PostgreSQL 9',
        'PostgreSQL 8',
      ],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        propertyName: [
          { required: true, message: "配置名称不能为空", trigger: "blur" },
          { pattern: /^[a-z]+$/, message: "只能输入小写字母" },
          { max: 16, message: "长度在16 个字符以内", trigger: "blur" },
        ],
        enabled: [
          { required: true, message: "是否启用不能为空", trigger: "change" }
        ],
        type: [
          { required: true, message: "数据库类型不能为空", trigger: "change" }
        ],
        version: [
          { required: true, message: "数据库版本不能为空", trigger: "change" }
        ],
        driverClass: [
          { required: true, message: "数据库驱动不能为空", trigger: "blur" }
        ],
        dataBase: [
          { required: true, message: "数据库名不能为空", trigger: "blur" },
          { pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+$/, message: "不允许输入空格等特殊符号" },
          { max: 20, message: "长度在20 个字符以内", trigger: "blur" },
        ],
        host: [
          { required: true, message: "数据库IP不能为空", trigger: "blur" },
          { pattern: /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/, message: "输入的IP不合法"},
        ],
        port: [
          { required: true, message: "端口不能为空", trigger: "blur" },
          { pattern: /^([0-9]|[1-9]\d|[1-9]\d{2}|[1-9]\d{3}|[1-5]\d{4}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]\d|6553[0-5])$/, message: "请输入在[0-65535]之间的端口值"},
        ],
        user: [
          { required: true, message: "用户名不能为空", trigger: "blur" },
          { pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+$/, message: "不允许输入空格等特殊符号" },
          { max: 20, message: "长度在20 个字符以内", trigger: "blur" },
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
          { pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+$/, message: "不允许输入空格等特殊符号" },
          { max: 20, message: "长度在20 个字符以内", trigger: "blur" },
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    typesChange(dict) {
      console.log("-----1-----=="+dict.label)
      this.form.version = '';
        this.versionList = [];
      if(dict.label == 'MySQL') {
        this.versionList = this.MySQL;
      }
      if(dict.label == 'SQLServer') {
        this.versionList = this.SQLServer;
      }
      if(dict.label == 'Oracle') {
        this.versionList = this.Oracle;
      }
      if(dict.label == 'PostgreSQL') {
        this.versionList = this.PostgreSQL;
      }
	    console.log("-----2-----=="+this.versionList)
    },
    versionChange(dict) {
      if(dict.includes('MySQL')) {
        if(dict >= 'MySQL 5.5') {
          this.form.driverClass = 'com.mysql.cj.jdbc.Driver';
        } else {
          this.form.driverClass = 'com.mysql.jdbc.Driver';
        }
      }
      if(dict.includes('SQLServer')) {
        if(dict == 'SQLServer 2000') {
          this.form.driverClass = 'com.microsoft.jdbc.sqlserver.SQLServerDriver';
        } else {
          this.form.driverClass = 'com.microsoft.sqlserver.jdbc.SQLServerDriver';
        }
      }
      if(dict.includes('Oracle')) {
        if(dict == 'Oracle 10g' || dict == 'Oracle 9i') {
          this.form.driverClass = 'oracle.jdbc.driver.OracleDriver';
        } else {
          this.form.driverClass = 'oracle.jdbc.OracleDriver';
        }
      }
      if(dict.includes('PostgreSQL')) {
        this.form.driverClass = 'org.postgresql.Driver';
      }
    },
    /** 查询多数据源配置列表 */
    getList() {
      this.loading = true;
      listDruid(this.queryParams).then(response => {
        this.druidList = response.rows;
        this.total = response.total;
        this.loading = false;
        console.log("enabled="+this.druidList[2].enabled)
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        type: null,
        version: null,
        driverClass: null,
        comment: null,
        dataBase: null,
        host: null,
        port: null,
        user: null,
        password: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.propertyName = selection.map(item => item.propertyName)
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加多数据源配置";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      //this.reset();
      //const id = row.id || this.ids
      //getDruid(id).then(response => {
        this.form = row;
        this.open = true;
        this.title = "修改多数据源配置";
      //});
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateDruid(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDruid(this.form).then(response => {
              this.$modal.msgSuccess(response.msg);
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const propertyName = row.propertyName;
      this.$modal.confirm('是否确认删除多数据源配置名称为"' + propertyName + '"的数据项？').then(function() {
        return delDruid(propertyName);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('druid/druid/export', {
        ...this.queryParams
      }, `druid_${new Date().getTime()}.xlsx`)
    },

    /** 数据库驱动上传按钮操作 */
    handleImport() {
      this.upload.title = "数据库驱动上传(本地文件)";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },

    handleDownload() {
      this.download.title = "数据库驱动上传(路径)";
      this.download.open = true;
    },
    driverClassDownload() {
      driverClassDownload({downloadPath:this.downloadPath, propertyName: this.propertyName}).then(response => {

        console.log("response===="+response)
      });
    }
  }
};
</script>
