<template>
  <div class="app-container">
    <el-form inline :model="queryParams">
      <el-form-item label="系统名称:">
        <el-select v-model="queryParams.ssysId" clearable style="width: 200px">
          <el-option v-for="item in dsSysList" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="模式名称:">
        <el-input v-model="queryParams.mdlName"></el-input>
      </el-form-item>
      <el-form-item label="批量对象表名:">
        <el-input v-model="queryParams.bathObjTabName"></el-input>
      </el-form-item>
      <el-form-item label="批里对象字段名:">
        <el-input v-model="queryParams.bathObjFldName"></el-input>
      </el-form-item>
      <el-form-item label="状态:">
        <el-select v-model="queryParams.status" style="width: 200px" clearable>
          <el-option label="正常" key="tsmcb-query-status-1" value="1"></el-option>
          <el-option label="弃用" key="tsmcb-query-status-1" value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="showDassetDialog"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Minus"
            @click="multDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="info"
            plain
            icon="Upload"
            @click="handleImport"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
        >导出</el-button>
      </el-col>
    </el-row>
    <el-table :data="dataList" @selection-change="handleSelection">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="系统名称" align="center">
        <template #default="scope">
           <span >
             {{
               getSrcSysName(scope.row.ssysId)
             }}
           </span>
        </template>
      </el-table-column>
      <el-table-column label="模式名称" align="center" prop="mdlName"></el-table-column>
      <el-table-column label="批量对象表名" align="center" prop="bathObjTabName"></el-table-column>
      <el-table-column label="批里对象字段名" align="center" prop="bathObjFldName"></el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <el-switch v-model="scope.row.status"
                     active-value="1"
                     inactive-value="0" @change="changeStatus(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column label="负责人员" align="center" prop="updateBy"></el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime">
        <template #default="scope">
          <span>{{scope.row.updateTime.replace("T"," ")}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" prop="operation">
        <template #default="scope">
          <el-link type="danger"  style="margin-left: 10px" @click="handleDelete([scope.row.onum])" :underline="false">删除</el-link>
        </template>
      </el-table-column>
    </el-table>
    <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload
          ref="uploadRef"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url + '?overWrite=' + upload.overWrite"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" :disabled="upload.isUploading" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog title="导入结果" v-model="upload.showResult" width="1000px" append-to-body>
      <template v-if="upload.showResult">
        <el-tabs type="border-card" v-if=" (upload.resultMsg.table && upload.resultMsg.table.length>0) || (upload.resultMsg.column && upload.resultMsg.column.length>0)">
          <el-tab-pane label="表级问题" v-if="upload.resultMsg.table && upload.resultMsg.table.length>0">
            <el-table :data="upload.resultMsg.table" stripe style="width: 100%">
              <el-table-column prop="row" label="行"  />
              <el-table-column prop="ssysCd" label="系统"  />
              <el-table-column prop="mdlName" label="模式" />
              <el-table-column prop="tabEngName" label="表名称" />
              <el-table-column prop="errorInfo" label="问题" />
            </el-table>
          </el-tab-pane>
          <el-tab-pane label="字段级问题" v-if="upload.resultMsg.column && upload.resultMsg.column.length>0">
            <el-table :data="upload.resultMsg.column" stripe style="width: 100%">
              <el-table-column prop="row" label="行"  />
              <el-table-column prop="ssysCd" label="系统"  />
              <el-table-column prop="mdlName" label="模式" />
              <el-table-column prop="tabEngName" label="表名称" />
              <el-table-column prop="fldEngName" label="字段名称" />
              <el-table-column prop="errorInfo" label="问题" />
            </el-table>
          </el-tab-pane>
        </el-tabs>
        <span v-if="  (upload.resultMsg.table && upload.resultMsg.table.length===0) &&  (upload.resultMsg.column && upload.resultMsg.column.length===0) && upload.resultMsg.successCount === 0">
          上传的文档内容为空，请进行有效上传
        </span>
      </template>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="upload.showResult = false">确 定</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog title="选择资产" v-model="dasset.open" width="1100px" append-to-body>
      <el-row>
        <el-col :span="5">
          <el-tree style="margin-top: 10px" ref="treeRef" node-key="id" :default-expand-all="true"
                   :highlight-current="true" :expand-on-click-node="false" :data="treeData" :props="defaultProps"
                   :filter-node-method="filterNode" :current-node-key="currentNode.id" @node-click="handleNodeClick">
          </el-tree>
        </el-col>
        <el-col :span="19">
          <el-form :model="queryDassetParams" ref="queryRef" :inline="true" label-width="68px">
            <el-form-item label="名称" prop="name">
              <el-input v-model="queryDassetParams.dataAstEngName" placeholder="请输入名称" clearable style="width: 160px"
                        @keyup.enter="handleDassetQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleDassetQuery">搜索</el-button>
            </el-form-item>
          </el-form>
          <el-table :data="dassetList"
                     @selection-change="handleParentSelectionChange"
                     ref="parentTable">
            <el-table-column type="selection" width="40"></el-table-column>
            <el-table-column label="资产编号" align="center"  prop="astNo"/>
            <el-table-column label="表来源系统" align="center" width="150" prop="dataAstSrc" >
              <template #default="scope">
                 <span >{{getSrcSysName(scope.row.dataAstSrc)}}</span>
              </template>
            </el-table-column>
            <el-table-column label="模式名称" align="center" prop="mdlName"></el-table-column>
            <el-table-column label="表英文名称" align="center" width="200" prop="dataAstEngName"/>
            <el-table-column label="表中文名称" align="center" width="200" prop="dataAstCnName"/>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button link type="primary" @click="showColumns(scope.row)">选择字段</el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination v-show="dassetTotal > 0" :total="dassetTotal" v-model:page="queryDassetParams.pageNum"
                      v-model:limit="queryDassetParams.pageSize" @pagination="getDassetList" />
        </el-col>
      </el-row>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="save">确 定</el-button>
          <el-button @click="dasset.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog  title="选择字段" v-model="openColumn" width="800px" append-to-body>
      <el-table :data="column.children" style="width: 100%"
                @selection-change="handleChildSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="字段英文名" prop="fld_eng_name" width="200"></el-table-column>
        <el-table-column label="字段中文名" prop="fld_cn_name" width="200"></el-table-column>
        <el-table-column label="字段类型" width="170" align="center" prop="fld_type"></el-table-column>
        <el-table-column label="主键标志" align="center" prop="pk_flag">
          <template #default="props">
            <span v-if="props.row.pkFlag === 'Y'">是</span>
            <span v-else>否</span>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="confirmColumns">确 定</el-button>
          <el-button @click="openColumn = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, nextTick, computed, watch, reactive, onMounted } from 'vue'
import { getCdplbList, saveCdplb, deleteCdplb } from "@/api/dataint/cdplb"
import {getToken} from "@/utils/auth.js";
import * as XLSX from "xlsx";
import {deptTreeSelect, getSearch, getSearchWithColumns} from "@/api/dataAsset/assetDetail.js";
import useUserStore from "@/store/modules/user.js";
const { proxy } = getCurrentInstance();
const userStore = useUserStore(); // 正确调用
const dsSysList = userStore.dsSysList; // 访问属性
const queryParams = ref({
  ssysId: null,
  mdlName:'',
  bathObjTabName:'',
  bathObjFldName:'',
  status:'',
  pageNum:1,
  pageSize:10
})
const selectedTables = ref([])
const selectedColumns = ref([])
const parentTable = ref(null)
const queryDassetParams = ref({
  pageNum: 1,
  pageSize: 10,
  dataAstEngName: undefined,
  name: undefined,
  dataAstType: 'TABLE',
  dataAstScreen: '智能助手',
  dataAstSrc: undefined,
})
const dassetList = ref([])
const dassetTotal = ref(0)
const multSelection = ref([])
const dataList = ref([])
const total = ref(0)
const dasset = ref({
  open: false,
})
const openColumn = ref(false)
const column = ref({})
const treeData = ref([])
const defaultProps = {
  children: 'children',
  label: 'label',
};
const currentNode = ref({})
const filterNode = (value, data) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};
function showColumns(row){
  column.value = row;
  openColumn.value = true;
}
function save(){
  if (selectedTables.value.length>0){
    let array = []
    selectedTables.value.forEach(table=>{
      if (table.children && table.children.length>0){
        table.children.forEach(child=>{
          array.push({
            ssysId: parseInt(table.dataAstSrc),
            mdlName: child.mdl_name,
            bathObjTabName: table.dataAstEngName,
            bathObjFldName: child.fld_eng_name,
          })
        })
      }
    })
    saveCdplb({list:array}).then(res=>{
      proxy.$modal.msgSuccess("保存成功")
      dasset.value.open = false;
      selectedTables.value = []
      handleQuery()
    })
  }else{
    proxy.$modal.msgWarning("请至少选择一条数据")
  }
}

