<template>
  <el-scrollbar height="100vh">
    <div class="wrapper">
      <datav-header/>
      <main>
        <el-row :gutter="16">
          <el-col :span="6">
            <datav-card>
              <datav-tabs v-model="activeTab">
                <datav-tab-item label="维权案件情况" name="1">
                  <datav-tabs
                      ref="firstAndRepeat"
                      v-model="activeMailTab"
                      type="bottom-button"
                      title="案件数"
                  >
                    <datav-tab-item label="分县市局" name="1">
                      <el-scrollbar height="300px">
                        <datav-chart-bar
                            :data="countyRightsBarList"
                            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="bureauRightsBarList"
                            :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="activeMailTab"
                      type="bottom-button"
                  >
                    <datav-tab-item label="分县市局" name="1">
                      <el-scrollbar height="300px">
                        <datav-chart-bar
                            :data="countyComfortMoneyBarList"
                            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="bureauComfortMoneyBarList"
                            :max="11"
                            size="large"
                            :color="colors"
                        />
                      </el-scrollbar>
                    </datav-tab-item>
                  </datav-tabs>
                </datav-tab-item>
              </datav-tabs>
            </datav-card>

            <datav-card title="案件类别占比">

              <datav-tabs
                  v-model="activeMailTabCase"
                  type="bottom-button"
              >
                <datav-tab-item label="刑事案件" name="1">
                  <v-charts
                      style="height: 350px"
                      :option="xsajCaseTypeOption"
                      autoresize
                  />
                </datav-tab-item>
                <datav-tab-item label="行政案件" name="2">
                  <v-charts
                      style="height: 350px"
                      :option="xzajCaseTypeOption"
                      autoresize
                  />
                </datav-tab-item>
              </datav-tabs>
            </datav-card>
          </el-col>

          <el-col :span="12">
            <datav-date-picker v-model="time"/>
            <div class="flex gap-42">
              <datav-statistic
                  :value="overview.rightsNumber"
                  title="维权案件总数"
                  style="width: 20%"
              />
              <datav-statistic
                  :value="overview.victimNumber"
                  title="受侵害人数"
                  style="width: 20%"
              />
              <datav-statistic
                  :value="overview.hitPersonNumber"
                  title="打击处理人数"
                  style="width: 20%"
              />
              <datav-statistic
                  :value="overview.comfortPersonNumber"
                  title="抚慰人数"
                  style="width: 20%"
              />
              <datav-statistic
                  :value="overview.comfortMoney"
                  :title="`抚慰金额\n（万元）`"
                  :isDecimal="true"
                  style="width: 20%"
              />
            </div>
            <v-charts
                style="height: 360px"
                :option="option"
                autoresize
                @click="handleClick"
            />
            <el-row :gutter="20">
              <el-col :span="12">
                <datav-card title="打处情况">
                  <v-charts
                      style="height: 300px"
                      :option="punishmentSituationOption"
                      autoresize
                  />
                </datav-card>
              </el-col>
              <el-col :span="12">
                <datav-card title="抚慰情况">
                  <v-charts
                      style="height: 300px"
                      :option="comfortPoliceInjurySituation"
                      autoresize
                  />
                </datav-card>
              </el-col>
            </el-row>
          </el-col>

          <el-col :span="6">

            <datav-card title="民辅警受伤情况" sub-title="数量">
              <datav-tabs
                  v-model="comfortInjuryActiveMailTab"
                  type="bottom-button"
              >
<!--                <datav-tab-item label="受伤人数" name="1">-->
<!--                  <v-charts-->
<!--                      style="height: 310px;"-->
<!--                      :option="comfortPoliceInjurySituation"-->
<!--                      autoresize-->
<!--                  />-->
<!--                </datav-tab-item>-->
                <datav-tab-item label="受伤类別" name="1">
                  <v-charts
                      style="height: 310px;"
                      :option="comfortInjuryCategory"
                      autoresize
                  />
                </datav-tab-item>
              </datav-tabs>
            </datav-card>

            <datav-card title="发案情况占比">

              <datav-tabs
                  v-model="activeMailTabAriseCase"
                  type="bottom-button"
              >
                <datav-tab-item label="发案环节" name="1">
                  <v-charts
                      style="height: 350px"
                      :option="ariseCaseLinkOption"
                      autoresize
                  />
                </datav-tab-item>
                <datav-tab-item label="发案警种" name="2">
                  <v-charts
                      style="height: 350px"
                      :option="ariseCasePoliceOption"
                      autoresize
                  />
                </datav-tab-item>
                <datav-tab-item label="发案单位" name="3">
                  <v-charts
                      style="height: 350px"
                      :option="ariseCaseORgOption"
                      autoresize
                  />
                </datav-tab-item>

              </datav-tabs>


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

