<template>
  <div style="height:100vh; min-height:1080px;">
    <!-- 头部 -->
    <div class="header">
      <h1 style="color: #77F8FF;">惠州市就业驿站大数据</h1>
      <div class="time">{{ formattedTime }}</div>
    </div>

    <!-- 内容区 -->
    <div class="body-content">
      <!-- 左 -->
      <div class="side" style="padding-left: 20px;">
        <div class="content-box">
          <div class="box-title">驿站运行情况</div>
          <div class="chart-box" id="yearSystemApplyBox"></div>
        </div>
        <div class="content-box">
          <div class="box-title">就业情况</div>
          <div class="chart-box" id="employedCountBox"></div>
        </div>
        <div class="content-box">
          <div class="box-title">区县就业困难人员</div>
          <div class="chart-box" id="ordinaryDifficultyCountBox"></div>
        </div>
      </div>

      <!-- 中 -->
      <div class="center">
        <div class="center-1">
          <div class="nav">
            <div class="nav-items nav-active">
              <div class="nav-1"></div>
              <h2 style="color: #77F8FF;">总体概况</h2></div>
            <div class="nav-items" @click="goCompany">
              <div class="nav-2"></div>
              <h2 style="color: #77F8FF;">企业情况</h2></div>
            <div class="nav-items" @click="goJobUser">
              <div class="nav-3"></div>
              <h2 style="color: #77F8FF;">求职情况</h2></div>
            <div class="nav-items">
              <div class="nav-4"></div>
              <h2 style="color: #77F8FF;">服务情况</h2></div>
          </div>
          <div class="s-box">
            <div class="statistics t-1">
              <div style="margin: 8px 0 0 18px; position: revert;">
                <div class="s-title">岗位数</div>
                <div class="s-number">{{ allSystemDataCountList.count.postCount }}</div>
                <div class="waves" style="right: -187px; top: 42px"></div>
              </div>
            </div>
            <div class="statistics t-2">
              <div style="margin: 8px 0 0 78px; position: revert;">
                <div class="s-title">企业数</div>
                <div class="s-number">{{ allSystemDataCountList.count.companyCount }}</div>
                <div class="waves" style="left: -86px; top: 42px"></div>
              </div>
            </div>
            <div class="statistics t-3">
              <div style="margin: 78px 0 0 98px; position: revert;">
                <div class="s-title">求职人员数</div>
                <div class="s-number">{{ allSystemDataCountList.count.jobUserCount }}</div>
                <div class="waves" style="left: -106px; top: -141px"></div>
              </div>
            </div>
          </div>
        </div>
        <div class="center-2">
          <div class="box-bigtitle">全市情况一览</div>
          <div class="chart-box" id="allSystemDatBox"></div>
        </div>
      </div>

      <!-- 右 -->
      <div class="side" style="padding-right: 20px;">
        <div class="content-box">
          <div class="box-title">区县服务榜</div>
          <div class="chart-box">
            <div class="tab-content" style="margin-bottom: 40px;">
              <div class="tab-item" :class="{'tab-active': regionTabAct == 'all'}" @click="changeRegionTab('all')">
                总榜
              </div>
              <div class="tab-item" :class="{'tab-active': regionTabAct == 'month'}" @click="changeRegionTab('month')">
                月榜
              </div>
              <div class="tab-item" :class="{'tab-active': regionTabAct == 'week'}" @click="changeRegionTab('week')">
                周榜
              </div>
            </div>
            <div class="ranking-1">
              <div class="ranking-1-item NO2">
                <div class="ranking-1-item-name">{{ regionServiceData.second.regionName }}</div>
                <div class="ranking-1-item-number">{{ regionServiceData.second.count }}</div>
              </div>
              <div class="ranking-1-item NO1">
                <div class="ranking-1-item-name">{{ regionServiceData.first.regionName }}</div>
                <div class="ranking-1-item-number">{{ regionServiceData.first.count }}</div>
              </div>
              <div class="ranking-1-item NO3">
                <div class="ranking-1-item-name">{{ regionServiceData.third.regionName }}</div>
                <div class="ranking-1-item-number">{{ regionServiceData.third.count }}</div>
              </div>
            </div>
          </div>
        </div>
        <div class="content-box">
          <div class="box-title">驿站服务榜</div>
          <div class="chart-box">
            <div class="tab-content">
              <div class="tab-item" :class="{'tab-active': siteTabAct == 'all'}" @click="changeSiteTab('all')">总榜
              </div>
              <div class="tab-item" :class="{'tab-active': siteTabAct == 'month'}" @click="changeSiteTab('month')">月榜
              </div>
              <div class="tab-item" :class="{'tab-active': siteTabAct == 'week'}" @click="changeSiteTab('week')">周榜
              </div>
            </div>
            <div class="ranking-2">
              <div class="ranking-2-item">
                <div class="ranking-number">1</div>
                <div class="ranking-column" style="width:60%;">
                  {{ siteServiceData[0] ? siteServiceData[0].count : '' }}
                </div>
                <div class="ranking-name">{{ siteServiceData[0] ? siteServiceData[0].siteName : '' }}</div>
              </div>
              <div class="ranking-2-item">
                <div class="ranking-number">2</div>
                <div class="ranking-column" style="width:50%;">
                  {{ siteServiceData[1] ? siteServiceData[1].count : '' }}
                </div>
                <div class="ranking-name">{{ siteServiceData[1] ? siteServiceData[1].siteName : '' }}</div>
              </div>
              <div class="ranking-2-item">
                <div class="ranking-number">3</div>
                <div class="ranking-column" style="width:40%;">
                  {{ siteServiceData[2] ? siteServiceData[2].count : '' }}
                </div>
                <div class="ranking-name">{{ siteServiceData[2] ? siteServiceData[2].siteName : '' }}</div>
              </div>
              <div class="ranking-2-item">
                <div class="ranking-number">4</div>
                <div class="ranking-column" style="width:30%;">
                  {{ siteServiceData[3] ? siteServiceData[3].count : '' }}
                </div>
                <div class="ranking-name">{{ siteServiceData[3] ? siteServiceData[3].siteName : '' }}</div>
              </div>
              <div class="ranking-2-item">
                <div class="ranking-number">5</div>
                <div class="ranking-column" style="width:20%;">
                  {{ siteServiceData[4] ? siteServiceData[4].count : '' }}
                </div>
                <div class="ranking-name">{{ siteServiceData[4] ? siteServiceData[4].siteName : '' }}</div>
              </div>
            </div>
          </div>
        </div>
        <div class="content-box">
          <div class="box-title">驿站实时服务</div>
          <div class="chart-box">
            <div class="text-list">
              <div class="text-list-item" v-for="(item, key) in systemServiceList" :key="key">
                <div class="list-left">{{ item.serviceContent }}</div>
                <div class="list-right">{{ dayjs(item.serviceTime).format("MM-DD HH:mm:ss") }}</div>
              </div>
            </div>
            <div class="text-list">
              <div class="text-list-item" v-for="(item, key) in systemServiceList" :key="key">
                <div class="list-left">{{ item.serviceContent }}</div>
                <div class="list-right">{{ dayjs(item.serviceTime).format("MM-DD HH:mm:ss") }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  getEmployedJobUserCount,
  getJobUserByRegionAndDifficulty,
  getSystemApplyCountBySite,
  getYearSystemDataCount
} from "@/api/statistics";
import {computed, onBeforeUnmount, onMounted, reactive, ref} from "vue";
import {
  initDataSetBarImageTable,
  initLineImageTable,
  initRingPieImageTable,
  PieColorData
} from "@/views/dataScreen/echarts";
import dayjs from "dayjs";
import weekOfYear from 'dayjs/plugin/weekOfYear';
import weekday from 'dayjs/plugin/weekday';
import {getSystemServiceList} from "@/api/jobUserManager/jobuser/jobUserService";
import {useRouter} from "vue-router";

