<template>
  <div class="totalContant">
    <div class="ns-form-title">
      <div class="title">
        <span>统计数据</span>
      </div>
    </div>
    <div
      style="
        display: flex;
        width: 100%;
        height: 5%;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 1%;
      ">
      <div>
        <a-button v-if="selectedTime" type="primary" @click="changeYear(-1)">上一年</a-button>
        <a-date-picker
          v-if="selectedTime"
          valueFormat="YYYY"
          format="YYYY"
          v-model:value="selectYear"
          @change="changeYear"
          picker="year" />
        <a-button v-if="selectedTime" type="primary" @click="changeYear(1)">下一年</a-button>
        <a-date-picker
          v-else
          valueFormat="YYYY-MM"
          v-model:value="selectMonth"
          @change="changeMonth"
          picker="month" />
      </div>
      <div class="operation">
        <div class="month" :style="monthStyles" @click="changeToMonth">
          <span :style="monthText">本月</span>
        </div>
        <div class="year" :style="yearStyles" @click="changeToYear">
          <span :style="yearText">本年</span>
        </div>
      </div>
    </div>
    <div class="contant">
      <div class="chartsPart">
        <template v-for="(item, index) in data" :key="index">
          <div class="electricityConsumption">
            <div :id="'ydlChart_' + index" style="height: 100%; width: 100%"></div>
          </div>
        </template>
      </div>
      <div class="tablePart">
        <a-table
          :columns="columns"
          :data-source="data"
          bordered
          :pagination="false"
          :scroll="{ x: 1300, y: 300 }">
        </a-table>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref, defineExpose } from 'vue';
  import dayjs, { Dayjs } from 'dayjs';
  import * as echarts from 'echarts';
  import { http } from '/nerv-lib/util/http';
  import { carbonPlanning } from '/@/api/carbonEmissionFactorLibrary';
  defineOptions({
    energyType: 'all', // 与页面路由name一致缓存才可生效
  });
  const orgId = ref('');
  const result = JSON.parse(sessionStorage.getItem('ORGID')!);
  orgId.value = result;
  const fetch = (api, params = { orgId }) => {
    return http.post(api, params);
  };
  const selectYear = ref<Dayjs>(dayjs(new Date().getFullYear().toString()));
  const selectMonth = ref<Dayjs>(dayjs().startOf('year').month(0));
  // 年/月切换
  const monthStyles = ref('background: transparent');
  const yearStyles = ref('background: #2778ff');
  const monthText = ref('color: #2778ff');
  const yearText = ref('color: #ffffff');
  const selectedTime = ref(true);
  const changeMonth = () => {
    queryParams.value.yearMonth = selectMonth.value;
    getTableData();
  };
  const changeToMonth = () => {
    monthStyles.value = 'background: #2778ff';
    yearStyles.value = 'background: transparent';
    monthText.value = 'color: #ffffff';
    yearText.value = 'color: #2778ff';
    queryParams.value.yearAndMonth = 'month';
    queryParams.value.yearMonth = selectMonth.value.format('YYYY-DD');
    columns.value[2].title = '月份';
    columns.value[2].dataIndex = 'yearMonth';
    selectedTime.value = false;
    getTableData();
  };
  const changeYear = (data) => {
    if (data) {
      const newYear = selectYear.value.year() + data;
      selectYear.value = dayjs().year(newYear);
      const queryYear = selectYear.value.format('YYYY');
      queryParams.value.year = queryYear;
    } else {
      queryParams.value.year = selectYear.value;
    }
    getTableData();
  };
  const changeToYear = () => {
    monthStyles.value = 'background:transparent';
    yearStyles.value = 'background: #2778ff';
    monthText.value = 'color: #2778ff';
    yearText.value = 'color: #ffffff';
    queryParams.value.yearAndMonth = 'year';
    delete queryParams.value.yearMonth;
    // queryParams.value.year = selectYear.value;
    columns.value[2].title = '年份';
    columns.value[2].dataIndex = 'year';
    selectedTime.value = true;
    getTableData();
  };
  // 用电量
  const ydlChart = ref({});
  let chartInstance: echarts.ECharts | null = null;
  const drawEcharts = () => {
    data.value.forEach((item, index) => {
      const chart = echarts.init(document.getElementById(`ydlChart_${index}`)!);
      const bottomColor = [
        'rgba(219, 222, 232, 1)',
        'rgba(221, 226, 223, 1)',
        'rgba(233, 228, 219, 1)',
        'rgba(221, 216, 235, 1)',
        'rgba(240, 228, 228, 1)',
      ];
      const mianColor = [
        'rgba(24, 106, 255, 1)',
        'rgba(58, 194, 127, 1)',
        'rgba(249, 183, 50, 1)',
        'rgba(120, 76, 212, 1)',
        'rgba(255, 55, 103, 1)',
      ];
      let point = parseInt(item.budgetAchievement.replace('%', ''));
      const option = {
        backgroundColor: 'transparent',
        title: [
          {
            text: point + '%',
            x: 'center',
            y: '35%',
            textStyle: {
              fontSize: 14,
              fontWeight: 'normal',
              fontStyle: 'normal',
            },
          },
          {
            text: item.budgetAchievementName,
            x: 'center',
            y: '85%',
            textStyle: {
              fontSize: 14,
              fontWeight: 'normal',
              fontStyle: 'normal',
            },
          },
        ],
        series: [
          {
            type: 'pie',
            radius: ['40%', '50%'],
            center: ['50%', '40%'],
            label: {
              normal: {
                show: false,
              },
            },
            data: [
              {
                name: '',
                value: 100,
                itemStyle: {
                  normal: {
                    color: bottomColor[index],
                  },
                },
              },
            ],
            zlevel: 1,
          },
          {
            name: 'main',
            type: 'pie',
            radius: ['38%', '55%'],
            center: ['50%', '40%'],
            data: [
              {
                value: point,
                label: {
                  show: true,
                  position: 'center',
                  fontSize: 40,
                },
                labelLine: { show: false },
                itemStyle: {
                  normal: {
                    color: mianColor[index],
                    shadowBlur: 10,
                    shadowColor: mianColor[index],
                  },
                },
              },
              {
                value: 100 - point,
                itemStyle: {
                  normal: {
                    color: 'transparent',
                  },
                },
              },
            ],
            zlevel: 2,
          },
        ],
      };
      chart.setOption(option);
    });
  };

  // 表格
  const queryParams = ref({
    orgId: orgId.value,
    year: selectYear.value.format('YYYY'),
    yearAndMonth: 'year',
  });
  const getTableData = () => {
    fetch(carbonPlanning.whole, queryParams.value).then((res) => {
      data.value = res.data;
      setTimeout(() => {
        drawEcharts();
      }, 500);
    });
  };
  const columns = ref([
    {
      title: '序号',
      width: 100,
      customRender: (text: any) => {
        return text.index + 1;
      },
    },
    {
      title: '名称',
      dataIndex: 'itemizeName',
    },
    {
      title: '年份',
      dataIndex: 'year',
    },
    {
      title: '计量单位',
      dataIndex: 'unitMeasurement',
    },
    {
      title: '总实际用量',
      dataIndex: 'actualUsage',
    },
    {
      title: '总预算量',
      dataIndex: 'budget',
    },
    {
      title: '基准值',
      dataIndex: 'referenceValue',
    },
    {
      title: '节能量',
      dataIndex: 'energyConservation',
    },
    {
      title: '预算达成率',
      dataIndex: 'budgetAchievement',
    },
  ]);

  const data = ref([]);
  getTableData();
  defineExpose({
    getTableData,
  });
