<template>
  <div class="countrybill-wrapper">
    <div class="header-box">
      <div class="header-top">
        <SelectBox :placeholder-name="personTypePlaceHolder" select-title="人物类别" :select-list="personTypeList"
          :select-name="selectedPersonType" @update:select-text="handlePersonType" />
        <SelectBox :placeholder-name="nationalityPlaceHolder" select-title="人物国籍" :select-list="nationalityList"
          :select-name="selectedNationality" @update:select-text="handleSelectNationality" />
        <SelectBox :placeholder-name="insPlaceHolder" select-title="所属机构" :select-list="insList"
          :select-name="selectedIns" @update:select-text="handleSelectIns" />
        <SelectBox :placeholder-name="partyPlaceHolder" select-title="党派" :select-list="partyList"
          :select-name="selectedParty" @update:select-text="handleSelectParty" />
      </div>
      <div class="header-footer">
        <div class="header-footer-left">
          <ActiveTag v-for="tag, index in activeTagList" :key="index" :tagName="tag.name"
            @close="handleCloseCurTag(tag, index)" />
        </div>
        <div class="header-footer-right">
          <HeaderBtnBox :isShowAll="isFolderAll" :isShowAllBtn="false" @show-all="handleSwitchFolderAll"
            @clear="handleClear" @confirm="handleConfirm" />
        </div>
      </div>
    </div>
    <div class="chart-main-box" v-if="isShowChart" v-loading="loading" element-loading-text="数据加载中，请稍候...">
      <div class="info-box">
        <div class="switch-box" @click="handleSwitchChartData">
          <DataChartSwitchBox :is-show-data="!isShowChart" />
        </div>
        <div class="num-box text-title-3-bold">
          {{ `共 ${totalNum} 条数据` }}
        </div>
      </div>
      <div class="content-box">
        <div class="content-header">
          <ChartHeader :list="staticsDemensionList" @clickItem="handleClickDemensionItem">
            <!-- <template #chart-header-right>
              <el-select v-model="selectedTime" placeholder="选择时间" style="width: 150px" v-show="curDemension === '发布时间'"
                @change="handleChangeTime">
                <el-option v-for="item in timeList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>

            </template> -->
          </ChartHeader>
        </div>
        <div class="content-main">
          <ChartContainer :chartTitle="curChartTitle" :chartTypeList="curChartTypeList"
            @clickChartItem="handleSwitchActiveChart" @download="handleDownloadCurChartData">
            <template #chart-box>
              <LineChart v-if="activeChart === '折线图'" :lineChartData="curChartData" />
              <BarChart v-if="activeChart === '柱状图'" :barChartData="curChartData" />
              <PieChart v-if="activeChart === '饼状图'" :pieChartData="curChartData" />
              <RaderChart v-if="activeChart === '雷达图'" :radarChartData="curChartData" />
            </template>
          </ChartContainer>

        </div>
      </div>
    </div>
    <div class="data-main-box" v-else v-loading="loading" element-loading-text="数据加载中，请稍候...">
      <div class="data-main-box-header">
        <div class="switch-box" @click="handleSwitchChartData">
          <DataChartSwitchBox :is-show-data="!isShowChart" />
        </div>
        <div class="num-box text-title-3-bold">
          {{ `共 ${totalNum} 条数据` }}
        </div>
      </div>
      <div class="data-main-box-main">
        <div class="data-main-box-main-header">
          <div class="header-left">
            <div class="header-left-item1">
              <el-checkbox v-model="isSelectedAll" label="全选" @change="handleSelectAllChange" size="large" />
            </div>
            <div class="header-left-item2 text-tip-1">{{ `已选择${selectedCount}项` }}</div>
            <div class="header-left-item2 text-tip-1 cancel" @click="handleClearAll" v-show="selectedCount">{{ '取消' }}
              <div class="header-left-item3 text-tip-1" v-if="isShowAllDataMaxLengthTip">{{ `(当前最大选择不能超过1万条！)` }}</div>

            </div>
          </div>
          <div class="header-right">
            <div class="header-right-item item1" @click="handleExport">
              <div class="icon">
                <img src="../assets/icons/download.svg" alt="">
              </div>
              <div class="text text-tip-1">{{ '导出' }}</div>
            </div>
            <div class="header-right-item2 item2">
              <el-select v-model="curOperation" placeholder="批量操作" style="width: 120px">
                <el-option v-for="item in operationList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </div>
            <div class="header-right-item3 item3">
              <el-select v-model="isSort" placeholder="发布时间" style="width: 166px" @change="handlePxChange">
                <template #prefix>
                  <div style="display: flex; align-items: center; height: 100%">
                    <img src="../assets/icons/desc-icon.svg" style="width: 14px; height: 14px" />
                  </div>
                </template>
                <el-option v-for="item in releaseTimeList" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </div>
          </div>
        </div>
        <div class="data-main-box-main-content">
          <el-table ref="tableRef" :data="tableData" row-key="id" @selection-change="handleSelectionChange"
            @select="handleSelect" @select-all="handleSelectAll" style="width: 100%" :row-style="{ height: '52px' }">
            <el-table-column type="selection" width="40" />
            <el-table-column label="姓名" width="360">
              <template #default="scope">
                <span class="title-item text-compact-bold" @click="handleClickToDetail(scope.row)">{{
                  scope.row.originalTitle
                }}</span>
              </template>
            </el-table-column>
            <el-table-column label="国籍" width="180" class-name="date-column">
              <template #default="scope">{{ scope.row.date }}</template>
            </el-table-column>
            <el-table-column label="党派" width="100">
              <template #default="scope">{{ scope.row.affiliation }}</template>
            </el-table-column>
            <el-table-column label="最新动态">
              <template #default="scope">
                <span class="person-item text-compact">{{ scope.row.organizationName
                }}</span>
              </template>
            </el-table-column>

          </el-table>
        </div>
      </div>
      <div class="data-main-box-footer">
        <el-pagination background layout="prev, pager, next" :total="totalNum" v-model:current-page="currentPage"
          :page-size="pageSize" @current-change="handleCurrentChange" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, nextTick } from 'vue'
