
<template>
  <div class="spatial-analysis-statistic">
    <div class="title">
      <span>{{ title }}</span>
      <span class="statistic">
        <span class="label">总次数: </span>
        <span class="value">{{ allTimes }}</span>
        <span :class="(activeBtn === 1 ? 'active' : '') + ' btn'" @click="selectType(1)">按月</span>
        <span :class="(activeBtn === 2 ? 'active' : '') + ' btn'" @click="selectType(2)">按年</span>
        <span class="select-div">
          <a-month-picker
            v-if="activeBtn === 1"
            v-model:value="month"
            format="YYYY-MM"
            :disabled-date="disabledDate"
            size="small"
            style="width: 90px"
            placeholder="选择月份"
            @change="dataChange"
          />
          <a-date-picker
            v-if="activeBtn === 2"
            v-model:value="year"
            mode="year"
            format="YYYY"
            :disabled-date="disabledYear"
            size="small"
            style="width: 90px"
            placeholder="请选择"
            :open="yearShow"
            @openChange="openChange"
            @panelChange="panelChange"
            @pressEnter="handleSaveOk()"
            @change="dataChange"
          />
        </span>
      </span>
    </div>
    <div class="echart-container" id="defect-column" ref="domRef"></div>
  </div>
</template>
    
  <script>
import {
  defineComponent,
  reactive,
  toRefs,
  onMounted,
  ref,
  watch,
  getCurrentInstance,
  shallowRef,
  onUnmounted,
} from 'vue';
import moment from 'moment';
import Moment from 'moment';
import { queryApiUseCountDays, queryIserverUseCountByType } from '/@/api/interface/interface';
const props = {
  type: {
    type: Object,
  },
};

