<template>
  <div class="obpm-dataSource">
    <div class="obpm-title">
      <div class="d-inline-block">
        <i class="el-icon-folder title-icon"></i>
        <div class="title-name d-inline-block ml-2">{{$t("datasource.title")}}</div>
      </div>
      <div class="bar d-inline-block float-right">
        <el-button type="primary" size="small" @click="doIndexManager" v-if="showIndManBtn">{{$t("btns.index_manager")}}</el-button>

        <el-button size="small" @click="testDatabase">{{$t("btns.test_db")}}</el-button>
        <el-button type="primary" size="small" @click="save('dataSourceForm')" :loading="btnLoading">{{$t("btns.save")}}</el-button>
        <el-button size="small" @click="close" v-if="showExitBtn">{{$t("btns.exit")}}</el-button>
      </div>
    </div>
    <div class="obpm-main overflow-ys" :style="'height:'+tableHeight">
      <el-form :model="formData"  ref="dataSourceForm" size="small" class="demo-form-inline" label-width="100px" label-position="top" :rules="rules">
        <el-row>
          <el-col :span="8">
            <el-form-item :label="$t('datasource.name')" prop="name" class="padding0Label">
              <el-input v-model="formData.name"  class="width-360"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="4">
            <el-form-item :label="$t('datasource.use_type')" class="padding0Label">
              <el-select v-model="formData.useType"  class="width-360">
                <el-option label="JDBC" value="JDBC"></el-option>
                <el-option label="JNDI" value="JNDI"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item :label="$t('datasource.database_type')" class="padding0Label" prop="dbType">
              <el-select v-model="formData.dbType" @change="dbTypeChange" class="width-360">
                <el-option label="Oracle" value="1"></el-option>
                <el-option label="SQLServer" value="2"></el-option>
                <el-option label="DB2" value="3"></el-option>
                <el-option label="MYSQL" value="4"></el-option>
                <el-option label="HSQL" value="5"></el-option>
                <el-option label="POSTGRESQL" value="6"></el-option>
                <el-option label="DM" value="7"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="4">
            <el-form-item :label="$t('datasource.user_name')" class="padding0Label">
              <el-input v-model="formData.username" class="width-360"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item :label="$t('datasource.driver_class')" class="padding0Label">
              <el-input v-model="formData.driverClass" class="width-360"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="4">
            <el-form-item :label="$t('datasource.pwd')" class="padding0Label">
              <el-input v-model="formData.password" class="width-360"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item :label="$t('datasource.url')" class="padding0Label">
              <el-input v-model="formData.url" class="width-360"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="4">
            <el-form-item :label="$t('datasource.db_poolsize')" class="padding0Label">
              <el-input v-model="formData.poolsize" class="width-360"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row> 
          <el-col :span="8">
            <el-form-item :label="$t('datasource.db_timeout')" class="padding0Label">
              <el-input v-model="formData.timeout" class="width-360"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="showReadonly">
          <el-form-item :label="$t('label.open_orno')" prop="readonly" class="padding0Label">
            <el-switch v-model="formData.readonly"
              :active-value="true"
              :inactive-value="false">
            </el-switch>
            <span style="color: red;">{{$t('view.just_read')}}</span>
          </el-form-item>
        </el-row>
        <el-row>
          <el-col :span="8"  v-if="formData.readonly">
            <el-form-item :label="$t('datasource.use_type')" class="padding0Label">
              <el-select v-model="formData.readonlyUseType" class="width-360">
                <el-option label="JDBC" value="JDBC"></el-option>
                <el-option label="JNDI" value="JNDI"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <span v-if="editDataSourceId">
          <el-row v-if="formData.readonly  && formData.readonlyUseType=='JDBC'">
          <!-- 读写分离数据库类型 -->
          <el-col :span="8" >
            <el-form-item :label="$t('datasource.database_type')" class="padding0Label" prop="readonlyDbType">
              <el-select v-model="formData.readonlyDbType" @change="dbReadonlyTypeChange" class="width-360">
                <el-option label="Oracle" :value="1"></el-option>
                <el-option label="SQLServer" :value="2"></el-option>
                <el-option label="DB2" :value="3"></el-option>
                <el-option label="MYSQL" :value="4"></el-option>
                <el-option label="HSQL" :value="5"></el-option>
                <el-option label="POSTGRESQL" :value="6"></el-option>
                <el-option label="DM" :value="7"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- 读写分离用户名称 -->
          <el-col :span="8" :offset="4"  v-if="formData.readonly && formData.readonlyUseType=='JDBC'">
            <el-form-item :label="$t('datasource.user_name')" class="padding0Label">
              <el-input v-model="formData.readonlyUsername" class="width-360"></el-input>
            </el-form-item>
          </el-col>
          </el-row>
          <el-row v-if="formData.readonly  && formData.readonlyUseType=='JDBC'">
            <!-- 读写分离数据驱动 -->
            <el-col :span="8">
              <el-form-item :label="$t('datasource.driver_class')" class="padding0Label">
                <el-input v-model="formData.readonlyDriverClass" class="width-360"></el-input>
              </el-form-item>
            </el-col>
            <!-- 读写分离密码 -->
            <el-col :span="8" :offset="4">
              <el-form-item :label="$t('datasource.pwd')" class="padding0Label">
                <el-input v-model="formData.readonlyPassword" class="width-360"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="formData.readonly && formData.readonlyUseType=='JDBC'">
            <!-- 读写分离地址 -->
            <el-col :span="8">
              <el-form-item :label="$t('datasource.url')" class="padding0Label">
                <el-input v-model="formData.readonlyUrl" class="width-360"></el-input>
              </el-form-item>
            </el-col>
            <!-- 读写分离连接池大小 -->
            <el-col :span="8" :offset="4">
              <el-form-item :label="$t('datasource.db_poolsize')" class="padding0Label">
                <el-input v-model="formData.readonlyPoolsize" class="width-360"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="formData.readonly && formData.readonlyUseType=='JDBC'">
            <!-- 读写分离链接超时时间 -->
            <el-col :span="8">
              <el-form-item :label="$t('datasource.db_timeout')" class="padding0Label">
                <el-input v-model="formData.readonlyTimeout" class="width-360"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="formData.readonly && formData.readonlyUseType=='JNDI'">
            <el-col :span="8">
              <el-form-item :label="$t('label.jndi')" class="padding0Label">
                <el-input v-model="formData.readonlyJndiName" class="width-360"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8" :offset="4">
              <el-form-item label="上下文:INITIAL_CONTEXT_FACTORY:" class="padding0Label">
                <el-select v-model="formData.readonlyInitialContextFactory"  class="width-360">
                  <el-option :label="$t('placeholder.select')" value=""></el-option>
                  <el-option label="org.jnp.interfaces.NamingContextFactory" value="org.jnp.interfaces.NamingContextFactory"></el-option>
                  <el-option label="weblogic.jndi.WLInitialContextFactory" value="weblogic.jndi.WLInitialContextFactory"></el-option>
                  <el-option label="com.apusic.jndi.InitialContextFactory" value="com.apusic.jndi.InitialContextFactory"></el-option>
                  <el-option label="com.ibm.websphere.naming.WsnInitialContextFactory" value="com.ibm.websphere.naming.WsnInitialContextFactory"></el-option>
                  <el-option label="com.sun.jndi.cosnaming.CNCtxFactory" value="com.sun.jndi.cosnaming.CNCtxFactory"></el-option>
                  <el-option label="com.sssw.rt.jndi.AgInitCtxFactory" value="com.sssw.rt.jndi.AgInitCtxFactory"></el-option>
                  <el-option label="com.evermind.server.rmi.RMIInitialContextFactory" value="com.evermind.server.rmi.RMIInitialContextFactory"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="formData.readonly && formData.readonlyUseType=='JNDI'">
            <el-col :span="8">
              <el-form-item label="URL_PKG_PREFIXES:" class="padding0Label">
                <el-input v-model="formData.readonlyUrlPkgPrefixes" class="width-360"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8" :offset="4">
              <el-form-item label="PROVIDER_URL:" class="padding0Label">
                <el-input v-model="formData.readonlyProviderUrl" class="width-360"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="formData.readonly && formData.readonlyUseType=='JNDI'">
            <el-col :span="8">
              <el-form-item label="SECURITY_PRINCIPAL:" class="padding0Label">
                <el-input v-model="formData.readonlySecurityPrincipal" class="width-360"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8" :offset="4">
              <el-form-item label="SECURITY_CREDENTIALS:" class="padding0Label">
                <el-input v-model="formData.readonlySecurityCredentials" class="width-360"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </span>
      </el-form>
    </div>
    <IndexManagerList v-if="doIndexManagerVisible" 
      :dialogvisible.sync='doIndexManagerVisible'
      :editDataSourceId='editDataSourceId'
    ></IndexManagerList>
  </div>
