<script setup name="DiscoverResult">
import { getCurrentInstance, reactive, ref, toRefs,onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

import { useRouter } from 'vue-router'
import useAppStore from '@/store/modules/app'
import usePermissionStore from '@/store/modules/permission'
import { changeRoute } from '@/utils/switchRoute'
import { getToken, removeToken } from '@/utils/auth'

import DomainRuleDialog from './modules/DomainRuleDialog.vue'
import MatchPreviewDialog from './modules/MatchPreviewDialog.vue'
import SaveVersionDialog from './modules/SaveVersionDialog.vue'

import {
  tdiscoverresultQuery,
  getdiscoverresultreport,
  getarearule,
  initExecute,
  discoverresultsure,
  discoverchangerule,
  showmatchrate,
  saveedition,
  download
} from '@/api/discover/index'
import { Loading } from '@element-plus/icons-vue'
import { version } from 'nprogress'

const appStore = useAppStore()
const permissionStore = usePermissionStore()
const router = useRouter()
const emit = defineEmits(['page'])
const { proxy } = getCurrentInstance()

const props = defineProps({
  listItem: {
    type: Object,
    default: () => ({})
  },
  type: {
    type: String,
    default: ''
  }
})

const requestParams = ref({
  taskid: '',
  page: 1,
  rows: 10,
  resultid: '',
  filter: {
    tablename: '', // 结果表名(resultid)
    nschema: '', // schema名称
    ntable: '', // 表名
    nfield: '', // 字段名
    checksure: '2', // 是否确认（0：未确认 1：已确认 2：全部
    issensitive: '0', // 显示模式（0：显示全部 1：显示敏感）
  }
})
const requestParamsCopy= ref({
  taskid: '',
  page: 1,
  rows: 10,
  resultid: '',
  filter: {
    tablename: '', // 结果表名(resultid)
    nschema: '', // schema名称
    ntable: '', // 表名
    nfield: '', // 字段名
    checksure: '2', // 是否确认（0：未确认 1：已确认 2：全部
    issensitive: '0', // 显示模式（0：显示全部 1：显示敏感）
  }
})




onMounted(() => {

    requestParams.value.taskid = appStore.queryData.taskid;
    requestParams.value.resultid = appStore.queryData.resultid;
    requestParams.value.filter.tablename = appStore.queryData.resultid;

    requestParamsCopy.value = JSON.parse(JSON.stringify(requestParams.value));

    saveVersionDialog.value.params.taskid = appStore.queryData.taskid;
    saveVersionDialog.value.params.resultid = appStore.queryData.resultid;

    getResultListRequest();
    displayTableAndFields();
    getDiscoverRuleListRequest();
    getVersionHistoryListRequest();

})
const totalCount = ref(0);
const collapseDataList = ref([]);

const listLoading = ref(false);
/**
 * 请求敏感类型列表
 */
const getResultListRequest = () => {
  listLoading.value = true
  tdiscoverresultQuery(requestParams.value).then(response => {
    const { list, total } = response.data

    list.map(item => {

      item.children.map(child => {
        child.icon = [
          {
            label: '匹配预览',
            name: "matchingPercent",
            color: "rgb(50,176,115)",
            icon: '&#xe7d2;',
            key: "actStatus"
          }
        ];

        if (child.dataarea_id) {
          child.icon.push({
            label: child.dataarea_name,
            icon: "",
            color: "rgb(83,144,213)",
            name: "setDataarea",
            key: "dataarea_name"
          })
        } else {
          child.icon.push({
            label: '设置',
            icon: "&#xe658;",
            color: "rgb(83,144,213)",
            name: "setDataarea",
            // fontStyle: {color: 'red'},
            key: "dataarea_name"
          })
        }

        if (child.correlation) {
          child.icon.push({
            label: '疑似敏感',
            name: "maybeKey",
            color: "rgb(250, 114, 86)",
            icon: '&#xe6a2;',
            key: "actStatus"
          })
        }

        child.button = child.issure === '1' ? [
          {
            label: '已确认',
            name: 'confirm',
            type: 'success',
            key: 'confirm'
          }
        ] : [
          {
            label: '未确认',
            name: 'unconfirmed',
            type: 'default',
            key: 'confirm'
          },
        ];

        child.discoverInfo = `${child.tsampling}/${child.teffe_sampling}/${child.tmatching}`
      })
    })
    collapseDataList.value = list;
    totalCount.value = total;
     listLoading.value = false
  })
}
const reportData = ref([])
const displayTableAndFields = () => { 
  getdiscoverresultreport({taskid: appStore.queryData.taskid}).then(response => {
    const { tasktime, tablecount, fieldcount, sensitivetable, sensitivefield } = response.data
    reportData.value = [
      {
        label: "任务运行时间",
        content: tasktime,
        color: "rgb(50,179,115)"
      },
      {
        label: "任务总对象数（表/文件）",
        content: tablecount,
        color: "rgb(250,114,86)"
      },
      {
        label: "发现敏感对象数（表/文件）",
        content: String(sensitivetable),
        color: "rgb(255,189,91)"
      },
      {
        label: "任务总列数",
        content: String(fieldcount),
        color: "rgb(83,144,213)"
      },
      {
        label: "发现敏感列数",
        content: String(sensitivefield),
        color: "rgb(157,90,178)"
      }
    ];
  })
}
const searchregexParams= ref({
  dataarea: '',
  rulename: ''
})
const dataAreaInfo = ref({
  dataArea: '',
  rule: '',
  dataAreaList: [],
  ruleList: []
})
const getDiscoverRuleListRequest = () => { 
  getarearule({
    project_id: sessionStorage.getItem("projectId"),
    rulename: searchregexParams.value.dataarea
    }).then(response => {

    let data = response.data;
    console.log(data)
    if(data && data.length > 0) {
      const newData = data.map(item => {
        return {
          dataarea: {
            dataarea: item.dataareaname,
            id: item.dataarea_id,
            // areatype: item.areatype,
            // ceatetime: item.createtime,
            // createuser: item.createuser,

            // flag: item.flag,
            // hasarea: item.hasarea,
            // note: item.note,
            // remark: item.remark,
            // updatetime: item.updatetime,
            // updateuser: item.updateuser
          },
          data: item.regexlist.length > 0 ? item.regexlist.map(rule => {
            return {
              createtime: rule.createTime,
              createuser: rule.createUser,
              dataarea: item.dataarea,
              datafile: null,
              defaulttype: String(rule.defaulttype),
              dictionaryClass: '',
              discoverway: '',
              name: rule.name,
              note: null,
              ruleid: String(rule.id),
              tid: item.tid
            }
          }) : []
        }
      })

      dataAreaInfo.value.dataAreaList = newData;
      console.log('123123',dataAreaInfo.value.dataAreaList)
    }


  })
}

const all_version_data = ref({})
const project_version_data = ref({})
const task_version_data = ref([])

const getVersionHistoryListRequest = () => { 
  initExecute({
    taskid: appStore.queryData.taskid,
    projectid: sessionStorage.getItem("projectId")
  }).then(response => {
    const { data } = response.data;

    let { all_version, project_version, task_version } = data;

    task_version.sort((a, b) =>  new Date(b.datetime).getTime() - new Date(a.datetime).getTime());

    all_version_data.value = all_version
    project_version_data.value = project_version
    task_version_data.value = task_version
  })
} 

const tableColumns= ref([
  {
    title: "序号",
    align: "center",
    width: 70,
    key: "index"
  },
  {
    title: "字段",
    align: "center",
    key: "tfields",
    ellipsis: true,
    tooltip: true,
    width: 150
  },
  {
    title: "字段说明",
    align: "center",
    key: "tfieldremark",
    tooltip: true,
    ellipsis: true,
  },
  {
    title: "采样数/有效采样数/匹配率",
    align: "center",
    key: "discoverInfo",
  },
  {
    title: "数据域",
    align: "center",
    key: "dataarea_name",
    slot: "action",
  },
  {
    title: "数据发现规则",
    align: "center",
    key: "sensitive_name"
  },
  {
    title: "梳理",
    align: "center",
    key: "confirm",
    slot: "button"
  },
  {
    title: "操作",
    align: "center",
    key: "actStatus",
    width: 260,
    slot: "action"
  }
])


function pageProjectManage() {
  if(props.type === 'process'){
       emit('page', 'discoverProcess', { listItem: props.listItem})
  }
  if(props.type === 'list'){
    emit('page', 'list', { listItem: null})
  }

}
// 折叠面板激活项
const activeNames = ref('gen_table')

// gen_table 数据
// const genTableData = ref([
//   { index: 1, field: 'business_name', fieldDesc: '', samplingInfo: '0/0/0%', dataDomain: '设置', discoveryRule: '', status: '未确认' },
//   { index: 2, field: 'business_name...', fieldDesc: '', samplingInfo: '0/0/0%', dataDomain: '设置', discoveryRule: '', status: '未确认' },
//   { index: 3, field: 'class_name', fieldDesc: '', samplingInfo: '0/0/0%', dataDomain: '设置', discoveryRule: '', status: '未确认' },
//   { index: 4, field: 'create_by', fieldDesc: '', samplingInfo: '0/0/0%', dataDomain: '设置', discoveryRule: '', status: '未确认' },
//   { index: 5, field: 'create_time', fieldDesc: '', samplingInfo: '0/0/0%', dataDomain: '设置', discoveryRule: '', status: '未确认' },
//   { index: 6, field: 'function_author', fieldDesc: '', samplingInfo: '0/0/0%', dataDomain: '设置', discoveryRule: '', status: '未确认' }
// ])

// 其他表格数据
// const allTableNames = ref([
//   { name: 'gen_table', sensitiveCount: 1 },
//   { name: 'ry.gen_table_column', sensitiveCount: 0 },
//   { name: 'ry.sys_config', sensitiveCount: 0 },
//   { name: 'ry.sys_dept', sensitiveCount: 1 },
//   { name: 'ry.sys_dict_data', sensitiveCount: 0 },
//   { name: 'ry.sys_dict_type', sensitiveCount: 0 },
//   { name: 'ry.sys_job', sensitiveCount: 0 },
//   { name: 'ry.sys_job_log', sensitiveCount: 0 },
//   { name: 'ry.sys_logininfor', sensitiveCount: 0 },
//   { name: 'ry.sys_menu', sensitiveCount: 0 }
// ])

const selectAll = ref(false)
/**
 * 显示敏感字段切换
 */
const displaySensitive = ()=>{
  console.log('显示敏感字段切换',selectAll.value)

  requestParams.value.filter.issensitive = selectAll.value === true ? '1' : '0'
   getResultListRequest()
    // console.log(requestParams.value.filter.issensitive)
}

/**
 * 批量设置规则
 */
const batchSettingRules = ()=>{
  console.log('批量设置规则')
}
const confirmAllLoading = ref(false)
/**
 * 确认所有
 */
const confirmAll = ()=>{
  confirmAllLoading.value = true
   discoverresultsure({
      resultid: appStore.queryData.resultid,
      filter: {
       ...requestParams.value.filter,
       issure: '1'
      }
    }).then((res) => {
      if(res.flag){
        ElMessage.success(res.msg)
        confirmAllLoading.value = false
        getResultListRequest()
      }else{
        confirmAllLoading.value = false
        ElMessage.error(res.msg)

      }
      
    })
}

const cancelAllLoading = ref(false) 
/**
 * 取消所有
 */
const cancelAll = ()=>{
  console.log('取消所有')
  ElMessageBox.confirm(
  `确认取消所有么？`,
  '警告',
  {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }
  ).then(() => {
    cancelAllLoading.value = true
    discoverresultsure({
      resultid: appStore.queryData.resultid,
      filter: {
       ...requestParams.value.filter,
       issure: '0'
      }
    }).then((res) => {
      if(res.flag){
        ElMessage.success(res.msg)
        cancelAllLoading.value = false
        getResultListRequest()
      }else{
        cancelAllLoading.value = false
        ElMessage.error(res.msg)

      }
      
    })
  })
}


const saveVersionDialog=ref({
  status: false,
  params: {
    versionname: '',
    taskid: '',
    flag: '1',
    resultid: '',
    projectid: '',
  },
  dataList: []
})

/**
 * 打开版本弹窗
 */
const openSaveDialog = () => {
  saveVersionDialog.value.status = true
}
/**
 * 保存
 */
// 处理保存
const handleSave = async (versionName) => {
  if (!versionName.trim()) {
    ElMessage.warning('请输入版本名称')
    return
  }

  try {
    const params = {
      ...saveVersionDialog.value.params,
      versionname: versionName,
      version: 'task_version',
      projectid: sessionStorage.getItem('projectId')
    }

    // 检查版本名是否重复
    const isDuplicate = task_version_data.value.some(
      item => item.versionname === versionName.trim()
    )

    if (isDuplicate) {
      await ElMessageBox.confirm('版本名重复,是否需要覆盖？', '提示', {
        confirmButtonText: '确认覆盖',
        cancelButtonText: '取消',
        type: 'warning'
      })
      
      // 覆盖保存
      await saveedition({ 
        ...params, 
        flag: '2' 
      })
    } else {
      // 新增保存
      await saveedition({ 
        ...params, 
        flag: '0' 
      })
    }

    ElMessage.success('保存成功！')
    saveVersionDialog.value.status = false
    saveVersionDialog.value.params.versionname = ''
    getVersionHistoryListRequest()
    
  } catch (error) {
    console.log(error)
    if (error !== 'cancel') {
      ElMessage.error('保存失败')
      console.error('Save error:', error)
    }
  }
}

// 关闭弹窗时的处理
const handleSaveDialogClose = () => {
  saveVersionDialog.value.params.versionname = ''
}

/**
 * 后退
 */
const handleBack = ()=>{
  console.log('后退')
}

const handleChangeTableByCollapse = ()=>{
  console.log('切换表格显示方式')
}




const confirmKey = (row) =>{
  discoverresultsure({
    resultid: appStore.queryData.resultid,
    tableid: row.id,
    filter: {
      ...requestParams.value.filter,
      issure: row.issure === '0' ? '1' : '0'
    }
  }).then(() => {
    getResultListRequest();


  })

}
const setDataareaDialog= ref({
  title: '',
  status: false,
  cacheData: {}
})

const setDataarea = (row) => { 
    console.log('row',row)
    setDataareaDialog.value.status = true;
    setDataareaDialog.value.cacheData = row;
    if (searchregexParams.value.dataarea.trim().length > 0) {
      searchregexParams.value.dataarea = '';
      getDiscoverRuleListRequest();
    }
    if (row.dataarea_id) {
      dataAreaInfo.value.dataArea = row.dataarea_id;
    } else {
      dataAreaInfo.value.dataArea = '';
    }
    if (row.sensitive_id) {
      console.log('dataAreaInfo.value.dataAreaList',dataAreaInfo.value.dataAreaList)
      dataAreaInfo.value.ruleList = dataAreaInfo.value.dataAreaList.filter(item => item.dataarea.id === row.dataarea_id)[0].data;
       console.log(' dataAreaInfo.value.ruleList', dataAreaInfo.value.ruleList)
      dataAreaInfo.value.rule = row.sensitive_id;
    } else {
      dataAreaInfo.value.rule = '';
      dataAreaInfo.value.ruleList = []
      console.log('123')
    }
}

const selectRule = ref({

})

// 处理规则确认
const handleRuleConfirm = (ruleData) => {
  console.log('选择的规则:', ruleData)
  selectRule.value = ruleData
  handlerSubmitRule()
}
const handlerSubmitRule = () => {
  console.log('setDataareaDialog.value.cacheData',setDataareaDialog.value.cacheData)
  discoverchangerule({
    resultid: appStore.queryData.resultid,
    tableid: setDataareaDialog.value.cacheData.id,
    filter: {
      ...requestParams.value.filter,
      nareaid: selectRule.value.domainValue,
      nareaname:selectRule.value.domain.dataarea,
      ntruleid: selectRule.value.ruleValue,
      ntrulename: selectRule.value.rule
    }
  }).then(() => {
    getResultListRequest();
    setDataareaDialog.value.status = false;
  })
}

const resetRule = () =>{
  discoverchangerule({
        resultid: appStore.queryData.resultid,
        tableid: setDataareaDialog.value.cacheData.id,
        filter: {
          ...requestParams.value.filter,
          nareaid: '',
          nareaname: '',
          ntruleid: '',
          ntrulename: ''
        }
      }).then(() => {
        getResultListRequest();
        setDataareaDialog.value.status = false;
        const { cacheData } = JSON.parse(JSON.stringify(setDataareaDialog.value));


        ElMessageBox.confirm(
          JSON.stringify(cacheData.value) === '{}' ? "撤销重置数据域操作！" : `撤销${cacheData.value.ttables}.${cacheData.value.tfields}的重置数据域操作！`,
          '警告',
          {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
          }
          ).then(() => {
            discoverchangerule({
              resultid: appStore.queryData.resultid,
              tableid: cacheData.value.id,
              filter: {
                ...requestParams.value.filter,
                nareaid: cacheData.value.dataarea_id,
                nareaname: cacheData.value.dataarea_name,
                ntruleid: String(cacheData.value.sensitive_id),
                ntrulename: cacheData.value.sensitive_name
              }
            }).then(() => {
              getResultListRequest()
            })
          })



      })
}

const closeDomainRuleDialog = () => {
  dataAreaInfo.value.rule = '';
  dataAreaInfo.value.ruleList = []
  dataAreaInfo.value.dataArea = '';
  searchregexParams.value.dataarea = '';
  setDataareaDialog.value.status = false
  console.log(1234)
}
const  matchingDiscoverDialog = ref({
  status: false,
  sampleViewList: [],
  unmatchDataList: []
})

/**
 * 匹配预览
 * @param row 
 */
const matchingPercent = (row) =>{
  showmatchrate({
    projectid: sessionStorage.getItem('projectId'),
    taskid: appStore.queryData.taskid,
    ttables: row.ttables,
    tfields: row.tfields,
    dataarea_name: row.dataarea_name
  }).then(response => {
    const { matchurl, unmatchurl } = response.data;
    matchingDiscoverDialog.value.status = true;
    matchingDiscoverDialog.value.sampleViewList = matchurl.map(item => ({label: item}));
    matchingDiscoverDialog.value.unmatchDataList = unmatchurl.map(item => ({label: item}));
  })
}
// 关闭弹窗时清空数据
const handleMatchDialogClose = () => {
  matchingDiscoverDialog.value.sampleViewList = []
  matchingDiscoverDialog.value.unmatchDataList = []
}



/**
 * 导出当前查询结果信息文件
 */
const exportData = () => {
  download({
      resultid: appStore.queryData.resultid
    }).then(res => {
      let blob = new Blob([res], {
        type: 'application/vnd.ms-excel,charset=utf-8'
      })
      let elink = document.createElement('a');
      elink.href = URL.createObjectURL(blob);
      elink.download = appStore.queryData.discoverTaskName + "发现结果.xlsx"
      document.body.appendChild(elink);
      elink.click();
      document.body.removeChild(elink);
    })
}

const handleImport = () => { 
   uploadRef.value?.$el.querySelector('input[type="file"]')?.click()
}
const uploadRef = ref(null) 
const uploadHeaders = ref({ Token: getToken() })

const uploadAction = computed(() => import.meta.env.VITE_APP_BASE_API + '/core/tdiscoverresult/importdata')

const uploadData = ref({
  resultid: appStore.queryData.resultid
})
/**
 * 上传前的验证
 */
const beforeUpload = (file) => {
  console.log(file)

  const isExcel = file.type === 'application/vnd.ms-excel' || 
                 file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
                 file.name.endsWith('.xlsx') || 
                 file.name.endsWith('.xls')
  
  if (!isExcel) {
    ElMessage.error('只能上传 Excel 文件!')
    return false
  }

  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isLt10M) {
    ElMessage.error('文件大小不能超过 10MB!')
    return false
  }

  // 显示加载中
  ElMessage.info('文件上传中...')
  return true
}

