<template>
  <el-scrollbar height="100vh">
    <div class="wrapper">
      <datav-header/>
      <main>
        <el-row :gutter="16">
          <el-col :span="6">
            <datav-card title="初访重访情况">
              <el-row class="mb-32">
                <el-col :span="12">
                  <div class="descriptions_cell text-center">
                    <div class="descriptions_content">
                      {{ currentLeftOverview.firstMail }}
                    </div>
                    <div class="descriptions_label">
                      初信初访
                    </div>
                  </div>
                </el-col>
                <el-col :span="12">
                  <div class="descriptions_cell text-center">
                    <div class="descriptions_content">
                      {{ currentLeftOverview.repeatMail }}
                    </div>
                    <div class="descriptions_label">
                      重复信访
                    </div>
                  </div>
                </el-col>

              </el-row>
              <datav-card>
                <datav-tabs v-model="activeTab" ref="firstAndRepeat">
                  <datav-tab-item label="分县市局" name="1">
                    <datav-tabs
                        v-model="fxsjFirstAndRepeatTab"
                        type="bottom-button"

                    >
                      <datav-tab-item label="初信初访" name="1">
                        <el-scrollbar height="300px">
                          <datav-chart-bar
                              :data="fxsjFirstMailList"
                              size="large"
                              :max="11"
                              :color="colors"

                          />
                        </el-scrollbar>
                      </datav-tab-item>
                      <datav-tab-item label="重复信访" name="2">
                        <el-scrollbar height="300px">
                          <datav-chart-bar
                              :data="fxsjRepeatMailList"
                              :max="11"
                              size="large"
                              :color="colors"
                          />
                        </el-scrollbar>
                      </datav-tab-item>

                    </datav-tabs>
                  </datav-tab-item>
                  <datav-tab-item label="局属单位" name="2">
                    <datav-tabs
                        v-model="bwzdFirstAndRepeatTab"
                        type="bottom-button"
                    >
                      <datav-tab-item label="初信初访" name="1">
                        <el-scrollbar height="300px">
                          <datav-chart-bar
                              :data="bwzdFirstMailList"
                              size="large"
                          />
                        </el-scrollbar>
                      </datav-tab-item>
                      <datav-tab-item label="重复信访" name="2">
                        <el-scrollbar height="300px">
                          <datav-chart-bar
                              :data="bwzdRepeatMailList"
                              :max="11"
                              size="large"
                          />
                        </el-scrollbar>
                      </datav-tab-item>

                    </datav-tabs>
                  </datav-tab-item>
                </datav-tabs>
              </datav-card>
            </datav-card>


            <datav-card title="信访投诉占比">
              <v-charts
                  style="height: 300px"
                  :option="option2"
                  autoresize
              />
              <div class="flex tab-title flex center mt-20" style="margin-bottom: 20px">
                <div class="tab-title-item active">
                </div>
              </div>
            </datav-card>

          </el-col>

          <el-col :span="12">
            <div class="datav-col">
              <datav-date-picker v-model="time"/>
            </div>
            <div class="flex gap-42 overview-stat-row">
              <el-tooltip
                  v-for="item in overviewCards"
                  :key="item.title"
                  placement="top"
                  :show-after="120"
                  :offset="18"
                  popper-class="mail-overview-tooltip"
              >
                <template #content>
                  <div class="overview-tip-card">
                    <div class="overview-tip-title">{{ item.title }}</div>
                    <div class="overview-tip-desc">{{ item.desc }}</div>
                    <div class="overview-tip-formula">{{ item.formula }}</div>
                  </div>
                </template>
                <div
                    class="overview-tip-trigger"
                    style="width: 33.33%"
                    :class="{ 'is-clickable': item.clickable }"
                    @click="item.onClick && item.onClick()"
                >
                  <datav-statistic
                      :value="item.value"
                      :title="item.title"
                  />
                </div>
              </el-tooltip>
            </div>

            <v-charts
                style="height: 450px"
                :option="option"
                autoresize
                @click="handleClick"
                ref="mailMap"
            />

            <datav-card title="信访趋势" ref="mailTrendCard">
              <datav-tabs v-model="mailTrendTabs" @change="handleTabChange">
                <datav-tab-item label="国家信访" name="1">
                  <v-charts
                      style="width: 105%; height: 300px;"
                      :option="countryTrend"
                      autoresize
                  />
                </datav-tab-item>
                <datav-tab-item label="公安部信访" name="2">
                  <v-charts
                      style="width: 105%; height: 300px; "
                      :option="policeTrend"
                      autoresize
                  />
                </datav-tab-item>
                <datav-tab-item label="局长信箱" name="3">
                  <v-charts
                      style="width: 105%; height: 300px; "
                      :option="manageTrend"
                      autoresize
                  />
                </datav-tab-item>
                <!-- 12337信访 - 已隐藏
                <datav-tab-item label="12337信访" name="4">
                  <v-charts
                      style="width: 105%; height: 300px; "
                      :option="numberTrend"
                      autoresize
                  />
                </datav-tab-item>
                -->
              </datav-tabs>
              <div class="gobal-dropdown-container">
                <el-dropdown class="test" @command="handleCommand">
                    <span class="el-dropdown-link my-gobal-yearselect">
                      {{ selectedYear + " 年" }}
                    </span>
                  <template #dropdown>
                    <el-dropdown-menu style="width: 90px">
                      <el-dropdown-item v-for="year in years" :key="year" :command="year">{{ year + " 年" }}
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </datav-card>

          </el-col>

          <el-col :span="6">
            <datav-card title="群众集访情况">
              <el-row class="mb-32">
                <el-col :span="12">
                  <div class="descriptions_cell text-center">
                    <div class="descriptions_content">
                      {{ currentRightOverview.mass }}
                    </div>
                    <div class="descriptions_label">
                      群体集访
                    </div>
                  </div>
                </el-col>
                <el-col :span="12">
                  <div class="descriptions_cell text-center">
                    <div class="descriptions_content">
                      {{ currentRightOverview.leaderReview }}
                    </div>
                    <div class="descriptions_label">
                      领导接访数
                    </div>
                  </div>
                </el-col>
              </el-row>

              <datav-card>
                <datav-tabs v-model="activeTabRight" ref="entanglement">
                  <datav-tab-item label="分县市局" name="1">
                    <datav-tabs
                        type="bottom-button"
                        v-model="fxsjEntanglementTab"
                    >

                      <datav-tab-item label="群体集访" name="1">
                        <el-scrollbar height="300px">
                          <datav-chart-bar
                              :data="fxsjMassMailList"
                              :max="11"
                              size="large"
                              :color="colors"
                          />
                        </el-scrollbar>
                      </datav-tab-item>
                      <datav-tab-item label="领导接访" name="2">
                        <el-scrollbar height="300px">
                          <datav-chart-bar
                              :data="fxsjLeaderViewMailList"
                              :max="11"
                              size="large"
                              :color="leaderViewColors"
                          />
                        </el-scrollbar>
                      </datav-tab-item>
                    </datav-tabs>
                  </datav-tab-item>
                  <datav-tab-item label="局属单位" name="2">
                    <datav-tabs
                        type="bottom-button"
                        v-model="bwzdEntanglementTab"
                    >
                      <datav-tab-item label="群体集访" name="1">
                        <el-scrollbar height="300px">
                          <datav-chart-bar
                              :data="bwzdMassMailList"
                              :max="11"
                              size="large"
                              :color="colors"
                          />
                        </el-scrollbar>
                      </datav-tab-item>
                      <datav-tab-item label="领导接访" name="2">
                        <el-scrollbar height="300px">
                          <datav-chart-bar
                              :data="bwzdLeaderViewMailList"
                              :max="11"
                              size="large"
                              :color="leaderViewColors"
                          />
                        </el-scrollbar>
                      </datav-tab-item>

                    </datav-tabs>
                  </datav-tab-item>
                </datav-tabs>
              </datav-card>
            </datav-card>

            <datav-card title="追责问责情况">
              <v-charts
                  style="height: 300px"
                  :option="option3"
                  autoresize
              />
              <div class="flex tab-title flex center mt-20" style="margin-bottom: 20px">
                <div class="tab-title-item active">
                </div>
              </div>
            </datav-card>
          </el-col>
        </el-row>
      </main>
    </div>
  </el-scrollbar>