import ChartContainer from '../components/ChartContainer/index.vue'
import ChartHeader from '../components/ChartHeader/index.vue'
import ActiveTag from '../components/ActiveTag/index.vue'
import HeaderBtnBox from '../components/HeaderBtnBox/index.vue'
import LineChart from '../components/LineChart/index.vue'
import PieChart from '../components/PieChart/index.vue'
import BarChart from '../components/BarChart/index.vue'
import RaderChart from '../components/RadarChart/idnex.vue'
import SelectBox from '../components/SelectBox/index.vue'
import DataChartSwitchBox from '../components/dataChartSwitchBox/index.vue'
import { useRoute } from "vue-router";
import router from '@/router'

import { search } from '@/api/comprehensiveSearch'
import { ElMessage } from 'element-plus'

import { getPersonType, getCountryList, getThinkTankList } from "@/api/comprehensiveSearch/index"

const route = useRoute();

// 图表/数据
const isShowChart = ref(false)
// 点击切换数据/图表
const handleSwitchChartData = () => {
  isShowChart.value = !isShowChart.value
  if (isShowChart.value) {
    const curDemensionItem = staticsDemensionList.value.filter(item => {
      return item.name === curDemension.value
    })[0]
    activeChart.value = curDemensionItem.chartTypeList[0].name
    curChartData.value = curDemensionItem.chartTypeList[0].data
  }
}

// 总计数据
const totalNum = ref(0)