function confirmColumns(){
  if (selectedColumns.value.length>0){
    let array = []
    selectedColumns.value.forEach(selectedCol=>{
      array.push({
        ssysId: parseInt(column.value.dataAstSrc),
        mdlName: selectedCol.mdl_name,
        bathObjTabName: column.value.dataAstEngName,
        bathObjFldName: selectedCol.fld_eng_name,
      })
    })
    saveCdplb({list:array}).then(res=>{
      proxy.$modal.msgSuccess("保存成功")
      openColumn.value = false;
      selectedColumns.value = [];
      handleQuery()
    })
  }else{
    proxy.$modal.msgWarning("请至少选择一条数据")
  }
}

function handleChildSelectionChange(selection){
  selectedColumns.value = selection
}
function handleParentSelectionChange(selection){
  dassetList.value.forEach((parentRow) => {
    selectedTables.value = selectedTables.value.filter(item => item.astNo !== parentRow.astNo);
  })
  selectedTables.value.push(...selection)
}

/*** 导入参数 */
const upload = reactive({
  // 是否显示弹出层（导入）
  open: false,
  // 弹出层标题（导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  overWrite: false,
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/dataint/cdplb/upload",
  showResult: false,
  resultMsg: {}
});
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
}
/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
}
/** 下载模板操作 */
function importTemplate() {
  proxy.download("/dataint/cdplb/importTemplate", {
  }, `meta_template_${new Date().getTime()}.xlsx`);
}
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  let resData = response.data
  if (resData.successCount > 0 && resData.rows.length === 0){
    proxy.$modal.msgSuccess("导入成功")
  }else {
    upload.resultMsg = resData
    upload.showResult = true
  }
  getList();
}
function handleQuery(){
  queryParams.value.pageNum = 1;
  getList()
}
function getList(){
  getCdplbList(queryParams.value).then(res=>{
    dataList.value = res.data.rows
    total.value = res.data.total
  })
}
function resetQuery(){
  queryParams.value = {
    ssysId: null,
    mdlName:'',
    bathObjTabName:'',
    bathObjFldName:'',
    status:'',
    pageNum:1,
    pageSize:10
  }
  handleQuery()
}
function handleNodeClick(data) {
  queryDassetParams.value.dataAstSrc = data.name;
  handleDassetQuery();
}
const handleDassetQuery = () => {
  queryDassetParams.value.pageNum = 1
  getDassetList()
}
function getDassetList(){
  getSearchWithColumns(proxy.addDateRange(queryDassetParams.value)).then(res => {
    dassetList.value = res.data.rows;
    if (dassetList.value && dassetList.value.length>0){
      dassetList.value.forEach(dasset=>{
        if (dasset.children && dasset.children.length>0){
          dasset.mdlName = dasset.children[0].mdl_name
        }
      })
    }
    dassetTotal.value = res.data.total;
  });
}
const getSrcSysName = (id) => {
  if (id === null || id === undefined) return '';
  const getName = (val) => {
    const match = dsSysList.find(item => item.id === parseInt(val));
    return match ? match.name : val;
  };
  return getName(id);
};
function changeStatus(row){
  let param = {
    onum: row.onum,
    status: row.status
  }
  saveCdplb({list:[param]}).then(res=>{
    proxy.$modal.msgSuccess("操作成功");
    getList()
  })
}
function showDassetDialog(){
  dasset.value.open = true
  getDeptTree();
  handleDassetQuery();
}
function multDelete(){
  let array = []
  if (multSelection.value.length>0){
    for (let i = 0; i < multSelection.value.length; i++) {
      array.push(multSelection.value[i].onum)
    }
    handleDelete(array)
  }else{
    proxy.$modal.msgWarning("请至少选择一条数据")
  }

}
function handleDelete(array){
  deleteCdplb(array).then(res=>{
    proxy.$modal.msgSuccess("操作成功");
    getList()
  })
}
function handleImport(){
  upload.title = "数据导入";
  upload.open = true;
}
function handleExport(){
  let data = [];
  if (dataList.value.length > 0){
    for (let i = 0; i < dataList.value.length; i++) {
      data.push({
        "系统":getSrcSysName(dassetList.value[i].ssysId),
        "模式":dassetList.value[i].mdlName,
        "批量对象表名":dataList.value[i].bathObjTabName,
        "批里对象字段名":dataList.value[i].bathObjFldName,
        "状态":dataList.value[i].status === '1'?"正常":"停用"
      })
    }
  }
  const workbook = XLSX.utils.book_new();
  const worksheet = XLSX.utils.json_to_sheet(data);
  XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");
  XLSX.writeFile(workbook, "数据导出.xlsx");
}
function handleSelection(val){
  multSelection.value= val
}
function getDeptTree() {
  deptTreeSelect().then(response => {
    const data = response.data || [];
    addLabel(data);
    treeData.value = data;
  });
}
function addLabel(nodes) {
  if (!nodes) return;
  nodes.forEach(node => {
    node.label = getSrcSysName(node.name); // 给每个节点加 label
    if (node.children && node.children.length > 0) {
      addLabel(node.children); // 递归处理子节点
    }
  });
}
onMounted(() => {
  handleQuery()
})
</script>
<style scoped lang="scss">
</style>