/**
 * 上传成功处理
 */
const handleSuccess = (response, file, fileList) => {
  if (response.flag) {
    ElMessage.success('导入成功！')
    // 刷新数据列表
    getResultListRequest()
  } else {
    ElMessage.error(response.msg || '导入失败')
  }
}

/**
 * 上传失败处理
 */
const handleError = (error, file, fileList) => {
  console.error('Upload error:', error)
  ElMessage.error('文件上传失败，请重试')
}

</script>

<template>
  <div class="app-container scroller">
    <PageTitle :back="true" @back="pageProjectManage">
      <template #title>
        查看结果
      </template>
      <template #buttons>
         <el-checkbox style="margin-right: 10px;" v-model="selectAll" @change="displaySensitive" class="select-all-checkbox">仅显示敏感字段</el-checkbox>
        <el-button
          type="primary"
          :Loading="confirmAllLoading"
          @click="confirmAll"
        > 
          确认所有
        </el-button>
        <el-button
          type="danger"
          :loading="cancelAllLoading"
          @click="cancelAll"
        > 
          取消所有
        </el-button>
        <el-button
          type="success"
          @click="openSaveDialog"
        > 
          保存版本
        </el-button>
        <el-button
          type="primary"
          @click="exportData"
        > 
          导出
        </el-button>

        <el-button
          type="success"
          @click="handleImport"
        > 
          导入
        </el-button>
       
        
      </template>
    </PageTitle>
    
    <div class="app-container__body">

      <div class="discovery-report-container">
        <!-- 上方：发现任务执行报告概览 -->
        <div class="report-overview">
          <h2 class="report-title">发现任务执行报告</h2>
          <div class="overview-cards">
            <el-descriptions :column="4" border>
              <el-descriptions-item :label="item.label" v-for="(item,index) in reportData" :key="index">
                <span class="highlight-text">{{item.content}}</span>
              </el-descriptions-item>
             
            </el-descriptions>
          </div>
        </div>

        <!-- 下方：详细数据表格 -->
        <div class="detailed-data">
          <el-collapse v-model="activeNames" v-if="collapseDataList.length > 0" v-loading="listLoading" accordion @change="handleChangeTableByCollapse">
            <!-- 第一个表格 -->
            <el-collapse-item :name="item.tfields" v-for="(item, index) in collapseDataList" :key="index">
              <template #title>
                <span class="collapse-title">{{ item.tfields }}</span>
                <span class="sensitive-count">{{item.dataarea_name}}</span>
              </template>
              <el-table :data="item.children" height="300px" style="width: 100%;">
                  
                <el-table-column 
                  v-for="(tableItem,tableIndex) in tableColumns"
                  :fixed="tableIndex === tableColumns.length - 1 ? 'right' : ''"
                  :key="tableIndex"
                  :prop="tableItem.key"
                  :label="tableItem.title"
                  :width="tableItem.width"
                  :align="tableItem.align"
                  :show-overflow-tooltip="tableItem.tooltip"
                >


                <template #default="scope">
                  <div v-if="tableItem.key === 'index'">{{ scope.$index + 1 }}</div>
                  <el-button type="primary" link v-if="tableItem.key === 'dataarea_name'" @click="setDataarea(scope.row)">{{ scope.row.icon.find(x =>x.key === 'dataarea_name').label }}</el-button>
                  <el-button type="primary" plain v-if="tableItem.key === 'confirm'" size="small" @click="confirmKey(scope.row)">{{ scope.row.button[0].label }}</el-button>
               
                   <el-button type="success" plain v-if="tableItem.key === 'actStatus'" size="small" @click="matchingPercent(scope.row)">{{ scope.row.icon.find(x =>x.key === 'actStatus').label }}</el-button>
               
               
                </template>
                </el-table-column>
                
              </el-table>
            </el-collapse-item>

          </el-collapse>

          <el-empty description="暂无数据" v-else/>
        </div>

        <pagination
          v-show="totalCount > 0"
          :total="totalCount"
          v-model:page="requestParams.page"
          v-model:limit="requestParams.rows"
          @pagination="getResultListRequest"
        />
      </div>

    </div>



    <DomainRuleDialog
      v-model="setDataareaDialog.status"
      :title="setDataareaDialog.title || '设置数据域与字段发现规则'"
      :data-area-list="dataAreaInfo.dataAreaList"
      :selected-data-area="dataAreaInfo.dataArea"
      :selected-rule="dataAreaInfo.rule"
      :ruleList="dataAreaInfo.ruleList"
      @update:selectedDataArea="(value) => dataAreaInfo.dataArea = value"
      @update:selectedRule="(value) => dataAreaInfo.rule = value"
      @confirm="handleRuleConfirm"
      @handleReset="resetRule"
      @closeDialog="closeDomainRuleDialog"
    />

    <MatchPreviewDialog
      v-model="matchingDiscoverDialog.status"
      :matched-data="matchingDiscoverDialog.sampleViewList"
      :unmatched-data="matchingDiscoverDialog.unmatchDataList"
      @close="handleMatchDialogClose"
    />

    <SaveVersionDialog
      v-model="saveVersionDialog.status"
      title="保存发现模板"
      :history-list="task_version_data"
      :version-name="saveVersionDialog.params.versionname"
      @update:versionName="(value) => saveVersionDialog.params.versionname = value"
      @save="handleSave"
      @close="handleSaveDialogClose"
    />


    <el-upload
      ref="uploadRef"
      class="hidden-upload"
      :action="uploadAction"
      :headers="uploadHeaders"
      :data="uploadData"
      :before-upload="beforeUpload"
      :on-success="handleSuccess"
      :on-error="handleError"
      :show-file-list="false"
      accept=".xlsx,.xls"
    />

    

  </div>
