<template>
  <div class="app-container">
    <el-row  :gutter="20">
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
              v-model="dasset"
              placeholder="请输入数据资产名称"
              clearable
              prefix-icon="Search"
              style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
              :data="dassetOptions"
              :props="{ label: 'contentName', children: 'children' }"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              ref="deptTreeRef"
              node-key="onum"
              highlight-current
              default-expand-all
              @node-click="handleNodeClick"
          >
            <template #default="{ data }">
              <div class="custom-tree-node" @mouseenter="data.show = true" @mouseleave="data.show = false">
                <span>{{ data.contentName }}</span>
              </div>
            </template>
          </el-tree>
        </div>
      </el-col>
      <el-col :span="20" :xs="24">
        <el-form inline :model="queryParams">
          <el-form-item label="关键词:">
            <el-input v-model="queryParams.keyword"></el-input>
          </el-form-item>
          <el-form-item label="类型:">
            <el-input v-model="queryParams.type"></el-input>
          </el-form-item>
          <el-form-item label="字段状态:">
            <el-select v-model="queryParams.status" style="width: 200px" clearable>
              <el-option label="正常" key="sscf-query-status-1" value="1"></el-option>
              <el-option label="弃用" key="sscf-query-status-2" 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="handleAdd"
            >新增</el-button>
          </el-col>
          <!--      <el-col :span="1.5">-->
          <!--        <el-button-->
          <!--            type="success"-->
          <!--            plain-->
          <!--            icon="Edit"-->
          <!--            @click="handleEdit"-->
          <!--        >修改</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" prop="onum"></el-table-column>-->
          <el-table-column label="关键词" align="center" prop="keyword"></el-table-column>
          <el-table-column label="算法" align="center" prop="algorithm"></el-table-column>
          <el-table-column label="按顺序匹配标志" align="center" prop="order"></el-table-column>
          <el-table-column label="整句" align="center" prop="wholeSentence"></el-table-column>
          <el-table-column label="类型" align="center" prop="type"></el-table-column>
          <el-table-column label="补充说明" align="center" prop="suppExpl" width="200">
            <template #default="scope">
              <el-popover
                  class="box-item"
                  :popper-style="{width:'300px'}"
                  :content="scope.row.suppExpl"
                  placement="right-start"
              >
                <template #reference>
                  <span>{{scope.row.suppExpl.substring(0, 20) + (scope.row.suppExpl && scope.row.suppExpl.length >= 20?"...":"")}}</span>
                </template>
              </el-popover>
            </template>
          </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="primary" @click="handleEdit(scope.row)" :underline="false">修改</el-link>
              <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-col>
    </el-row>
    <el-dialog
        v-model="showDialog"
        :title="currentForm.operate === 'ADD'?'新增字段':'编辑字段'"
        width="500"
    >
      <el-form
          v-if="showDialog"
          :model="currentForm"
          ref="formRef"
          :rules="rules"
          label-width="125px">
        <el-form-item label="归属资产名:" prop="dassetId">
          <el-tree-select
              v-model="currentForm.dassetId"
              :data="dassetOptions"
              multiple
              default-expand-all
              check-on-click-node
              check-strictly
              :props="{
                label: 'contentName',  // 必须对应节点显示文本的字段
                value: 'contentOnum',   // 必须对应节点值的字段
                children: 'children'    // 必须对应子节点字段
              }"
              @change="changeDassetId"
              style="width: 100%;" clearable />
        </el-form-item>
        <el-form-item label="关键词:" prop="keyword">
          <el-input
              v-model="currentForm.keyword" clearable
          />
        </el-form-item>
        <el-form-item label="字段状态:">
          <el-radio-group v-model="currentForm.status">
            <el-radio value="1" size="large">正常</el-radio>
            <el-radio value="0" size="large">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="算法:">
          <el-radio-group v-model="currentForm.algorithm">
            <el-radio value="包含" size="large">包含</el-radio>
            <el-radio value="等于" size="large">等于</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="按顺序匹配标志:">
          <el-switch v-model="currentForm.order"
                     active-value="True"
                     inactive-value="False"  />
        </el-form-item>
        <el-form-item label="整句:">
          <el-switch v-model="currentForm.wholeSentence"
                     active-value="True"
                     inactive-value="False"  />
        </el-form-item>
        <el-form-item label="类型:">
          <el-radio-group v-model="currentForm.type">
            <el-radio value="补充" size="large">补充</el-radio>
            <el-radio value="替换" size="large">替换</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="补充说明:">
          <el-input
              v-model="currentForm.suppExpl" clearable
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showDialog = false">取消</el-button>
          <el-button type="primary" @click="handleSave">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
        v-model="showTreeDialog"
        :title="currentTreeNode.operate === 'ADD'?'新增目录':'编辑目录'"
        width="500"
    >
      <el-form
          v-if="showTreeDialog"
          :model="currentTreeNode"
          ref="formRef"
          :rules="dassetRules"
          label-width="125px">
        <el-form-item label="目录编码:" prop="dassetCode">
          <el-input
              v-model="currentTreeNode.dassetCode" clearable :disabled="currentTreeNode.dassetCode === 'root'"
          />
        </el-form-item>
        <el-form-item label="目录名称:" prop="dassetName">
          <el-input
              v-model="currentTreeNode.dassetName" clearable
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showTreeDialog = false">取消</el-button>
          <el-button type="primary" @click="handleSaveTree">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
    <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>
  </div>
