<template>
  <div class="table-box">
    <ProTable ref="proTable" :columns="columns" row-key="id" :request-api="listConnectionApi">
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <el-button type="primary" v-auth="['db:connection:add']" icon="CirclePlus" @click="openDialog(1, '数据库链接新增')"> 新增 </el-button>
        <el-button
          type="danger"
          v-auth="['db:connection:remove']"
          icon="Delete"
          plain
          :disabled="!scope.isSelected"
          @click="batchDelete(scope.selectedListIds)"
        >
          批量删除
        </el-button>
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" link icon="View" v-auth="['db:connection:query']" @click="openDialog(3, '数据库链接查看', scope.row)">
          查看
        </el-button>
        <el-button type="primary" link icon="View" v-auth="['db:connection:query']" @click="test(scope.row)"> 测试 </el-button>
        <el-button type="primary" link icon="EditPen" v-auth="['db:connection:edit']" @click="openDialog(2, '数据库链接编辑', scope.row)">
          编辑
        </el-button>
        <el-button type="primary" link icon="Delete" v-auth="['db:connection:remove']" @click="deleteConnection(scope.row)"> 删除 </el-button>
      </template>
    </ProTable>
    <FormDialog :items-options="itemsOptions" :model="connectionForm" ref="formDialogRef" />
  </div>
</template>

<script setup lang="tsx" name="Connection">
import { ref, reactive } from 'vue'
import { useHandleData } from '@/hooks/useHandleData'
import ProTable from '@/components/ProTable/index.vue'
import FormDialog from '@/components/FormDialog/index.vue'
import { ElMessage } from 'element-plus'
import { ProTableInstance, ColumnProps } from '@/components/ProTable/interface'
import {
  listConnectionApi,
  delConnectionApi,
  addConnectionApi,
  updateConnectionApi,
  getConnectionApi,
  getTypesApi,
  getDriversApi,
  testApi
} from '@/api/modules/db/connection'

// ProTable 实例
const proTable = ref<ProTableInstance>()

let connectionForm = ref({ type: '' })

let databaseType = ref([])

// 删除数据库链接信息
const deleteConnection = async (params: any) => {
  await useHandleData(delConnectionApi, params.id, '删除【' + params.id + '】数据库链接')
  proTable.value?.getTableList()
}

// 批量删除数据库链接信息
const batchDelete = async (ids: string[]) => {
  await useHandleData(delConnectionApi, ids, '删除所选数据库链接信息')
  proTable.value?.clearSelection()
  proTable.value?.getTableList()
}
const test = async (params: any) => {
  const res = await testApi(params.id)
  if (res.code == 200) {
    ElMessage.success('测试连接成功!')
  } else {
    ElMessage({
      type: 'error',
      message: '测试失败!'
    })
  }
}

const formDialogRef = ref<InstanceType<typeof FormDialog> | null>(null)
// 打开弹框的功能
const openDialog = async (type: number, title: string, row?: any) => {
  connectionForm.value = { type: '' }
  if (row?.id) {
    const res = await getConnectionApi(row?.id || null)
    connectionForm.value = res.data
  }
  const params = {
    title,
    width: 580,
    isEdit: type !== 3,
    api: type == 1 ? addConnectionApi : updateConnectionApi,
    getTableList: proTable.value?.getTableList
  }
  formDialogRef.value?.openDialog(params)
}

// 表格配置项
const columns = reactive<ColumnProps<any>[]>([
  { type: 'selection', fixed: 'left', width: 70 },
  {
    prop: 'id',
    label: '编号'
  },
  {
    prop: 'name',
    label: '链接名称',
    search: {
      el: 'input'
    }
  },
  {
    prop: 'type',
    label: '数据库类型',
    search: {
      el: 'input'
    }
  },
  {
    prop: 'driverVersion',
    label: '驱动版本',
    search: {
      el: 'input'
    }
  },
  {
    prop: 'driver',
    label: '驱动类名',
    search: {
      el: 'input'
    }
  },
  {
    prop: 'url',
    label: 'jdbc-url连接串'
  },
  {
    prop: 'userName',
    label: '数据库账号'
  },
  {
    prop: 'password',
    label: '账号密码'
  },
  { prop: 'operation', label: '操作', width: 230, fixed: 'right' }
])
// 表单配置项
let itemsOptions = ref<ProForm.ItemsOptions[]>([
  {
    label: '链接名称',
    prop: 'name',
    rules: [{ required: true, message: '链接名称不能为空', trigger: 'blur' }],
    compOptions: {
      placeholder: '请输入链接名称'
    }
  },
  {
    label: '数据库类型',
    prop: 'type',
    rules: [{ required: true, message: '数据库类型不能为空', trigger: 'blur' }],
    compOptions: {
      elTagName: 'select',
      enum: getTypesApi,
      labelKey: 'type',
      valueKey: 'type',
      placeholder: '请输入数据库类型',
      onChange: value => {
        if (value) {
          connectionForm.value['driverVersion'] = ''
          getDriversApi(value).then(res => {
            itemsOptions.value[2].compOptions.enum = res.data
            databaseType.value = res.data
          })
        }
      }
    }
  },
  {
    label: '驱动版本',
    prop: 'driverVersion',
    rules: [{ required: true, message: '驱动版本不能为空', trigger: 'blur' }],
    compOptions: {
      elTagName: 'select',
      labelKey: 'driverVersion',
      valueKey: 'driverVersion',
      onChange: value => {
        if (value) {
          if (databaseType.value.length > 0) {
            for (let i = 0; i < databaseType.value.length; i++) {
              if (value == databaseType.value[i]['driverVersion']) {
                connectionForm.value['driver'] = databaseType.value[i]['driverClass']
                break
              }
            }
          }
        }
      },
      placeholder: '请选择驱动版本'
    }
  },
  {
    label: 'jdbc-url',
    prop: 'url',
    tooltip: 'jdbc:dm://localhost:5236',
    rules: [{ required: true, message: 'jdbc-url连接串不能为空', trigger: 'blur' }],
    compOptions: {
      type: 'textarea',
      clearable: true,
      placeholder: '请输入内容'
    }
  },
  {
    label: '数据库账号',
    prop: 'userName',
    rules: [{ required: true, message: '数据库账号不能为空', trigger: 'blur' }],
    compOptions: {
      placeholder: '请输入数据库账号'
    }
  },
  {
    label: '账号密码',
    prop: 'password',
    rules: [{ required: true, message: '账号密码不能为空', trigger: 'blur' }],
    compOptions: {
      placeholder: '请输入账号密码',
      type: 'password',
      showPassword: true
    }
  }
])
</script>