</script>

<style lang="less" scoped>
  .totalContant {
    height: 100%;
    padding: 12px;
  }
  :deep(.ant-tabs-content) {
    padding: 16px;
  }
  .ns-form-title {
    font-weight: bold;
    user-select: text;
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    height: 5vh;

    .title {
      text-align: left;
      height: 32px;
      line-height: 32px;
      font-weight: bold;
      user-select: text;
      position: relative;
      padding-left: 9px;
      width: 50%;
    }
    .title::before {
      content: '';
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      height: 13px;
      width: 3px;
      border-radius: 1px;
      background-color: #2778ff;
    }
  }
  .operation {
    display: flex;
    margin-right: 10px;
    font-weight: 400;
    height: 90%;
    cursor: pointer;
    width: 10%;
    border-radius: 4px;
    border: 1px solid rgba(39, 120, 255, 1);
  }
  :deep(.ant-btn-primary) {
    border-radius: unset !important;
    border-color: #d7d7d7 !important;
    background: #f2f2f2 !important;
    color: black !important;
  }
  .month {
    width: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .year {
    width: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .contant {
    width: 100%;
    height: calc(94% - 5vh);
    .chartsPart {
      width: 100%;
      height: 35%;
      display: flex;
      justify-content: space-between;
      .electricityConsumption {
        width: 19%;
        height: 100%;
        background: rgba(39, 120, 255, 0.05);
        border-radius: 8px;
      }
    }
    .tablePart {
      height: calc(65% - 20px);
      margin-top: 20px;
    }
  }
</style>
