<template>
  <home-container :customStyle="{ background: 'none' }">
    <view class="seize-statistics-container">
      <!-- 筛选区域 -->
      <view class="filter-section">
        <view class="filter-row">
          <uni-data-picker
            v-if="curUserRoles.includes('test') || curUserRoles.includes('jingli') || curUserRoles.includes('xingzheng')"
            class="filter-select" :localdata="departments" :placeholder="'请选择'" @change="handleinspectDeptIdChange"
            :clear-icon="false" />
          <text v-if="dateRange.length > 0" class="days-count">共 {{ totalDays }} 天</text>
          <!-- 时间范围选择器 -->
          <uni-datetime-picker v-model="dateRange" type="daterange" rangeSeparator="至" @change="handleDateRangeChange"
            class="date-range-picker" />
        </view>
      </view>

      <!-- 筛选区域占位 -->
      <view class="filter-placeholder"></view>

      <!-- 今日总览 -->
      <view class="overview-section">
        <view class="section-card">
          <view class="section-title">{{ dateRange.length > 0 ? '自定义' : '今日' }}总览</view>
          <view class="overview-grid">
            <view :class="{ 'active': curType === 'total', 'overview-item': true }"
              @click="handleOverviewItemClick('total')">
              <view class="overview-label">总查获数</view>
              <view class="overview-number">{{ overviewData.total }}</view>
            </view>
            <view :class="{ 'active': curType === 'policeTotal', 'overview-item': true }"
              @click="handleOverviewItemClick('policeTotal')">
              <view class="overview-label">移交公安</view>
              <view class="overview-number">{{ overviewData.policeTotal }}</view>
            </view>
            <view :class="{ 'active': curType === 'concealTotal', 'overview-item': true }"
              @click="handleOverviewItemClick('concealTotal')">
              <view class="overview-label">隐匿夹带</view>
              <view class="overview-number">{{ overviewData.concealTotal }}</view>
            </view>
          </view>
        </view>
      </view>

      <!-- 今日总览占位 -->
      <view class="overview-placeholder"></view>

      <!-- 今日明细 -->
      <view class="detail-section">
        <view class="section-card">
          <view class="section-header">
            <view class="section-title">{{ dateRange.length > 0 ? '自定义' : '今日' }}明细</view>
            <!-- <view class="detail-filter">
              <uni-data-select v-model="detailFilter" :localdata="detailOptions" placeholder="总数量"
                class="detail-select" />
            </view> -->
          </view>

          <!-- 图表区域 -->
          <view class="charts-grid">
            <!-- 违禁品类别饼图 -->
            <view class="chart-item">
              <view class="chart-title">违禁品类别</view>
              <view class="chart-container">
                <view id="forbiddenPieChart" class="echarts-chart"></view>
              </view>
            </view>

            <!-- 查获部位饼图 -->
            <view class="chart-item">
              <view class="chart-title">查获部位</view>
              <view class="chart-container">
                <view id="mailPieChart" class="echarts-chart"></view>
              </view>
            </view>

            <!-- 安检岗位饼图 -->
            <view class="chart-item">
              <view class="chart-title">安检岗位</view>
              <view class="chart-container">
                <view id="positionPieChart" class="echarts-chart"></view>
              </view>
            </view>

            <uni-data-picker :localdata="item_category_options1" :map="dataTreeOptionMap" popup-title="请选择一级违禁品类别"
              v-model="formData.categoryCodeOne" @change="onCategoryChange" v-if="showForbiddenCategory" />
            <uni-data-picker :localdata="item_category_options2" :map="dataTreeOptionMap" popup-title="请选择二级违禁品类别"
              v-model="formData.categoryCodeTwo" v-if="showForbiddenCategory" @change="onTypeChange"
              :readonly="!formData.categoryCodeOne" />

            <!-- 安检岗位嵌套环形图 -->
            <!-- <view class="chart-item">
              <view class="chart-title">查获地点</view>
              <view class="chart-container-position">
                <view id="positionRingChart" class="echarts-chart-position"></view>
              </view>
            </view> -->

            <!-- 查获时间分布折线图 -->
            <view class="chart-item full-width">
              <view class="chart-title">查获时间分布</view>
              <view class="chart-container" :style="{ height: '450rpx' }">
                <view id="timeLineChart" class="echarts-chart"></view>
              </view>
            </view>
          </view>
          <view class="ranking-header">
            <view class="section-title">查获排名</view>
            <SwitchTab :tabList="tabList" :defaultActive="defaultActive" @tabChange="handleTabChange"
              class="ranking-tab" />
          </view>
          <statistic-table :columns="rankingColumns" :data="rankingData">
            <template #column-rank="{ row, index }">
              <text>{{ index + 1 }}</text>
            </template>
            <template #column-completionRate="{ row, index }">
              <view class="progress-container">
                <u-line-progress :percentage="row.completionRate" :showText="false"
                  :activeColor="getProgressColor(row.completionRate)" height="20rpx" width="200rpx"></u-line-progress>
                <text class="progress-text">{{ row.completionRate }}</text>
              </view>
            </template>
            <template #column-scale="{ row, index }">
              <text>{{ row.scale }}%</text>
            </template>
          </statistic-table>
        </view>
      </view>

      <!-- 查获排名 -->
      <!-- <view class="ranking-section">
        <view class="section-card">

        </view>
      </view> -->
    </view>
  </home-container>