// 统计维度列表
const staticsDemensionList = ref([
  {
    name: '人物国籍',
    active: true,
    chartTypeList: [{
      name: '饼状图',
      data: []
    },
    {
      name: '柱状图',
      data: {
        dataX: [],
        dataY: []
      }
    }],
    chartTitle: '科技人物国籍分布',
    data: []
  },
  {
    name: '党派',
    active: false,
    chartTypeList: [{
      name: '饼状图',
      data: []
    },
    {
      name: '柱状图',
      data: {
        dataX: [],
        dataY: []
      }
    }],
    chartTitle: '科技人物党派分布',
    data: []
  },

  {
    name: '所属机构',
    active: false,
    chartTypeList: [{
      name: '饼状图',
      data: []
    },
    {
      name: '柱状图',
      data: {
        dataX: [],
        dataY: []
      }
    }],
    chartTitle: '科技人物所属机构分布',
  },
  {
    name: '人物类别',
    active: false,
    chartTypeList: [{
      name: '饼状图',
      data: []
    },
    {
      name: '柱状图',
      data: {
        dataX: [],
        dataY: []
      }
    }],
    chartTitle: '科技人物类别分布',
  },

])

// 当前维度下的图表列表
const curChartTypeList = computed(() => {
  let arr = staticsDemensionList.value.filter(item => item.active)
  return arr[0].chartTypeList
})

// 当前图表标题
const curChartTitle = computed(() => {
  let arr = staticsDemensionList.value.filter(item => item.active)
  return arr[0].chartTitle
})

// 当前维度
const curDemension = ref('人物国籍')

// 点击维度item
const handleClickDemensionItem = (val) => {
  activeChart.value = ''
  staticsDemensionList.value.forEach(item => {
    item.active = false
  })
  val.active = true
  nextTick(() => {
    activeChart.value = val.chartTypeList[0].name
    curChartData.value = val.chartTypeList[0].data
    curDemension.value = val.name
  })
}

// 时间图表 当前选择时间
const selectedTime = ref('按年度统计')
// 时间图表-时间列表
const timeList = ref([
  {
    label: '按年度统计',
    value: '按年度统计'
  },
  {
    label: '按季度统计',
    value: '按季度统计'
  },
  {
    label: '按月度统计',
    value: '按月度统计'
  },
])
// const handleChangeTime = value => {
//   let curChart = activeChart.value
//   activeChart.value = ''
//   if (value === '按月度统计') {
//     setTimeout(() => {
//       activeChart.value = curChart
//       curChartData.value = staticsDemensionList.value[0].data
//     })
//   } else if (value === '按季度统计') {
//     setTimeout(() => {
//       activeChart.value = curChart
//       curChartData.value = staticsDemensionList.value[0].quatarData
//     })
//   } else {
//     setTimeout(() => {
//       activeChart.value = curChart
//       curChartData.value = staticsDemensionList.value[0].yearData
//     })
//   }
// }


// 激活的标签列表
const activeTagList = computed(() => {
  const arr = []
  if (selectedPersonType.value && selectedPersonType.value !== '全部人物类别') {
    arr.push(
      {
        tag: '人物类别',
        name: selectedPersonType.value
      }
    )
  }
  if (selectedNationality.value && selectedNationality.value !== '全部人物国籍') {
    let nationalityStr = nationalityList.value.filter(item => item.id === selectedNationality.value)[0]?.name
    arr.push(
      {
        tag: '人物国籍',
        name: nationalityStr
      }
    )
  }
  if (selectedIns.value && selectedIns.value !== '全部机构') {
    arr.push(
      {
        tag: '所属机构',
        name: selectedIns.value
      }
    )
  }
  if (selectedParty.value && selectedParty.value !== '全部党派') {
    arr.push(
      {
        tag: '党派',
        name: selectedParty.value
      }
    )
  }

  return arr

})

// 关闭当前标签
const handleCloseCurTag = (tag, index) => {
  switch (tag.tag) {
    case '人物类别':
      selectedPersonType.value = '全部人物类别'
      break
    case '人物国籍':
      selectedNationality.value = '全部人物国籍'
      break
    case '所属机构':
      selectedIns.value = '全部机构'
      break
    case '党派':
      selectedParty.value = '全部党派'
      break

  }

}

