<template>
  <div>
    <el-form :model="queryParams" inline class="query-form" ref="queryForm">
      <el-form-item label="数据模型名称" prop="dsName">
        <el-input v-model="queryParams.dsName" placeholder="请输入数据模型名称" clearable></el-input>
      </el-form-item>
      <el-form-item label="数据库名称" prop="dbName">
        <el-input v-model="queryParams.dbName" placeholder="请输入数据库名称" clearable></el-input>
      </el-form-item>
      <el-form-item label="配置类型" prop="configType">
        <el-select v-model="queryParams.configType" placeholder="请选择配置类型" clearable filterable>
<!--          <el-option label="主机" value="1"/>-->
<!--          <el-option label="JDBC" value="2"/>-->
          <el-option
              v-for="item in cacheStore.getDict('data_source_config')"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch" :icon="Search">搜索</el-button>
        <el-button @click="handleReset" :icon="Refresh">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="query-btn">
      <el-button type="primary" v-perm="['query:source:add']" @click="handleAdd" :icon="Plus" plain>新增</el-button>
      <el-button type="danger" :icon="Delete" v-perm="['query:source:del']"
                 @click="handleMoreDelete(sourceId,sourceName)" :disabled="disabled" plain>删除
      </el-button>
      <el-button type="warning" v-perm="['query:source:export']" @click="handleExport" :icon="Download" plain>导出
      </el-button>
    </div>
    <div class="table">
      <el-table
          :data="list"
          row-key="id"
          :lazy="true"
          ref="singleTable"
          v-loading="loading"
          @select="handleSelect"
      >
        <el-table-column type="selection" width="55"/>
        <el-table-column label="序号" type="index" width="60" align="center"/>
        <el-table-column prop="dsName" label="数据模型名称" align="center"/>
        <el-table-column prop="dbName" label="数据库名称" align="center"/>
        <el-table-column prop="username" label="数据模型用户名" align="center"/>
        <el-table-column prop="type" label="数据模型类型" align="center"/>
        <el-table-column prop="confType" label="数据模型配置类型" align="center">
          <template #default="scope">
            <tag dict-type="data_source_config" :value="scope.row.configType"/>
          </template>
        </el-table-column>
        <el-table-column prop="url" label="数据模型连接地址" align="center"/>
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button type="text" size="mini" v-perm="['query:source:edit']"
                       @click="handleEdit(scope.row.id)">编辑
            </el-button>
            <popover-delete :name="scope.row.dsName" :type="'数据模型'" :perm="['query:source:del']"
                            @delete="handleDelete(scope.row.id)"/>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <paging :current-page="pageInfo.pageNum" :page-size="pageInfo.pageSize" :page-sizes="[10, 20, 30, 40,50]"
            :total="total" @changeSize="handleSizeChange" @goPage="handleCurrentChange"/>
    <el-dialog v-model="isVisited" :title="title" width="900px">
      <el-form :model="form" ref="formInstance" :rules="formRules" class="dialog-form" :validate-on-rule-change="false">
        <el-row>
          <el-col :span="11">
            <el-form-item label="数据模型名称" prop="dsName">
              <el-input v-model="form.dsName" placeholder="请输入数据模型名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11" :offset="2">
            <el-form-item label="数据模型用户名" prop="username">
              <el-input v-model="form.username" placeholder="请输入数据模型用户名"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="数据模型密码" prop="password">
              <el-input v-model="form.password" placeholder="请输入数据模型密码"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11" :offset="2">
            <el-form-item label="数据模型类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择数据模型类型" filterable @change="handleTypeChange(form.type)">
                <el-option
                    v-for="typeItem in typeList"
                    :key="typeItem.value"
                    :label="typeItem.label"
                    :value="typeItem.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="配置类型" prop="configType">
              <el-radio-group v-model="form.configType">
                <el-radio border :label="1">主机</el-radio>
                <el-radio border :label="2">JDBC</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="11" :offset="2" v-if="form.configType === 1">
            <el-form-item label="数据模型端口" prop="port">
              <el-input-number v-model="form.port"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="11" v-if="form.configType === 1">
            <el-form-item label="数据模型服务地址" prop="host">
              <el-input v-model="form.host" placeholder="请输入数据模型服务地址"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11" :offset="2">
            <el-form-item label="数据库名称" prop="dbName" v-if="form.configType === 1">
              <el-input v-model="form.dbName" placeholder="请输入数据库名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="form.configType === 2">
            <el-form-item label="数据模型连接地址" prop="url">
              <el-input v-model="form.url" :rows="4"
                        type="textarea" placeholder="请输入数据模型连接地址"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="form.configType === 1">
            <el-form-item label="配置参数" prop="args">
              <el-input v-model="form.args" :rows="4"
                        type="textarea" placeholder="请输入配置参数"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="服务名称" prop="params.serviceName" v-if="form.type === 'ORACLE' && form.configType===1">
              <el-input v-model="form.params.serviceName" placeholder="请输入服务名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="命名空间" prop="params.namespace" v-if="form.type === 'POSTGRES' && form.configType===1">
              <el-input v-model="form.params.namespace" placeholder="请输入命名空间"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit(formInstance)">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  getDataSourceManageList,
  getDataSourceManageDetails,
  addDataSourceManage,
  editDataSourceManage,
  delDataSourceManage,
  getDataSourceType
} from "@/api/custom-query/datamodel";
import {Search, Refresh, Delete, Plus, Edit, Download} from '@element-plus/icons-vue'
import {ElMessage, ElMessageBox} from "element-plus";
import {downLoadExcel} from "@/utils/downloadZip";
import Paging from "@/components/pagination/index.vue";
import {useCacheStore} from '@/stores/cache.js'
const cacheStore = useCacheStore()
cacheStore.setCacheKey(['data_source_config'])
//查询参数
const queryParams = reactive({
  dsName: '',
  dbName: '',
  type: '',
})
//页面信息
const pageInfo = reactive({
  pageNum: 1,
  pageSize: 10,
})
const disabled = ref(true)
const typeList = ref([])
const list = ref([])
const queryForm = ref([])
const loading = ref(true)
const total = ref()
const sourceId = ref()
const sourceName = ref()
const singleTable = ref()
const title = ref('')
const isVisited = ref(false)
const form = ref()
const formInstance = ref()
const formRules = ref({
  dsName: [{required: true, message: '请输入数据模型名称', trigger: 'blur'}],
  username: [{required: true, message: '请输入数据模型用户名', trigger: 'blur'}],
  password: [{required: true, message: '请输入数据模型密码', trigger: 'blur'}],
  type: [{required: true, message: '请选择数据模型类型', trigger: 'blur'}],
  configType: [{required: true, message: '请选择配置类型', trigger: 'blur'}],
  port: [{required: true, message: '请输入数据模型端口', trigger: 'blur'}],
  host: [{required: true, message: '请输入数据模型服务地址', trigger: 'blur'}],
  dbName: [{required: true, message: '请输入数据库名称', trigger: 'blur'}],
  url: [{required: true, message: '请输入数据模型连接地址', trigger: 'blur'}],
  params: {
    serviceName: [{required: true, message: '请输入服务名称', trigger: 'blur'}],
    namespace: [{required: true, message: '请输入命名空间', trigger: 'blur'}]
  }
})
const getTypeOption = () => {
  getDataSourceType().then(res => {
    typeList.value = res.data
  })
}