</template>

<script>
import * as echarts from 'echarts'
import { buildManagerOptions, buildBrigadeOptions } from '@/utils/common'
import HomeContainer from "@/components/HomeContainer.vue";
import SwitchTab from "./components/switch-tab.vue";
import { getTotalSome, getPost, getPosition, getRank, getTimeSpan, getCategory } from "@/api/seizeStatistics/seizeStatistics";
import { treeSelectByType } from "@/api/system/common";
import { getDeptList } from "@/api/system/dept/dept.js"

export default {
  name: 'SeizeStatistics',
  components: {
    HomeContainer,
    SwitchTab
  },
  data() {
    return {
      departments: [

      ],
      showForbiddenCategory: true, // 控制违禁品类别的显示
      dateRange: [],
      totalDays: 0,
      detailFilter: '',     // 明细筛选
      detailOptions: [
        { value: 'total', text: '总数量' },
        { value: 'forbidden', text: '移交公安' },
        { value: 'limited', text: '限带品' }
      ],
      overviewData: {      // 数据
        total: 0,
        policeTotal: 0,
        concealTotal: 0
      },
      // 图表实例
      charts: {
        forbiddenPie: null,
        mailPie: null,
        positionPie: null,
        positionRing: null,
        timeLine: null
      },
      rankingData: [],      // 查获排名数据
      curType: 'total',
      defaultActive: 1,
      // activeTab: 1,
      item_category_options1: [], // 违禁品类别选项
      item_category_options2: [], // 违禁品类别选项
      formData: {
        categoryCodeOne: '', // 违禁品类别
        categoryCodeTwo: '', // 违禁品类型
        inspectDeptId: null // 被检查科ID
      },
      dataTreeOptionMap: { text: 'label', value: 'id' }, // 级联字段映射关系树结构
      // allPositionData: [],
      positionData: [],
      forbiddenPieData: [],//违禁品类别数据
      levelType: 1,
      secondLevelType: 1,
      getType: ''
    }
  },
  computed: {
    currentUser() {
      return this.$store.state.user;
    },
    curUserRoles() {
      return this.$store.state.user && this.$store.state.user.roles;
    },
    // 表格列配置
    rankingColumns() {
      let name = this.defaultActive == 1 ? '主管' : this.defaultActive == 2 ? '班组' : this.defaultActive == 3 ? '个人' : '大队';
      return [
        { props: 'rank', title: '排名', slot: true },
        { props: 'name', title: name },
        { props: 'scale', title: '占比', slot: true },
        { props: 'total', title: '数量' },

      ]
    },
    tabList() {
      if (this.getType === null) {
        return [
          { label: '按大队', value: 4 },
          { label: '按主管', value: 1 },
          { label: '按班组', value: 2 },
          { label: '按个人', value: 3 }
        ];
      }
      if (this.getType == "BRIGADE") {
        return [
          { label: '按主管', value: 1 },
          { label: '按班组', value: 2 },
          { label: '按个人', value: 3 }
        ];
      }
      if (this.getType == "MANAGER" || this.curUserRoles.includes('kezhang')) {
        return [
          { label: '按班组', value: 2 },
          { label: '按个人', value: 3 }
        ];
      }
    }
  },
  mounted() {
    this.initData()
    this.$nextTick(() => {
      this.initCharts()
    })
  },
  methods: {
    // 处理今日总览项的点击
    handleOverviewItemClick(type) {
      this.curType = type;
      if (type === 'total') {
        this.showForbiddenCategory = true;
      } else {
        this.showForbiddenCategory = false;
      }
      this.$nextTick(() => {
        this.initCharts()
      })
    },

    // 处理部门选择变化
    async handleinspectDeptIdChange(e) {
      console.log(e, 111, this.departments)
      let depart = e.detail && e.detail.value[0];
      this.getType = this.departments.find(item => item.value == depart.value).deptType;

      if (this.getType == null) {
        this.defaultActive = 4;
      }
      if (this.getType == "BRIGADE") {
        this.defaultActive = 1;
      }
      if (this.getType == "MANAGER") {
        this.defaultActive = 2;
      }

      // 刷新总览数据
      this.getTotalData();
      // 加载排名数据
      this.loadRankingData(this.defaultActive);
      // 刷新所有图表
      await this.$nextTick();
      this.initCharts();
    },
    getParams() {
      // 如果dateRange为空，设置默认日期为今天
      let startDate, endDate;

      if (this.dateRange && this.dateRange.length === 2) {
        // 使用选择的日期范围
        startDate = this.dateRange[0];
        endDate = this.dateRange[1];
      } else {
        // 默认使用今天日期
        const today = new Date();
        const todayStr = today.toISOString().split('T')[0];
        startDate = todayStr;
        endDate = todayStr;
      }
      let obj = {}
      if (this.curType === 'policeTotal') {
        obj = { isPolice: 1 }
      }
      if (this.curType === 'concealTotal') {
        obj = { isConceal: 1 }
      }
      let dept = {};

      if (this.getType == "BRIGADE") {
        dept = { inspectBrigadeId: this.formData.inspectDeptId || this.currentUser.userInfo.deptId }
      }
      if (this.getType == "MANAGER") {
        dept = { inspectDepartmentId: this.formData.inspectDeptId }
      }
      if (this.curUserRoles.includes('kezhang')) {
        const deptId = this.currentUser.userInfo.deptId;
        dept = { inspectDepartmentId: deptId }
      }


      let params = {

        ...obj,
        startDate: startDate,
        endDate: endDate,
        ...dept
      }

      return params
    },
    //总览
    getTotalData() {
      let params = this.getParams()
      getTotalSome(params).then(res => {
        this.overviewData = {
          total: res.data.total,
          policeTotal: res.data.policeTotal,
          concealTotal: res.data.concealTotal
        }

      })
    },
    // 根据完成比例返回对应的颜色
    getProgressColor(percentage) {
      if (percentage >= 100) {
        return '#2B7BFF'; // 大于等于100%时使用蓝色
      } else if (percentage > 0 && percentage < 100) {
        return '#03AF43'; // 0-100%之间使用绿色
      } else {
        return '#E40808'; // 0%时使用红色
      }
    },
    // 初始化数据
    async initData() {
      if (this.curUserRoles.includes('kezhang')) {
        this.defaultActive = 2
      }
      // 使用data()中设置的默认今天日期，不再重置dateRange
      this.calculateDays()

      //总览数据
      this.getTotalData()
      // 加载排名数据
      this.loadRankingData()
      // 获取违禁品类别数据
      await this.getEnumOption()
    },

    // 获取违禁品类别选项
    async getEnumOption() {
      try {
        const itemCategoryRes = await treeSelectByType("ITEM_CATEGORY", 3);
        //站长先获取所有部门；
        const deptTree = await getDeptList();
        //经理和行政先获取登陆角色部门下的部门
        const deptId = this.currentUser.userInfo && this.currentUser.userInfo.deptId;
        const subDeptTree = await getDeptList({ parentId: deptId });
        // console.log(subDeptTree, "subDeptTree")
        let firstOption = this.curUserRoles.includes('test') ? [{ value: null, deptType: null, text: '全站' }] : this.curUserRoles.includes('jingli') || this.curUserRoles.includes('xingzheng') ? [{ value: deptId, deptType: 'BRIGADE', text: '本队' }] : [];
        //如果是站长，则获取所有部门的大队，如果是经理或行政，则获取登陆角色部门下的主管
        let otherOption = this.curUserRoles.includes('test') ? buildBrigadeOptions(deptTree.data || [], true) : buildManagerOptions(subDeptTree.data, true);
        console.log(otherOption, "this.departments")
        this.departments = [...firstOption, ...otherOption.map(item => ({
          ...item,
          text: this.curUserRoles.includes('test') ? item.text?.split('/')[1] : item.text,
          value: item.value.toString()
        }))];
        console.log(itemCategoryRes.data, "itemCategoryRes.data")
        // debugger
        this.all_item_category = itemCategoryRes.data || [];
        this.item_category_options1 = itemCategoryRes.data.map(item => ({
          ...item,
          children: []
        })) || [];

      } catch (err) {
        console.error('获取违禁品类别数据失败:', err);
        this.item_category_options1 = [];

      }
    },

    // 违禁品类别变化
    onCategoryChange(e) {
      // console.log(e,"e")
      if (!e.detail.value || !e.detail.value.length) {
        this.formData.categoryCodeOne = ''
        this.formData.categoryCodeTwo = ''
        this.initTimeLineChart()
        this.loadRankingData();
        return
      }
      let value = e.detail.value[0].value;
      this.formData.categoryCodeOne = value;



      this.item_category_options2 = this.all_item_category.find(item => item.id === value).children;

      this.initTimeLineChart()
      this.loadRankingData();
    },
    // 违禁品类型变化
    onTypeChange(e) {


      this.initTimeLineChart()
      this.loadRankingData();
    },

    // 处理时间范围变化
    handleDateRangeChange(e) {
      // 处理日期范围变化，包括清空操作
      if (e && Array.isArray(e) && e.length === 2) {
        // 正常选择日期范围
        this.dateRange = e
      } else {
        // 清空操作，将dateRange设置为空数组
        this.dateRange = []
      }

      // this.levelType = 1;
      this.calculateDays()
      //总览数据
      this.getTotalData()
      this.initCharts()
    },

    // 计算天数
    calculateDays() {
      if (this.dateRange && this.dateRange.length === 2) {
        const start = new Date(this.dateRange[0])
        const end = new Date(this.dateRange[1])
        const diffTime = Math.abs(end - start)
        this.totalDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)) + 1
      }
    },





    // 初始化图表
    initCharts() {
      this.initForbiddenPieChart()
      this.initMailPieChart()
      this.initPositionPieChart()
      this.initPositionRingChart()
      this.initTimeLineChart()
      this.loadRankingData();
    },

    // 违禁品类别饼图
    async initForbiddenPieChart() {
      const chartDom = document.getElementById('forbiddenPieChart')
      if (!chartDom) return

      try {
        let params = this.getParams()
        params.levelType = 1;
        this.levelType = 2;
        let response = await getCategory(params)

        // 检查数据是否为空
        if (!response.data || response.data.length === 0) {
          this.setEmptyForbiddenPieChart()
          return
        }

        let series = response.data.map(item => ({
          ...item,
          name: item.name,
          value: item.total
        })) || [];
        this.forbiddenPieData = series

        // 如果图表实例不存在，先初始化
        if (!this.charts.forbiddenPie) {
          this.charts.forbiddenPie = echarts.init(chartDom, null, {
            renderer: 'canvas'
          })
        }

        // 清除图表之前的状态，确保不会残留缺省图
        this.charts.forbiddenPie.clear();

        const option = {
          tooltip: {
            show: false,
            // trigger: 'item',
            // formatter: '{a} <br/>{b}: {c} '
          },
          series: [
            {
              name: '',
              type: 'pie',
              radius: '60%',
              data: series,
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              },
              label: {
                formatter: this.subLabel,
                overflow: 'truncate'
              }
            }
          ]
        }

        this.charts.forbiddenPie.setOption(option)
      } catch (error) {
        console.error('违禁品类别饼图初始化失败:', error)
        this.setEmptyForbiddenPieChart()
      }

      // 添加点击事件监听（兼容移动端和H5）
      this.charts.forbiddenPie.on('click', async (params) => {

        if (this.levelType == 1) {
          this.charts.forbiddenPie.setOption({
            series: [
              {
                data: this.forbiddenPieData
              }
            ]
          })
          this.levelType = 2;
          return
        }
        if (this.levelType == 2) {

          let query = this.getParams()
          query.levelType = 2;
          this.levelType = 1;

          query.categoryCode = params.data.code;

          let response = await getCategory(query)

          let series = response.data.map(item => ({
            ...item,
            name: item.name,
            value: item.total
          })) || []
          if (series.length > 0) {
            this.charts.forbiddenPie.setOption({
              series: [
                {
                  data: series
                }
              ]
            })
          }

          return
        }

        console.log('点击了饼图区块:', params)
        console.log('区块名称:', params.name)
        console.log('区块值:', params.value)
        console.log('区块数据索引:', params.dataIndex)



      })


    },
    subLabel(params) {
      let name = params.name;
      let value = params.value;
      // 如果名称超过5个字符，显示前2个字符+省略号+后2个字符
      if (name && name.length > 5) {
        return name.substring(0, 2) + '...' + name.substring(name.length - 2) + ':' + value;
      } else {
        return name + ':' + value;
      }
    },

    // 设置空违禁品类别饼图状态
    setEmptyForbiddenPieChart() {
      const chartDom = document.getElementById('forbiddenPieChart')

      if (!chartDom) return

      // 如果图表实例不存在，先初始化
      if (!this.charts.forbiddenPie) {
        this.charts.forbiddenPie = echarts.init(chartDom, null, {
          renderer: 'canvas'
        })
      }
      this.charts.forbiddenPie.clear();

      const option = {
        title: {
          text: '暂无数据',
          left: 'center',
          top: 'center',
          textStyle: {
            color: '#999',
            fontSize: 16
          }
        },
        xAxis: {
          show: false
        },
        yAxis: {
          show: false
        },
        series: []
      }

      this.charts.forbiddenPie.setOption(option)
    },



    // 查获部位饼图
    async initMailPieChart() {
      const chartDom = document.getElementById('mailPieChart')
      if (!chartDom) return

      try {
        let query = this.getParams()
        const { data } = await getPosition({
          ...query,
          levelType: 1
        })


        // 检查数据是否为空
        if (!data || data.length === 0) {
          this.setEmptyMailPieChart()
          return
        }

        // this.allPositionData = data
        let mainData = data.map(item => ({
          ...item,
          value: item.total
        })) || []
        // data.forEach(item => {
        //   if (mainData.filter(item2 => item2.name === item.checkPositionNameOne).length === 0) {
        //     mainData.push({
        //       name: item.checkPositionNameOne,
        //       value: item.total
        //     })
        //   } else {
        //     mainData.filter(item2 => item2.name === item.checkPositionNameOne)[0].value += item.total
        //   }
        // })

        console.log(mainData, "mainData")

        this.positionData = mainData

        // 如果图表实例不存在，先初始化
        if (!this.charts.mailPie) {
          this.charts.mailPie = echarts.init(chartDom)
        }

        // 清除图表之前的状态，确保不会残留缺省图
        this.charts.mailPie.clear();

        const option = {
          // tooltip: {
          //   trigger: 'item',
          //   formatter: '{a} <br/>{b}: {c} '
          // },
          series: [
            {
              name: '查获部位',
              type: 'pie',
              radius: '60%',
              data: mainData,
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              },
              label: {
                formatter: this.subLabel,
                overflow: 'truncate'
              }
            }
          ]
        }

        this.charts.mailPie.setOption(option)
      } catch (error) {
        console.error('查获部位饼图初始化失败:', error)
        this.setEmptyMailPieChart()
      }

      // 添加点击事件监听
      this.charts.mailPie.on('click', async (params) => {
        if (this.secondLevelType == 1) {
          this.charts.mailPie.setOption({
            series: [
              {
                data: this.positionData
              }
            ]
          })
          this.secondLevelType = 2;
          return
        }
        if (this.secondLevelType == 2) {

          let query = this.getParams()
          query.levelType = 2;
          this.secondLevelType = 1;

          query.positionCode = params.data.code;

          let response = await getPosition(query)

          let series = response.data.map(item => ({
            ...item,
            value: item.total
          })) || []
          if (series.length > 0) {
            this.charts.mailPie.setOption({
              series: [
                {
                  data: series
                }
              ]
            })
          }

          return
        }

        // let query = this.getParams()
        // const { data: secondData } = await getPosition({
        //   ...query,
        //   levelType: 2,
        //   positionCode: params.data.code
        // })

        // if (secondData.length === 0) {
        //   this.charts.mailPie.setOption({
        //     series: [{
        //       data: this.positionData
        //     }]
        //   })
        //   return
        // }
        // // 更新饼图数据
        // this.charts.mailPie.setOption({
        //   series: [{
        //     data: secondData.map(item => ({
        //       ...item,
        //       value: item.total
        //     }))
        //   }]
        // })
      })
    },

    // 处理部位饼图点击事件
    handleMailPieChartClick(params) {
      // 根据点击的区块执行相应操作
      switch (params.name) {
        case '国内邮件':
          console.log('处理国内邮件点击')
          break
        case '国际邮件':
          console.log('处理国际邮件点击')
          break
        case '快递包裹':
          console.log('处理快递包裹点击')
          break
        default:
          console.log('未知部位类别点击')
      }
    },

    // 设置空查获部位饼图状态
    setEmptyMailPieChart() {
      const chartDom = document.getElementById('mailPieChart')

      if (!chartDom) return

      // 如果图表实例不存在，先初始化
      if (!this.charts.mailPie) {
        this.charts.mailPie = echarts.init(chartDom)
      }
      this.charts.mailPie.clear();

      const option = {
        title: {
          text: '暂无数据',
          left: 'center',
          top: 'center',
          textStyle: {
            color: '#999',
            fontSize: 16
          }
        },
        xAxis: {
          show: false
        },
        yAxis: {
          show: false
        },
        series: []
      }

      this.charts.mailPie.setOption(option)
    },

    // 安检岗位饼图
    async initPositionPieChart() {
      const chartDom = document.getElementById('positionPieChart')
      if (!chartDom) return

      try {
        // 使用getPost接口请求数据
        const response = await getPost(this.getParams())

        // 检查数据是否为空
        if (!response.data || response.data.length === 0) {
          this.setEmptyPositionPieChart()
          return
        }

        // 如果图表实例不存在，先初始化
        if (!this.charts.positionPie) {
          this.charts.positionPie = echarts.init(chartDom)
        }

        // 清除图表之前的状态，确保不会残留缺省图
        this.charts.positionPie.clear();

        if (response.code === 200 && response.data) {
          // 转换接口返回的数据为ECharts需要的格式
          const chartData = response.data.map((el, idx) => {
            return {
              value: el.total,
              name: el.name,
            };
          });

          const option = {
            tooltip: {
              trigger: 'item',
              formatter: '{a} <br/>{b} {c}'
            },
            series: [
              {
                name: '安检岗位',
                type: 'pie',
                radius: '60%',
                data: chartData,
                emphasis: {
                  itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                  }
                },
                label: {
                  formatter: this.subLabel,
                  overflow: 'truncate'
                }
              }
            ]
          }

          this.charts.positionPie.setOption(option)
        } else {
          console.error('获取岗位数据失败:', response)
          this.setEmptyPositionPieChart()
        }
      } catch (error) {
        console.error('请求岗位数据异常:', error)
        this.setEmptyPositionPieChart()
      }
    },

    // 设置空安检岗位饼图状态
    setEmptyPositionPieChart() {
      const chartDom = document.getElementById('positionPieChart')

      if (!chartDom) return

      // 如果图表实例不存在，先初始化
      if (!this.charts.positionPie) {
        this.charts.positionPie = echarts.init(chartDom)
      }
      this.charts.positionPie.clear();

      const option = {
        title: {
          text: '暂无数据',
          left: 'center',
          top: 'center',
          textStyle: {
            color: '#999',
            fontSize: 16
          }
        },
        xAxis: {
          show: false
        },
        yAxis: {
          show: false
        },
        series: []
      }

      this.charts.positionPie.setOption(option)
    },


    // 安检岗位嵌套环形图
    async initPositionRingChart() {
      const chartDom = document.getElementById('positionRingChart')
      if (!chartDom) return

      try {
        // 使用getPosition接口请求数据
        const response = await getPosition(this.getParams())

        // 检查数据是否为空
        if (!response.data || response.data.length === 0) {
          this.setEmptyPositionRingChart()
          return
        }

        // 如果图表实例不存在，先初始化
        if (!this.charts.positionRing) {
          this.charts.positionRing = echarts.init(chartDom)
        }

        if (response.code === 200 && response.data) {
          // 按照指定的数据处理方式处理数据
          const innerData = response.data.map((el, idx) => {
            if (el.checkPositionNameTwo == '无') {
              return {
                value: el.total,
                name: el.checkPositionNameOne,
              };
            }
          }).filter(item => item !== undefined);

          const outerData = response.data.map((el, idx) => {
            if (el.checkPositionNameTwo != '无') {
              return {
                value: el.total,
                name: el.checkPositionNameTwo,
              };
            }
          }).filter(item => item !== undefined);

          const option = {
            tooltip: {
              trigger: 'item',
              formatter: '{b}: {c}'
            },
            series: [
              {
                name: '',
                type: 'pie',
                radius: ['0%', '60%'],
                data: innerData,
                label: {
                  position: 'inner',
                  formatter: '{b}\n{c}'
                }
              },
              {
                name: '',
                type: 'pie',
                radius: ['60%', '70%'],
                data: outerData,
                label: {
                  formatter: '{b}: {c} '
                }
              }
            ]
          }

          this.charts.positionRing.setOption(option)
        } else {
          console.error('获取查获地点数据失败:', response)
          this.setEmptyPositionRingChart()
        }
      } catch (error) {
        console.error('请求查获地点数据异常:', error)
        this.setEmptyPositionRingChart()
      }
    },

    // 设置空安检岗位嵌套环形图状态
    setEmptyPositionRingChart() {
      const chartDom = document.getElementById('positionRingChart')

      if (!chartDom) return

      // 如果图表实例不存在，先初始化
      if (!this.charts.positionRing) {
        this.charts.positionRing = echarts.init(chartDom)
      }
      this.charts.positionRing.clear();

      const option = {
        title: {
          text: '暂无数据',
          left: 'center',
          top: 'center',
          textStyle: {
            color: '#999',
            fontSize: 16
          }
        },
        xAxis: {
          show: false
        },
        yAxis: {
          show: false
        },
        series: []
      }

      this.charts.positionRing.setOption(option)
    },

    // 查获时间分布折线图
    async initTimeLineChart() {
      const chartDom = document.getElementById('timeLineChart')
      if (!chartDom) return

      try {
        let query = this.getParams();
        query.categoryCodeOne = this.formData.categoryCodeOne;
        query.categoryCodeTwo = this.formData.categoryCodeTwo;
        const response = await getTimeSpan(query)

        // 检查数据是否为空
        if (!response.data || response.data.length === 0) {
          this.setEmptyTimeLineChart()
          return
        }

        // 如果图表实例不存在，先初始化
        if (!this.charts.timeLine) {
          this.charts.timeLine = echarts.init(chartDom)
        }

        // 清除图表之前的状态，确保不会残留缺省图
        this.charts.timeLine.clear();

        if (response.code === 200 && response.data) {
          // 转换接口返回的数据为ECharts需要的格式
          const xAxisData = response.data.map((el, idx) => {
            return el.hourOfDay + ':00';
          });

          const seriesData = response.data.map((el, idx) => {
            return el.total;
          });
          const maxValue = Math.max(...seriesData);
          console.log(xAxisData, seriesData, 11111111111)
          const option = {
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                type: 'shadow'
              }
            },
            xAxis: {
              type: 'category',
              data: xAxisData,
              axisLabel: {
                interval: 0,
                rotate: 45
              }
            },
            yAxis: {
              type: 'value',
              splitNumber: 5, // 减少分割段数为4，增加间距
              minInterval: 1, // 最小间隔为1

            },
            series: [
              {
                data: seriesData,
                type: 'line',
                smooth: true,
                lineStyle: {
                  color: '#5470c6'
                },
                itemStyle: {
                  color: '#5470c6'
                }
              }
            ]
          }

          this.charts.timeLine.setOption(option)
        } else {
          console.error('获取时间分布数据失败:', response)
          this.setEmptyTimeLineChart()
        }
      } catch (error) {
        console.error('请求时间分布数据异常:', error)
        this.setEmptyTimeLineChart()
      }
    },

    // 设置空查获时间分布折线图状态
    setEmptyTimeLineChart() {
      const chartDom = document.getElementById('timeLineChart')

      if (!chartDom) return

      // 如果图表实例不存在，先初始化
      if (!this.charts.timeLine) {
        this.charts.timeLine = echarts.init(chartDom)
      }
      this.charts.timeLine.clear();

      const option = {
        title: {
          text: '暂无数据',
          left: 'center',
          top: 'center',
          textStyle: {
            color: '#999',
            fontSize: 16
          }
        },
        xAxis: {
          show: false
        },
        yAxis: {
          show: false
        },
        series: []
      }

      this.charts.timeLine.setOption(option)
    },

    // 窗口大小变化时重绘图表
    onResize() {
      Object.values(this.charts).forEach(chart => {
        if (chart) {
          chart.resize()
        }
      })
    },

    // 处理tab切换
    handleTabChange(e) {
      console.log('Tab切换:', e.value)
      // this.activeTab = e.value
      this.defaultActive = e.value
      // 根据切换的tab重新加载数据
      this.loadRankingData()
    },

    // 加载排名数据
    loadRankingData(type) {
      console.log('加载排名数据，类型:', type)
      let query = this.getParams();
      query.categoryCodeOne = this.formData.categoryCodeOne;
      query.categoryCodeTwo = this.formData.categoryCodeTwo;
      query.type = type || this.defaultActive;
      console.log(query, "query")

      getRank(query).then(res => {
        const newList = res.data.map(el => {
          return {
            ...el,

          };
        });

        this.rankingData = newList
      })
      // 这里可以根据不同的统计类型加载不同的排名数据
      // 暂时使用模拟数据
    }
  },

  beforeDestroy() {
    // 销毁图表实例
    Object.values(this.charts).forEach(chart => {
      if (chart) {
        chart.dispose()
      }
    })
  }

}
</script>