</template>


<script setup>
import vCharts from "vue-echarts";
import changshaMap from "@/assets/data/changsha.json";
import * as echarts from "echarts/core";
import moment from "moment/moment.js";
import {
  getFirstAndRepeatMail,
  getEntanglementAndMassMail, getAllMailCount, getMailMapIcon, getMailTrend, getResultCount
} from "@/api/screen/mail.ts";
import {mapOrgNameMapping} from "@/enums/orgMapping.js";


//region  所有变量

const router = useRouter();
const activeTab = ref("1");
const bwzdActiveTab = ref("1");  // 部委支队初重信tab


const activeTabRight = ref("1");
const overview = ref({
  totalMail: 0,
  countryMail: 0,
  policeMail: 0,
  numberMail: 0,
  manageMail: 0,
});
const overviewCards = computed(() => [
  {
    title: "局长信箱",
    value: overview.value.manageMail,
    desc: "统计时间范围内局长信箱中的来信数量。",
    formula: "统计方式：局长信箱有效来信数量汇总",
    clickable: true,
    onClick: () => open('/query?open=Mailbox'),
  },
  {
    title: "信访总数",
    value: overview.value.totalMail,
    desc: "统计时间范围内纳入信访总数口径的数据量。",
    formula: "统计方式：国家信访 + 公安部信访 + 12337信访",
  },
  {
    title: "国家信访",
    value: overview.value.countryMail,
    desc: "统计时间范围内国家信访来源的数据数量。",
    formula: "统计方式：国家信访数据数量汇总",
    clickable: true,
    onClick: () => open('/data/gjxf?open=view'),
  },
  {
    title: "公安部信访",
    value: overview.value.policeMail,
    desc: "统计时间范围内公安部信访来源的数据数量。",
    formula: "统计方式：公安部信访数据数量汇总",
    clickable: true,
    onClick: () => open('/data/gabxf?open=view'),
  },
  // 12337信访 - 已隐藏
  // {
  //   title: "12337信访",
  //   value: overview.value.numberMail,
  //   desc: "统计时间范围内 12337 平台来源的数据数量。",
  //   formula: "统计方式：12337信访数据数量汇总",
  //   clickable: true,
  //   onClick: () => open('/query?open=12337'),
  // },
]);
//总览
//分县市局
const fxjsFirstAndRepeatOverview = ref({
  firstMail: 0,
  repeatMail: 0,
  leaderMail: 0
});
//局属单位
const bwzdFirstAndRepeatOverview = ref({
  firstMail: 0,
  repeatMail: 0,
  leaderMail: 0
});

