<template>
  <el-scrollbar height="100vh">
    <div class="wrapper">
      <sub-one-header :depart-id="currentDepartId"/>
      <main>
        <el-row :gutter="16">

          <el-col :span="6">
            <datav-card title="现场督察">
              <datav-tabs
                  v-model="subOneRcdcProRankTab"
                  type="bottom-button"
                  ref="subOneSceneInspRcdcProRankTabs"
              >
                <datav-tab-item label="派出所" name="1">
                  <el-row class="mb-32">
                    <el-col :span="6">
                      <div class="descriptions_cell text-center">
                        <div class="descriptions_content">
                          {{ leftOverview.proTotal }}
                        </div>
                        <div class="descriptions_label">
                          问题数
                        </div>
                      </div>
                    </el-col>
                    <el-col :span="6">
                      <div class="descriptions_cell text-center">
                        <div class="descriptions_content">
                          {{ leftOverview.changing }}
                        </div>
                        <div class="descriptions_label">
                          办理中
                        </div>
                      </div>
                    </el-col>
                    <el-col :span="6">
                      <div class="descriptions_cell text-center">
                        <div class="descriptions_content">
                          {{ leftOverview.changed }}
                        </div>
                        <div class="descriptions_label">
                          已办结
                        </div>
                      </div>
                    </el-col>
                    <el-col :span="6">
                      <div class="descriptions_cell text-center">
                        <div class="descriptions_content">
                          {{ leftOverview.correctionRate }}%
                        </div>
                        <div class="descriptions_label">
                          整改率
                        </div>
                      </div>
                    </el-col>
                  </el-row>
                  <el-scrollbar height="350px">
                    <datav-chart-bar
                        :data="fxsjChangedRankList"
                        size="small"
                        title="整改率排名"
                        sub-title="已办结/问题数"
                        unit="%"
                        :label-width="110"
                        :color="dayTimeColors"
                    />
                  </el-scrollbar>
                </datav-tab-item>
                <datav-tab-item label="大队" name="2">
                  <el-row class="mb-32">
                    <el-col :span="6">
                      <div class="descriptions_cell text-center">
                        <div class="descriptions_content">
                          {{ leftOverview.proTotal }}
                        </div>
                        <div class="descriptions_label">
                          问题数
                        </div>
                      </div>
                    </el-col>
                    <el-col :span="6">
                      <div class="descriptions_cell text-center">
                        <div class="descriptions_content">
                          {{ leftOverview.changing }}
                        </div>
                        <div class="descriptions_label">
                          办理中
                        </div>
                      </div>
                    </el-col>
                    <el-col :span="6">
                      <div class="descriptions_cell text-center">
                        <div class="descriptions_content">
                          {{ leftOverview.changed }}
                        </div>
                        <div class="descriptions_label">
                          已办结
                        </div>
                      </div>
                    </el-col>
                    <el-col :span="6">
                      <div class="descriptions_cell text-center">
                        <div class="descriptions_content">
                          {{ leftOverview.correctionRate }}%
                        </div>
                        <div class="descriptions_label">
                          整改率
                        </div>
                      </div>
                    </el-col>
                  </el-row>
                  <el-scrollbar height="350px">
                    <datav-chart-bar
                        :data="jsdwChangedRankList"
                        size="large"
                        title="整改率排名"
                        sub-title="已办结/问题数"
                        unit="%"
                        :label-width="110"
                        :color="dayTimeColors"
                    />
                  </el-scrollbar>
                </datav-tab-item>
              </datav-tabs>
            </datav-card>


            <datav-card title="问题涉及方面分布">
              <v-charts
                  style="height: 310px"
                  :option="wtlxPieOption"
                  autoresize
                  ref="subOneSceneProblemTypeRate"
              />
            </datav-card>
          </el-col>

          <el-col :span="12">
            <datav-date-picker v-model="time"/>
            <div class="flex gap-42">

              <datav-statistic
                  :value="overview.supervisionNotifyTotal"
                  title="通报问题数"
                  style="width: 16.66%"
              />
              <datav-statistic
                  :value="overview.reportNumber"
                  title="通报期数"
                  style="width: 16.66%"
                  @click="handleShow"
              />
              <datav-statistic
                  :value="overview.supervisionNotifyChangingTotal"
                  title="办理中"
                  style="width: 20%"
              />
              <datav-statistic
                  :value="overview.supervisionNotifyChangedTotal"
                  title="已办结"
                  style="width: 16.66%"
              />
              <datav-statistic
                  :value="overview.supervisionNotifyOrgTotal"
                  title="问责单位数"
                  style="width: 16.66%"
              />
              <datav-statistic
                  :value="overview.supervisionNotifyPreTotal"
                  title="问责人次"
                  style="width: 16.66%"
              />
            </div>
            <v-charts
                style="height: 450px"
                :option="option"
                autoresize
                ref="subOneSceneInspMapChart"
                @click="handleClick"
            />
            <datav-card title="问题趋势">
              <v-charts
                  style="height: 280px"
                  :option="proTrend"
                  autoresize
                  ref="subOneSceneInspProTrend"
              />
              <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>
              <datav-tabs v-model="subOneZxdcProRankTab" size="small" ref="subOneSceneInspZxdcProRankTabs">
                <template v-for="item in dictData" :key="item.dictValue">
                  <datav-tab-item
                     :label="item.dictLabel"
                    :name="item.dictValue"
                    >
                    <datav-tabs type="bottom-button">
                      <datav-tab-item label="派出所" name="1">
                        <el-row class="mb-32">
                          <el-col :span="6">
                            <div class="descriptions_cell text-center">
                              <div class="descriptions_content">
                                {{ fxsjYellowBetOverview.proTotal }}
                              </div>
                              <div class="descriptions_label">
                                问题数
                              </div>
                            </div>
                          </el-col>
                          <el-col :span="6">
                            <div class="descriptions_cell text-center">
                              <div class="descriptions_content">
                                {{ fxsjYellowBetOverview.changing }}
                              </div>
                              <div class="descriptions_label">
                                办理中
                              </div>
                            </div>
                          </el-col>
                          <el-col :span="6">
                            <div class="descriptions_cell text-center">
                              <div class="descriptions_content">
                                {{ fxsjYellowBetOverview.changed }}
                              </div>
                              <div class="descriptions_label">
                                已办结
                              </div>
                            </div>
                          </el-col>
                          <el-col :span="6">
                            <div class="descriptions_cell text-center">
                              <div class="descriptions_content">
                                {{ fxsjYellowBetOverview.correctionRate }}%
                              </div>
                              <div class="descriptions_label">
                                整改率
                              </div>
                            </div>
                          </el-col>
                        </el-row>
                        <el-scrollbar height="330px">
                          <datav-chart-bar
                              :data="fxsjYellowBetRankList"
                              size="large"
                              title="问题数排名"
                              sub-title="问题数"
                              :color="colors"
                              :label-width="110"
                          />
                        </el-scrollbar>
                      </datav-tab-item>
                      <datav-tab-item label="大队" name="2">
                        <el-row class="mb-32">
                          <el-col :span="6">
                            <div class="descriptions_cell text-center">
                              <div class="descriptions_content">
                                {{ jsdwYellowBetOverview.proTotal }}
                              </div>
                              <div class="descriptions_label">
                                问题数
                              </div>
                            </div>
                          </el-col>
                          <el-col :span="6">
                            <div class="descriptions_cell text-center">
                              <div class="descriptions_content">
                                {{ jsdwYellowBetOverview.changing }}
                              </div>
                              <div class="descriptions_label">
                                办理中
                              </div>
                            </div>
                          </el-col>
                          <el-col :span="6">
                            <div class="descriptions_cell text-center">
                              <div class="descriptions_content">
                                {{ jsdwYellowBetOverview.changed }}
                              </div>
                              <div class="descriptions_label">
                                已办结
                              </div>
                            </div>
                          </el-col>
                          <el-col :span="6">
                            <div class="descriptions_cell text-center">
                              <div class="descriptions_content">
                                {{ jsdwYellowBetOverview.correctionRate }}%
                              </div>
                              <div class="descriptions_label">
                                整改率
                              </div>
                            </div>
                          </el-col>
                        </el-row>
                        <el-scrollbar height="330px">
                          <datav-chart-bar
                              :data="jsdwYellowBetRankList"
                              size="large"
                              title="问题数排名"
                              sub-title="问题数"
                              :color="colors"
                              :label-width="110"
                          />
                        </el-scrollbar>
                      </datav-tab-item>
                    </datav-tabs>
                  </datav-tab-item>
                </template>
              </datav-tabs>
            </datav-card>
           <datav-card title="督察工作动态">
              <el-scrollbar height="310px" ref="subOneSceneScrollbar">
                <datav-message
                    v-for="(msg, index) in messages"
                    :key="index"
                    :type="msg.type"
                    :title="msg.workType"
                    :content="msg.contentTxt"
                    :date="msg.releaseTime"
                />
              </el-scrollbar>
            </datav-card>
          </el-col>

        </el-row>
      </main>
    </div>
  </el-scrollbar>
  <negative-info-depart-dialog v-model="showDialog" :departId="tempDepartId"/>


  <el-dialog v-model="show" width="70vw" title="通报报告" >
    <div class="table-container" v-loading="loading">
      <el-table
          :data="listData"
          ref="tableRef"
          style="width: 100%"
      >
        <el-table-column prop="reportName" label="督察报告名称"></el-table-column>
        <el-table-column prop="crtTime" label="创建时间" >
          <template #default="{row}">
            {{row.crtTime }}
          </template>
        </el-table-column>
        <el-table-column prop="superviseNumber" label="督察问题数">
          <template #default="{row}">
            <el-button type="primary" link @click="handleNegativeTable(row)">{{row.superviseNumber}}</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="flex end mt-8">
      <el-pagination
          @size-change="getReportList"
          @current-change="getReportList"
          :page-sizes="[10, 20, 50]"
          v-model:page-size="query.size"
          v-model:current-page="query.current"
          layout="total, sizes, prev, pager, next"
          :total="total"
      />
    </div>
  </el-dialog>

  <!--    督察报告关联问题-->
  <el-dialog :title="`督察报告关联问题`" v-model="negativeShow" width="90vw" >
    <el-table :data="negativeTable" v-loading="loading">
      <el-table-column
          label="问题录入时间"
          prop="crtTime"
          width="150"
          sortable="custom"
      />
      <el-table-column
          label="问题发现时间"
          prop="discoveryTime"
          width="150"
          sortable="custom"
      />
      <el-table-column
          label="问题来源"
          prop="problemSources"
          width="110"
          show-overflow-tooltip
      />
      <el-table-column
          label="业务类别"
          prop="businessTypeName"
          width="110"
      />
      <el-table-column
          label="问题内容"
          prop="thingDesc"
          show-overflow-tooltip
      />
      <el-table-column label="办理单位" show-overflow-tooltip>
        <template #default="{ row }">
                            <span
                            >{{ row.handleSecondDepartName
                              }}{{ row.handleThreeDepartName }}</span
                            >
        </template>
      </el-table-column>
      <el-table-column
          label="是否属实"
          prop="checkStatusName"
          width="100"
          align="center"
      />
      <el-table-column
          label="流程限时"
          width="150"
          align="center"
          v-if="remainingTimeFlag"
      >
        <template #default="{ row }">
          <countdown
              :time="row.remainingDuration"
              v-if="
                                    row.remainingDuration &&
                                    row.processingStatus !==
                                        ProcessingStatus.COMPLETED
                                "
          />
          <el-tag
              v-else-if="row.handleTimeout"
              type="danger"
              effect="dark"
          >办结超时
            {{ formatTimeText(row.handleTimeout) }}</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column label="办理状态" width="110">
        <template #default="{ row }">
          <el-tag
              :type="
                                    row.processingStatus ===
                                    ProcessingStatus.COMPLETED
                                        ? 'success'
                                        : 'primary'
                                "
              v-if="row.processingStatus"
          >{{
              getDictLable(
                  dict.processingStatus,
                  row.processingStatus
              )
            }}</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column
          label="当前处理对象"
          prop="currentProcessingObject"
          show-overflow-tooltip
      >
        <template #default="{ row }">
                            <span
                                v-if="
                                    row.processingStatus ===
                                    ProcessingStatus.COMPLETED
                                "
                            >无</span
                            >
          <span v-else>{{
              row.currentProcessingObject
            }}</span>
        </template>
      </el-table-column>
    </el-table>
    <div class="flex end mt-8">
      <el-pagination
          @size-change="getNegativePageFun"
          @current-change="getNegativePageFun"
          :page-sizes="[10, 20, 50, 100]"
          v-model:page-size="negativeQuery.size"
          v-model:current-page="negativeQuery.current"
          layout="total, sizes, prev, pager, next"
          :total="negativeTotal"
      >
      </el-pagination>
    </div>
  </el-dialog>