dayjs.extend(weekOfYear);
dayjs.extend(weekday);

const router = useRouter();

// 查询参数
const searchParams = reactive({
  monthStartDate: "",
  monthEndDate: "",
  weekStartDate: "",
  weekEndDate: "",
})
// 系统年度使用情况
const yearSystemDataCountList = ref([]);
// 全市数据情况
const allSystemDataCountList = ref({
  count: {
    companyCount: 0,
    postCount: 0,
    jobUserCount: 0
  },
  list: []
});
// 普通求职者与就业困难人员
const ordinaryDifficultyUser = ref([]);
// 已就业人数
const employedData = ref({
  count: 0,
  list: []
})
// 区县榜当前显示tab
const regionTabAct = ref("all");
// 区县服务榜数据
const regionServiceData = reactive({
  first: {
    regionName: "",
    count: 0,
  },
  second: {
    regionName: "",
    count: 0,
  },
  third: {
    regionName: "",
    count: 0,
  }
});
// 驿站榜当前显示tab
const siteTabAct = ref("all");
// 驿站服务榜数据
const siteServiceData = ref<Array<any>>([]);
// 系统服务记录信息
const systemServiceList = ref<Array<any>>([]);
// 实时时间
const currentTime = ref(new Date());
const formattedTime = computed(() => {
  const days = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
  const year = currentTime.value.getFullYear();
  const month = (currentTime.value.getMonth() + 1).toString().padStart(2, '0');
  const date = currentTime.value.getDate().toString().padStart(2, '0');
  const day = days[currentTime.value.getDay()];
  const hours = currentTime.value.getHours().toString().padStart(2, '0');
  const minutes = currentTime.value.getMinutes().toString().padStart(2, '0');
  // const seconds = currentTime.value.getSeconds().toString().padStart(2, '0');

  return `${year}-${month}-${date} ${day} ${hours}:${minutes}`;
});