</template>
<script setup>
import { ref, nextTick, computed, watch, reactive, onMounted } from 'vue'
import { getSscfList, saveSscf, deleteSscf, get_dasset_tree, saveDassetTreeNode } from "@/api/dataint/sscf"
import * as XLSX from "xlsx";
import {getToken} from "../../../utils/auth.js";
import {getDirectoryTree} from "../../../api/dataAsset/directory.js";


const { proxy } = getCurrentInstance();

const queryParams = ref({
  dassetId:[],
  keyword:'',
  type:'',
  status:'',
  pageNum:1,
  pageSize:10
})
const currentForm = ref({
  operate: 'ADD',
  dassetId:[],
  status:'1',
  keyword:'',
  algorithm:'包含',
  order:'True',
  wholeSentence:'True',
  type:'补充',
  suppExpl:''
})
const dassetList = ref([])
const rules = ref({
  dassetId: [{required: true, message: '归属资产不能为空！', trigger: 'change',},],
  keyword: [{required: true, message: '关键词不能为空！', trigger: 'change',},],
})
const dassetRules = ref({
  dassetCode: [{required: true, message: 'code不能为空！', trigger: 'change',},],
  dassetName: [{required: true, message: '名称不能为空！', trigger: 'change',},],
})
const multSelection =ref([])
const dassetOptions = ref([])
const dasset =ref('')
const dataList = ref([])
const total = ref(0)
const showDialog = ref(false)
const showTreeDialog = ref(false)
const currentTreeNode = ref({})
/*** 导入参数 */
const upload = reactive({
  // 是否显示弹出层（导入）
  open: false,
  // 弹出层标题（导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  overWrite: false,
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/dataint/sscf/upload",
  showResult: false,
  resultMsg: {}
});
/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
}
/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
}
/** 下载模板操作 */
function importTemplate() {
  proxy.download("/dataint/sscf/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 handleSaveTree(){
  let param = {
    operate: currentTreeNode.value.operate,
    dassetCode: currentTreeNode.value.dassetCode,
    dassetName: currentTreeNode.value.dassetName,
    onum: currentTreeNode.value.onum
  }
  saveDassetTreeNode(param).then(res=>{
    proxy.$modal.msgSuccess("操作成功")
    showTreeDialog.value = false
    get_tree_data()
  })
}

function handleQuery(){
  queryParams.value.pageNum = 1;
  getList()
}
function getList(){
  getSscfList(queryParams.value).then(res=>{
    dataList.value = res.data.rows
    total.value = res.data.total
  })
}
function changeDassetId(){
  console.log(dassetOptions.value)
  console.log(currentForm.value.dassetId)
}
/** 节点单击事件 */
function handleNodeClick(data) {
  queryParams.value.dassetId = getAllChildOnums(data).join(',');
  handleQuery();
}
const getAllChildOnums = (node) => {
  const onums = [node.contentOnum]; // 当前节点的 onum
  if (node.children && node.children.length > 0) {
    node.children.forEach(childNode => {
      onums.push(...getAllChildOnums(childNode)); // 递归子节点
    });
  }
  return onums;
};

function resetQuery(){
  queryParams.value = {
    pos:'',
    type:'',
    stdRplStr:'',
    status:'',
    pageNum:1,
    pageSize:10
  }
  handleQuery()
}
function handleAdd(){
  showDialog.value = true
  currentForm.value ={
    operate: 'ADD',
    dassetId:[1],
    status:'1',
    keyword:'',
    algorithm:'包含',
    order:'True',
    wholeSentence:'True',
    type:'补充',
    suppExpl:''
  }
}
function handleEdit(row){
  currentForm.value = JSON.parse(JSON.stringify(row))
  currentForm.value.operate = 'UPDATE'
  showDialog.value = true
}
function changeStatus(row){
  let param = {
    onum: row.onum,
    status: row.status
  }
  saveSscf(param).then(res=>{
    proxy.$modal.msgSuccess("操作成功");
    getList()
  })
}
function handleSave(){
  proxy.$refs.formRef.validate(valid => {
    if (valid) {
      let data = currentForm.value;
      data.dassetId = data.dassetId.join(',')
      saveSscf(data).then(res=>{
        proxy.$modal.msgSuccess("操作成功");
        showDialog.value = false
        getList()
      })
    }
  });
}
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){
  deleteSscf(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({
        "关键词":dataList.value[i].keyword,
        "算法":dataList.value[i].algorithm,
        "按顺序匹配标志":dataList.value[i].order,
        "整句":dataList.value[i].wholeSentence,
        "类型":dataList.value[i].type,
        "补充说明":dataList.value[i].suppExpl,
        "状态":dataList.value[i].status,
        "负责人员":dataList.value[i].updateBy
      })
    }
  }
  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 cleanTreeData(nodes) {
  if (!nodes || nodes.length === 0) return;
  nodes.forEach(node => {
    // 优先处理子节点（深度优先）
    if (node.children?.length > 0) {
      cleanTreeData(node.children);
    }
    // 过滤当前层级无效节点
    if (node.children) {
      node.children = node.children.filter(child =>
          Boolean(child.contentName)  // 更严谨的空值检查
      );
    }
  });
}
function get_tree_data(){
  getDirectoryTree({pageSize: 999}).then(res => {
    dassetOptions.value = []
    let array = res.rows;
    if(array.length >0 && array[0].children && array[0].children.length>0){
      array[0].children = array[0].children.filter(child =>
          Boolean(child.contentName !== '我的收藏')  // 更严谨的空值检查
      );
    }
    cleanTreeData(array)
    dassetOptions.value = array
  })

  // get_dasset_tree().then(res=>{
  //   let treeList = res.data
  //   if(treeList.length > 0){
  //     let children = []
  //     dassetOptions.value = []
  //     for (let i = 0; i < treeList.length; i++) {
  //       if (treeList[i].dassetCode === "root"){
  //         dassetOptions.value.push(treeList[i])
  //       }else {
  //         children.push(treeList[i])
  //       }
  //     }
  //     dassetOptions.value[0].children = children
  //     dassetList.value = children
  //   }
  // })
}
/** 通过条件过滤节点  */
const filterNode = (value, data) => {
  if (!value) return true;
  return data.dassetName.indexOf(value) !== -1;
};
watch(dasset, val => {
  proxy.$refs["deptTreeRef"].filter(val);
});
onMounted(() => {
  get_tree_data()
  handleQuery()
})
</script>
<style scoped lang="scss">
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  .tree-node__action {
    padding: 0 8px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>