</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";

import {getSubOneStreetMap} from "@/api/screen/subScreen/subOneGlobal.ts";
import {
  getSubOneChangedRank,
  getSubOneProblemTypeRate, getSubOneSupervisionMap, getSubOneSupervisionNotifyCount,
  getSubOneSupervisionTrend, getSubOneWorkDynamics, getSubOneYellowBetDrug
} from "@/api/screen/subScreen/subOneSupervisionNotify.ts";
import {workDynamicColorMapping} from "@/enums/workDynamicColorMapping.js";
import SubOneHeader from "@/components/datav/subOne/subOneHeader.vue";
import useUserStore from "@/stores/modules/user";
import useCatchStore from "@/stores/modules/catch";
import {getSubListData,getNegativePageByQuery} from "@/api/superviseReport/superviseReport";
import {timeFormat,formatTimeText, getDictLable, getInvolveProblem} from "@/utils/util";
import {ProcessingStatus} from "@/enums/flowEnums";
const userStore = useUserStore();
const show =ref(false)
// region 所有变量
const time = ref([
  moment().startOf("year").format("YYYY-MM-DD"),
  moment().format("YYYY-MM-DD"),
]);
const route = useRoute();
let currentDepartId = route.query.departId;
const catchStore = useCatchStore();
const dict = catchStore.getDicts(["specialSupervision"]);
const dictData = computed(()=>{
  return dict?.specialSupervision?.filter((s)=>s.dictLabel !== '枪支管理')
})