const activeChart = ref('')  // 当前激活的图表
// 切换当前图表
const handleSwitchActiveChart = val => {
  activeChart.value = val.name
  const curChartItem = curChartTypeList.value.filter(item => item.name === val.name)[0]
  curChartData.value = curChartItem.data
}



// 数据- 是否全选
const isSelectedAll = ref(false)
// 批量操作-当前操作
const curOperation = ref('')
const operationList = ref([

])

// 人物类别
const personTypePlaceHolder = ref('请选择人物类别')
const selectedPersonType = ref('全部人物类别')
const personTypeList = ref([
  {
    name: '全部人物类别',
    id: '全部人物类别'

  }
])
const handlePersonType = (value) => {
  selectedPersonType.value = value
}
// 获取人物类别
const handleGetPersonType = async () => {
  try {
    const res = await getPersonType()
    console.log('人物类别', res);
    if (res && res.length) {
      personTypeList.value = res.map(item => {
        return {
          name: item,
          id: item
        }
      })
      personTypeList.value = [
        {
          name: '全部人物类别',
          id: '全部人物类别'
        },
        ...personTypeList.value
      ]
    }

  } catch (error) {
    console.error(error);

  }
}

// 国籍
const nationalityPlaceHolder = ref('请选择人物国籍')
const selectedNationality = ref('全部人物国籍')
const nationalityList = ref([
  {
    name: '全部人物国籍',
    id: '全部人物国籍'

  },

])
const handleSelectNationality = (value) => {
  selectedNationality.value = value
}
// 获取国籍列表
const handleGetCountryList = async () => {
  try {
    const res = await getCountryList()
    console.log('国籍列表', res);
    if (res.code === 200 && res.data) {
      nationalityList.value = res.data.map(item => {
        return {
          name: item.name,
          id: item.id
        }
      })
      nationalityList.value = [
        {
          name: '全部人物国籍',
          id: '全部人物国籍'

        },
        ...nationalityList.value
      ]
    }

  } catch (error) {
    console.error(error);

  }
}


// 所属机构
const insList = ref([
  {
    name: '全部机构',
    id: '全部机构'
  },
])
const selectedIns = ref('全部机构')
const insPlaceHolder = ref('请选择所属机构')
const handleSelectIns = value => {
  selectedIns.value = value
}
// 获取所属机构列表
const handleGetInsList = async () => {
  const params = {
    type: 6
  }
  try {
    const res = await getThinkTankList(params)
    console.log('所属机构列表', res);
    if (res && res.length) {
      insList.value = res.map(item => {
        return {
          name: item,
          id: item
        }
      })
      insList.value = [
        {
          name: '全部机构',
          id: '全部机构'

        },
        ...insList.value
      ]
    }

  } catch (error) {
    console.error(error);

  }
}

// 党派列表
const partyList = ref([
  {
    name: '全部党派',
    id: '全部党派'
  },
  {
    name: '民主党',
    id: '民主党'
  },
  {
    name: '共和党',
    id: '共和党'
  },

])
const selectedParty = ref('全部党派')
const partyPlaceHolder = ref('请选择党派')
const handleSelectParty = value => {
  selectedParty.value = value
}


// 清空条件
const handleClear = () => {
  selectedPersonType.value = '全部人物类别'
  selectedNationality.value = '全部人物国籍'
  selectedIns.value = '全部机构'
  selectedParty.value = '全部党派'
  ElMessage.success('已清空条件！')
}

// 确定
const handleConfirm = () => {
  currentPage.value = 1
  fetchTableData()
}

// 展开全部 / 收起
const isFolderAll = ref(false)
const handleSwitchFolderAll = () => {
  isFolderAll.value = !isFolderAll.value
}

const tableRef = ref(null)

// 表格数据
const tableData = ref([
])

const releaseTimeList = ref([
  {
    label: "按发布时间倒序",
    value: true
  },
  {
    label: "按发布时间升序",
    value: false
  }
]);
const isSort = ref(true); // true 倒序  false 升序
const handlePxChange = val => {
  fetchTableData()
};