import {
  getComfortMapIcon,
  getRightsBarList,
  getComfortMoneyBarList,
  getCaseAriseSituationRate,
  getRightsComfortData,
  getPoliceHurtSituationAndHurtType,
  getComfortSituation
} from "@/api/screen/rightsComfort.ts";


// 数据
const router = useRouter();
const time = ref([
  moment().startOf("year").format("YYYY-MM-DD"),
  moment().format("YYYY-MM-DD"),
]);

const overview = ref({
  rightsNumber: 0,
  victimNumber: 0,
  hitPersonNumber: 0,
  comfortPersonNumber: 0,
  comfortMoney: 0
})
//维权（分县、局属）、抚慰饼图（分县、局属）
const activeMailTab = ref("1")

//案件类别占比(刑事、行政)
const activeMailTabCase = ref("1")

//发案情况占比(发案环节、发案警种、发案单位)
const activeMailTabAriseCase = ref("1")
//民辅警受伤情况（受伤类型）
const comfortInjuryActiveMailTab = ref("1")

/**
 * //维权（分县、局属）、抚慰饼图（分县、局属）
 * 切换动画
 * */
let activeMailTabIntervalId;
const activeMailTabRepeatAnimation = () => {
  activeMailTab.value = (parseInt(activeMailTab.value) % 2 + 1).toString();
};
activeMailTabIntervalId = setInterval(activeMailTabRepeatAnimation, 3000);
/**
 * 绑定自动事件
 * */
let firstAndRepeat =ref(null)
const activeMailTabAnimationStop = () => {

  const temp = firstAndRepeat.value.$el;
  temp.addEventListener('mouseenter', () => {
    clearInterval(activeMailTabIntervalId)
  });
  temp.addEventListener('mouseleave', () => {
    activeMailTabIntervalId = setInterval(activeMailTabRepeatAnimation, 3000);
  });
}
const countyRightsBarList = ref([
  {
    label: "岳麓分局",
    value: 23
  },
  {
    label: "芙蓉分局",
    value: 20
  },
  {
    label: "天心分局",
    value: 20
  },
  {
    label: "雨花分局",
    value: 19
  },
  {
    label: "浏阳市局",
    value: 17
  },
  {
    label: "宁乡市局",
    value: 11
  },
  {
    label: "开福分局",
    value: 11
  },
  {
    label: "望城分局",
    value: 9
  },
  {
    label: "长沙县局",
    value: 9
  },
  {
    label: "高新分局",
    value: 4
  }
]);
// 局属单位维权案件情况
const bureauRightsBarList = ref([
  {
    label: "交警支队",
    value: 27
  }
]);
// 抚慰金情况
const countyComfortMoneyBarList = ref([])
const bureauComfortMoneyBarList = ref([])
// 打处情况
const punishmentSituationOption = ref({
  series: [
    {
      type: "pie",
      radius: ["40%", "70%"],
      label: {
        color: "#fff",
      },
      data: [],
    },
  ],
  tooltip: {
    trigger: "item",
  },
});

// 抚慰情况
const comfortPoliceInjurySituation = ref(
  {
  series: [
    {
      type: "pie",
      radius: ["40%", "70%"],
      label: {
        color: "#fff",
      },
      data: [],
    },
  ],
  tooltip: {
    trigger: "item",
  },
}
);