</template>
<script>
import { saveDataSource,testDataSource,getDataSource,updateDataSource } from "@/service/AdvancedToolAPI.js";
import IndexManagerList from "@/components/AdvancedTool/IndexManagerList.vue";
import { getSuperuser } from "@/service/CommonApi.js";
import { nameCheck } from '@/utils/utils.js'

export default {
  name: "dataSource",
  props:{
    editDataSourceId: String,
    showExitBtn: { // 显示退出按钮
      type: Boolean,
      default: true
    },
    tableHeight:{ // 动态计算table高度【在元数据管理页面有嵌套到】
      type: String,
      default: ((document.documentElement.clientHeight || document.body.clientHeight) - 60 - 32 - 41 - 40 - 50) + 'px', ////60 头部， 32 面包屑， 41 第一层页签， 40 第二层页签， 50 列表标题， 71 查询， 20 父组件外边距, 38分页
    },
    showIndManBtn:{
      type: Boolean,
      default: false
    }
  },
  components:{
    IndexManagerList
  },
  data() {
    return {
      formData: {
        name: "",
        useType: "JDBC",
        dbType: "",
        username: "",
        driverClass: "",
        password: "",
        url: "",
        poolsize: "",
        "readonly" : false,
        "readonlyUseType": 'JDBC',
        "readonlyDbType": 0,
        "readonlyUsername": '',
        "readonlyDriverClass": '',
        "readonlyPassword": '',
        "readonlyUrl": '',
        "readonlyPoolsize": '',
        "readonlyTimeout": '',
        "readonlyJndiName": '',
        "readonlyInitialContextFactory": "",
        "readonlyUrlPkgPrefixes": "",
        "readonlyProviderUrl": "",
        "readonlySecurityPrincipal": "",
        "readonlySecurityCredentials": ""
      },
      showReadonly: true, // 是否显示读写分离开启按钮
      
      rules:{
        name: [
          { required: true, message: this.$t('placeholder.name'), trigger: 'blur' },
          { validator: nameCheck, trigger: "blur" },
        ],
        dbType: [
          { required: true, message: this.$t('placeholder.select_db_type'), trigger: 'change' }
        ],
        readonlyDbType: [
          { required: true, message: this.$t('placeholder.select_db_type'), trigger: 'change' }
        ],
      },
      doIndexManagerVisible:false,
      btnLoading: false, // 按钮显示加载的图标
    }
  },
  mounted(){
    if(this.editDataSourceId){
      this.getDataSource();
    }
    //获取是否需要显示读写分离
    this.getSuperuser();
  },
  methods: {
    //索引管理
    doIndexManager(){
      this.doIndexManagerVisible=true;
    },
    /**
     * 选择只读数据库类型
     */
    dbReadonlyTypeChange(val){
      switch(val){
        case 1:   //Oracle
          this.formData.readonlyDriverClass = "oracle.jdbc.driver.OracleDriver";
          this.formData.readonlyUrl = "jdbc:oracle:thin:@<server>:1521:<database_name>";
          break;
        case 2:   //SQLServer
          this.formData.readonlyDriverClass = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
          this.formData.readonlyUrl = "jdbc:sqlserver://<hostname>:1433;DatabaseName=<dbname>";
          break;
        case 3:   //DB2
          this.formData.readonlyDriverClass = "com.ibm.db2.jcc.DB2Driver";
          this.formData.readonlyUrl = "jdbc:db2://<hostname>:50000/<dbname>";
          break;
        case 4:   //MYSQL
          this.formData.readonlyDriverClass = "com.mysql.jdbc.Driver";
          this.formData.readonlyUrl = "jdbc:mysql://<hostname>:3306/<dbname>?useUnicode=true&characterEncoding=utf8&useSSL=false";
          break;
        case 5:   //HSQL
          this.formData.readonlyDriverClass = "org.hsqldb.jdbcDriver";
          this.formData.readonlyUrl = "jdbc:hsqldb:hsql://<hostname>:9001/<dbname>";
          break;
        case 6:   //POSTGRESQL
          this.formData.readonlyDriverClass = "org.postgresql.Driver";
          this.formData.readonlyUrl = "jdbc:postgresql://<hostname>:5866/<dbname>";
          break;
        case 7:   //DM
          this.formData.readonlyDriverClass = "org.postgresql.Driver";
          this.formData.readonlyUrl = "jdbc:postgresql://<hostname>:5866/<dbname>";
          break;
      }
    },
    /**
     * 选择数据库类型
     */
    dbTypeChange(val){
      switch(val){
        case "1":   //Oracle
          this.formData.driverClass = "oracle.jdbc.driver.OracleDriver";
          this.formData.url = "jdbc:oracle:thin:@<server>:1521:<database_name>";
          break;
        case "2":   //SQLServer
          this.formData.driverClass = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
          this.formData.url = "jdbc:sqlserver://<hostname>:1433;DatabaseName=<dbname>";
          break;
        case "3":   //DB2
          this.formData.driverClass = "com.ibm.db2.jcc.DB2Driver";
          this.formData.url = "jdbc:db2://<hostname>:50000/<dbname>";
          break;
        case "4":   //MYSQL
          this.formData.driverClass = "com.mysql.jdbc.Driver";
          this.formData.url = "jdbc:mysql://<hostname>:3306/<dbname>?useUnicode=true&characterEncoding=utf8&useSSL=false";
          break;
        case "5":   //HSQL
          this.formData.driverClass = "org.hsqldb.jdbcDriver";
          this.formData.url = "jdbc:hsqldb:hsql://<hostname>:9001/<dbname>";
          break;
        case "6":   //POSTGRESQL
          this.formData.driverClass = "org.postgresql.Driver";
          this.formData.url = "jdbc:postgresql://<hostname>:5866/<dbname>";
          break;
        case "7":   //DM
          this.formData.driverClass = "org.postgresql.Driver";
          this.formData.url = "jdbc:postgresql://<hostname>:5866/<dbname>";
          break;
      }
    },
    /**
     * 保存表单
     */
    save(formName){
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          let appId = sessionStorage.getItem("appId");
          let editDataSourceId = this.editDataSourceId
          let data = JSON.parse(JSON.stringify(this.formData));
          data.dbType = parseInt(data.dbType);
          // 编辑
          if(this.editDataSourceId){
            this.btnLoading = true;
            const response = await updateDataSource(appId, editDataSourceId, data);
            this.btnLoading = false;
            if (response.data.errcode == 0) {
              this.$message.success(this.$t('msg.update_ss'));
            }
          }else{
            // 新建
            this.btnLoading = true;
            const response = await saveDataSource(appId,data)
            this.btnLoading = false;
            if (response.data.errcode == 0) {
              this.$message.success(this.$t('msg.created_ss'));
              this.$emit('updateDataSourceId', response.data.data.id)
            }
          }
        } else {
          return false;
        }
      });
    },
    /**
     * 测试数据库
     */
    async testDatabase() {
      let appId = sessionStorage.getItem("appId");
      let data = {
        "username": this.formData.username ? this.formData.username : "",
        "password": this.formData.password ? this.formData.password : "",
        "driverClass": this.formData.driverClass,
        "url": this.formData.url
      }
      const response = await testDataSource(appId,data)
      if (response.data.errcode == 0) {
        this.$message.success(response.data.data);
      }
    },
    /**
     * 获取数据源详情
     */
    async getDataSource(){
      let appId = sessionStorage.getItem("appId");
      let dataSourceId = this.editDataSourceId;
      const response = await getDataSource(appId,dataSourceId)
      if (response.data.errcode == 0) {
        this.formData = response.data.data;
        this.formData.dbType = this.formData.dbType + "";
        // 兼容旧数据[只读数据库类型]
        if(this.formData.readonlyDbType == 0){
          this.formData.readonlyDbType = null
        }
      }
    },
    /**
     * 退出
     */
    close(){
      this.$store.dispatch("rightHelpPageParams", { title: this.$t('report.datasourcename'), url: "application/application_info_advancedTools_dataSource_list_help.html" });
      this.$emit('exit')
    },
    /**
     * **获取版本信息**
     */
    getSuperuser(){
      getSuperuser({
        onSucess: response => {
          if (response.data.errcode == 0) {
            if(response.data.data.license.includes('标准版'))
            this.showReadonly = false
          }
        }
      })
    },
  },
  watch: {
    "$store.state.rightHelpPageParams": {
      handler() {
        if (this.$store.state.rightHelpFrame) {
          this.$store.state.rightHelpFrame.contentWindow.showHelpContentHtml(this.$store.state.rightHelpPageParams.title, this.$store.state.rightHelpPageParams.url);
        }
      },
      deep: true,
    },
  },
}
</script>