const currentYear = new Date().getFullYear();
const years = ref([currentYear.toString(), (currentYear - 1).toString(), (currentYear - 2).toString()]); // 年份列表
const selectedYear = ref(currentYear); // 当前选中的年份

const overview = ref({
  correctionRate: 0,
  supervisionNotifyPreTotal: 0,
  supervisionNotifyChangingTotal: 0,
  supervisionNotifyChangedTotal: 0,
  supervisionNotifyTotal: 0,
  supervisionNotifyOrgTotal: 0,
});  // 中央数据总览
const leftOverview = ref({})
const fxsjRankOverview = ref({});  // 日常督察总览分县市局
const jsdwRankOverview = ref({});  // 日常督察总览局属单位
const fxsjChangedRankList = ref([]);  // 日常督察问题排行分县市局
const jsdwChangedRankList = ref([]);  // 日常督察问题排行局属单位
const wtlxList = ref([]);  // 问题涉及方面分布

const fxsjYellowBetOverview = ref({
  proTotal: 0,
  changing: 0,
  changed: 0,
  correctionRate: 0,
})  // 黄赌毒总览分县市局
const jsdwYellowBetOverview = ref({
  proTotal: 0,
  changing: 0,
  changed: 0,
  correctionRate: 0,
})  // 黄赌毒总览局属单位
const fxsjYellowBetRankList = ref([])  // 黄赌毒问题排行分县市局
const jsdwYellowBetRankList = ref([])  // 黄赌毒问题排行局属单位