// 获取年度使用数据
function loadYearData() {
  const currentYear = new Date().getFullYear();
  getYearSystemDataCount({year: currentYear}).then((result: any) => {
    yearSystemDataCountList.value = result;
    let regionNameList = new Array<any>();
    let yearNameList = new Array<any>();

    // 获取到区县名称信息
    if (yearSystemDataCountList.value && Object.keys(yearSystemDataCountList.value).length > 0) {
      // 获取到查询结果Map中的第一个键值对，解析获取到县区信息，填充进初始数组中
      yearSystemDataCountList.value[Object.keys(yearSystemDataCountList.value)[0]].forEach((item: any) => {
        if (item.regionCode != 100) {
          regionNameList.push(item.regionName);
        }
      });
    }
    // 初始化折线图数据
    let yearLineData = [
      {
        name: '驿站人员',
        type: 'line',
        data: new Array<any>(),
        symbol: 'circle',
        itemStyle: {
          color: '#f6b400'
        }
      },
      {
        name: '企业数量',
        type: 'line',
        data: new Array<any>(),
        symbol: 'circle',
        itemStyle: {
          color: "#006efe"
        }
      },
      {
        name: '岗位数量',
        type: 'line',
        data: new Array<any>(),
        symbol: 'circle',
        itemStyle: {
          color: "#6cd300"
        }
      },
      {
        name: '求职人数',
        type: 'line',
        data: new Array<any>(),
        symbol: 'circle',
        itemStyle: {
          color: "#76f7fe"
        }
      },
    ]

    // 解析1到12月的统计数据
    for (let i = 1; i <= 12; i++) {
      if (yearSystemDataCountList.value[i + '月']) {
        yearNameList.push(i + '月');

        // 查询获取到每周的合计总数，填充进折线图数据中
        const hjData = yearSystemDataCountList.value[i + '月'].find(item => item.regionCode == '100');
        if (hjData) {
          yearLineData[0].data.push(hjData.siteUserCount);
          yearLineData[1].data.push(hjData.companyCount);
          yearLineData[2].data.push(hjData.postCount);
          yearLineData[3].data.push(hjData.jobUserCount);
        }
      }
    }

    // 初始化图表
    initLineImageTable(yearNameList, yearLineData, ["驿站人员", "企业数量", "岗位数量", "求职人数"], "yearSystemApplyBox");
  })
}