const currentPage = ref(1);
const pageSize = ref(10)

// 存储选中的数据（跨页）[citation:3][citation:8]
const selectedMap = ref(new Map())  // 使用 Map 存储，key 为唯一 id

// 计算已选中的条数
const selectedCount = computed(() => selectedMap.value.size)

// 获取当前页表格数据（示例）
const fetchTableData = async () => {
  // isSelectedAll.value = false
  // selectedMap.value.clear()
  loading.value = true
  // 调用接口获取数据...
  const params = {
    page: currentPage.value,
    size: pageSize.value,
    type: 6,  // type 1= 法案  2= 政令 3 =智库 4=智库报告 5=实体清单【制裁记录】 6= 人物 7= 机构 8=新闻 9= 社媒
    countryId: selectedNationality.value === '全部人物国籍' ? null : selectedNationality.value,
    personType: selectedPersonType.value === '全部人物类别' ? null : selectedPersonType.value,
    organizationName: selectedIns.value === '全部机构' ? null : selectedIns.value,
    affiliation: selectedParty.value === '全部党派' ? null : selectedParty.value,
    sort: isSort.value ? 0 : 1     // 0 先按分数降序 后按时间降序  1 先按分数降序，再按时间升序
  }
  try {
    const res = await search(params)
    console.log('搜索结果', res);
    if (res.code === 200 && res.data) {
      tableData.value = res.data.records
      totalNum.value = res.data.total
      staticsDemensionList.value[0].chartTypeList[0].data = Object.entries(res.data.aggregationCountryId).map(([key, value]) => ({
        name: key,
        value: Number(value)
      }))
      staticsDemensionList.value[0].chartTypeList[1].data = {
        dataX: Object.keys(res.data.aggregationCountryId),
        dataY: Object.values(res.data.aggregationCountryId).map(value => Number(value))
      }
      staticsDemensionList.value[1].chartTypeList[0].data = Object.entries(res.data.aggregationsAffiliation).map(([key, value]) => ({
        name: key,
        value: Number(value)
      }))
      staticsDemensionList.value[1].chartTypeList[1].data = {
        dataX: Object.keys(res.data.aggregationsAffiliation),
        dataY: Object.values(res.data.aggregationsAffiliation).map(value => Number(value))
      }
      staticsDemensionList.value[2].chartTypeList[0].data = Object.entries(res.data.aggregationsorganizationName).map(([key, value]) => ({
        name: key,
        value: Number(value)
      }))
      staticsDemensionList.value[2].chartTypeList[1].data = {
        dataX: Object.keys(res.data.aggregationsorganizationName),
        dataY: Object.values(res.data.aggregationsorganizationName).map(value => Number(value))
      }
      staticsDemensionList.value[3].chartTypeList[0].data = Object.entries(res.data.aggregationPersonType).map(([key, value]) => ({
        name: key,
        value: Number(value)
      }))
      staticsDemensionList.value[3].chartTypeList[1].data = {
        dataX: Object.keys(res.data.aggregationPersonType),
        dataY: Object.values(res.data.aggregationPersonType).map(value => Number(value))
      }
    }

    const curDemensionItem = staticsDemensionList.value.filter(item => {
      return item.name === curDemension.value
    })[0]

    activeChart.value = ''

    setTimeout(() => {
      activeChart.value = curDemensionItem.chartTypeList[0]
      curChartData.value = curDemensionItem.data
    })

  } catch (error) {
    console.error(error);

  } finally {
    loading.value = false
  }


  // 数据加载后，回显已选中的行 
  nextTick(() => {
    tableData.value.forEach(row => {
      if (selectedMap.value.has(row.id)) {
        tableRef.value?.toggleRowSelection(row, true)
      }
    })
  })
}
const allData = ref([])