const messages = ref([]);

const subOneZxdcProRankTab = ref("1"); // 专项督察问题排行tab
const subOneRcdcProRankTab = ref("1")
const subOneSceneInspRcdcProRankTabs = ref(null)
const subOneSceneProblemTypeRate = ref(null);
const subOneSceneInspMapChart = ref(null);
const subOneSceneInspProTrend = ref(null);
const subOneSceneInspZxdcProRankTabs = ref(null);
const subOneSceneScrollbar = ref(null);
const currentIndex = ref(0);
let subOneSceneInspRcdxIntervalId;
let subOneSceneProblemTypeRateIntervalId;
let subOneSceneInspMapIntervalId;
let subOneSceneInspTrendIntervalId;
let subOneSceneInspZxdxIntervalId;
let subOneSceneWorkDynamicsIntervalId;

const tempDepartId = ref(0);  // 临时部门id
const showDialog = ref(false);  // 负面信息弹窗显示
const rightOverview =ref({})
const getYellowBetDrugData = async (departId,times) => {
  const res = await getSubOneYellowBetDrug(departId, times,subOneZxdcProRankTab.value)
  rightOverview.value = res.overview;
  fxsjYellowBetOverview.value = res.fxsjYellowBetOverview
  jsdwYellowBetOverview.value = res.jsdwYellowBetOverview
  fxsjYellowBetRankList.value = res.fxsjYellowBetRankList
  jsdwYellowBetRankList.value = res.jsdwYellowBetRankList
};