const handleTypeChange = (type) => {
  if (form.value.configType !== 1) {
    return;
  }
  if (type === 'ORACLE') {
    form.value.params = {
      serviceName: ''
    }
  }
  if (type === 'POSTGRES') {
    form.value.params = {
      namespace: ''
    }
  }
}


//搜索功能
const handleSearch = () => {
  getList()
}
//重置搜索
const handleReset = () => {
  queryForm.value.resetFields()
  getList()
}
//获取数据
const getList = async () => {
  let params = {
    ...queryParams,
    ...pageInfo
  }
  loading.value = true
  getDataSourceManageList(params).then(res => {
    if (res.code === 1000) {
      list.value = res.data.rows
      total.value = res.data.total
      loading.value = false
    } else {
      ElMessage.error(res.msg)
    }
  })
}
//重置from表单
const restFrom = () => {
  form.value = {
    dsName: null,
    username: null,
    password: null,
    host: null,
    port: 0,
    type: null,
    dbName: null,
    configType: 1,
    url: null,
    args: null,
    params: {}
  }
}
//取消
const handleCancel = () => {
  restFrom()
  isVisited.value = false
}
//提交
const handleSubmit = async (instance) => {
  if (!instance) return
  instance.validate(async (valid) => {
    if (!valid) return
    if (title.value === '新增数据模型管理') {
      addDataSourceManage(form.value).then(res => {
        if (res.code === 1000) {
          ElMessage.success(res.msg)
          getList()
          isVisited.value = false
        } else {
          ElMessage.error(res.msg)
        }
      })
    } else {
      editDataSourceManage(form.value).then(res => {
        if (res.code === 1000) {
          ElMessage.success(res.msg)
          getList()
          isVisited.value = false
        } else {
          ElMessage.error(res.msg)
        }
      })
    }
  })
}
//添加
const handleAdd = async () => {
  formRules.value.password[0].required = true
  restFrom()
  title.value = "新增数据模型管理"
  isVisited.value = true
  nextTick(() => {
    // 清空校验
    formInstance.value.clearValidate()
  })
}
//修改
const handleEdit = async (id) => {
  restFrom()
  getDataSourceManageDetails(id).then(res => {
    if (res.code === 1000) {
      console.log('res', res.data)
      formRules.value.password[0].required = false
      form.value = res.data
      title.value = "编辑数据模型管理"
      isVisited.value = true
      nextTick(() => {
        // 清空校验
        formInstance.value.clearValidate()
      })
    } else {
      ElMessage.error(res.msg)
    }
  })
}
//导出excel
const handleExport = () => {
  downLoadExcel('/query/query/source/export', {...queryParams})
}

//勾选table数据行的 Checkbox
const handleSelect = async (selection) => {
  if (selection.length !== 0) {
    disabled.value = false
    sourceId.value = selection.map(item => item.id).join()
    sourceName.value = selection.map(item => item.dsName).join()
  } else {
    disabled.value = true
  }
}

//切换每页显示条数
const handleSizeChange = async (val) => {
  pageInfo.pageSize = val
  await getList()
}

//点击页码进行分页功能
const handleCurrentChange = async (val) => {
  pageInfo.pageNum = val
  await getList()
}
//删除
const handleDelete = async (id) => {
  delDataSourceManage(id).then(res => {
    if (res.code === 1000) {
      ElMessage.success(res.msg)
      getList()
    } else {
      ElMessage.error(res.msg)
    }
  })
}
//多删
const handleMoreDelete = (sourceId, sourceName) => {
  ElMessageBox.confirm(`确认删除名称为${sourceName}的数据模型吗?`, '系统提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    handleDelete(sourceId)
  })
}
getTypeOption()
getList()
</script>