// 民辅警受伤类别
const comfortInjuryCategory = ref(
  {
  series: [
    {
      type: "pie",
      radius: ["40%", "70%"],
      label: {
        color: "#fff",
      },
      data: [],
    },
  ],
  tooltip: {
    trigger: "item",
  },
}
);
function getData() {
  // 维权案件情况
  getRightsBarListFun();
  // 抚慰金额情况
  getComfortMoneyBarListFun();
  getRightsComfortData(time.value).then(data => {
    overview.value.rightsNumber = data.rightsNumber
    overview.value.victimNumber = data.victimNumber
    overview.value.hitPersonNumber = data.hitPersonNumber
    overview.value.comfortPersonNumber = data.comfortPersonNumber
    overview.value.comfortMoney = data.comfortMoney
    punishmentSituationOption.value.series[0].data = data.punishmentSituation
    // comfortPoliceInjurySituation.value.series[0].data = data.comfortPoliceInjurySituation
    // comfortInjuryCategory.value.series[0].data = data.comfortInjuryCategory
    xsajCaseTypeOption.value.series[0].data =  data.crownCaseBarList;
    xzajCaseTypeOption.value.series[0].data =  data.administrativeCaseList;
  })
  // 抚慰情况
  getComfortSituationFun();
  // 受伤情况
  getPoliceHurtSituationAndHurtTypeFun();
  // 发案情况占比
  getCaseAriseSituationRateFun();
  // 地图数据
  getMapData(time.value)
}

watch(time, () => {
  getData();
})
onMounted(() => {
  getData();
});

// region 数据获取函数
/**
 * 维权抚慰一级 维权案件情况
 * @param body
 */
const getRightsBarListFun = async() =>{
  const body = {
    beginTime: time.value[0],
    endTime: time.value[1]
  }
  const res = await getRightsBarList(body);
  countyRightsBarList.value = res.countyRightsBarList;
  bureauRightsBarList.value = res.bureauRightsBarList;
}

/**
 * 维权抚慰一级 抚慰金额情况
 * @param body
 */
const getComfortMoneyBarListFun = async() =>{
  const body = {
    beginTime: time.value[0],
    endTime: time.value[1]
  }
  const res = await getComfortMoneyBarList(body);
  countyComfortMoneyBarList.value = res.countyComfortMoneyBarList;
  bureauComfortMoneyBarList.value = res.bureauComfortMoneyBarList;
}


/**
 * 维权抚慰一级 抚慰情况
 * @param body
 */
const getComfortSituationFun = async ()=>{
  const body = {
    beginTime: time.value[0],
    endTime: time.value[1]
  }

  const res = await getComfortSituation(body);
  comfortPoliceInjurySituation.value.series[0].data = res.comfortPoliceInjurySituation
}
/**
 * 维权抚慰一级 民辅警受伤情况
 * @param body
 */
const getPoliceHurtSituationAndHurtTypeFun = async ()=>{
  const body = {
    beginTime: time.value[0],
    endTime: time.value[1]
  }
  const res = await getPoliceHurtSituationAndHurtType(body);
  comfortInjuryCategory.value.series[0].data = res.comfortInjuryCategory
}

/**
 * 维权抚慰一级 发案情况占比
 * @param body
 */
const getCaseAriseSituationRateFun = async ()=>{
  const body = {
    beginTime: time.value[0],
    endTime: time.value[1]
  }
  const res = await getCaseAriseSituationRate(body);
  ariseCaseLinkOption.value.series[0].data = res.incidentLinkList
  ariseCasePoliceOption.value.series[0].data = res.incidentPoliceTypeList
  ariseCaseORgOption.value.series[0].data = res.incidentOrgList
}



// endregion


let globalTempMapVoList = ref([]);

// 地图数据
const getMapData = async (timeValue) => {
  const res = await getComfortMapIcon(timeValue);
  console.log('后端返回原始数据:', res.comfortMapVoList);
  const mappedData = res.comfortMapVoList?.map(item => {
    let name;
    switch (item.name) {
      case '长沙县局':
        name = '长沙县';
        break;
      case '芙蓉分局':
        name = '芙蓉区';
        break;
      case '天心分局':
        name = '天心区';
        break;

      case '湘江新区公安局':
        name = '湘江新区';
        break;
      case '开福分局':
        name = '开福区';
        break;
      case '雨花分局':
        name = '雨花区';
        break;
      case '望城分局':
        name = '望城区';
        break;
      case '宁乡市局':
        name = '宁乡市';
        break;
      case '浏阳市局':
        name = '浏阳市';
        break;
      case '高新分局':
        name = '高新区';
        break;
      default:
        name = item.name;
        break;
    }
    return {
      ...item,
      originalName: setNameFun(item.name), // 添加原始名称
      name: name,
      value: item.rightsNumber,
    };
  });
  console.log('转换后数据:', mappedData);
  globalTempMapVoList.value = mappedData

  const maxItem = mappedData.reduce(
      (max, item) => (Number(item.rightsNumber) > Number(max.rightsNumber) ? item : max),
      mappedData[0]
  );
  const range60Percent = maxItem.rightsNumber * 0.6;
  const range80Percent = maxItem.rightsNumber * 0.8;
  console.log('mappedData',mappedData)
  option.value.series[0].data = mappedData;
  console.log('option series data:', option.value.series[0].data);
  option.value.visualMap.pieces = [
    {gte: 0, lte: range60Percent, label: "低于最大维权案件60%", color: "#4987F6"},
    {gte: range60Percent, lte: range80Percent, label: "介于最大维权案件60%~80%", color: "#F6A149"},
    {gte: range80Percent, label: "高于最大维权案件80%", color: "#D34343"},
  ];
}



