<template>
  <div :class="datasourceClass">
    <div class="obpm-title" v-if="dataSourceType=='list'">
      <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" v-if="!type" @click="addDataSource">{{$t('btns.new')}}</el-button>
        <el-button type="danger" plain size="small" v-if="!type" @click="remove">{{$t('btns.delete')}}</el-button>
        <el-button  plain size="small" v-if="type=='dialog'" @click="clean">{{$t('btns.clean')}}</el-button>
        <el-button  plain size="small" v-if="type=='dialog'" @click="exit">{{$t('btns.exit')}}</el-button>
      </div>
    </div>
    <div class="obpm-content mt-2" v-if="dataSourceType=='list'">
      <div class="search">
        <el-form ref="form" :inline="true" :model="formInline" class="demo-form-inline" size="mini" @submit.native.prevent>
          <el-form-item>
            <el-input v-model="formInline.inputName"
              :placeholder="$t('placeholder.name')"
              @keyup.enter.native="selectInputName"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button @click="selectInputName" type="primary" plain>{{$t('btns.query')}}</el-button>
            <el-button @click="resetApplictions">{{$t('btns.reset')}}</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="obpm-content-table">
        <el-table
          ref="multipleTable"
          :data="tableData.datas"
          tooltip-effect="dark"
          style="width: 100%"
          :height="tableHeight"
          @selection-change="handleSelectionChange"
          @row-click="rowClick"
          :row-class-name='rowClassName'
          size='small'
          >
          <el-table-column
            v-if="!type"
            type="selection"
            width="55">
          </el-table-column>
          <el-table-column
            prop="name"
            :label="$t('datasource.name')"
            min-width="13%">
          </el-table-column>
          <el-table-column
            v-if="type=='dialog'"
            prop="useType"
            :label="$t('datasource.use_type')"
            width="100">
          </el-table-column>
          <el-table-column
            v-if="type=='dialog'"
            prop="dbTypeName"
            :label="$t('datasource.database_type')"
            width="100">
          </el-table-column>
          <el-table-column
            v-if="type!='dialog'"
            prop="driverClass"
            :label="$t('datasource.driver_class')"
            min-width="20%">
          </el-table-column>
          <el-table-column
            prop="url"
            :label="dataSourceUrlLabel"
            min-width="60%"
            >
          </el-table-column>
          <!-- <el-table-column
            v-if="type=='dialog'"
            prop=""
            label="操作"
            width="100"
            align="right">
            <template slot-scope="scope">
              <el-button
                size="mini"
                @click.stop="editDataSourceDetail(scope.row)">编辑</el-button>
            </template>
          </el-table-column> -->
          <el-table-column
            v-if="type!='dialog'"
            prop="username"
            :label="$t('datasource.user_name')"
            min-width="15%"
            >
          </el-table-column>
          <el-table-column
            v-if="type!='dialog'"
            prop="password"
            :label="$t('datasource.pwd')"
            min-width="15%"
            >
          </el-table-column>
        </el-table>
        <el-pagination
          class="text-right pt-2"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="tableData.pageNo"
          :page-sizes="[10, 25, 50, 100]"
          :page-size="10"
          background
          layout="total, prev, pager, next, sizes"
          :total="tableData.rowCount">
        </el-pagination>
      </div>
    </div>
    <div v-if="dataSourceType=='detail'" >
      <DataSource :editDataSourceId='editDataSourceId' @exit="onExitDetail" @updateDataSourceId="updateDataSourceId"></DataSource>
    </div>
  </div>
</template>