watch(subOneZxdcProRankTab, () => {
  getYellowBetDrugData(currentDepartId, time.value)
})



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: 0,
  },
];
const dayTimeColors = [
  {
    color: "linear-gradient( 270deg, #63E700 0%, #19674C 100%)",

    percentage: 80,
  },
  {
    color: "linear-gradient( 270deg, #FFB90E 0%, #71501D 100%)",
    percentage: 75,
  },
  {
    color: "linear-gradient( 270deg, #FB002D 0%, #822232 100%)",
    percentage: 0,
  },
];

// endregion

// region 所有图表
echarts.registerMap("changsha", changshaMap);
const option = ref({
  tooltip: {
    trigger: 'item',
    position: 'bottom',
    formatter: function (params) {
      const dataItem = superviseTempMapVoList.value.find(item => item.name === params.name) || {}; // 找到对应的数据项

      if (dataItem.name === params.name) {
        return `
        <div class="tooltip">
          <div class="tooltip-title">${params.name}</div>
          <div class="tooltip-content">
            <ul class="tooltip-ul" >
              <li>通报问题数 <span>${dataItem.totalPro}</span></li>
              <li>办理中 <span>${dataItem.processingNumber}</span></li>
              <li>已办结 <span>${dataItem.completedNumber}</span></li>
              <li>问责单位数 <span>${dataItem.relationOrg}</span></li>
              <li>问责人次 <span>${dataItem.personNum}</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>-</span></li>
              <li>办理中 <span>-</span></li>
              <li>已办结 <span>-</span></li>
              <li>问责单位数 <span>-</span></li>
              <li>问责人次 <span>-</span></li>

            </ul>
          </div>
        </div>`;
      }
    },
  },
  visualMap: {
    type: "piecewise",
    bottom: 10,
    pieces: [
      {gte: 0, lte: 200, label: "低于平均问题30%", color: "#4987F6"},
      {gte: 200, lte: 400, label: "平均问题上下浮动30%内", color: "#F6A149"},
      {gte: 400, label: "高于平均问题30%", color: "#D34343"},],
    right: 10,
    realtime: false,
    orient: "horizontal",
    textStyle: {
      color: "#fff",
    },
    calculable: true,

  },
  series: [
    {
      name: "长沙",
      type: "map",
      map: "changsha",
      hoverAnimation: true,
      roam: true,
      label: {
        show: true,
        color: "white",
      },
      itemStyle: {
        normal: {
          areaColor: "#02215E",
          borderColor: "#24D2EE",
          borderWidth: 1 // 高亮时边框宽度
        },
      },
      emphasis: {
        areaColor: "#FFD700", // 高亮时区域颜色
        borderColor: "#FF0000", // 高亮时边框颜色
        borderWidth: 4 // 高亮时边框宽度
      },
      data: []
    }
  ],
})
const wtlxPieOption = computed(() => {
  return {
    tooltip: {
      trigger: "item",
    },
    series: [
      {
        type: "pie",
        radius: ["40%", "70%"],
        label: {
          color: "#fff",
        },
        data: wtlxList.value,
      },
    ],
  };
});
const superviseTempMapVoList = ref([]);
const proTrend = 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: [],
    },
  ],
});
// endregion