const handleClick = (params) => {
  console.log('点击事件参数:', params);
// 1) 直接点到有 data 的区域
  let departId = params?.data?.departId;
  // 2) 点到 geo / data 匹配不上：用 name 反查
  if (!departId) {
    const hit = globalTempMapVoList.value.find((item) =>
        item.name?.includes(params?.name?.substring?.(0, 2))
    );
    departId = hit?.departId;
  }
  if (!departId) {
    ElMessage({
      message: "数据加载中，请稍后再试",
      type: "warning",
      duration: 1500,
    });
    return;
  }
  const url = router.resolve({
    path: "/datav/subOneRightsComfort",
    query: {departId: departId},
  }).href;
  window.open(url, "_blank");
}

// region 所有图表
echarts.registerMap("changsha", changshaMap);
const option = ref({
  geo: {
    map: "changsha",
    itemStyle: {
      opacity: 0,
    },
  },
  tooltip: {
    trigger: 'item',
    formatter: function (params) {
      const dataItem = globalTempMapVoList.value.find(item => item.name.includes(params.name.substring(0, 2)));
      if (dataItem) {
        return `
        <div class="tooltip">
          <div class="tooltip-title">${dataItem.name}</div>
          <div class="tooltip-content">
            <ul class="tooltip-ul" >
              <li>维权案件总数 <span>${dataItem.rightsNumber }</span></li>
              <li>受侵害人数 <span>${dataItem.victimNumber}</span></li>
              <li>抚慰人数 <span>${dataItem.comfortPersonNumber}</span></li>
              <li>打击处理人数 <span>${dataItem.hitPersonNumber}</span></li>
              <li>抚慰金额 <span>${dataItem.comfortMoney|| '-'}</span></li>
            </ul>
          </div>
        </div>`;
      } else {
        return `<div class="tooltip">
          <div class="tooltip-title">${dataItem?dataItem.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: [],
    right: 10,
    realtime: false,
    orient: "horizontal",
    textStyle: {
      color: "#fff",
    },
    calculable: true,
    inRange: {
      color: ["#4987F6", "#F6A149", "#D34343",],
    },
  },
  series: [
    {
      name: "长沙",
      type: "map",
      map: "changsha",
      roam: true,
      label: {
        show: true,
        color: "white",
      },
      itemStyle: {
        areaColor: "#02215E",
        borderColor: "#24D2EE",
        borderWidth: 1,
        opacity: 1,
      },
      emphasis: {
        areaColor: "#FFD700",
        borderColor: "#FF0000",
        borderWidth: 4,
      },
      data: []
    }
  ],
})
const xsajCaseTypeOption = ref({
  series: [
    {
      type: "pie",
      radius: ["40%", "70%"],
      label: {
        color: "#fff",
      },
      data: [

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

      ],
    },
  ],
  tooltip: {
    trigger: "item",
  },
});


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

      ],
    },
  ],
  tooltip: {
    trigger: "item",
  },
});

function  setNameFun(name){
  if(name == '湘江新区公安局'){
    return '湘江新区'
  }
  return name;
}
const hurtTypeOption = ref({
  series: [
    {
      type: "pie",
      radius: ["30%", "50%"],
      label: {
        color: "#fff",
      },
      tooltip: {
        trigger: "item",
      },
      data: [

      ],

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

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

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

      ],
    },
  ],
  tooltip: {
    trigger: "item",
  },
});
// endregion

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,
  },
];

</script>

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


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