// 获取筛选条件下全部表格数据
const fetchAllData = async () => {
  const params = {
    page: 1,
    size: 9999,
    type: 6,  // type 1= 法案  2= 政令 3 =智库 4=智库报告 5=实体清单【制裁记录】 6= 人物 7= 机构 8=新闻 9= 社媒
    countryId: selectedNationality.value === '全部人物国籍' ? null : selectedNationality.value,
    personType: selectedPersonType.value === '全部人物类别' ? null : selectedPersonType.value,
    organizationName: selectedIns.value === '全部机构' ? null : selectedIns.value,
    affiliation: selectedParty.value === '全部党派' ? null : selectedParty.value,
    sort: isSort.value ? 0 : 1     // 0 先按分数降序 后按时间降序  1 先按分数降序，再按时间升序
  }
  try {
    const res = await search(params)
    console.log('搜索结果', res);
    if (res.code === 200 && res.data) {
      allData.value = res.data.records
    }

  } catch (error) {
    ElMessage.error('加载全部数据出错！')
  }
}

// 单选事件 
const handleSelect = (selection, row) => {
  if (selection.some(item => item.id === row.id)) {
    // 选中：添加到 Map
    selectedMap.value.set(row.id, row)
  } else {
    // 取消选中：从 Map 移除
    selectedMap.value.delete(row.id)
  }
}

// 表格自带 当前页 全选/全不选事件 
const handleSelectAll = (selection) => {
  if (selection.length > 0) {
    // 全选：将当前页所有数据添加到 Map
    tableData.value.forEach(row => {
      if (!selectedMap.value.has(row.id)) {
        selectedMap.value.set(row.id, row)
      }
    })
  } else {
    // 全不选：从 Map 中移除当前页的所有数据
    tableData.value.forEach(row => {
      selectedMap.value.delete(row.id)
    })
  }
}

// 处理选择变化（用于统计）
const handleSelectionChange = (val) => {
  // 这里可以做一些额外的处理，但主要统计使用 selectedMap
  console.log('当前页选中数量:', val.length)
}

// 全选当前页按钮
const handleSelectAllPage = () => {
  if (tableData.value.length === 0) return

  // 检查当前页是否已全选
  const currentPageSelected = tableData.value.every(row =>
    selectedMap.value.has(row.id)
  )

  if (currentPageSelected) {
    // 已全选，则不动当前页的全选
    tableData.value.forEach(row => {
      tableRef.value.toggleRowSelection(row, false)
      // selectedMap.value.delete(row.id)
    })
  } else {
    // 未全选，则全选当前页
    tableData.value.forEach(row => {
      tableRef.value.toggleRowSelection(row, true)
      if (!selectedMap.value.has(row.id)) {
        selectedMap.value.set(row.id, row)
      }
    })
  }
}

// 全选最大1万条提示
const isShowAllDataMaxLengthTip = ref(false)
const loading = ref(false)  // 加载数据loading

// 处理 全选(全部数据)
const handleSelectAllChange = async () => {
  if (isSelectedAll.value) {

    if (totalNum.value > 10000) {
      isShowAllDataMaxLengthTip.value = true
    }
    loading.value = true

    await fetchAllData()
    handleSelectAllPage()
    allData.value.forEach(row => {
      if (!selectedMap.value.has(row.id)) {
        selectedMap.value.set(row.id, row)
      }
    })
    loading.value = false
  } else {
    handleClearAll()
  }

}

// 清空所有选择
const handleClearAll = () => {
  isSelectedAll.value = false
  selectedMap.value.clear()
  tableRef.value?.clearSelection()
}

// 翻页
const handleCurrentChange = async (val) => {
  currentPage.value = val
  await fetchTableData()
  if (isSelectedAll.value) {
    handleSelectAllPage()
  }
}


// 监听数据变化，回显选中状态 [citation:4][citation:8]
watch(tableData, () => {
  nextTick(() => {
    tableData.value.forEach(row => {
      if (selectedMap.value.has(row.id)) {
        tableRef.value?.toggleRowSelection(row, true)
      }
    })
  })
})