// region 所有函数
const getMapJSON = async (departId = currentDepartId) => {
  const res = await getSubOneStreetMap(departId)
  echarts.registerMap("changsha", res);
  subOneSceneInspMapChart.value.chart.setOption(option.value);
}
const getSubOneChangedRankData = async (departId, times) => {
  const res = await getSubOneChangedRank(departId, times)
  leftOverview.value =res.overview;
  fxsjRankOverview.value = res.fxsjRankOverview;
  jsdwRankOverview.value = res.jsdwRankOverview;
  fxsjChangedRankList.value = res.fxsjChangedRankList;
  jsdwChangedRankList.value = res.jsdwChangedRankList;
  console.log(res);

}
const getSubOneProblemTypeRateData = async (departId, times) => {
  const res = await getSubOneProblemTypeRate(departId, times)
  // wtlxList.value = circularChart;
  wtlxList.value = res.wtlxList
}
const getSubOneSupervisionNotifyCountData = async (departId, times) => {
  const res = await getSubOneSupervisionNotifyCount(departId, times)
  Object.assign(overview.value, {
    correctionRate: Number(res.overview.completedRate),
    supervisionNotifyPreTotal: Number(res.overview.personNumber),
    supervisionNotifyChangingTotal: Number(res.overview.processingNumber),
    supervisionNotifyChangedTotal: Number(res.overview.completedNumber),
    supervisionNotifyTotal: Number(res.overview.problemNumber),
    supervisionNotifyOrgTotal: Number(res.overview.departNumber),
    reportNumber: Number(res.overview.reportNumber)
  });
}
const getSubOneSupervisionMapData = async (departId, times) => {
  const res = await getSubOneSupervisionMap(departId, times);
  const mappedData = res.superviseTempMapVoList.map(item => {
    return {
      ...item,
      value: item.totalPro,
    };
  });
  const total = mappedData.reduce((sum, item) => sum + Number(item.value), 0);
  const avg = total / mappedData.length; // 计算平均值
  const range30Percent = avg * 0.3   // 不用取整，小数也可以
  option.value.visualMap.pieces = [
    {gte: 0, lte: avg - range30Percent, label: "低于平均问题30%", color: "#4987F6"},
    {gte: avg - range30Percent, lte: avg + range30Percent, label: "平均问题上下浮动30%内", color: "#F6A149"},
    {gte: avg + range30Percent, label: "高于平均问题30%", color: "#D34343"},
  ];
  superviseTempMapVoList.value = mappedData;
  option.value.series[0].data = mappedData;
}
const getSubOneSupervisionTrendData = async (departId, year) => {
  const res = await getSubOneSupervisionTrend(departId, year)
  const supervisionTrend = res.supervisionTrend;
  const categories = supervisionTrend.map(item => item.name);
  const values = supervisionTrend.map(item => item.value);
  proTrend.value.xAxis.data = categories;
  proTrend.value.series[0].data = values;
}
const getSubOneYellowBetDrugData = async (departId, times) => {
  const res = await getSubOneYellowBetDrug(departId, times)
  fxsjYellowBetOverview.value = res.fxsjYellowBetOverview
  jsdwYellowBetOverview.value = res.jsdwYellowBetOverview
  fxsjYellowBetRankList.value = res.fxsjYellowBetRankList
  jsdwYellowBetRankList.value = res.jsdwYellowBetRankList
}




const getSubOneWorkDynamicsData = async (departId, times) => {
  const data = await getSubOneWorkDynamics(departId, times);
  const colorNewsVoList = workDynamicColorMapping(data);
  messages.value = colorNewsVoList;
}
const getData = async () => {
 await Promise.all([
    getMapJSON(currentDepartId),
    getSubOneSupervisionMapData(currentDepartId, time.value),
    getSubOneChangedRankData(currentDepartId, time.value),
    getSubOneProblemTypeRateData(currentDepartId, time.value),
    getSubOneSupervisionNotifyCountData(currentDepartId, time.value),
    getSubOneSupervisionTrendData(currentDepartId, selectedYear.value),
    getYellowBetDrugData(currentDepartId, time.value),
    getSubOneWorkDynamicsData(currentDepartId, time.value)
  ]);
}

// endregion

// region 动画
// 日常督察问题排行动画
const subOneSceneInspRcdxRankAnimation = () => {
  subOneRcdcProRankTab.value = (parseInt(subOneRcdcProRankTab.value) % 2 + 1).toString();
};
subOneSceneInspRcdxIntervalId = setInterval(subOneSceneInspRcdxRankAnimation, 3000);
// 问题涉及方面分布
const subOneSceneProblemTypeRateAnimation = () => {
  const temp = subOneSceneProblemTypeRate?.value?.chart;
  if (!temp) return;
  const length = wtlxPieOption.value.series[0].data.length;
  const randomNum = Math.floor(Math.random() * length);
  temp?.dispatchAction({type: 'downplay', seriesIndex: 0});
  temp?.dispatchAction({type: 'highlight', seriesIndex: 0, dataIndex: randomNum}); // 显示
  temp?.dispatchAction({type: 'showTip', seriesIndex: 0, dataIndex: randomNum});
}
subOneSceneProblemTypeRateIntervalId = setInterval(subOneSceneProblemTypeRateAnimation, 2000);