</template>

<style lang="scss" scoped>


  .flex-container { 
    display: flex;
  }

  .align-center {
    align-items: center;
  }

  .justify-between {
    justify-content: space-between;
  }

  .flex1 {
    flex: 1;
  }
  .flex-wrap {
    flex-direction: wrap;
  }



.discovery-report-container {
  padding: 20px;
  background: #f5f7fa;
  // min-height: 100vh;
}

.report-overview {
  background: white;
  border-radius: 8px;
  padding: 24px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.report-title {
  margin: 0 0 20px 0;
  color: #303133;
  font-size: 20px;
  font-weight: 600;
}

.overview-content {
  display: flex;
  gap: 20px;
  align-items: flex-start;
}

.main-cards {
  flex: 1;
}

.sensitive-column-card {
  background: #f0f7ff;
  border: 1px solid #1890ff;
  border-radius: 6px;
  padding: 20px;
  min-width: 150px;
  text-align: center;
  
  .card-content {
    display: flex;
    flex-direction: column;
    gap: 8px;
  }
  
  .card-label {
    color: #606266;
    font-size: 14px;
  }
  
  .card-value {
    color: #1890ff;
    font-size: 24px;
    font-weight: 600;
  }
}

:deep(.el-descriptions) {
  .el-descriptions__header {
    display: none;
  }
  
  .el-descriptions__body {
    background: #f0f7ff;
    border-radius: 6px;
    
    .el-descriptions__table {
      tbody {
        tr {
          background: transparent;
          
          &:hover {
            background: #e6f7ff;
          }
        }
      }
    }
  }
}

.highlight-text {
  color: #1890ff;
  font-weight: 600;
  font-size: 16px;
}

.detailed-data {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

:deep(.el-collapse) {
  border: none;
  
  .el-collapse-item {
    margin-bottom: 12px;
    
    &__header {
      background: #f0f7ff;
      border: 1px solid #1890ff;
      border-radius: 4px;
      padding: 0 16px;
      height: 48px;
      font-weight: 600;
      
      .collapse-title {
        color: #303133;
        font-size: 14px;
      }
      
      .sensitive-count {
        color: #1890ff;
        margin-left: 12px;
        font-size: 13px;
        font-weight: normal;
      }
    }
    
    &__wrap {
      border: none;
    }
    
    &__content {
      padding: 0;
      border: 1px solid #e0e0e0;
      border-top: none;
      border-radius: 0 0 4px 4px;
    }
  }
}

// 表格样式
:deep(.el-table) {
  border-radius: 0 0 4px 4px;
  
  .el-table__header-wrapper {
    th {
      background: #f0f7ff;
      color: #606266;
      font-weight: 600;
      
      .cell {
        font-weight: 600;
      }
    }
  }
  
  .el-table__body-wrapper {
    .el-table__row {
      &:nth-child(even) {
        background-color: #fafafa;
      }
      
      &:hover {
        background-color: #f5f7fa;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .discovery-report-container {
    padding: 12px;
  }
  
  .report-overview {
    padding: 16px;
  }
  
  .overview-content {
    flex-direction: column;
  }
  
  .sensitive-column-card {
    width: 100%;
  }
  
  :deep(.el-descriptions) {
    .el-descriptions__body {
      .el-descriptions__table {
        tbody {
          tr {
            display: flex;
            flex-wrap: wrap;
            
            .el-descriptions__cell {
              flex: 1 0 50%;
              min-width: 120px;
            }
          }
        }
      }
    }
  }
}
</style>