const fxsjFirstMailList = ref([]);  // 分局初信初访
const fxsjRepeatMailList = ref([]);  // 分局重访
const fxsjLeaderViewMailList = ref([]);   // 分局领导接访
const bwzdFirstMailList = ref([]);   // 部委初信
const bwzdRepeatMailList = ref([]);   // 部委重访
const bwzdLeaderViewMailList = ref([]);   // 部委领导接访
const fxsjMailEntanglementMassOverview = ref({
  entanglement: 0,
  mass: 0,
  leaderReview: 0,
})
const bwzdMailEntanglementMassOverview = ref({
  entanglement: 0,
  mass: 0,
  leaderReview: 0,
})
const fxsjLeaderReviewMailList = ref([]);   // 分局领导督察
const fxsjEntanglementMailList = ref([]);  // 分局缠闹
const fxsjMassMailList = ref([]);   // 分局集访
const bwzdLeaderReviewMailList = ref([]);   // 分局领导督察
const bwzdEntanglementMailList = ref([]);  // 部委缠闹
const bwzdMassMailList = ref([]);  // 部委集访

const time = ref([
  moment().startOf("year").format("YYYY-MM-DD"),
  moment().format("YYYY-MM-DD"),
]);
const currentYear = new Date().getFullYear();
const years = ref([currentYear.toString(), (currentYear - 1).toString(), (currentYear - 2).toString()]); // 年份列表
const selectedYear = ref(currentYear); // 当前选中的年份
const colors = [
  {
    color: "linear-gradient( 270deg, #FB002D 0%, #822232 100%)",
    percentage: 80,
  },
  {
    color: "linear-gradient( 270deg, #FFB90E 0%, #71501D 100%)",
    percentage: 60,
  },
  {
    color: "linear-gradient( 270deg, #63E700 0%, #19674C 100%)",
    percentage: 40,
  },
];
const leaderViewColors = [
  {
    color: "linear-gradient( 270deg, #63E700 0%, #19674C 100%)",
    percentage: 80,
  },
  {
    color: "linear-gradient( 270deg, #FFB90E 0%, #71501D 100%)",
    percentage: 60,
  },
  {
    color: "linear-gradient( 270deg, #FB002D 0%, #822232 100%)",
    percentage: 0,
  },
];


const fxsjFirstAndRepeatTab = ref("1");
const bwzdFirstAndRepeatTab = ref("1");
const firstAndRepeat = ref(null)
const mailMap = ref(null);
const mailMapIconList = ref([]);
const mailTrendTabs = ref("1");
const mailTrendCard = ref(null)
const fxsjEntanglementTab = ref("1");
const bwzdEntanglementTab = ref("1");
const entanglement = ref(null)
let fxsjFirstAndRepeatIntervalId;
let fxsjEntanglementIntervalId;
let mailTrendIntervalId;
let mailMapIntervalId;
//endregion

// region 所有图
echarts.registerMap("changsha", changshaMap);
const gobalTempMapVoList = [
  {
    "name": "芙蓉分局",
    "total": 0,
    "countryTotal": 0,
    "policeTotal": 0,
    "commissionerTotal": 0,
    "numTotal": 0,
  }
];