// 地图动画
const subOneSceneInspMapAnimation = () => {
  const mapTemp = subOneSceneInspMapChart?.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,
  });
};
// 启动定时器，每隔 2 秒执行一次
subOneSceneInspMapIntervalId = setInterval(subOneSceneInspMapAnimation, 2000);
// 问题趋势动画
const subOneSceneInspTrendAnimation = () => {
  const trendTemp = subOneSceneInspProTrend?.value?.chart;
  if (!trendTemp) return;
  const randomNum = Math.floor(Math.random() * 12);
  trendTemp.dispatchAction({
    type: 'showTip',
    seriesIndex: 0,
    dataIndex: randomNum,
  });
}
subOneSceneInspTrendIntervalId = setInterval(subOneSceneInspTrendAnimation, 2000);
// // 专项督察问题排行动画  直接切换大tab，里面不管了
const subOneSceneInspZxdxRankAnimation = () => {
   const dictItem = dictData.value.find(
      (item) => (item.dictValue === subOneZxdcProRankTab.value)
  );
  if (dictItem) {
    const index = dictData.value.indexOf(dictItem);
    if (index === dictData.value.length - 1) {
      subOneZxdcProRankTab.value = dictData[0].dictValue;
    } else {
      subOneZxdcProRankTab.value = dictData[index + 1].dictValue;
    }
  }
};
subOneSceneInspZxdxIntervalId = setInterval(subOneSceneInspZxdxRankAnimation, 5000);
// 工作动态动画
const subOneSceneWorkDynamicsAnimation = () => {
  const sceneScrollTemp = subOneSceneScrollbar?.value;
  const maxScroll = sceneScrollTemp?.wrapRef?.scrollHeight - sceneScrollTemp?.wrapRef?.clientHeight;
  currentIndex.value > maxScroll ? currentIndex.value = 0 : currentIndex.value += 1;
  if (currentIndex.value === 0) {
    sceneScrollTemp?.scrollTo({top: currentIndex.value});
  } else {
    sceneScrollTemp?.scrollTo({top: currentIndex.value});
  }
}
subOneSceneWorkDynamicsIntervalId = setInterval(subOneSceneWorkDynamicsAnimation, 50);
// endregion

// region 监听
watch(time, () => {
  getData();
});
watch(()=>route.query.departId,(newVal)=>{
  if(newVal!= null){
    currentDepartId = newVal
  }else{
    currentDepartId=userStore.user.departId;
  }
},{immediate:true})
onMounted(() => {
  getData();
  setupEventListeners();
});
const handleCommand = (year) => {
  selectedYear.value = year; // 更新当前选中的年份
  getSubOneSupervisionTrendData(currentDepartId, selectedYear.value);
};
const handleClick = (params) => {
  const departId = params.data.departId;
  showDialog.value = true;
  tempDepartId.value = departId
  clearInterval(subOneGlobalMapIntervalId);
}

// 鼠标经过地图事件
const setupEventListeners = () => {
  subOneSceneInspRcdxRankAnimationStop();
  subOneSceneProblemTypeRateAnimationStop();
  subOneSceneInspMapAnimationStop();
  subOneSceneInspTrendAnimationStop();
  subOneSceneInspZxdxRankAnimationStop();
  subOneSceneWorkDynamicsAnimationStop();
};
const subOneSceneInspRcdxRankAnimationStop = () => {
  const temp = subOneSceneInspRcdcProRankTabs.value?.$el;
  temp.addEventListener('mouseenter', () => {
    clearInterval(subOneSceneInspRcdxIntervalId)
  });
  temp.addEventListener('mouseleave', () => {
    clearInterval(subOneSceneInspRcdxIntervalId);
    subOneSceneInspRcdxIntervalId = setInterval(subOneSceneInspRcdxRankAnimation, 3000);
  });
}
const subOneSceneProblemTypeRateAnimationStop = () => {
  const temp = subOneSceneProblemTypeRate?.value?.chart;
  temp.on('mousemove', (e) => {
    clearInterval(subOneSceneProblemTypeRateIntervalId);
    temp.dispatchAction({type: "downplay", seriesIndex: 0,});
    temp.dispatchAction({type: "highlight", seriesIndex: 0, dataIndex: e.dataIndex,});
    temp.dispatchAction({type: "showTip", seriesIndex: 0, dataIndex: e.dataIndex,});
  })
  temp.on('mouseout', () => {
    clearInterval(subOneSceneProblemTypeRateIntervalId);
    subOneSceneProblemTypeRateIntervalId = setInterval(subOneSceneProblemTypeRateAnimation, 2000);
  })
}
const subOneSceneInspMapAnimationStop = () => {
  const mapTemp = subOneSceneInspMapChart?.value?.chart;
  // 鼠标移入
  mapTemp.on('mousemove', (e) => {
    clearInterval(subOneSceneInspMapIntervalId);
    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(subOneSceneInspMapIntervalId); // 确保没有多个定时器同时运行
    subOneSceneInspMapIntervalId = setInterval(subOneSceneInspMapAnimation, 2000);
  });
}
const subOneSceneInspTrendAnimationStop = () => {
  const temp = subOneSceneInspProTrend?.value.getDom();
  temp.addEventListener('mouseenter', () => {
    clearInterval(subOneSceneInspTrendIntervalId);
  });
  temp.addEventListener('mouseleave', () => {
    clearInterval(subOneSceneInspTrendIntervalId);
    subOneSceneInspTrendIntervalId = setInterval(subOneSceneInspTrendAnimation, 2000);
  });
}
const subOneSceneInspZxdxRankAnimationStop = () => {
  const temp = subOneSceneInspZxdcProRankTabs.value?.$el;
  temp.addEventListener('mouseenter', () => {
    clearInterval(subOneSceneInspZxdxIntervalId)
  });
  temp.addEventListener('mouseleave', () => {
    clearInterval(subOneSceneInspZxdxIntervalId);
    subOneSceneInspZxdxIntervalId = setInterval(subOneSceneInspZxdxRankAnimation, 3000);
  });
}
const subOneSceneWorkDynamicsAnimationStop = () => {
  const temp = subOneSceneScrollbar.value?.$el;
  temp.addEventListener('mouseenter', () => {
    // alert(1);
    clearInterval(subOneSceneWorkDynamicsIntervalId)
  });
  temp.addEventListener('mouseleave', () => {
    clearInterval(subOneSceneWorkDynamicsIntervalId);
    subOneSceneWorkDynamicsIntervalId = setInterval(subOneSceneWorkDynamicsAnimation, 50);
  });
}

