<template>
  <view class="risk-hazard mobile-section">
    <!-- 风险隐患标题 -->
    <view class="section-title">
      <text class="title-text">风险隐患</text>
    </view>

    <!-- 九个面板布局，使用CSS Grid实现自动补位 -->
    <view class="nine-panel-layout">
      <!-- 第一个：查获违禁品类别 -->
      <view class="panel-item">
        <view class="panel-header">
          <text class="header-text">查获违禁品类别</text>
        </view>

        <!-- 描述卡片 -->
        <view class="describe-card">
          <view class="describe-content">
            {{ categoryStatsDescription }}
          </view>
        </view>

        <!-- 饼图 -->
        <view class="chart-container">
          <view ref="captureRankChartRef" class="echarts-chart"></view>
        </view>
      </view>

      <!-- 第二个：问题发现统计 -->
      <view class="panel-item">
        <view class="panel-header">
          <text class="header-text">问题发现统计</text>
        </view>

        <!-- 描述卡片 -->
        <view class="describe-card">
          <view class="describe-content">
            {{ seizureTimeTrendDescription }}
          </view>
        </view>

        <!-- 折线图 -->
        <view class="chart-container">
          <view ref="problemDiscoveryChartRef" class="echarts-chart"></view>
        </view>
      </view>

      <!-- 第三个：隐匿物品查获部位 -->
      <view class="panel-item">
        <view class="panel-header">
          <text class="header-text">隐匿物品查获部位</text>
        </view>

        <!-- 描述卡片 -->
        <view class="describe-card">
          <view class="describe-content">
            {{ concealmentPositionStatsDescription }}
          </view>
        </view>

        <!-- 饼图 -->
        <view class="chart-container">
          <view ref="problemRectificationChartRef" class="echarts-chart"></view>
        </view>
      </view>

      <!-- 第四个：查获排名表格 -->
      <view class="panel-item" v-if="!isUserType">
        <view class="panel-header">
          <text class="header-text">查获排名</text>
        </view>

        <!-- 描述卡片 -->
        <view class="describe-card">
          <view class="describe-content">
            {{ departmentRankingDescription }}
          </view>
        </view>

        <!-- 表格 -->

        <StatisticTable :columns="captureRankColumns" :data="captureRankData" />

      </view>

      <!-- 第五个：查获岗位分布 -->
      <view class="panel-item" v-show="!isUserType">
        <view class="panel-header">
          <text class="header-text">查获岗位分布</text>
        </view>

        <!-- 描述卡片 -->
        <view class="describe-card">
          <view class="describe-content">
            {{ postCategoryStatsDescription }}
          </view>
        </view>

        <!-- 饼图 -->
        <view class="chart-container">
          <view ref="rectificationStatsChartRef" class="echarts-chart"></view>
        </view>
      </view>

      <!-- 第六个：查获通道TOP5 -->
      <view class="panel-item" v-show="!isUserType">
        <view class="panel-header">
          <text class="header-text">查获通道TOP5</text>
        </view>

        <!-- 描述卡片 -->
        <view class="describe-card">
          <view class="describe-content">
            {{ channelRankingStatsDescription }}
          </view>
        </view>

        <!-- 表格 -->

        <StatisticTable :columns="captureChannelColumns" :data="captureChannelData" />

      </view>

      <!-- 第七个：移交公安数据 -->
      <view class="panel-item">
        <view class="panel-header">
          <text class="header-text">移交公安数据</text>
        </view>

        <!-- 描述卡片 -->
        <view class="describe-card">
          <view class="describe-content">
            {{ policeTransferStats || '移交公安的违禁品数量共X件，主要集中于XX。' }}
          </view>
        </view>

        <!-- 表格 -->

        <StatisticTable :columns="policeTransferColumns" :data="policeTransferData" />

      </view>

      <!-- 第八个：X光机漏检数据 -->
      <view class="panel-item" v-show="!isUserType">
        <view class="panel-header">
          <text class="header-text">X光机漏检数据</text>
        </view>

        <!-- 描述卡片 -->
        <view class="describe-card">
          <view class="describe-content">
            {{ xrayMissStats || 'X光机漏检事件主要集中于以下开机员：张三、李四、王五，可针对性开展判图技能强化培训。' }}
          </view>
        </view>

        <!-- 表格 -->

        <StatisticTable :columns="xrayMissColumns" :data="xrayMissData" />

      </view>

      <!-- 第九个：可能异常查获数据 -->
      <view class="panel-item" v-show="!isTeamsType && !isUserType && !isDepartmentType">
        <view class="panel-header">
          <text class="header-text">可能异常查获数据</text>
        </view>

        <!-- 描述卡片 -->
        <view class="describe-card" v-if="abnormalCaptureStats">
          <view class="describe-content">
            {{ abnormalCaptureStats || '安检一大队、安检二大队、安检三大队查获违禁品数量显著高于整体水平，旅检四科、旅检五科查获违禁品数量显著低于整体水平。' }}
          </view>
        </view>

        <!-- 表格 -->

        <StatisticTable :columns="abnormalCaptureColumns" :data="abnormalCaptureData" />

      </view>
    </view>
  </view>