const option = ref({
  geo: {
    map: "changsha",
  },
  tooltip: {
    trigger: 'item',
    position: 'bottom',
    formatter: function (params) {
      // <li>局长信箱 <span>  ${dataItem.commissionerTotal}</span></li>
      //  <li>局长信箱 <span>0</span></li>
      const dataItem = mailMapIconList.value.find(item => item.name.includes(params.name.substring(0, 2)));
      if (dataItem) {
        return `
        <div class="tooltip">
          <div class="tooltip-title">${dataItem.originalName} </div>
          <div class="tooltip-content">
            <ul class="tooltip-ul" >
              <li>信访总件数 <span>${dataItem.total}</span></li>
              <li>国家信访 <span> ${dataItem.countryTotal}</span></li>
              <li>公安部信访 <span>  ${dataItem.policeTotal}</span></li>
              <!-- 12337信访 - 已隐藏
              <li>12337信访 <span>${dataItem.numTotal}</span></li>
              -->
            </ul>
          </div>
        </div>`;
      } else {
        return `<div class="tooltip">
          <div class="tooltip-title">${params.name}</div>
          <div class="tooltip-content">
            <ul class="tooltip-ul"">
              <li>信访总件数 <span>0</span></li>
              <li>国家信访 <span>0</span></li>
              <li>公安部信访 <span>0</span></li>
              <!-- 12337信访 - 已隐藏
              <li>12337信访 <span>0</span></li>
              -->
            </ul>
          </div>
        </div>`;
      }
    },
  },
  visualMap: {
    type: "piecewise",
    bottom: 10,
    pieces: [
      {gte: 0, lte: 10, label: "问题数低于500"},
      {gte: 10, lte: 20, label: "问题数介于500-1000"},
      {gte: 30, label: "问题数高于1000"},
    ],
    right: 10,
    realtime: false,
    orient: "horizontal",
    textStyle: {
      color: "#fff",
    },
    calculable: true,
    inRange: {
      color: ["#4987F6", "#F6A149", "#D34343",],
    },
  },
  series: [
    {
      name: "长沙",
      type: "map",
      map: "changsha",
      hoverAnimation: true,
      label: {
        show: true,
        color: "white",
      },
      itemStyle: {
        normal: {
          areaColor: "#02215E",
          borderColor: "#24D2EE",
          borderWidth: 1 // 高亮时边框宽度
        },
      },
      emphasis: {
        areaColor: "#FFD700", // 高亮时区域颜色
        borderColor: "#FF0000", // 高亮时边框颜色
        borderWidth: 4 // 高亮时边框宽度
      },
      data: []
    }
  ],
})
const policeTrend = ref({
  grid: {
    left: '5%', // 图表距离容器左边的距离
    right: '2%', // 图表距离容器右边的距离
    top: '10%', // 图表距离容器上边的距离
    bottom: '20%', // 图表距离容器下边的距离
    containLabel: false // 是否包含坐标轴的标签
  },
  xAxis: {
    type: "category",
    data: [],
    boundaryGap: true,
    axisTick: {
      // 去掉X轴刻度线
      show: false
    },
  },
  yAxis: {
    type: "value",
    splitLine: {
      show: true,
      lineStyle: {
        color: "#193775",
      },
    }
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'line',
      label: {
        backgroundColor: '#6a7985'
      }
    }
  },
  series: [
    {
      type: "line",
      smooth: true,
      label: {
        show: false
      },
      lineStyle: {
        color: "#28E6FF",
        width: 4,
      },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          {
            offset: 0,
            color: "rgba(40,230,255,0.47)", // 渐变起始颜色
          },
          {
            offset: 1,
            color: "rgba(40,230,255,0)", // 渐变结束颜色
          },
        ]),
      },
      data: [],
    },
  ],
});
const manageTrend = ref({
  grid: {
    left: '5%', // 图表距离容器左边的距离
    right: '2%', // 图表距离容器右边的距离
    top: '10%', // 图表距离容器上边的距离
    bottom: '20%', // 图表距离容器下边的距离
    containLabel: false // 是否包含坐标轴的标签
  },
  xAxis: {
    type: "category",
    data: [],
    boundaryGap: true,
    axisTick: {
      // 去掉X轴刻度线
      show: false
    },
  },
  yAxis: {
    type: "value",
    splitLine: {
      show: true,
      lineStyle: {
        color: "#193775",
      },
    }
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'line',
      label: {
        backgroundColor: '#6a7985'
      }
    }
  },
  series: [
    {
      type: "line",
      smooth: true,
      label: {
        show: false
      },
      lineStyle: {
        color: "#28E6FF",
        width: 4,
      },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          {
            offset: 0,
            color: "rgba(40,230,255,0.47)", // 渐变起始颜色
          },
          {
            offset: 1,
            color: "rgba(40,230,255,0)", // 渐变结束颜色
          },
        ]),
      },
      data: [],
    },
  ],
});
const numberTrend = ref({
  grid: {
    left: '5%', // 图表距离容器左边的距离
    right: '2%', // 图表距离容器右边的距离
    top: '10%', // 图表距离容器上边的距离
    bottom: '20%', // 图表距离容器下边的距离
    containLabel: false // 是否包含坐标轴的标签
  },
  xAxis: {
    type: "category",
    data: [],
    boundaryGap: true,
    axisTick: {
      // 去掉X轴刻度线
      show: false
    },
  },
  yAxis: {
    type: "value",
    splitLine: {
      show: true,
      lineStyle: {
        color: "#193775",
      },
    }
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'line',
      label: {
        backgroundColor: '#6a7985'
      }
    }
  },
  series: [
    {
      type: "line",
      smooth: true,
      label: {
        show: false
      },
      lineStyle: {
        color: "#28E6FF",
        width: 4,
      },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          {
            offset: 0,
            color: "rgba(40,230,255,0.47)", // 渐变起始颜色
          },
          {
            offset: 1,
            color: "rgba(40,230,255,0)", // 渐变结束颜色
          },
        ]),
      },
      data: [],
    },
  ],
});
const countryTrend = ref({
  grid: {
    left: '5%', // 图表距离容器左边的距离
    right: '2%', // 图表距离容器右边的距离
    top: '10%', // 图表距离容器上边的距离
    bottom: '20%', // 图表距离容器下边的距离
    containLabel: false // 是否包含坐标轴的标签
  },
  xAxis: {
    type: "category",
    data: [],
    boundaryGap: true,
    axisTick: {
      // 去掉X轴刻度线
      show: false
    },
  },
  yAxis: {
    type: "value",
    splitLine: {
      show: true,
      lineStyle: {
        color: "#193775",
      },
    }
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'line',
      label: {
        backgroundColor: '#6a7985'
      }
    }
  },
  series: [
    {
      type: "line",
      smooth: true,
      label: {
        show: false
      },
      lineStyle: {
        color: "#28E6FF",
        width: 4,
      },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          {
            offset: 0,
            color: "rgba(40,230,255,0.47)", // 渐变起始颜色
          },
          {
            offset: 1,
            color: "rgba(40,230,255,0)", // 渐变结束颜色
          },
        ]),
      },
      data: [],
    },
  ],
});
const option2 = ref({
  series: [
    {
      type: "pie",
      radius: ["40%", "70%"],
      label: {
        color: "#fff",
      },
      data: [],
    },
  ],
  tooltip: {
    trigger: "item",
  },
});