// 当前图表数据
const curChartData = ref(null)

// 下载当前图表数据
const handleDownloadCurChartData = () => {
  const jsonStr = JSON.stringify(curChartData.value, null, 2);
  const blob = new Blob([jsonStr], { type: 'application/json' });
  const url = URL.createObjectURL(blob);

  const link = document.createElement('a');
  link.href = url;
  link.download = 'chartData.json';
  link.click();

  URL.revokeObjectURL(url);
}

// 跳转到当前页 初始化筛选条件
const initParam = () => {
  const hasQuery = Object.keys(route.query).length > 0;
  if (hasQuery) {
    selectedPersonType.value = route.query.domains ? route.query.domains : '全部人物类别'

    selectedIns.value = route.query.orgnizationName ? route.query.orgnizationName : '全部机构'

    selectedParty.value = route.query.selectedParty ? route.query.selectedParty : '全部党派'

    const query = route.query;
    if (Object.keys(query).length > 0) {
      sessionStorage.setItem('decreeRouteQuery', JSON.stringify(query));
    }
  } else {
    const savedQuery = JSON.parse(sessionStorage.getItem('decreeRouteQuery') || '{}');
    selectedPersonType.value = savedQuery.domains ? savedQuery.domains : '全部人物类别'


    selectedParty.value = savedQuery.selectedParty ? savedQuery.selectedParty : '全部党派'
  }

}

// 跳转人物详情
const handleClickToDetail = (item) => {
  window.sessionStorage.setItem('curTabName', item.name)
  const routeData = router.resolve({
    path: "/characterPage",
    query: {
      personId: item.id
    }
  });
  window.open(routeData.href, "_blank");
};

// 跳转机构详情
const handleOrgClick = item => {
  console.log('item', item);

  window.sessionStorage.setItem("curTabName", item.organizationName);
  const route = router.resolve({
    path: "/institution",
    query: {
      id: item.organizationId
    }
  });
  window.open(route.href, "_blank");
};

// 导出
const handleExport = () => {
  if (!selectedCount.value) {
    ElMessage.warning('请选择至少一项数据！')
    return
  }
  console.log(selectedMap.value);
  const arr = Array.from(selectedMap.value);

  const jsonStr = JSON.stringify(arr, null, 2);
  const blob = new Blob([jsonStr], { type: 'application/json' });
  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.download = 'export.json';
  link.click();

  URL.revokeObjectURL(url);
};

onMounted(async () => {
  await handleGetCountryList()   // 获取国籍列表
  await handleGetInsList()
  await handleGetPersonType()
  initParam()

  // 初始化
  await fetchTableData()


})

</script>