</template>

<script>
import * as echarts from 'echarts'
import StatisticTable from '@/components/statistic-table/statistic-table.vue'
import {
  getCategoryStats,
  getSeizureTimeTrend,
  getConcealmentPositionStats,
  getDepartmentRanking,
  getPostCategoryStats,
  getChannelRankingStats,
  getPoliceData,
  getPoliceDataStats,
  getXrayMissCheck,
  getXrayMissCheckStats,
  getAbnormalSeizureData,
  getAbnormalSeizureStats
} from '@/api/qualityControlAnalysisReport/qualityControlAnalysisReport'

export default {
  name: 'RiskHazard',
  components: {
    StatisticTable
  },
  props: {
    queryForm: {
      type: Object,
      default: () => ({
        dateRangeQueryType: '',
        year: '',
        quarter: '',
        month: ''
      })
    }

  },
  data() {
    return {
      // 六个API接口的数据
      categoryStatsData: [],
      seizureTimeTrendData: [],
      concealmentPositionStatsData: [],
      departmentRankingData: [],
      postCategoryStatsData: [],
      channelRankingStatsData: [],

      // 新增三个API接口的数据
      policeTransferData: [],
      xrayMissData: [],
      abnormalCaptureData: [],

      // 新增三个统计API接口的数据
      policeTransferStats: '',
      xrayMissStats: '',
      abnormalCaptureStats: '',

      // 表格数据
      captureRankData: [],
      captureChannelData: [],

      // 图表实例
      captureRankChart: null,
      problemDiscoveryChart: null,
      problemRectificationChart: null,
      rectificationStatsChart: null,

      loading: false
    }
  },

  computed: {
    // 查获排名表格列配置
    captureRankColumns() {

      const deptLabel = this.isStationType ? '大队' : this.isBrigadeType ? '主管' : this.isDepartmentType ? '班组' : this.isTeamsType ? '姓名' : '';

      return [
        { props: 'rank', title: '排名' },
        { props: 'department', title: deptLabel },
        { props: 'percentage', title: '占比' },
        { props: 'count', title: '数量' }
      ]
    },

    // 查获通道表格列配置
    captureChannelColumns() {
      return [
        { props: 'channel', title: '查获通道' },
        { props: 'count', title: '查获数量' },
        { props: 'area', title: '所在区域' }
      ]
    },

    // 移交公安数据表格列配置
    policeTransferColumns() {
      return [
        { props: 'departmentName', title: '主管' },
        { props: 'teamName', title: '班组' },
        { props: 'userName', title: '姓名' },
        { props: 'itemName', title: '查获物品' },
        { props: 'quantity', title: '查获数量' },
        { props: 'positionName', title: '查获部位' },
        { props: 'seizureTime', title: '查获时间' },
        { props: 'channelName', title: '查获通道' }
      ]
    },

    // X光机漏检数据表格列配置
    xrayMissColumns() {
      return [
        { props: 'departmentName', title: '主管' },
        { props: 'teamName', title: '班组' },
        { props: 'userName', title: '姓名' },
        { props: 'missItemName', title: '漏检物品' },
        { props: 'missQuantity', title: '漏检数量' },
        { props: 'missPosition', title: '漏检部位' },
        { props: 'channelName', title: '漏检通道' }
      ]
    },

    // 可能异常查获数据表格列配置
    abnormalCaptureColumns() {
      return [
        { props: 'departmentName', title: '主管' },
        { props: 'teamName', title: '班组' },
        { props: 'userName', title: '姓名' },
        { props: 'seizureQuantity', title: '查获数量' }
      ]
    },
    isBrigadeType() {
      const roles = this.$store.state?.user?.roles || []
      return roles.includes('jingli') || roles.includes('xingzheng')
    },
    // 计算属性：检查是否为STATION类型
    isStationType() {
      const roles = this.$store.state?.user?.roles || []

      return roles.includes('zhijianke') || roles.includes('test')
    },

    // 计算属性：检查是否为DEPARTMENT类型
    isDepartmentType() {
      const roles = this.$store.state?.user?.roles || []
      return roles.includes('kezhang')
    },

    // 计算属性：检查是否为TEAMS类型
    isTeamsType() {
      const roles = this.$store.state?.user?.roles || []
      // 如果是班组长且选择了班组视图，则视为班组类型
      if (roles.includes('banzuzhang') && this.queryForm.scopedType === 'TEAMS') {
        return true
      }
      return roles.includes('banzuzhang')
    },

    // 计算属性：检查是否为USER类型
    isUserType() {
      const roles = this.$store.state?.user?.roles || []
      // 如果是班组长且选择了个人视图，则视为用户类型
      if (roles.includes('banzuzhang') && this.queryForm.scopedType === 'USER') {
        return true
      }
      return roles.includes('SecurityCheck')
    },

    // 计算属性：动态生成查获违禁品类别描述
    categoryStatsDescription() {
      if (!this.categoryStatsData || !Array.isArray(this.categoryStatsData)) {
        return '查获物品以[占比最高物品类型]为主，占比达[X]%，其次为[第二高占比物品类型]（[X]%）、[第三高占比物品类型]（[X]%），需重点强化对应物品的安检识别与管控力度。'
      }

      const categoryData = this.categoryStatsData

      // 1. 按数量排序，获取前三名
      const sortedData = [...categoryData].sort((a, b) => (b.quantity || 0) - (a.quantity || 0))

      // 2. 计算总数量
      const totalCount = sortedData.reduce((sum, item) => sum + (item.quantity || 0), 0)

      // 3. 获取前三名数据
      const top1 = sortedData[0] || { categoryNameOne: '未知类型', quantity: 0 }
      const top2 = sortedData[1] || { categoryNameOne: '未知类型', quantity: 0 }
      const top3 = sortedData[2] || { categoryNameOne: '未知类型', quantity: 0 }

      // 4. 计算百分比
      const top1Percentage = totalCount > 0 ? ((top1.quantity / totalCount) * 100).toFixed(2) : '0.00'
      const top2Percentage = totalCount > 0 ? ((top2.quantity / totalCount) * 100).toFixed(2) : '0.00'
      const top3Percentage = totalCount > 0 ? ((top3.quantity / totalCount) * 100).toFixed(2) : '0.00'

      // 5. 生成描述文字
      return `查获物品以${top1.categoryNameOne || '未知类型'}为主，占比达${top1Percentage}%，其次为${top2.categoryNameOne || '未知类型'}（${top2Percentage}%）、${top3.categoryNameOne || '未知类型'}（${top3Percentage}%），需重点强化对应物品的安检识别与管控力度。`
    },

    // 计算属性：动态生成查获时间趋势描述
    seizureTimeTrendDescription() {
      if (!this.seizureTimeTrendData || !Array.isArray(this.seizureTimeTrendData)) {
        return '高峰时段：XX:XX、XX:XX左右（平均查获量达XX件），需强化对应时段的安检力度。低峰时段：XX:XX、XX:XX后（平均查获量XX件）'
      }

      const trendData = this.seizureTimeTrendData

      // 1. 按查获量排序，找出最高和最低的两个时段
      const sortedData = [...trendData].sort((a, b) => (b.total || 0) - (a.total || 0))

      // 2. 获取最高的两个时段
      const peakHours = sortedData.slice(0, 2).map(item => item.hourOfDay || '').filter(Boolean)

      // 3. 获取最低的两个时段
      const lowHours = sortedData.slice(-2).map(item => item.hourOfDay || '').filter(Boolean)

      // 4. 计算高峰时段平均查获量
      const peakData = trendData.filter(item => peakHours.some(hour => item.hourOfDay?.includes(hour)))
      const peakAvg = peakData.length > 0
        ? Math.round(peakData.reduce((sum, item) => sum + (item.total || 0), 0) / peakData.length)
        : 0

      // 5. 计算低峰时段平均查获量
      const lowData = trendData.filter(item => lowHours.some(hour => item.hourOfDay?.includes(hour)))
      const lowAvg = lowData.length > 0
        ? Math.round(lowData.reduce((sum, item) => sum + (item.total || 0), 0) / lowData.length)
        : 0

      // 6. 生成描述文字
      return `高峰时段：${peakHours.join('、')}左右（平均查获量达${peakAvg}件），需强化对应时段的安检力度。低峰时段：${lowHours.join('、')}后（平均查获量${lowAvg}件）`
    },

    // 计算属性：动态生成隐匿物品查获部位描述
    concealmentPositionStatsDescription() {
      if (!this.concealmentPositionStatsData || !Array.isArray(this.concealmentPositionStatsData)) {
        return '违禁品主要藏匿于"XX"，是安检搜检的重点部位。'
      }

      const positionData = this.concealmentPositionStatsData

      // 1. 按查获量排序，找出查获量最高的部位
      const sortedData = [...positionData].sort((a, b) => (b.count || 0) - (a.count || 0))

      // 2. 获取查获量最高的部位
      const topPosition = sortedData[0] || { positionName: 'XX', count: 0 }

      // 3. 生成描述文字
      return `违禁品主要藏匿于"${topPosition.positionName || 'XX'}"，是安检搜检的重点部位。`
    },

    // 计算属性：动态生成主管查获排名描述
    departmentRankingDescription() {
      if (!this.departmentRankingData || !Array.isArray(this.departmentRankingData)) {
        return 'XXXX是违禁品查获的主力主管，查获违禁物品数量为XX，占比XX%。'
      }

      const rankingData = this.departmentRankingData

      // 1. 按查获量排序，找出查获量最高的主管
      const sortedData = [...rankingData].sort((a, b) => (b.seizureCount || 0) - (a.seizureCount || 0))

      // 2. 获取查获量最高的主管
      const topDepartment = sortedData[0] || { brigadeName: 'XXXX', seizureCount: 234 }

      const str = this.isStationType ? '大队' : this.isBrigadeType ? '主管' : this.isDepartmentType ? '班组' : this.isTeamsType ? '成员' : '';

      // 5. 生成描述文字
      return `${topDepartment.brigadeName || 'XXXX'}是违禁品查获的主力${str}，查获违禁物品数量为${topDepartment.seizureCount || 'XX'}，占比${topDepartment.currentRatio}%。`
    },

    // 计算属性：动态生成查获岗位分布描述
    postCategoryStatsDescription() {
      if (!this.postCategoryStatsData || !Array.isArray(this.postCategoryStatsData)) {
        return '"XX"的查获数量最多，为XX件，占比XX%。'
      }

      const postData = this.postCategoryStatsData

      // 1. 按查获量排序，找出查获量最高的岗位
      const sortedData = [...postData].sort((a, b) => (b.quantity || 0) - (a.quantity || 0))

      // 2. 获取查获量最高的岗位
      const topPost = sortedData[0] || { postName: 'XX', quantity: 124 }

      // 3. 计算总查获量
      const totalCount = postData.reduce((sum, item) => sum + (item.quantity || 0), 0)

      // 4. 计算占比
      const percentage = totalCount > 0 ? ((topPost.quantity / totalCount) * 100).toFixed(0) : '45'

      // 5. 生成描述文字
      return `"${topPost.postName || 'XX'}"的查获数量最多，为${topPost.quantity || 124}件，占比${percentage}%。`
    },

    // 计算属性：动态生成查获通道TOP5描述
    channelRankingStatsDescription() {
      if (!this.channelRankingStatsData || !Array.isArray(this.channelRankingStatsData)) {
        return '违禁物品查获主要集中于XXXX，查获数量为XX，占比XX%。'
      }

      const channelData = this.channelRankingStatsData

      // 1. 按查获量排序，找出查获量最高的通道
      const sortedData = [...channelData].sort((a, b) => (b.seizureQuantity || 0) - (a.seizureQuantity || 0))

      // 2. 获取查获量最高的通道
      const topChannel = sortedData[0] || { channelName: 'XXXX', seizureQuantity: 123 }

      // 3. 计算总查获量
      const totalCount = channelData.reduce((sum, item) => sum + (item.seizureQuantity || 0), 0)

      // 4. 计算占比
      const percentage = totalCount > 0 ? ((topChannel.seizureQuantity / totalCount) * 100).toFixed(0) : '23'

      // 5. 生成描述文字
      return `违禁物品查获主要集中于${topChannel.channelName || 'XXXX'}，查获数量为${topChannel.seizureQuantity || 'XX'}，占比${percentage}%。`
    }
  },

  mounted() {
    this.loadData()
    this.$nextTick(() => {
      this.initCharts()
    })
  },

  beforeDestroy() {
    this.disposeCharts()
  },

  watch: {
    queryForm: {
      handler() {
        this.loadData()
      },
      deep: true
    },
    selectedDeptObject: {
      handler() {
        this.loadData()
      },
      deep: true
    }
  },

  methods: {
    // 初始化图表
    initCharts() {
      // 查获违禁品类别饼图
      if (this.$refs.captureRankChartRef) {
        this.initCaptureRankChart()
      }

      // 问题发现统计折线图
      if (this.$refs.problemDiscoveryChartRef) {
        this.initProblemDiscoveryChart()
      }

      // 隐匿物品查获部位饼图
      if (this.$refs.problemRectificationChartRef) {
        this.initProblemRectificationChart()
      }

      // 查获岗位分布饼图
      if (this.$refs.rectificationStatsChartRef) {
        this.initRectificationStatsChart()
      }
    },

    // 初始化查获违禁品类别饼图
    initCaptureRankChart() {
      const options = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 10,
          top: 'center',
          show: false
        },
        series: [
          {
            name: '查获违禁品类别',
            type: 'pie',
            radius: ['0%', '45%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 12,
                fontWeight: 'bold'
              }
            },
            label: {
              show: true,
              formatter: '{b}\n{c} ({d}%)',
              fontSize: 12,
              fontWeight: 'normal'
            },
            labelLine: {
              show: true,
              length: 10,
              length2: 20
            },
            data: []
          }
        ]
      }

      this.captureRankChart = this.createEChartsInstance(this.$refs.captureRankChartRef, options)
    },

    // 初始化问题发现统计折线图
    initProblemDiscoveryChart() {
      const options = {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: []
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: []
        },
        yAxis: {
          type: 'value'
        },
        series: []
      }

      this.problemDiscoveryChart = this.createEChartsInstance(this.$refs.problemDiscoveryChartRef, options)
    },

    // 初始化隐匿物品查获部位饼图
    initProblemRectificationChart() {
      const options = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c}件'
        },
        legend: {
          orient: 'vertical',
          left: 10,
          top: 'center',
          show: false
        },
        series: [
          {
            name: '隐匿物品查获部位',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 12,
                fontWeight: 'bold'
              }
            },
            label: {
              show: true,
              formatter: '{b}\n{c}件',
              fontSize: 12,
              fontWeight: 'normal'
            },
            labelLine: {
              show: true,
              length: 10,
              length2: 20
            },
            data: []
          }
        ]
      }

      this.problemRectificationChart = this.createEChartsInstance(this.$refs.problemRectificationChartRef, options)
    },

    // 初始化查获岗位分布饼图
    initRectificationStatsChart() {
      const options = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          top: 'center',
          show: false
        },
        series: [
          {
            name: '查获岗位分布',
            type: 'pie',
            radius: ['0%', '50%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 12,
                fontWeight: 'bold'
              }
            },
            label: {
              show: true,
              formatter: '{b}\n{c} ({d}%)',
              fontSize: 12,
              fontWeight: 'normal'
            },
            labelLine: {
              show: true,
              length: 10,
              length2: 20
            },
            data: []
          }
        ]
      }

      this.rectificationStatsChart = this.createEChartsInstance(this.$refs.rectificationStatsChartRef, options)
    },

    // 创建ECharts实例（适配uni-app环境）
    createEChartsInstance(chartRef, options) {
      if (!chartRef) return null

      // 获取DOM元素
      const chartDom = chartRef.$el || chartRef
      if (!chartDom) return null

      // 创建ECharts实例
      const chartInstance = echarts.init(chartDom)

      // 设置初始选项
      if (options) {
        chartInstance.setOption(options)
      }

      return chartInstance
    },

    // 销毁图表
    disposeCharts() {
      if (this.captureRankChart) {
        this.captureRankChart.dispose()
        this.captureRankChart = null
      }
      if (this.problemDiscoveryChart) {
        this.problemDiscoveryChart.dispose()
        this.problemDiscoveryChart = null
      }
      if (this.problemRectificationChart) {
        this.problemRectificationChart.dispose()
        this.problemRectificationChart = null
      }
      if (this.rectificationStatsChart) {
        this.rectificationStatsChart.dispose()
        this.rectificationStatsChart = null
      }
    },

    // 加载数据
    async loadData() {
      if (this.loading) return

      this.loading = true
      try {
        // 处理查询参数
        const processedParams = this.processQueryParams(this.queryForm)

        // 按顺序调用九个API接口
        await this.fetchRiskHazardData(processedParams)

      } catch (error) {
        console.error('加载风险隐患数据失败:', error)

      } finally {
        this.loading = false
      }
    },

    // 处理query参数
    processQueryParams(queryParams) {
      const processedParams = { ...queryParams }
      if (processedParams.dateRangeQueryType === 'YEAR') {
        processedParams.yearOnYear = true
        delete processedParams.chainRatio
      } else {
        processedParams.chainRatio = true
        processedParams.yearOnYear = true
      }

      const { scopedType = "", scopedId } = processedParams ? processedParams : { scopedType: "", scopedId: "" }

      let otherParams = {
        ...(scopedType == 'BRIGADE' ? { brigadeId: scopedId } : {}),
        ...(scopedType == 'MANAGER' ? { departmentId: scopedId } : {}),
        ...(scopedType == 'TEAMS' ? { teamId: scopedId } : {}),
        ...(scopedType == 'USER' ? { userId: scopedId } : {})
      }

      if (scopedType != 'TEAMS') {
        delete otherParams.teamId;
      }
      if (scopedType != 'USER') {
        delete otherParams.userId;
      }
      delete processedParams.scopedType;
      delete processedParams.scopedId;

      return { ...processedParams, ...otherParams }
    },

    // 调用API获取风险隐患数据
    async fetchRiskHazardData(processedParams) {
      try {
        // 1. 查获违禁品类别统计
        const categoryStatsResponse = await getCategoryStats(processedParams)
        if (categoryStatsResponse.code === 200) {
          this.categoryStatsData = categoryStatsResponse.data?.categoryStats || []
          this.updateCaptureRankChart(this.categoryStatsData)
        }

        // 2. 查获时间趋势
        const seizureTimeTrendResponse = await getSeizureTimeTrend(processedParams)
        if (seizureTimeTrendResponse.code === 200) {
          this.seizureTimeTrendData = seizureTimeTrendResponse.data || []
          this.updateProblemDiscoveryChart(this.seizureTimeTrendData)
        }

        // 3. 隐匿物品查获部位统计
        const concealmentPositionStatsResponse = await getConcealmentPositionStats(processedParams)
        if (concealmentPositionStatsResponse.code === 200) {
          this.concealmentPositionStatsData = concealmentPositionStatsResponse?.data?.positionStats || []
          this.updateProblemRectificationChart(this.concealmentPositionStatsData)
        }

        // 4. 查获排名
        const departmentRankingResponse = await getDepartmentRanking(processedParams)
        if (departmentRankingResponse.code === 200) {
          this.departmentRankingData = departmentRankingResponse.data || []
          this.captureRankData = this.formatCaptureRankData(this.departmentRankingData)
        }

        // 5. 查获岗位分布
        const postCategoryStatsResponse = await getPostCategoryStats(processedParams)
        if (postCategoryStatsResponse.code === 200) {
          this.postCategoryStatsData = postCategoryStatsResponse.data?.postStats || []
          this.updateRectificationStatsChart(this.postCategoryStatsData)
        }

        // 6. 查获通道TOP5
        const channelRankingStatsResponse = await getChannelRankingStats(processedParams)
        if (channelRankingStatsResponse.code === 200) {

          this.channelRankingStatsData = channelRankingStatsResponse?.data?.channelRankings || []
          this.captureChannelData = this.formatCaptureChannelData(this.channelRankingStatsData)
        }

        // 7. 移交公安数据
        const policeDataResponse = await getPoliceData(processedParams)

        if (policeDataResponse.code === 200) {
          this.policeTransferData = policeDataResponse.data || []
        }

        // 8. X光机漏检数据
        const xrayMissCheckResponse = await getXrayMissCheck(processedParams)

        if (xrayMissCheckResponse.code === 200) {
          this.xrayMissData = xrayMissCheckResponse.data || []
        }

        // 9. 可能异常查获数据
        const abnormalSeizureDataResponse = await getAbnormalSeizureData(processedParams)
        if (abnormalSeizureDataResponse.code === 200) {
          this.abnormalCaptureData = abnormalSeizureDataResponse.data || []
        }

        // 获取统计描述数据
        await this.fetchStatsDescriptions(processedParams)

      } catch (error) {
        console.error('获取风险隐患数据失败:', error)
        throw error
      }
    },

    // 获取统计描述数据
    async fetchStatsDescriptions(processedParams) {
      try {
        // 移交公安统计
        const policeDataStatsResponse = await getPoliceDataStats(processedParams)

        if (policeDataStatsResponse.code === 200) {

          this.policeTransferStats = this.generatePoliceTransferStats(policeDataStatsResponse.data || {})
        }

        // X光机漏检统计
        const xrayMissCheckStatsResponse = await getXrayMissCheckStats(processedParams)

        if (xrayMissCheckStatsResponse.code === 200) {
          let userName = xrayMissCheckStatsResponse?.data?.map(item => item.xrayOperatorName).join('、') || ''
          this.xrayMissStats = `X光机漏检事件主要集中于以下开机员：${userName}，可针对性开展判图技能强化培训。`
        }

        // 可能异常查获统计
        const abnormalSeizureStatsResponse = await getAbnormalSeizureStats(processedParams)
        if (abnormalSeizureStatsResponse.code === 200) {
          this.abnormalCaptureStats = this.generateAbnormalCaptureStats(abnormalSeizureStatsResponse.data || {})
        }

      } catch (error) {
        console.error('获取统计描述数据失败:', error)
      }
    },

    // 格式化查获排名数据
    formatCaptureRankData(data) {
      if (!Array.isArray(data)) {
        return [

        ]
      }

      return data.map((item, index) => ({
        rank: index + 1,
        department: item.brigadeName || `部门${index + 1}`,
        percentage: `${item.currentRatio || 0}%`,
        count: item.seizureCount || 0
      }))
    },

    // 格式化查获通道数据
    formatCaptureChannelData(data) {

      if (!Array.isArray(data)) {
        return [

        ]
      }

      return data.slice(0, 5).map(item => ({
        channel: item.channelName || '未知通道',
        count: item.seizureQuantity || 0,
        area: item.regionalName || '未知区域'
      }))
    },

    // 生成移交公安统计描述
    generatePoliceTransferStats(data) {
      const { totalQuantity, brigadeRankList } = data;
      const topDepartment = brigadeRankList.map(item => item.brigadeName).join('、')
      return `移交公安的违禁品数量共${totalQuantity}件，主要集中于${topDepartment}。`
    },



    // 生成可能异常查获统计描述
    generateAbnormalCaptureStats(data) {
      const { higList, lowList } = data;
      let first = !!higList && higList.map((item) => item.departmentName).length > 0 ? `${higList.map((item) => item.departmentName).join("、")}查获违禁品数量显著高于整体水平` : '';
      let second = !!lowList && lowList.map((item) => item.departmentName).length > 0 ? `${lowList.map((item) => item.departmentName).join("、")}查获违禁品数量显著低于整体水平` : '';
      return `${first}${!!second ? '，' : first && second ? '。' : ''}${second}`
    },

    // 更新查获违禁品类别图表
    updateCaptureRankChart(data) {
      if (this.captureRankChart) {
        const chartData = data.map(item => ({
          value: item.quantity || 0,
          name: item.categoryNameOne || '未知类型'
        }))

        this.captureRankChart.setOption({
          series: [{
            data: chartData
          }]
        })
      }
    },

    // 更新问题发现统计图表
    updateProblemDiscoveryChart(data) {
      if (this.problemDiscoveryChart) {
        const xAxisData = data.map(item => item.hourOfDay || '')
        const seriesData = data.map(item => item.total || 0)

        this.problemDiscoveryChart.setOption({
          xAxis: {
            data: xAxisData
          },
          series: [{
            name: '查获数量',
            type: 'line',
            data: seriesData,
            symbol: 'circle',
            symbolSize: 6,
            smooth: true,
            lineStyle: { width: 3 }
          }]
        })
      }
    },

    // 更新隐匿物品查获部位图表
    updateProblemRectificationChart(data) {

      if (this.problemRectificationChart) {
        const chartData = data.map(item => ({
          value: item.quantity || 0,
          name: item.positionName || '未知部位'
        }))

        this.problemRectificationChart.setOption({
          series: [{
            data: chartData
          }]
        })
      }
    },

    // 更新查获岗位分布图表
    updateRectificationStatsChart(data) {
      if (this.rectificationStatsChart) {
        const chartData = data.map(item => ({
          value: item.quantity || 0,
          name: item.postName || '未知岗位'
        }))

        this.rectificationStatsChart.setOption({
          series: [{
            data: chartData
          }]
        })
      }
    },



    // 使用模拟数据更新图表
    updateChartsWithMockData() {
      this.updateCaptureRankChart(this.categoryStatsData)
      this.updateProblemDiscoveryChart(this.seizureTimeTrendData)
      this.updateProblemRectificationChart(this.concealmentPositionStatsData)
      this.updateRectificationStatsChart(this.postCategoryStatsData)
    }
  }
}
</script>

<style lang="scss" scoped>
.risk-hazard {
  // padding: 24rpx;
  background: #fff;
  border-radius: 16rpx;
  margin-bottom: 24rpx;
}

.section-title {
  margin-bottom: 24rpx;

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

.nine-panel-layout {
  display: flex;
  flex-direction: column;
  gap: 32rpx;
}

.panel-item {
  // background: #f8f9fa;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.1);
  padding: 20rpx;
  margin-bottom: 16rpx;
}

.panel-header {
  margin-bottom: 16rpx;

  .header-text {
    font-size: 28rpx;
    font-weight: 600;
    color: #333;
  }
}

.describe-card {
  background: #f8f9fa;
  border-radius: 8rpx;
  padding: 16rpx;
  margin-bottom: 16rpx;

  .describe-content {
    font-size: 24rpx;
    line-height: 1.5;
    color: #666;
  }
}

.chart-container {
  background: #fff;
  border-radius: 8rpx;
  padding: 16rpx;
  height: 400rpx;

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



@media (min-width: 768px) {
  .nine-panel-layout {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300rpx, 1fr));
    gap: 24rpx;
  }

  .panel-item {
    margin-bottom: 0;
  }
}
</style>