const option3 =ref( {
  tooltip: {
    trigger: "item",
  },
  series: [
    {
      type: "pie",
      radius: ["40%", "70%"],
      label: {
        color: "#fff",
      },
      data: [

      ],
    },
  ],
});
// endregion



//获取追责问责情况
const getResultCountDataFun = async ()=>{
  const body = {
    beginTime: time.value[0],
    endTime: time.value[1],
  }
  const res = await  getResultCount(body);
  option3.value.series[0].data=res.resultCountArray;
}

// region 所有函数

const getAllMailCountDataFun = async () => {
  const body = {
    beginTime: time.value[0],
    endTime: time.value[1],
  }
  const res = await getAllMailCount(body)
  overview.value = res.overview;
  option2.value.series[0].data= [{value:overview.value.manageMail,name:"局长信箱"},
    {value:overview.value.countryMail,name:"国家信访"},
    {value:overview.value.policeMail,name:"公安部信访"},
//    {value:overview.value.numberMail,name:"12337信访"},  // 已隐藏
    ].filter(item => item.value > 0);
}


const getMailMapIconDataFun = async () => {
  const body = {
    beginTime: time.value[0],
    endTime: time.value[1],
  }
  console.log('-------执行')
  const res = await getMailMapIcon(body);
  const mappedData = mapOrgNameMapping(res.mailMapIconList, "total");
  mailMapIconList.value = mappedData;
  console.log('-------执行2')
  console.log(mailMapIconList)
  const total = mappedData.reduce((sum, item) => sum + Number(item.value), 0);
  const avg = total / mappedData.length; // 计算平均值
  const range30Percent = avg * 0.3   // 不用取整，小数也可以
  option.value.series[0].data = mappedData;
  option.value.visualMap.pieces = [
    {gte: 0, lte: avg - range30Percent, label: "低于平均信件数30%", color: "#4987F6"},
    {gte: avg - range30Percent, lte: avg + range30Percent + 0.1, label: `平均信件数上下浮动30%内`, color: "#F6A149"},
    {gte: avg + range30Percent, label: "高于平均信件数30%", color: "#D34343"},
  ];
}
const getMailTrendDataFun = async (year = selectedYear.value) => {
  const res = await getMailTrend(year);
  const policeList = res.policeList;
  const commissionerList = res.commissionerList;
  const numberList = res.numberList;
  const countryList = res.countryList;
  const policecategories = policeList.map(item => item.name);
  const policevalues = policeList.map(item => item.value);
  const managecategories = commissionerList.map(item => item.name);
  const managevalues = commissionerList.map(item => item.value);
  const numbercategories = numberList.map(item => item.name);
  const numbervalues = numberList.map(item => item.value);
  const countrycategories = countryList.map(item => item.name);
  const countryvalues = countryList.map(item => item.value);
  // 更新图表数据
  policeTrend.value.xAxis.data = policecategories;
  policeTrend.value.series[0].data = policevalues;
  manageTrend.value.xAxis.data = managecategories;
  manageTrend.value.series[0].data = managevalues;
  numberTrend.value.xAxis.data = numbercategories;
  numberTrend.value.series[0].data = numbervalues;
  countryTrend.value.xAxis.data = countrycategories;
  countryTrend.value.series[0].data = countryvalues;
}