// 获取已就业人数
function loadEmployedUser() {
  getEmployedJobUserCount().then((result: any) => {
    employedData.value.list = result;

    let arr = new Array<any>();
    result.forEach((item: any) => {
      if (item.regionName != "市本级") {
        employedData.value.count += item.jobUserCount;
        let data = {
          value: item.jobUserCount,
          name: item.regionName,
          itemStyle: {
            color: PieColorData[item.regionName]
          }
        };
        arr.push(data);
      }
    })

    // 设置中间的文本
    const graphicChildren = [
      {
        type: 'text',
        left: 'center',
        top: '43%',
        style: {
          fill: 'rgba(119,248,255,0.7)',
          text: '已就业人数',
          font: 'bold 12px Arial',
          textAlign: 'center'
        }
      },
      {
        type: 'text',
        left: 'center',
        top: '53%',
        style: {
          fill: '#77F8FF',
          text: employedData.value.count,
          font: 'bold 16px Arial',
          textAlign: 'center'
        }
      }
    ]

    // 生成图表
    initRingPieImageTable(arr, graphicChildren, "employedCountBox", "已就业人数", 10);
  })
}

// 获取区县普通求职人员与就业困难人员
function loadDifficultyUser() {
  getJobUserByRegionAndDifficulty({}).then((result: any) => {
    // 保存原始数据
    ordinaryDifficultyUser.value = result;

    let arr: any[] = [];
    arr.push(['类型', '失业人数', '就业困难人数'])
    result.forEach((item: any) => {
      if (item.regionName != "市本级") {
        arr.push([item.regionName, item.jobUserCount, item.difficultyCount]);
      }
    })

    initDataSetBarImageTable(arr, [{type: 'bar', barMaxWidth: '10px', color: "#0062cc"}, {
      type: 'bar',
      barMaxWidth: '10px',
      color: '#73ecf3'
    }], 'ordinaryDifficultyCountBox', 3)
  })
}

// 获取年度使用数据
function loadAllData() {
  getYearSystemDataCount({}).then((result: any) => {
    allSystemDataCountList.value.list = result['汇总'];
    allSystemDataCountList.value.count = result['汇总'].filter(item => item.regionCode == '100')[0];

    let arr = new Array<any>();
    arr.push(['类型', '企业数', '岗位数', "求职人员数"]);
    result['汇总'].forEach((item: any) => {
      if (item.regionName != '合计' && item.regionName != '市本级') {
        arr.push([item.regionName, item.companyCount, item.postCount, item.jobUserCount]);
      }
    })

    initDataSetBarImageTable(arr,
      [
        {type: 'bar', barMaxWidth: '15px', color: "#0062cc"},
        {type: 'bar', barMaxWidth: '15px', color: '#73ecf3'},
        {type: 'bar', barMaxWidth: '15px', color: '#67ca00'},
      ], 'allSystemDatBox', 6)
  })
}