const handleShow =()=>{
  show.value=true
  getReportList()
}


const tableRef = ref(null)
const query = ref({
  current: 1,
  size: 10,
  departBranch:false
})
const listData = ref([]);
const total = ref(0);
const loading = ref(false);
/**
 * 获取表单数据
 * */
const getReportList =async ()=>{
  loading.value=true
  try{
    query.value.deptId=currentDepartId;
    const res = await  getSubListData(query.value);
    listData.value=res.records;
    total.value = res.total;
    loading.value = false
  }catch (e) {
    loading.value = false
  }
}
//督察问题
const negativeShow = ref(false)
const negativeTable = ref();
const negativeQuery = ref({
  current: 1,
  size: 10,
  departBranch:false
})
const negativeTotal = ref(0);
const negativeLoging = ref(false);
const handleNegativeTable =async (row)=>{
  if(row.superviseNumber > 0){
    try{
      negativeLoging.value=true;
      await getNegativePageFun(row);
      negativeShow.value = true;
    }catch (e){
      console.log("督察问题获取失败")
      negativeLoging.value=false;
    }
  }
}
const getNegativePageFun = async (row)=>{
  negativeQuery.value.id =row.id;
  const res = await getNegativePageByQuery(row);
  negativeTable.value =res.records;
  negativeTotal.value = res.total;
  negativeLoging.value=false;
}

// endregion
</script>

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

.message {
  padding: 10px;
  margin-bottom: 10px;
  background: linear-gradient(270deg, rgba(16, 151, 255, 0.1) 0%, rgba(0, 55, 236, 0.87) 100%);

  &[type=warning] {
    background: linear-gradient(270deg, rgba(255, 190, 16, 0.1) 0%, rgba(236, 84, 0, 0.87) 100%);
  }

  &[type=success] {
    background: linear-gradient(270deg, rgba(91, 216, 9, 0.14) 0%, #28813D 100%);
  }

  .message-title {
    font-size: 14px;
    margin-bottom: 10px;
  }

  .message-content {
    margin-bottom: 10px;
  }
}

:deep() {
  // 弹框整体
  .tooltip {
    position: relative;
    width: 160px;
    height: 194px;
    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: 150px;
    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; /* 水平居中 */
  }

  //.tooltip::before {
  //  content: '';
  //  position: absolute;
  //  top: 90px; /* 调整尖角的垂直位置 */
  //  left: -10px; /* 调整尖角的水平位置 */
  //  width: 0;
  //  height: 0;
  //  //border-top: 10px solid red; /* 顶边颜色 */
  //  //border-bottom: 10px solid green; /* 底边颜色 */
  //  //border-right: 10px solid blue; /* 右边颜色，与背景颜色相同 */
  //}

}

.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>