const getData = () => {
  // 初访重访情况
  getFirstAndRepeatMailFun();
  // 信访投诉占比 && 总览数据
  getAllMailCountDataFun();
  // 地图数据
  getMailMapIconDataFun()
  // 趋势
  getMailTrendDataFun();
  // 群众集访情况
  getEntanglementAndMassMailFun();
  // 追责问责情况
  getResultCountDataFun();
}


const getFirstAndRepeatMailFun = async ()=>{
  const body = {
    beginTime: time.value[0],
    endTime: time.value[1],
  }
  const res = await getFirstAndRepeatMail(body)
  fxsjFirstMailList.value = res.fxsjFirstRankList;
  fxsjRepeatMailList.value = res.fxsjRepeatRankList;
  bwzdFirstMailList.value = res.bwzdFirstRankList;
  bwzdRepeatMailList.value = res.bwzdRepeatRankList;
  fxjsFirstAndRepeatOverview.value = res.fxsjOverview
  bwzdFirstAndRepeatOverview.value = res.bwzdOverview
}

const getEntanglementAndMassMailFun = async ()=>{

  const body = {
    beginTime: time.value[0],
    endTime: time.value[1],
  }
  const res = await getEntanglementAndMassMail(body)

  // ✅ overview
  fxsjMailEntanglementMassOverview.value = res.fxsjOverview
  bwzdMailEntanglementMassOverview.value = res.bwzdOverview

  // ✅ 列表（右侧柱状图用）
  fxsjMassMailList.value = res.fxsjMassMailList
  bwzdMassMailList.value = res.bwzdMassMailList

  fxsjLeaderViewMailList.value = res.fxsjLeaderReviewMailList
  bwzdLeaderViewMailList.value = res.bwzdLeaderReviewMailList
}


const currentLeftOverview = computed(() => {
  return activeTab.value === '1' ? fxjsFirstAndRepeatOverview.value : bwzdFirstAndRepeatOverview.value;
});

const currentRightOverview = computed(() => {
  return activeTabRight.value === '1' ? fxsjMailEntanglementMassOverview.value : bwzdMailEntanglementMassOverview.value;
});
// endregion


// region 动画
const fxsjFirstAndRepeatAnimation = () => {
  fxsjFirstAndRepeatTab.value = (parseInt(fxsjFirstAndRepeatTab.value) % 2 + 1).toString();
};
fxsjFirstAndRepeatIntervalId = setInterval(fxsjFirstAndRepeatAnimation, 3000);
// 业务类型占比环形图
// const ywlxzbCircularAnimation = () => {
//   const ywlxzbOptionTemp = ywlxzbOption?.value?.chart;
//   if (!ywlxzbOptionTemp) return;
//   const length = ywlxPieOption.value.series[0].data.length;
//   const randomNum = Math.floor(Math.random() * length);
//   ywlxzbOptionTemp?.dispatchAction({type: 'downplay', seriesIndex: 0});
//   ywlxzbOptionTemp?.dispatchAction({type: 'highlight', seriesIndex: 0, dataIndex: randomNum}); // 显示
//   ywlxzbOptionTemp?.dispatchAction({type: 'showTip', seriesIndex: 0, dataIndex: randomNum});
// };
// ywlxPieCircularIntervalId = setInterval(ywlxzbCircularAnimation, 2000);