export default defineComponent({
  name: 'InterfaceEveryday',
  components: {},
  props,
  setup(props) {
    const data = reactive({
      title: '空间服务支撑访问统计',
      interval: null,
      allTimes: 0,
      activeBtn: 1,
      month: moment().format('YYYY-MM'),
      year: moment().format('YYYY'),
      yearShow: false,
      timer: null,
      loading: false,
    });
    const domRef = ref(null);
    const { proxy } = getCurrentInstance();
    const echarts = proxy.$echarts;
    const mychart = shallowRef(null);
    const disabledDate = (current) => {
      // Can not select days before today and today
      return current && current > moment().endOf('day');
    };

    const disabledYear = (current) => {
      return current && current > moment().endOf('year');
    };

    const dataChange = () => {
      queryData();
    };

    /**
     * 查询统计数据
     */
    const queryData = async () => {
      let xAxisData = [],
        seriesData = [];
      // const res = await queryApiUseCountDays();
      // if (res.dateArr) {
      //   res.dateArr.map((item) => {
      //     const Arr = item.split('-');
      //     xAxisData.push(`${Arr[1]}/${Arr[2]}`);
      //   });
      //   res.list.map((item) => {
      //     seriesData.push(parseInt(item));
      //   });
      // }
      data.loading = true;
      let params = null;
      //生成查询条件
      if (data.activeBtn === 1) {
        //月类型统计
        params = {
          startCreateTimeStr: moment(data.month).startOf('months').format('YYYY-MM-DD'), //获取当月的一号
          endCreateTimeStr: moment(data.month).endOf('months').format('YYYY-MM-DD'), //获取当月的最后一天
          tjType: data.activeBtn,
        };
      } else {
        //年类型统计
        params = {
          startCreateTimeStr: moment(data.year + '-01-01')
            .startOf('year')
            .format('YYYY-MM-DD'), //获取年初第一天
          endCreateTimeStr: moment(data.year + '-01-01')
            .endOf('year')
            .format('YYYY-MM-DD'), //获取年末最后一天
          tjType: data.activeBtn,
        };
      }
      data.allTimes = 0;
      if (!params) return;
      const res = await queryIserverUseCountByType(params);
      data.loading = false;
      if (res) {
        //如果是月类型统计，生成所有日期
        if (data.activeBtn === 1) {
          for (
            let t = params.startCreateTimeStr;
            moment(params.endCreateTimeStr).diff(moment(t), 'days') > 0;
            t = moment(t).add(1, 'days').format('YYYY-MM-DD')
          ) {
            //如果日期大于当前日期，跳过
            xAxisData.push(moment(t).format('MM/DD'));
            if (res.length === 0) seriesData.push(0);
            else {
              const obj = res.find(
                (item) => item['STATISTICS_START_TIME'] === moment(t).format(YYYYMMDD)
              );
              seriesData.push(obj ? parseInt(obj['SUM(COUNT)']) : 0);
            }
          }
        } else {
          for (
            let t = moment(params.startCreateTimeStr).format('YYYY-MM');
            moment(params.endCreateTimeStr).diff(moment(t), 'months') > 0;
            t = moment(t).add(1, 'months').format('YYYY-MM')
          ) {
             //如果日期大于当前日期，跳过
            xAxisData.push(parseInt(moment(t).format('MM')) + '月');
            if (res.length === 0) seriesData.push(0);
            else {
              const obj = res.find(
                (item) => item['STATISTICS_START_TIME'] === moment(t).format(YYYYMM)
              );
              seriesData.push(obj ? parseInt(obj['SUM(COUNT)']) : 0);
            }
          }
        }
        let allTimes = 0;
        res.map((item) => {
          allTimes += parseInt(item['SUM(COUNT)']);
        });
        data.allTimes = allTimes;
      }
      if (seriesData.length < 1 || xAxisData.length < 1) return;
      const option = getOption(seriesData, xAxisData);
      mychart.value.setOption(option, true);
    };

    const setEcharts = (option) => {
      if (mychart.value) mychart.value.clear();
      mychart.value = echarts.init(domRef.value);
      //const option = getOption(seriesData,xAxisData);
      window.onresize = () => {
        mychart.value.resize();
      };
    };

    const selectType = (type) => {
      data.activeBtn = type;
      queryData();
    };

    const getOption = (seriesData, xAxisData) => {
      //const seriesData = [60, 52, 200, 334, 390, 330, 220, 200, 334, 390, 330, 220];
      const maxValue = Math.max.apply(null, seriesData);
      //const xAxisData = ['09/01','09/02','09/03','09/04', '09/05','09/06','09/07','09/08','09/09','09/10','09/11','09/12'];
      const colorList = [
        {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            {
              offset: 0,
              color: 'rgba(6,113,221,1)', // 0% 处的颜色
            },
            {
              offset: 0.5,
              color: 'rgba(6,113,221,0.9)', // 0% 处的颜色
            },
            {
              offset: 1,
              color: 'rgba(6,113,221,0)', // 100% 处的颜色
            },
          ],
          global: false, // 缺省为 false
        },
        {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            {
              offset: 0,
              color: 'rgba(237,172,75,1)', // 0% 处的颜色
            },
            {
              offset: 0.5,
              color: 'rgba(237,172,75,0.9)', // 0% 处的颜色
            },
            {
              offset: 1,
              color: 'rgba(237,172,75,0.2)', // 100% 处的颜色   'rgba(6,113,221,0.2)'
            },
          ],
          global: false, // 缺省为 false
        },
      ];
      return {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'none', // 'shadow',
          },
          formatter: (params) => {
            if (data.activeBtn === 1) {
              const names = params[0].name.split('/');
              const nameLable = `${parseInt(names[0])}月${parseInt(names[1])}`;
              return nameLable + ': ' + params[0].value + '次';
            } else return params[0].name + '月: ' + params[0].value + '次';
          },
        },
        grid: {
          top: '10%',
          left: '1%',
          right: '1%',
          bottom: '1%',
          containLabel: true,
        },
        xAxis: [
          {
            data: xAxisData,
            axisTick: { show: false },
            axisLine: { show: false },
            axisLabel: {
              color: '#000',
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: 'rgba(222, 222, 222, 1)',
              },
            },
          },
        ],
        yAxis: {
          splitLine: { show: false },
          axisTick: { show: false },
          axisLine: { show: false },
          axisLabel: { show: true },
          minInterval: 1,
        },
        series: [
          {
            name: '调用次数',
            type: 'bar',
            barWidth: '12',
            data: seriesData, //[60, 52, 200, 334, 390, 330, 220, 200, 334, 390, 330, 220],
            itemStyle: {
              // 柱形图圆角，鼠标移上去效果，如果只是一个数字则说明四个参数全部设置为那么多
              normal: {
                // 柱形图圆角，初始化效果
                borderRadius: [15, 15, 0, 0],
                color: (params) => {
                  let color = colorList[0];
                  if (params.data === maxValue) color = colorList[1];
                  return color;
                },
              },
            },
            barGap: '0%',
          },
        ],
        animationDuration: 0, //这里两个动画设置可以让图表更顺滑
        animationEasing: 'cubicInOut', //这里两个动画设置可以让图表更顺滑
      };
    };
    //选择年度-弹出日历回调
    function openChange(status) {
      data.yearShow = status;
      //日期禁用规则
      data.timer = setTimeout(() => {
        dateYearDisabledRule();
      }, 0);
    }
    //选择年度-面板关闭回调
    function panelChange(value) {
      data.yearShow = false;
      data.year = moment(value).format('YYYY');
      //清除定时器
      clearTimeout(data.timer);
    }
    /**
     * 日期禁用规则
     * type{String} 规则类型  lteNow(默认)   rangeNowStart  rangeNowEnd
     * value{String} 需要对比值
     * */
    function dateYearDisabledRule(type, value) {
      const typeR = type ? type : 'lteNow';
      const valueR = value ? moment(value).format('YYYY') : '';
      //获取dom元素
      const tableDom = document.querySelectorAll('.ant-calendar-year-panel-body');
      const prevBtn = document.querySelector('.ant-calendar-year-panel-prev-decade-btn');
      const nextBtn = document.querySelector('.ant-calendar-year-panel-next-decade-btn');
      const tdDom = tableDom[0].querySelectorAll('td');
      // 当前面板的第一个和最后一个年份类似年份翻页按钮因此和年份翻页按钮做相同处理，否则会有错误
      const prevBtnTd = tdDom[0];
      const nextBtnTd = tdDom[tdDom.length - 1];
      //定义所需对比值
      const nowDate = moment().format('YYYY');
      if (tableDom.length > 0) {
        switch (typeR) {
          //<=当前年
          case 'lteNow':
            (() => {
              tdDom.forEach((item) => {
                if (item.innerText > nowDate) {
                  item.setAttribute('class', 'datepicker-year-disabled');
                } else {
                  item.classList.remove('datepicker-year-disabled');
                }
              });
              // 年份翻页按钮
              const ev = dateYearDisabledRule.bind(this, 'lteNow');
              prevBtn.removeEventListener('click', ev);
              nextBtn.removeEventListener('click', ev);
              prevBtn.addEventListener('click', ev);
              nextBtn.addEventListener('click', ev);

              prevBtnTd.removeEventListener('click', ev);
              nextBtnTd.removeEventListener('click', ev);
              prevBtnTd.addEventListener('click', ev);
              nextBtnTd.addEventListener('click', ev);
            })();
            break;

          //<=当前年、<=结束日期
          case 'rangeNowStart':
            (() => {
              tdDom.forEach((item) => {
                if (item.innerText > nowDate || (valueR && item.innerText > valueR)) {
                  item.setAttribute('class', 'datepicker-year-disabled');
                } else {
                  item.classList.remove('datepicker-year-disabled');
                }
              });

              // 年份翻页按钮
              const ev = dateYearDisabledRule.bind(this, 'rangeNowStart', value);
              prevBtn.removeEventListener('click', ev);
              nextBtn.removeEventListener('click', ev);
              prevBtn.addEventListener('click', ev);
              nextBtn.addEventListener('click', ev);

              prevBtnTd.removeEventListener('click', ev);
              nextBtnTd.removeEventListener('click', ev);
              prevBtnTd.addEventListener('click', ev);
              nextBtnTd.addEventListener('click', ev);
            })();
            break;

          //<=当前年、>=开始日期
          case 'rangeNowEnd':
            (() => {
              tdDom.forEach((item) => {
                if (item.innerText > nowDate || (valueR && item.innerText < valueR)) {
                  item.setAttribute('class', 'datepicker-year-disabled');
                } else {
                  item.classList.remove('datepicker-year-disabled');
                }
              });
              // 年份翻页按钮
              const ev = dateYearDisabledRule.bind(this, 'rangeNowEnd', value);
              prevBtn.removeEventListener('click', ev);
              nextBtn.removeEventListener('click', ev);
              prevBtn.addEventListener('click', ev);
              nextBtn.addEventListener('click', ev);

              prevBtnTd.removeEventListener('click', ev);
              nextBtnTd.removeEventListener('click', ev);
              prevBtnTd.addEventListener('click', ev);
              nextBtnTd.addEventListener('click', ev);
            })();
            break;
        }
      }
    }

    onMounted(() => {
      setEcharts();
      queryData();
      // if (data.interval) return;
      // data.interval = setInterval(() => {
      //   queryData();
      // }, 3000);
    });

    onUnmounted(() => {
      if (data.interval) clearInterval(data.interval);
    });
    return {
      domRef,
      mychart,
      ...toRefs(data),
      queryData,
      setEcharts,
      getOption,
      selectType,
      disabledDate,
      disabledYear,
      openChange,
      panelChange,
      dateYearDisabledRule,
      dataChange,
    };
  },
});
</script>
    <style lang="less" scoped>
.spatial-analysis-statistic {
  height: 100%;
  width: 100%;
  padding: 1rem;
  .title {
    height: 1.2rem;
    font-family: Source Han Sans CN;
    font-size: 1.012rem;
    font-weight: bold;
    line-height: normal;
    letter-spacing: 0em;
    color: #3d3d3d;
    margin-bottom: 1.2rem;
    .statistic {
      display: flex;
      width: 330px;
      height: 22px;
      float: right;
      .label {
        margin-right: 10px;
        font-weight: 400;
      }
      .value {
        width: 60px;
        color: #0671dd;
        font-family: 思源黑体;
        font-size: 18px;
        font-weight: 500;
        line-height: normal;
        letter-spacing: 0em;
        margin-right: 10px;
      }
      .btn {
        width: 48px;
        height: 24px;
        font-weight: 400;
        border-radius: 180px;
        margin: 0 2px;
        text-align: center;
        cursor: pointer;
      }
      .active {
        background: #0671dd;
        color: #fff;
      }
    }
  }
  .echart-container {
    height: calc(100% - 2.4rem);
    width: 100%;
  }
}
</style>