<style lang="scss" scoped>
.countrybill-wrapper {
  width: 1600px;
  height: 968px;
  overflow: hidden;
  overflow-y: auto;

  .headere-box {
    width: 1568px;
    height: 112px;
    border-radius: 10px;
    background: rgb(255, 255, 255);
    border: 1px solid var(--bg-black-5);
    margin: 16px auto;
  }

  .header-box {
    width: 1568px;
    min-height: 112px;
    border-radius: 10px;
    background: rgb(255, 255, 255);
    border: 1px solid var(--bg-black-5);
    margin: 16px auto;
    box-sizing: border-box;
    padding: 16px 24px;

    .header-top {
      min-height: 28px;
      display: flex;
      flex-wrap: wrap;
      gap: 12px 42px;

      // transition: all ease 1s;
      .check-box {
        display: flex;
        width: 348px;
        height: 28px;
        align-items: center;
        gap: 8px;

        .check-box-left {
          width: 100px;
          color: var(--text-primary-65-color);
        }
      }
    }


    .header-footer {
      margin-top: 16px;
      display: flex;
      justify-content: space-between;

      .header-footer-left {
        display: flex;
        justify-content: space-between;
        gap: 8px;
      }
    }
  }

  .chart-main-box {
    width: 1568px;
    height: 809px;
    margin: 0 auto;
    background: rgba(255, 255, 255);
    border: 1px solid var(--bg-black-5);
    border-radius: 10px;

    .info-box {
      margin: 0 auto;
      margin-top: 16px;
      width: 1520px;
      height: 30px;
      display: flex;
      justify-content: space-between;

      .switch-box {
        width: 160px;
        height: 28px;
        border: none;
        cursor: pointer;
      }

      .num-box {
        color: var(--color-red-100);
      }
    }

    .content-box {
      margin: 0 auto;
      margin-top: 16px;
      width: 1520px;
      height: 726px;
      border: none;


      .content-header {
        margin: 16px 0;
        width: 1520px;
        height: 28px;
      }

      .content-main {
        width: 1520px;
        margin: 0 auto;
      }
    }
  }

  .data-main-box {
    width: 1568px;
    min-height: 810px;
    border-radius: 10px;
    background: var(--bg-white-100);
    margin: 0 auto;
    margin-bottom: 20px;
    overflow: hidden;

    .data-main-box-header {
      margin: 16px auto;
      width: 1520px;
      height: 30px;
      display: flex;
      justify-content: space-between;

      .switch-box {
        width: 160px;
        height: 28px;
        border: none;
        cursor: pointer;
      }

      .num-box {
        box-sizing: border-box;
        padding: 2px 0;
        color: var(--color-red-100);
      }
    }

    .data-main-box-main {
      width: 1520px;
      // height: 633px;
      min-height: 680px;
      border-radius: 10px;
      border: 1px solid var(--bg-black-5);
      margin: 0 auto;

      .data-main-box-main-header {
        height: 48px;
        background: var(--bg-black-2);
        display: flex;
        justify-content: space-between;

        .header-left {
          margin-left: 16px;
          height: 48px;
          display: flex;
          gap: 16px;
          align-items: center;

          .header-left-item2 {
            color: var(--color-primary-100);
            display: flex;
            gap: 8px;

          }

          .header-left-item3 {
            color: var(--color-orange-100);
          }

          .cancel {
            cursor: pointer;
          }
        }

        .header-right {
          margin-right: 16px;
          display: flex;
          gap: 8px;
          align-items: center;

          .header-right-item {
            height: 30px;
            padding: 5px 16px;
            border: 1px solid var(--bg-black-10);
            border-radius: 4px;
            background: var(--bg-white-100);
            cursor: pointer;
          }

          .item1 {
            display: flex;
            gap: 2px;
            justify-content: center;
            align-items: center;

            &:hover {
              background: var(--color-primary-2);
            }

            .icon {
              width: 16px;
              height: 16px;

              img {
                width: 100%;
                height: 100%;
              }
            }

            .text {
              color: var(--text-primary-65-color);
            }
          }

          .item2 {}

          .item3 {}
        }
      }

      .data-main-box-main-content {}
    }

    .data-main-box-footer {
      margin: 16px auto 0;
      height: 40px;
      width: 1520px;
      display: flex;
      align-items: center;
      justify-content: flex-end;
    }
  }
}

.date-column {
  background-color: #ecf5ff;

  .tag-box {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    width: 340px;

  }
}

.date-column .cell {
  color: #409eff !important;
  font-weight: 500;
}

.title-item {
  color: var(--text-primary-80-color);
  cursor: pointer;

  &:hover {
    color: var(--color-primary-100);
    text-decoration: underline;
  }
}

.person-item {
  color: var(--color-primary-100);
  cursor: pointer;

  &:hover {
    font-weight: bold;
    text-decoration: underline;
  }
}



:deep(.el-table__header-wrapper) {
  // background-color: #f5f7fa;
  height: 48px;

}

:deep(.el-table__header th) {
  // background-color: #f5f7fa;
  color: var(--text-primary-50-color);
  font-weight: bold;
}

/* 针对特定列 */
// :deep(.el-table__header th:first-child) {
//   background-color: #e6f7ff;
//   color: #1890ff;
// }</style>