// 地图动画
const mailMapAnimation = () => {
  const mapTemp = mailMap?.value?.chart;
  if (!mapTemp) return;
  // 来个随机数，9个图  0~8的整数就ok
  const randomNum = Math.floor(Math.random() * 9);
  mapTemp.dispatchAction({
    type: "downplay", //downplay 取消高亮
    seriesIndex: 0,
  });
  mapTemp.dispatchAction({
    type: "highlight", //highLight 高亮指定的数据图形
    seriesIndex: 0, //系列index
    dataIndex: randomNum, //数据index
  });
  mapTemp.dispatchAction({
    type: "showTip", //showTip 显示提示框
    seriesIndex: 0,
    dataIndex: randomNum,
  });
};
mailMapIntervalId = setInterval(mailMapAnimation, 2000);

// 趋势动画 - 已隐藏12337信访Tab
const mailTrendAnimation = () => {
  mailTrendTabs.value = (parseInt(mailTrendTabs.value) % 3 + 1).toString();
}
mailTrendIntervalId = setInterval(mailTrendAnimation, 2000);
// 缠访集访情况动画
const fxsjEntanglementAnimation = () => {
  fxsjEntanglementTab.value = (parseInt(fxsjEntanglementTab.value) % 2 + 1).toString();
};
fxsjEntanglementIntervalId = setInterval(fxsjEntanglementAnimation, 3000);
// // 问题涉及方面分布环形图
// const wtlxzbCircularAnimation = () => {
//   const wtlxzbOptionTemp = wtlxzbOption?.value?.chart;
//   if (!wtlxzbOptionTemp) return;
//   const length = ywlxPieOption.value.series[0].data.length;
//   const randomNum = Math.floor(Math.random() * length);
//   wtlxzbOptionTemp?.dispatchAction({type: 'downplay', seriesIndex: 0});
//   wtlxzbOptionTemp?.dispatchAction({type: 'highlight', seriesIndex: 0, dataIndex: randomNum}); // 显示
//   wtlxzbOptionTemp?.dispatchAction({type: 'showTip', seriesIndex: 0, dataIndex: randomNum});
// };
// wtlxPieCircularIntervalId = setInterval(wtlxzbCircularAnimation, 2000);
// endregion

// region 监听|事件

// 监听信访趋势tab切换
watch(time, () => {
  getData();
})
onMounted(() => {
  getData();
  setupEventListeners();
});
const handleCommand = (year) => {
  selectedYear.value = year;
  getMailTrendDataFun()
};
const handleClick = (params) => {
  const departId = params.data.departId;
  const url = router.resolve({
    path: "/datav/subOneMailVisits",
    query: {departId: departId},
  }).href;
  window.open(url, "_blank");
}
const setupEventListeners = () => {
  firstAndRepeatAnimationStop();
  mailMapAnimationStop();
  mailTrendAnimationStop();
  fxsjEntanglementAnimationStop();
};
const firstAndRepeatAnimationStop = () => {
  const temp = firstAndRepeat.value.$el;
  temp.addEventListener('mouseenter', () => {
    clearInterval(fxsjFirstAndRepeatIntervalId)
  });
  temp.addEventListener('mouseleave', () => {
    fxsjFirstAndRepeatIntervalId = setInterval(fxsjFirstAndRepeatAnimation, 3000);
  });
}
const mailMapAnimationStop = () => {
  const mapTemp = mailMap?.value?.chart;
  mapTemp.on('mousemove', (e) => {
    clearInterval(mailMapIntervalId);
    mapTemp.dispatchAction({type: "downplay", seriesIndex: 0,});
    mapTemp.dispatchAction({type: "highlight", seriesIndex: 0, dataIndex: e.dataIndex,});
    mapTemp.dispatchAction({type: "showTip", seriesIndex: 0, dataIndex: e.dataIndex,});
  });
  mapTemp.on('mouseout', () => {
    clearInterval(mailMapIntervalId); // 确保没有多个定时器同时运行
    mailMapIntervalId = setInterval(mailMapAnimation, 2000);
  });
}
const mailTrendAnimationStop = () => {
  const temp = mailTrendCard?.value.$el;
  temp.addEventListener('mouseenter', () => {
    clearInterval(mailTrendIntervalId);
  });
  temp.addEventListener('mouseleave', () => {
    clearInterval(mailTrendIntervalId);
    mailTrendIntervalId = setInterval(mailTrendAnimation, 2000);
  });
}
const fxsjEntanglementAnimationStop = () => {
  const temp = entanglement.value.$el;
  temp.addEventListener('mouseenter', () => {
    clearInterval(fxsjEntanglementIntervalId)
  });
  temp.addEventListener('mouseleave', () => {
    fxsjEntanglementIntervalId = setInterval(fxsjEntanglementAnimation, 3000);
  });
}


function open(path) {
    window.open(router.resolve(path).href);
}

</script>


