<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-form :inline="true" :model="queryForm">
        <el-form-item label="业务域名称">
          <el-input v-model="queryForm.bizName" placeholder="请输入业务域名称" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleSearch">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-row>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="openAddDialog">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="selectedRows.length !== 1" @click="openEditDialog(selectedRows[0])">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="selectedRows.length === 0" @click="deleteSelected">删除</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="bizList" @selection-change="handleSelectionChange" style="width: 100%" border stripe>
      <el-table-column type="selection" width="55" />
      <el-table-column prop="bizName" label="业务域名称" />
      <el-table-column prop="createBy" label="创建者" />
      <el-table-column prop="createTime" label="创建时间" width="180">
        <template #default="{ row }">
          {{ formatDateTime(row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="updateBy" label="更新者" />
      <el-table-column prop="updateTime" label="更新时间" width="180">
        <template #default="{ row }">
          {{ formatDateTime(row.updateTime) }}
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryForm.pageNum" v-model:limit="queryForm.pageSize" @pagination="getList" />

    <el-dialog :title="title" v-model="open" width="1600px" append-to-body :before-close="handleClose">
      <el-form ref="bizFormRef" :model="form" :rules="rules" label-width="130px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="业务域名称" prop="bizName">
              <el-input v-model="form.bizName" style="width: 200px" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-row :gutter="20" style="margin-top: 20px">
        <el-col :span="10">
          <el-form :model="leftQueryForm" inline size="small">
            <el-form-item label="系统名">
              <el-select v-model="leftQueryForm.ssysCd" placeholder="请选择系统" clearable filterable style="width: 180px">
                <el-option v-for="item in dsSysList" :key="item.id" :label="item.name" :value="item.name" />
              </el-select>
            </el-form-item>
            <el-form-item label="表名">
              <el-input v-model="leftQueryForm.tabName" placeholder="请输入表名" clearable style="width: 180px" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="loadLeftTable">查询</el-button>
            </el-form-item>
          </el-form>

          <el-table :data="leftTableData" height="300" border style="margin-top: 10px" @selection-change="handleLeftSelect">
            <el-table-column type="selection" width="50" />
            <el-table-column prop="ssysCd" label="系统名" />
            <el-table-column prop="mdlName" label="模式名" />
            <el-table-column prop="tabEngName" label="表名" />
          </el-table>

          <pagination v-show="leftTotal > 0" :total="leftTotal" v-model:page="leftQueryForm.pageNum" v-model:limit="leftQueryForm.pageSize" @pagination="loadLeftTable" />
        </el-col>

        <el-col :span="4" class="flex-col-center">
          <el-button type="primary" @click="moveToRight" :disabled="leftSelected.length === 0"> > </el-button>
          <el-button type="danger" style="margin-top: 10px" @click="moveToLeft" :disabled="rightSelected.length === 0"> < </el-button>
        </el-col>

        <el-col :span="10">
          <el-table :data="rightTableData" height="360" border @selection-change="handleRightSelect">
            <el-table-column type="selection" width="50" />
            <el-table-column prop="ssysCd" label="系统名" />
            <el-table-column prop="mdlName" label="模式名" />
            <el-table-column prop="tabEngName" label="表名" />
          </el-table>
        </el-col>
      </el-row>

      <template #footer>
        <el-button @click="open = false">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import useUserStore from '@/store/modules/user'
import { getMetaDataList } from '@/api/meta/metaInfo'

const userStore = useUserStore()
const dsSysList = userStore.dsSysList

import {
  listTaskBizConfig,
  addTaskBizConfig,
  updateTaskBizConfig,
  getTaskBizRelaList,
  delTaskBizConfig
} from '@/api/taskMetadataConfig/metadataConfig'

const queryForm = reactive({
  bizName: '',
  riskLvl: '',
  pageNum: 1,
  pageSize: 10
})
const leftQueryForm = reactive({
  ssysCd: '',
  tabName: '',
  pageNum: 1,
  pageSize: 10
})

const bizList = ref([])
const secList = ref([])
const total = ref(0)
const loading = ref(false)
const open = ref(false)
const title = ref('')

const bizFormRef = ref(null)

const form = reactive({
  onum: null,
  bizName: '',
  riskLvl: '',
  isStop: null
})

const rules = {
  bizName: [{ required: true, message: '请输入业务域名称', trigger: 'blur' }],
  riskLvl: [{ required: true, message: '请选择风险等级', trigger: 'blur' }],
  isStop: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

const selectedRows = ref([])

function handleSelectionChange(val) {
  selectedRows.value = val
}

async function getList() {
  loading.value = true
  try {
    const res = await listTaskBizConfig(queryForm)
    bizList.value = res.rows || []
    total.value = res.total || 0
  } catch (error) {
    ElMessage.error('获取列表失败，请重试')
  } finally {
    loading.value = false
  }
}

async function getSecList() {
  // TODO: 实现安全等级下拉数据接口逻辑
}

function getSecLevelName(value) {
  const item = secList.value.find((d) => d.onum === value)
  return item ? item.secLevelSummary : value
}

function resetQuery() {
  queryForm.bizName = ''
  queryForm.riskLvl = ''
  queryForm.pageNum = 1
  getList()
}

function handleSearch() {
  queryForm.pageNum = 1
  getList()
}

function openAddDialog() {
  title.value = '新增业务域配置'
  Object.assign(form, {
    onum: null,
    bizName: '',
    riskLvl: '',
    isStop: null
  })
  rightTableData.value = []
  open.value = true
}

function openEditDialog(row) {
  if (!row) {
    ElMessage.warning('请选择一条记录进行编辑')
    return
  }
  title.value = '编辑业务域配置'
  loadRightTable(row.onum)
  Object.assign(form, row)
  open.value = true
}

function submitForm() {
  bizFormRef.value.validate(async (valid) => {
    if (!valid) return
    let tabonums = []
    rightTableData.value.forEach(item => {
      tabonums.push(item.onum)
    })

    const submitData = { ...form, tabOnumList: tabonums }
    try {
      if (title.value.includes('新增')) {
        await addTaskBizConfig(submitData)
        ElMessage.success('新增成功')
      } else {
        await updateTaskBizConfig(submitData)
        ElMessage.success('编辑成功')
      }
      open.value = false
      getList()
    } catch (error) {
      ElMessage.error('操作失败，请重试')
    }
  })
}

function deleteRow(onum) {
  ElMessageBox.confirm('确定删除该条记录吗？', '提示', { type: 'warning' })
    .then(async () => {
      try {
        await delTaskBizConfig(onum)
        ElMessage.success('删除成功')
        getList()
      } catch (error) {
        ElMessage.error('删除失败，请重试')
      }
    })
    .catch(() => { })
}

function deleteSelected() {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条记录删除')
    return
  }
  ElMessageBox.confirm(`确定删除选中的 ${selectedRows.value.length} 条记录吗？`, '提示', { type: 'warning' })
    .then(async () => {
      try {
        for (const row of selectedRows.value) {
          await delTaskBizConfig(row.onum)
        }
        ElMessage.success('删除成功')
        getList()
      } catch (error) {
        ElMessage.error('删除失败，请重试')
      }
    })
    .catch(() => { })
}

function handleClose(done) {
  bizFormRef.value.resetFields()
  done()
}

// ==== 穿梭框逻辑 ====
const leftTableData = ref([])
const leftTotal = ref(0)
const leftSelected = ref([])
const rightTableData = ref([])
const rightSelected = ref([])

function handleLeftSelect(rows) {
  leftSelected.value = rows
}
function handleRightSelect(rows) {
  rightSelected.value = rows
}

async function loadLeftTable() {
  const res = await getMetaDataList(leftQueryForm)
  leftTableData.value = res.data.rows || []
  leftTotal.value = res.data.total || 0
}

async function loadRightTable(onum) {
  const res = await getTaskBizRelaList(onum)
  rightTableData.value = res.data || []
}

function buildKey(row) {
  return `${row.ssysCd}||${row.mdlName}||${row.tabEngName}`
}

function moveToRight() {
  const existingKeys = new Set(rightTableData.value.map(buildKey))
  leftSelected.value.forEach(item => {
    if (!existingKeys.has(buildKey(item))) {
      let additem = item
      additem.onum = item.extractOnum
      rightTableData.value.push(item)
    }
  })
}

function moveToLeft() {
  const removeKeys = new Set(rightSelected.value.map(buildKey))
  rightTableData.value = rightTableData.value.filter(item => !removeKeys.has(buildKey(item)))
}

onMounted(() => {
  getList()
  getSecList()
  loadLeftTable()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.mb8 {
  margin-bottom: 8px;
}
.flex-col-center {
  display: flex;
  flex-direction: column;
  margin-top: 150px;
  justify-content: center;
  align-items: center;
  height: 100%;
}
</style>
