<template>
  <a-drawer
    width="60%"
    @cancel="handleCancel"
    v-model:visible="visible"
    unmountOnClose
    @open="handleDrawerOpen"
  >
    <template #footer>
      <a-button type="outline" status="danger" @click="handleCancel"> 取消</a-button>
      <a-button type="outline" @click="handleOk">保存</a-button>
      <a-button type="primary" @click="handleSaveAndManager">保存管理字段</a-button>
    </template>
    <template #title>
      <h3>新增数据库关联</h3>
    </template>
    <!-- 虚拟表名称 -->
    <div class="virtual-table-name">
      <div class="label">虚拟表名称:</div>
      <a-input v-model="submitData.name" class="label-input" placeholder="请输入表名" />
      <div class="data-source-container">
        <div class="source-item" v-for="(item, index) in dataSourceTables" :key="index">
          <div class="label-data">{{ item.label }}</div>
          <a-select
            v-model="item.relation_table"
            :loading="selectLoading"
            placeholder="请选择数据表名"
            @change="handleSelectTableName(item)"
          >
            <a-option v-for="table in actualTable" :key="table.name" :value="table.name">{{
              table.name
            }}</a-option>
          </a-select>
          <a-select v-model="item.relation_field" placeholder="请选择关联字段">
            <a-option v-for="field in item.table_fields">{{ field.column_name }}</a-option>
          </a-select>
          <a-button
            status="danger"
            type="primary"
            shape="circle"
            size="mini"
            @click="handleRemoveDataSourceTable(index)"
          >
            <template #icon>
              <icon-minus />
            </template>
          </a-button>
        </div>

        <a-button type="outline" @click="addDataSourceTable">
          <template #icon>
            <icon-plus />
          </template>
          新增
        </a-button>
      </div>
    </div>
    <!-- 虚拟表备注 -->
    <div class="remark">
      <div class="remark-label">虚拟表备注:</div>
      <a-input v-model="submitData.remark" class="label-input" placeholder="请输入表名" />
    </div>
  </a-drawer>
</template>
<script setup>
/* @Author: 邓威 ilovede@163.com
 * @Date: 2024-11-19 14:26:01
 * @LastEditors: 邓威
 * @LastEditTime:
 * @Description:
 */
import request from '../utils/request'
import emitter from '../utils/mitt'
let visible = defineModel('visible', { default: false })
let selectLoading = ref(true)
let submitData = ref({
  name: '', //虚拟表表名称
  remark: '', //虚拟表备注
  columnList: []
})
let dataSourceTables = ref([
  {
    label: '数据源表1',
    relation_table: '',
    relation_field: '',
    table_fields: []
  }
])

let addDataSourceTable = (index) => {
  let num = dataSourceTables.value.length + 1
  dataSourceTables.value.push({
    label: '数据源表' + num,
    relation_table: '',
    relation_field: '',
    table_fields: []
  })
}

let handleRemoveDataSourceTable = (index) => {
  //   处理序号
  dataSourceTables.value.splice(index, 1)
  for (let i = 0; i < dataSourceTables.value.length; i++) {
    dataSourceTables.value[i].label = '数据源表' + (i + 1)
  }
}

//选中表名
let handleSelectTableName = (item) => {
  //处理二级选择内容
  let target = actualTable.value.find((table) => table.name === item.relation_table)
  item.table_fields.length = 0
  target.field.forEach((field) => {
    item.table_fields.push(field)
  })
}

let actualTable = ref([])

//获取实体表

let getActualTableList = async () => {
  try {
    let res = await request('getActualTableList')
    // console.log(res)
    actualTable.value = res.data.items
    selectLoading.value = false
  } catch (e) {
    console.log(e)
  }
}

//保存虚拟表

let saveVirtualTable = async () => {
  try {
    handleSubmitData()
    let res = await request('saveVirtualTable', submitData.value)
    return Promise.resolve(res.data.table_id)
  } catch (e) {
    return Promise.reject(e)
  }
}

//处理需要提交的数据

let handleSubmitData = () => {
  let columnList = dataSourceTables.value.map((item) => {
    return {
      relation_table: item.relation_table,
      relation_field: item.relation_field
    }
  })
  submitData.value.columnList = columnList
}

//清空数据
let clearData = () => {
  dataSourceTables.value.length = 0
  dataSourceTables.value.push({
    label: '数据源表1',
    relation_table: '',
    relation_field: '',
    table_fields: []
  })

  submitData.value = {
    name: '', //虚拟表表名称
    remark: '', //虚拟表备注
    columnList: []
  }
}
//抽屉打开
let handleDrawerOpen = () => {
  getActualTableList()
}

const handleClick = () => {
  //   emit('update:visible', false)
}
const handleOk = async () => {
  try {
    await saveVirtualTable()
    visible.value = false
    clearData()
  } catch (e) {
    console.log(e)
  }
}
const handleCancel = () => {
  clearData()
  visible.value = false
}
//保存并管理
let handleSaveAndManager = async () => {
  try {
    let res = await saveVirtualTable()
    let table_id = res
    emitter.emit('virtualTableSaveAnddManager', table_id)
    visible.value = false
    clearData()
  } catch (e) {
    console.log(e)
  }
}
</script>

<style scoped lang="scss">
.virtual-table-name {
  display: grid;
  grid-template-columns: 1fr 7fr; /* 两列，均分 */

  align-items: center;
  //   gap: 20px;
  margin-bottom: 10px;
  ::v-deep(.arco-input-wrapper) {
    // width: 70% !important;
  }
  .label {
    grid-row: 1 / span 2;
    display: flex;
    align-self: start;
    margin-top: 5%;
  }
  .label-input {
    align-self: start;
  }
  .source-item {
    display: grid;
    gap: 10px;
    margin-bottom: 10px;
    grid-template-columns: 1fr 4fr 4fr 1fr;
    align-self: center;
    .arco-btn {
      align-self: center !important;
      border-radius: 50%;
      margin: 0;
    }
    .label-data {
      display: flex;
      align-items: center;
    }
  }
  .arco-btn {
    border-radius: 6px;
    margin-top: 10px;
  }
}
.data-source-container {
  background-color: #f9f9f9;
  padding: 10px;
  box-sizing: border-box;
  margin-top: 10px;
  border-radius: 6px;
}
.remark {
  display: grid;
  grid-template-columns: 1fr 7fr;
  .remark-label {
    display: flex;
    align-items: center;
  }
}
</style>