// 查询区县服务榜
function loadRegionTop(params: any) {
  getYearSystemDataCount(params).then((result: any) => {
    let countMap: { [key: string]: number } = {}
    result['汇总'].forEach((item: any) => {
      if (item.regionName != '市本级' && item.regionName != '合计') {
        countMap[item.regionName] = item.companyCount + item.postCount + item.jobUserCount;
      }
    })
    // 按相加结果的大小进行排序，分别获取前三名
    const topThreeRegions = Object.entries(countMap)
      .sort((a, b) => b[1] - a[1])
      .slice(0, 3);

    // 保存到regionServiceData变量中
    if (topThreeRegions.length > 0) {
      regionServiceData.first.regionName = topThreeRegions[0][0];
      regionServiceData.first.count = topThreeRegions[0][1];
    }
    if (topThreeRegions.length > 1) {
      regionServiceData.second.regionName = topThreeRegions[1][0];
      regionServiceData.second.count = topThreeRegions[1][1];
    }
    if (topThreeRegions.length > 2) {
      regionServiceData.third.regionName = topThreeRegions[2][0];
      regionServiceData.third.count = topThreeRegions[2][1];
    }
  })
}

// 改变区县服务榜展示的tab
function changeRegionTab(value: any) {
  regionTabAct.value = value;
  if (value == 'all') {
    // 查询总榜
    loadRegionTop({});
  }
  if (value == 'month') {
    // 查询月榜
    loadRegionTop({startDate: searchParams.monthStartDate, endDate: searchParams.monthEndDate});
  }
  if (value == 'week') {
    // 查询周榜
    loadRegionTop({startDate: searchParams.weekStartDate, endDate: searchParams.weekEndDate});
  }
}

// 查询驿站服务榜
function loadSiteTop(params: any) {
  getSystemApplyCountBySite(params).then((result: any) => {
    let countMap: { [key: string]: number } = {}
    result.forEach((item: any) => {
      if (item.regionName != '市本级' && item.siteName != '惠州市就业驿站') {
        countMap[item.siteName] = item.companyCount + item.postCount + item.jobUserCount;
      }
    })
    siteServiceData.value = Object.entries(countMap)
      .sort((a, b) => b[1] - a[1])
      .slice(0, 5)
      .map(entry => ({siteName: entry[0], count: entry[1]}));
  })
}

// 改变驿站服务榜展示的tab
function changeSiteTab(value: any) {
  siteTabAct.value = value;
  if (value == 'all') {
    loadSiteTop({});
  }
  if (value == 'month') {
    // 查询月榜
    loadSiteTop({startDate: searchParams.monthStartDate, endDate: searchParams.monthEndDate});
  }
  if (value == "week") {
    // 查询周榜
    loadSiteTop({startDate: searchParams.weekStartDate, endDate: searchParams.weekEndDate})
  }
}

// 加载服务记录
function loadSystemService() {
  getSystemServiceList().then((result) => {
    systemServiceList.value = result;
  })
}

function updateTime() {
  currentTime.value = new Date();
}

// 跳转企业面板
function goCompany() {
  router.push({name: "dataScreenCompany"})
}

// 跳转求职人员面板
function goJobUser() {
  router.push({name: "dataScreenJobUser"})
}

onMounted(() => {
  const now = dayjs();
  searchParams.monthStartDate = now.startOf('month').format('YYYY-MM-DD');
  searchParams.monthEndDate = now.endOf('month').format('YYYY-MM-DD');
  searchParams.weekStartDate = now.startOf('week').weekday(1).format('YYYY-MM-DD');
  searchParams.weekEndDate = now.endOf('week').weekday(7).format('YYYY-MM-DD');

  loadYearData();
  loadDifficultyUser();
  loadEmployedUser();
  loadAllData();
  setInterval(loadAllData, 1000 * 60 * 5)
  changeRegionTab("all");
  changeSiteTab("all");
  loadSystemService();
  setInterval(loadSystemService, 1000 * 60 * 5);
  updateTime();
  const timer = setInterval(updateTime, 1000);
  onBeforeUnmount(() => {
    clearInterval(timer);
  });
})

</script>

<style scoped>
@import url('@/views/dataScreen/html/css/reset.css');
@import url('@/views/dataScreen/html/css/style.css');
</style>