<style lang="scss" scoped>
.seize-statistics-container {
  padding: 20rpx;
  flex-direction: row;
  position: relative;

  .filter-section {
    position: fixed;
    top: 80rpx;
    left: 0;
    right: 0;
    z-index: 10;
    background: #fff;
    padding: 16rpx 20rpx;
    margin-bottom: 24rpx;

    .filter-row {
      display: flex;
      align-items: center;
      //gap: 24rpx;

      .filter-select {
        max-width: 200rpx;
        position: relative;
        top: 4rpx;

        ::v-deep .uni-stat-box {
          background: transparent !important;
          color: black !important;

          .border-default {
            border: none !important;
          }
        }

        ::v-deep .input-value-border {
          border: none !important;

        }

        ::v-deep .placeholder {
          color: black !important;
        }

        ::v-deep .uni-select__input-text {
          color: black !important;
        }

        //::v-deep .uniui-clear {
        //   display: none !important;
        //  }

        ::v-deep .uni-select__selector-item {
          color: #333 !important;
        }

        ::v-deep .text-color {
          color: black !important;
        }

        ::v-deep .input-arrow {
          border-left: 4rpx solid black !important;
          border-bottom: 4rpx solid black !important;
        }
      }

      .date-range-picker {
        ::v-deep .icon-calendar {
          display: none !important;
        }

        ::v-deep .uni-date-range {
          font-size: 16rpx !important;
          background: transparent !important;
          color: black !important;
        }

        ::v-deep .uni-date-x {
          height: 25rpx !important;
          line-height: 25rpx !important;

          .range-separator {
            font-size: 26rpx !important;
            padding: 0 !important
          }

          .uni-date__x-input {
            height: 25rpx !important;
            line-height: 25rpx !important;
          }
        }


        ::v-deep .uni-date-x--border {
          border: none !important;
        }
      }

      .days-count {
        font-size: 26rpx;
        color: black;
        white-space: nowrap;
      }
    }
  }

  .filter-placeholder {
    height: 120rpx;
    /* 与筛选区域高度一致 */
    margin-bottom: 24rpx;
  }

  .overview-placeholder {
    height: 160rpx;
    /* 与今日总览区域高度一致 */
    margin-bottom: 44rpx;
  }

  .overview-section {
    position: fixed;
    top: 170rpx;
    left: 0;
    right: 0;
    z-index: 9;
    background: #fff;
    padding: 16rpx 20rpx;
    margin-bottom: 24rpx;

    .section-card {
      background: #ffffff;
      border-radius: 16rpx;
      padding: 32rpx;
      box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);

      .section-title {

        font-size: 32rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 24rpx;
      }

      .overview-grid {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 24rpx;

        .active {
          background: #f8f9fa !important;
        }

        .overview-item {
          text-align: center;
          padding: 24rpx;
          // border-right: 1rpx solid #e5e5e5;
          // background: #f8f9fa;
          border-radius: 12rpx;
          transition: all 0.3s ease;
          cursor: pointer;

          // &:active {
          //   background: #e8eaed;
          // }

          .overview-number {
            font-size: 35rpx;
            font-weight: 600;
            // color: #1890ff;

          }

          .overview-label {
            margin-bottom: 8rpx;
            font-size: 24rpx;
            color: #666;
          }
        }

        .overview-item:not(:last-child) {
          position: relative;

          &::after {
            content: '';
            position: absolute;
            left: 106%;
            top: 20%;
            bottom: 20%;
            width: 1rpx;
            background-color: #e5e5e5;
          }
        }
      }
    }
  }

  .detail-section {
    .section-card {
      background: #ffffff;
      border-radius: 16rpx;
      padding: 32rpx;
      box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);

      .section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 32rpx;

        .section-title {
          font-size: 32rpx;
          font-weight: bold;
          color: #333;
        }

        .detail-filter {
          width: 200rpx;

          .detail-select {
            width: 100%;
          }
        }
      }

      .charts-grid {
        display: grid;
        grid-template-columns: 1fr;
        gap: 32rpx;

        .chart-item {
          &.full-width {
            grid-column: 1 / -1;
          }

          .chart-title {
            font-size: 22rpx;
            font-weight: 500;
            color: #fff;
            margin-bottom: 16rpx;
            height: 50rpx;
            padding-left: 10rpx;
            line-height: 50rpx;
            border-radius: 8rpx;
            background: linear-gradient(to right, #4873E3, #fff);
          }

          .chart-container {
            height: 300rpx;



            padding: 16rpx 0;

            .echarts-chart {
              width: 100%;
              height: 100%;
            }
          }

          .chart-container-position {
            height: 450rpx;



            padding: 16rpx;

            .echarts-chart-position {
              width: 100%;
              height: 100%;
            }
          }
        }
      }

      .ranking-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 24rpx;

        .section-title {
          min-width: 150rpx;
          font-size: 32rpx;
          font-weight: bold;
          color: #333;
          margin: 0;
        }

        .ranking-tab {
          flex-shrink: 0;
        }
      }

      .progress-container {
        display: flex;
        align-items: center;
        gap: 16rpx;

        .progress-text {
          font-size: 24rpx;
          color: #4873E3;
          font-weight: 500;
          min-width: 60rpx;
        }
      }
    }
  }


}
</style>