<script>
import { getDataSourceList,deleteDataSourceList } from "@/service/AdvancedToolAPI.js";
import DataSource from "@/components/AdvancedTool/DataSource.vue";
import {delMsg} from '@/utils/elementui'
export default {
  name: "dataSourceList",
  props:['nowDataSourceName','type'],
  components:{
    DataSource
  },
  data () {
    return {
      formInline: {
        inputName: "",        //名称
      },
      tableHeight: "100",
      tableData: {},
      params: {
        id: "",
        searchword: "",
        pageNo: 1,
        pagelines: 10
      },
      multipleSelection: [],   //将获取选中的数组放进去
      datasourceClass:'obpm-common-tool',//数据源的class名
      dataSourceUrlLabel: this.$t('datasource.url'),
      dataSourceType:'list',
      editDataSourceId:'',
    }
  },
  created(){
    if(this.type=='dialog'){
      this.datasourceClass=''
      this.dataSourceUrlLabel='JNDI/JDBC ' + this.$t('datasource.url')
    }
    
  },
  mounted(){
    this.getScollerHeight();
    this.getDataSourcetions();
  },
  methods:{
    //退出弹窗
    exit(){
      this.$emit("closeDatasource")
    },
    // 请选已选中的数据源
    clean(){
      this.$emit("cleanDatasource")
    },
    //设置选中行的类名
    rowClassName({row}){
      if(this.nowDataSourceName == row.name){
        return 'datasourceChecked';
      }
    },
    /**
     * 动态计算页面table高度
     */
    getScollerHeight() {
      setTimeout(() => {
        let clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
        //60 头部， 32 面包屑， 41 第一层页签， 40 第二层页签， 50 列表标题， 71 查询， 20 父组件外边距, 38分页
        this.tableHeight = (clientHeight - 60 - 32 - 41 - 40 - 50 - 71 - 20 - 38) + 'px'
      }, 100)
    },
    /**
     *  获取数据源列表的数据
     */
    async getDataSourcetions(searchword,pagelines,pageNo = 1){
      let params = {
        ...this.params,
        searchword: searchword ? searchword : "",
        pagelines: pagelines ? pagelines : 10,
        pageNo
      }
      this.params = params;
      let appId = sessionStorage.getItem("appId");
      const response = await getDataSourceList(params, appId)
      if (response.data.errcode == 0) {
        this.tableData = response.data.data;
      }
    },
    /**
     * 当前页
     */
    handleCurrentChange(val) {
      let params = {
        ...this.params,
        pageNo: val
      }
      this.params = params;
      this.getDataSourcetions(this.params.searchword, this.params.pagelines, this.params.pageNo);
    },

    /**
     * 切换分页，每页显示多少条
     */
    handleSizeChange(val){
      let params = {
        ...this.params,
        pagelines: val
      }
      this.params = params;
      this.getDataSourcetions(this.params.searchword, this.params.pagelines, this.params.pageNo);
    },
    /**
     * 点击列表某一列进去编辑
     */
    rowClick(row){
      this.$store.dispatch("rightHelpPageParams", { title: this.$t('label.dbsource_info'), url: "application/application_info_advancedTools_dataSource_info_help.html" });
      if(this.type=='dialog'){
        this.$emit("checkDataSourceOk",row)
      }else{
        this.dataSourceType='detail';
        this.editDataSourceId=row.id;
      }
    },
    //退出详情
    onExitDetail(){
      this.dataSourceType='list';
      this.editDataSourceId='';
      this.getDataSourcetions()
      
    },
    
    // 新建后获取数据源id
    updateDataSourceId(editDataSourceId){
      this.editDataSourceId = editDataSourceId
    },
    //弹窗模式下编辑数据源详情
    editDataSourceDetail(row){
      this.dataSourceType='detail';
      this.editDataSourceId=row.id;
    },
    /**
     * selectInputName
     * 名称查询
     */
    selectInputName(){
      this.params.searchword = this.formInline.inputName
      this.getDataSourcetions(this.params.searchword, this.params.pagelines, this.params.pageNo);
    },
    /**
     * 重置查询
     */
    resetApplictions(){
      this.formInline.inputName='';
      this.selectInputName();
    },
    /**
     * 获取选中的表格数据
     */
    handleSelectionChange(val){
      this.multipleSelection = val;
    },
    /**
     * 新建数据源详情
     */
    addDataSource(){
      this.$store.dispatch("rightHelpPageParams", { title: this.$t('label.dbsource_info'), url: "application/application_info_advancedTools_dataSource_info_help.html" });
      this.dataSourceType='detail';
    },
    /**
     * 移除
     */
    async remove(){
      let selectData = this.multipleSelection;
      let data = [];
      for(let i=0;i<selectData.length;i++){
        data.push(selectData[i].id);
      }
      let appId = sessionStorage.getItem("appId");
      if(data.length>0){
        try{
          await delMsg(this.$t('msg.delConfirm'), this.$t('msg.tip'))
          const response = await deleteDataSourceList(appId, data)
          if (response.data.errcode == 0) {
            this.$message.success(this.$t('msg.del_ss'));
            this.getDataSourcetions();
          }
        }catch(e){
          console.log(e)
        }
      }else{
        this.$message({
          message: this.$t('msg.select_dbSource'),
          type: 'error'
        });
      }
      
    },
  },
  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>