<style lang="scss" scoped>
@import "@/style/datav.scss";

.dropdown-container {
  position: absolute;
  right: 30px;
  top: 65px;
}

.datav-tab-item {
  display: flex;
  justify-content: center;
  align-items: center;
}

.overview-stat-row {
  margin-bottom: 8px;
}

.overview-tip-trigger {
  cursor: help;
  transition: transform 0.22s ease, filter 0.22s ease;
}

.overview-tip-trigger:hover {
  transform: translateY(-3px);
  filter: drop-shadow(0 8px 18px rgba(28, 217, 255, 0.18));
}

.overview-tip-trigger.is-clickable {
  cursor: pointer;
}

:global(.mail-overview-tooltip) {
  border: none !important;
  background: transparent !important;
  box-shadow: none !important;
  padding: 0 !important;
  color: inherit !important;
}

:global(.mail-overview-tooltip .el-popper__arrow),
:global(.mail-overview-tooltip .el-popper__arrow::before) {
  display: none !important;
  background: transparent !important;
  border: none !important;
}


:deep() {
  // 弹框整体
  .tooltip {
    position: relative;
    width: 160px;
    height: 178px;
    background: linear-gradient(180deg, rgba(1, 4, 87, 0.8) 0%, rgba(3, 21, 119, 0.8) 100%);
    border: 1px solid #4E8FFF;
    margin: -10px -10px -10px -10px;

  }

  ////浏阳市局
  .tooltip-title {
    width: 160px;
    height: 43px;
    background: linear-gradient(180deg, #0A2F86 0%, #04154E 100%);
    box-shadow: inset 0px -1px 0px 0px #253755;
    display: flex;
    justify-content: center; /* 水平居中 */
    align-items: center; /* 垂直居中 */
    font-weight: 400;
    font-size: 16px;
    color: #FFFFFF;
    border-bottom: 1px solid #253755; /* 设置下边框 */
  }

  .tooltip-content {
    width: 160px;
    height: 133px;
    background: linear-gradient(180deg, #010457 0%, #031577 100%)
  }

  .tooltip-content ul {
    list-style-type: none; /* 移除默认的小圆点 */
    padding-left: 5px;
    margin: 0;
  }

  .tooltip-content ul li {
    display: flex;
    justify-content: space-around;
    height: 26px;
    color: #597AE9;
    font-weight: 400;
    font-size: 14px;
  }

  .tooltip-ul span {
    display: inline-block;
    float: right;
    color: #fff;
    font-size: 14px;
    //text-align: center; /* 水平居中 */
  }

}

.overview-tip-card {
  position: relative;
  width: 260px;
  padding: 14px 16px;
  border: 1px solid rgba(77, 145, 255, 0.72);
  border-radius: 14px;
  background:
      radial-gradient(circle at top right, rgba(41, 126, 255, 0.25), transparent 38%),
      linear-gradient(180deg, rgba(3, 13, 74, 0.96) 0%, rgba(2, 26, 112, 0.96) 100%);
  box-shadow:
      0 16px 40px rgba(0, 10, 48, 0.45),
      inset 0 1px 0 rgba(132, 201, 255, 0.24);
  backdrop-filter: blur(8px);
}

.overview-tip-card::before {
  content: "";
  position: absolute;
  left: 50%;
  top: -12px;
  transform: translateX(-50%);
  width: 0;
  height: 0;
  border-left: 11px solid transparent;
  border-right: 11px solid transparent;
  border-bottom: 12px solid rgba(77, 145, 255, 0.72);
}

.overview-tip-card::after {
  content: "";
  position: absolute;
  left: 50%;
  top: -10px;
  transform: translateX(-50%);
  width: 0;
  height: 0;
  border-left: 10px solid transparent;
  border-right: 10px solid transparent;
  border-bottom: 11px solid rgba(2, 26, 112, 0.98);
}

.overview-tip-title {
  font-size: 15px;
  font-weight: 700;
  color: #f3fbff;
  margin-bottom: 8px;
  letter-spacing: 0.5px;
}

.overview-tip-desc {
  font-size: 13px;
  line-height: 1.6;
  color: #9fc2ff;
  margin-bottom: 10px;
}

.overview-tip-formula {
  padding-top: 10px;
  border-top: 1px solid rgba(111, 164, 255, 0.24);
  font-size: 12px;
  line-height: 1.5;
  color: #e7f6ff;
}


.test {
  width: 95px;
  height: 25px;
  background: #1C3472;
}

.gobal-dropdown-container {
  position: absolute;
  right: 20px;
  top: 15px;
}

.my-gobal-yearselect {
  font-size: 14px;
  padding-top: 6px;
  padding-left: 20px;
  width: 90px;
  color: #fff;
}

</style>


