<template>
  <div v-loading="loading">
    <div class="titles">整体统计</div>
    <div class="item-wapper">
      <div class="one item-box" @click="$emit('handleClick', 'project')">
        <div class="data-left">
          <div class="data-title">{{ thisYear }}年项目总数</div>
          <div class="number">{{ projectNum.toLocaleString('en-US') }}</div>
          <div class="compare-row">
            <span class="text-1">同比</span>
            <span class="text-2" :class="{ upColor: isProjectUp, dowColor: !isProjectUp }">{{ subYear }}</span>
            <img :src="isProjectUp ? upImg : downImg" alt="">
            <span class="text-1 compare-gap">环比</span>
            <span class="text-2" :class="{ upColor: isProjectMonthUp, dowColor: !isProjectMonthUp }">{{ subMonth
            }}</span>
            <img :src="isProjectMonthUp ? upImg : downImg" alt="">
          </div>
        </div>
        <div class="chart-box">
          <div id="thisYear"></div>
        </div>
      </div>
      <div class="two item-box" @click="$emit('handleClick', 'contract')">
        <div class="data-left">
          <div class="data-title">{{ thisYear }}年承接合同数</div>
          <div class="number">{{ contractNum.toLocaleString('en-US') }}</div>
          <div class="compare-row">
            <span class="text-1">同比</span>
            <span class="text-2" :class="{ upColor: isContractUp, dowColor: !isContractUp }">{{ contractSubYear
              }}</span>
            <img :src="isContractUp ? upImg : downImg" alt="">
            <span class="text-1 compare-gap">环比</span>
            <span class="text-2" :class="{ upColor: isContractMonthUp, dowColor: !isContractMonthUp }">{{
              contractSubMonth }}</span>
            <img :src="isContractMonthUp ? upImg : downImg" alt="">
          </div>
        </div>
        <div class="chart-box">
          <div id="thisContract"></div>
        </div>
      </div>
      <div class="four item-box" @click="$emit('handleClick', 'borrow')">
        <div class="data-left">
          <div class="data-title">{{ thisYear }}借款次数</div>
          <div class="number">{{ borrowNum.toLocaleString('en-US') }}</div>
          <div class="compare-row">
            <span class="text-1">同比</span>
            <span class="text-2" :class="{ upColor: isBorrowUp, dowColor: !isBorrowUp }">{{ borrowSubYear }}</span>
            <img :src="isBorrowUp ? upImg : downImg" alt="">
            <span class="text-1 compare-gap">环比</span>
            <span class="text-2" :class="{ upColor: isBorrowMonthUp, dowColor: !isBorrowMonthUp }">{{ borrowSubMonth }}</span>
            <img :src="isBorrowMonthUp ? upImg : downImg" alt="">
          </div>
        </div>
        <div class="chart-box">
          <div id="thisBorrow"></div>
        </div>
      </div>

      <!-- <div class="five item-box" @click="$emit('handleClick', 'settle')">
        <div class="data-left">
          <div class="data-title">{{ thisYear }}结算次数</div>
          <div class="number">{{ settleNum.toLocaleString('en-US') }}</div>
          <div>
            <span class="text-1">较去年</span>
            <span class="text-2" :class="{ upColor: isSettleUp, dowColor: !isSettleUp }">{{ settleSubYear }}</span>
            <img :src="isSettleUp ? upImg : downImg" alt="">
          </div>
        </div>
        <div class="chart-box">
          <div id="thisSettle"></div>
        </div>
      </div> -->
      <div class="three item-box" @click="$emit('handleClick', 'device')">
        <div class="data-left">
          <div class="data-title">{{ thisYear }}年设备申领</div>
          <div class="number">{{ deviceNum.toLocaleString('en-US') }}</div>
          <div class="compare-row">
            <span class="text-1">同比</span>
            <span class="text-2" :class="{ upColor: isDeviceUp, dowColor: !isDeviceUp }">{{ deviceSubYear }}</span>
            <img :src="isDeviceUp ? upImg : downImg" alt="">
            <span class="text-1 compare-gap">环比</span>
            <span class="text-2" :class="{ upColor: isDeviceMonthUp, dowColor: !isDeviceMonthUp }">{{ deviceSubMonth }}</span>
            <img :src="isDeviceMonthUp ? upImg : downImg" alt="">
          </div>
        </div>
        <div class="chart-box">
          <div id="thisDevice"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import upSrc from '@/assets/icons/up.png'
import downSrc from '@/assets/icons/down.png'
import { echartsInit } from '@/utils/echarts'
import { getProjectStatistic } from '@/api/oa/project/project'
import { getContractStatistic } from '@/api/oa/contract/contract'
import { getBorrowStatistic } from '@/api/oa/borrow/borrow'
import { getDeviceStatistic } from '@/api/oa/device/device'

let thisYearChart, contractYearChart, deviceYearChart, borrowYearChart, settleYearChart
export default {
  props: {
    pDatas: {
      type: Object,
      require: true,
    },
    cDatas: {
      type: Object,
      require: true,
    },
    dDatas: {
      type: Object,
      require: true,
    },
    bDatas: {
      type: Object,
      require: true,
    },
    sDatas: {
      type: Object,
      require: true,
    }
  },
  data() {
    return {
      projectNum: 0,
      contractNum: 0,
      deviceNum: 0,
      borrowNum: 0,
      settleNum: 0,
      upImg: upSrc,
      downImg: downSrc,
      isProjectUp: false,
      isProjectMonthUp: false,
      isContractUp: false,
      isContractMonthUp: false,
      isDeviceUp: false,
      isDeviceMonthUp: false,
      isBorrowUp: false,
      isBorrowMonthUp: false,
      isSettleUp: false,
      thisYear: new Date().getFullYear(),
      year: {},
      type: {},
      source: {},
      dept: {},
      contractAmount: {},
      contractCwAmount: {},
      contractSource: {},
      contractYear: {},
      deviceApproval: {},
      deviceStatus: {},
      deviceYear: {},
      borrowAmount: {},
      borrowUsage: {},
      borrowUsageAmount: {},
      borrowYear: {},
      settleAmount: {},
      settleType: {},
      settleTypeAmount: {},
      settleYear: {},
      subYear: 0,
      subMonth: 0,
      contractSubYear: 0,
      contractSubMonth: 0,
      deviceSubYear: 0,
      deviceSubMonth: 0,
      borrowSubYear: 0,
      borrowSubMonth: 0,
      settleSubYear: 0,
      projectMonthLabels: [],
      projectMonthThisYear: [],
      projectMonthLastYear: [],
      contractMonthLabels: [],
      contractMonthThisYear: [],
      contractMonthLastYear: [],
      borrowMonthLabels: [],
      borrowMonthThisYear: [],
      borrowMonthLastYear: [],
      deviceMonthLabels: [],
      deviceMonthThisYear: [],
      deviceMonthLastYear: [],
      loading: true,
      statsLoading: false
    }
  },
  watch: {
    projectMonthThisYear() {
      this.initChartOne();
    },
    contractMonthThisYear() {
      this.initChartTwo();
    },
    borrowMonthThisYear() {
      this.initChartFour();
    },
    deviceMonthThisYear() {
      this.initChartThree();
    },
    settleYear() {
      this.initChartFive();
    },
    pDatas: {
      handler(newVal) {
        if (newVal) {
          this.initDatas();
        }
      },
      immediate: true,  // 在绑定时立即执行一次  
      deep: true       // 深度监听对象的变化  
    },
    cDatas: {
      handler(newVal) {
        if (newVal) {
          this.initDatas();
        }
      },
      immediate: true,  // 在绑定时立即执行一次  
      deep: true       // 深度监听对象的变化  
    },
    dDatas: {
      handler(newVal) {
        if (newVal) {
          this.initDatas();
        }
      },
      immediate: true,  // 在绑定时立即执行一次  
      deep: true       // 深度监听对象的变化  
    },
    bDatas: {
      handler(newVal) {
        if (newVal) {
          this.initDatas();
        }
      },
      immediate: true,  // 在绑定时立即执行一次  
      deep: true       // 深度监听对象的变化  
    },
    sDatas: {
      handler(newVal) {
        if (newVal) {
          this.initDatas();
        }
      },
      immediate: true,  // 在绑定时立即执行一次  
      deep: true       // 深度监听对象的变化  
    }
  },
  created() {
    this.loadHeadStats()
  },
  mounted() {
  },
  methods: {
    async loadHeadStats() {
      if (this.statsLoading) {
        return
      }
      this.statsLoading = true
      this.loading = true
      try {
        await Promise.all([
          this.loadProjectStats(),
          this.loadContractStats(),
          this.loadBorrowStats(),
          this.loadDeviceStats()
        ])
      } finally {
        this.loading = false
        this.statsLoading = false
      }
    },
    initDatas() {
      if (Object.keys(this.pDatas).length !== 0) {
        this.year = this.pDatas.year[0];
        this.type = this.pDatas.type[0];
        this.source = this.pDatas.source[0];
        this.dept = this.pDatas.dept[0];
      }
      if (Object.keys(this.cDatas).length !== 0) {
        this.contractAmount = this.cDatas.yearAmount[0];
        this.contractCwAmount = this.cDatas.sourceAmount[0];
        this.contractSource = this.cDatas.sourceCount[0];
        this.contractYear = this.cDatas.yearCount[0];
      }
      if (Object.keys(this.dDatas).length !== 0) {
        this.deviceApproval = this.dDatas.approval[0];
        this.deviceStatus = this.dDatas.status[0];
        this.deviceYear = this.dDatas.year[0];
      }
      if (Object.keys(this.bDatas).length !== 0) {
        this.borrowAmount = this.bDatas.amount[0];
        this.borrowUsage = this.bDatas.usage[0];
        this.borrowUsageAmount = this.bDatas.usageAmount[0];
        this.borrowYear = this.bDatas.year[0];
      }
      if (Object.keys(this.sDatas).length !== 0) {
        this.settleAmount = this.sDatas.amount[0];
        this.settleType = this.sDatas.type[0];
        this.settleTypeAmount = this.sDatas.typeAmount[0];
        this.settleYear = this.sDatas.year[0];
        this.getSettleYearSub(this.settleYear);
      }
    },
    getMonthKey(year, month) {
      return `${year}-${String(month).padStart(2, '0')}`
    },
    getMonthValue(monthData, year, month) {
      return Number(monthData[this.getMonthKey(year, month)] || 0)
    },
    parseMonthSeries(monthData, year, upToMonth) {
      const labels = []
      const values = []
      for (let m = 1; m <= upToMonth; m++) {
        labels.push(`${m}月`)
        values.push(this.getMonthValue(monthData, year, m))
      }
      return { labels, values }
    },
    sumMonths(monthData, year, fromMonth, toMonth) {
      let sum = 0
      for (let m = fromMonth; m <= toMonth; m++) {
        sum += this.getMonthValue(monthData, year, m)
      }
      return sum
    },
    calcCompareStats(thisYearData, lastYearData, year, currentMonth) {
      const thisYearCount = this.sumMonths(thisYearData, year, 1, currentMonth)
      const lastYearCount = this.sumMonths(lastYearData, year - 1, 1, currentMonth)
      const thisMonthCount = this.getMonthValue(thisYearData, year, currentMonth)
      let lastMonthYear = year
      let lastMonth = currentMonth - 1
      if (lastMonth === 0) {
        lastMonth = 12
        lastMonthYear = year - 1
      }
      const lastMonthData = lastMonthYear === year ? thisYearData : lastYearData
      const lastMonthCount = this.getMonthValue(lastMonthData, lastMonthYear, lastMonth)
      return { thisYearCount, lastYearCount, thisMonthCount, lastMonthCount }
    },
    applyCompareResult(result, prefix) {
      const {
        thisYearCount,
        lastYearCount,
        thisMonthCount,
        lastMonthCount,
        labels,
        thisYearValues,
        lastYearValues
      } = result
      const fieldMap = {
        project: { num: 'projectNum', subYear: 'subYear', subMonth: 'subMonth', up: 'isProjectUp', monthUp: 'isProjectMonthUp' },
        contract: { num: 'contractNum', subYear: 'contractSubYear', subMonth: 'contractSubMonth', up: 'isContractUp', monthUp: 'isContractMonthUp' },
        borrow: { num: 'borrowNum', subYear: 'borrowSubYear', subMonth: 'borrowSubMonth', up: 'isBorrowUp', monthUp: 'isBorrowMonthUp' },
        device: { num: 'deviceNum', subYear: 'deviceSubYear', subMonth: 'deviceSubMonth', up: 'isDeviceUp', monthUp: 'isDeviceMonthUp' }
      }
      const fields = fieldMap[prefix]
      this[fields.num] = thisYearCount
      this[fields.subYear] = Math.abs(thisYearCount - lastYearCount)
      this[fields.up] = thisYearCount >= lastYearCount
      this[fields.subMonth] = Math.abs(thisMonthCount - lastMonthCount)
      this[fields.monthUp] = thisMonthCount >= lastMonthCount
      this[`${prefix}MonthLabels`] = labels
      this[`${prefix}MonthThisYear`] = thisYearValues
      this[`${prefix}MonthLastYear`] = lastYearValues
    },
    async fetchYearMonthData(fetchFn, year) {
      const res = await fetchFn(year)
      return res.data || {}
    },
    async loadProjectStats() {
      const year = new Date().getFullYear()
      const currentMonth = new Date().getMonth() + 1
      const [thisYearRes, lastYearRes] = await Promise.all([
        this.fetchYearMonthData(y => getProjectStatistic({ projectNumber: String(y) }), year),
        this.fetchYearMonthData(y => getProjectStatistic({ projectNumber: String(y) }), year - 1)
      ])
      const thisYearData = thisYearRes.month ? thisYearRes.month[0] : {}
      const lastYearData = lastYearRes.month ? lastYearRes.month[0] : {}
      const { labels, values: thisYearValues } = this.parseMonthSeries(thisYearData, year, currentMonth)
      const { values: lastYearValues } = this.parseMonthSeries(lastYearData, year - 1, currentMonth)
      const compare = this.calcCompareStats(thisYearData, lastYearData, year, currentMonth)
      this.applyCompareResult({ ...compare, labels, thisYearValues, lastYearValues }, 'project')
    },
    async loadContractStats() {
      const year = new Date().getFullYear()
      const currentMonth = new Date().getMonth() + 1
      const fetchContractMonths = y => getContractStatistic({ signDate: `${y}-01-01` })
      const [thisYearRes, lastYearRes] = await Promise.all([
        this.fetchYearMonthData(fetchContractMonths, year),
        this.fetchYearMonthData(fetchContractMonths, year - 1)
      ])
      const thisYearData = thisYearRes.monthCount ? thisYearRes.monthCount[0] : {}
      const lastYearData = lastYearRes.monthCount ? lastYearRes.monthCount[0] : {}
      const { labels, values: thisYearValues } = this.parseMonthSeries(thisYearData, year, currentMonth)
      const { values: lastYearValues } = this.parseMonthSeries(lastYearData, year - 1, currentMonth)
      const compare = this.calcCompareStats(thisYearData, lastYearData, year, currentMonth)
      this.applyCompareResult({ ...compare, labels, thisYearValues, lastYearValues }, 'contract')
    },
    async loadBorrowStats() {
      const year = new Date().getFullYear()
      const currentMonth = new Date().getMonth() + 1
      const fetchBorrowMonths = y => getBorrowStatistic({ lendTime: `${y}-01-01` })
      const [thisYearRes, lastYearRes] = await Promise.all([
        this.fetchYearMonthData(fetchBorrowMonths, year),
        this.fetchYearMonthData(fetchBorrowMonths, year - 1)
      ])
      const thisYearData = thisYearRes.month ? thisYearRes.month[0] : {}
      const lastYearData = lastYearRes.month ? lastYearRes.month[0] : {}
      const { labels, values: thisYearValues } = this.parseMonthSeries(thisYearData, year, currentMonth)
      const { values: lastYearValues } = this.parseMonthSeries(lastYearData, year - 1, currentMonth)
      const compare = this.calcCompareStats(thisYearData, lastYearData, year, currentMonth)
      this.applyCompareResult({ ...compare, labels, thisYearValues, lastYearValues }, 'borrow')
    },
    async loadDeviceStats() {
      const year = new Date().getFullYear()
      const currentMonth = new Date().getMonth() + 1
      const fetchDeviceMonths = y => getDeviceStatistic({ applyDate: `${y}-01-01` })
      const [thisYearRes, lastYearRes] = await Promise.all([
        this.fetchYearMonthData(fetchDeviceMonths, year),
        this.fetchYearMonthData(fetchDeviceMonths, year - 1)
      ])
      const thisYearData = thisYearRes.month ? thisYearRes.month[0] : {}
      const lastYearData = lastYearRes.month ? lastYearRes.month[0] : {}
      const { labels, values: thisYearValues } = this.parseMonthSeries(thisYearData, year, currentMonth)
      const { values: lastYearValues } = this.parseMonthSeries(lastYearData, year - 1, currentMonth)
      const compare = this.calcCompareStats(thisYearData, lastYearData, year, currentMonth)
      this.applyCompareResult({ ...compare, labels, thisYearValues, lastYearValues }, 'device')
    },
    initChartOne() {
      let option = {
        grid: {
          left: '1%',
          right: '1%',
          bottom: '0%',
          height: '60%',
          containLabel: true
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'none',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        xAxis: {
          type: 'category',
          data: this.projectMonthLabels.slice(-6),
          show: false
        },
        yAxis: {
          type: 'value',
          axisLabel: { show: false },
          splitLine: { show: false }
        },
        series: [
          {
            name: '今年',
            min: 0,
            data: this.projectMonthThisYear.slice(-6),
            type: 'line',
            smooth: true,
            itemStyle: { color: '#3498DB' }
          },
          {
            name: '去年同期',
            min: 0,
            data: this.projectMonthLastYear.slice(-6),
            type: 'line',
            smooth: true,
            itemStyle: { color: '#A0CFFF' },
            lineStyle: { type: 'dashed' }
          }
        ]
      };
      echartsInit(thisYearChart, 'thisYear', option);
    },
    initChartTwo() {
      let option = {
        grid: {
          left: '1%',
          right: '1%',
          bottom: '0%',
          height: '60%',
          containLabel: true
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'none',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        xAxis: {
          type: 'category',
          data: this.contractMonthLabels.slice(-6),
          show: false
        },
        yAxis: {
          type: 'value',
          axisLabel: { show: false },
          splitLine: { show: false }
        },
        series: [
          {
            name: '今年',
            min: 0,
            data: this.contractMonthThisYear.slice(-6),
            type: 'line',
            smooth: true,
            itemStyle: { color: '#00B42A' }
          },
          {
            name: '去年同期',
            min: 0,
            data: this.contractMonthLastYear.slice(-6),
            type: 'line',
            smooth: true,
            itemStyle: { color: '#95DE64' },
            lineStyle: { type: 'dashed' }
          }
        ]
      };
      echartsInit(contractYearChart, 'thisContract', option);
    },
    initChartThree() {
      let option = {
        grid: {
          left: '1%',
          right: '1%',
          bottom: '0%',
          height: '60%',
          containLabel: true
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'none',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        xAxis: {
          type: 'category',
          data: this.deviceMonthLabels.slice(-6),
          show: false
        },
        yAxis: {
          type: 'value',
          axisLabel: { show: false },
          splitLine: { show: false }
        },
        series: [
          {
            name: '今年',
            min: 0,
            data: this.deviceMonthThisYear.slice(-6),
            type: 'line',
            smooth: true,
            itemStyle: { color: '#3498DB' }
          },
          {
            name: '去年同期',
            min: 0,
            data: this.deviceMonthLastYear.slice(-6),
            type: 'line',
            smooth: true,
            itemStyle: { color: '#A0CFFF' },
            lineStyle: { type: 'dashed' }
          }
        ]
      };
      echartsInit(deviceYearChart, 'thisDevice', option);
    },
    initChartFour() {
      let option = {
        grid: {
          left: '1%',
          right: '1%',
          bottom: '0%',
          height: '60%',
          containLabel: true
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'none',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        xAxis: {
          type: 'category',
          data: this.borrowMonthLabels.slice(-6),
          show: false
        },
        yAxis: {
          type: 'value',
          axisLabel: { show: false },
          splitLine: { show: false }
        },
        series: [
          {
            name: '今年',
            min: 0,
            data: this.borrowMonthThisYear.slice(-6),
            type: 'line',
            smooth: true,
            itemStyle: { color: '#7B68EE' }
          },
          {
            name: '去年同期',
            min: 0,
            data: this.borrowMonthLastYear.slice(-6),
            type: 'line',
            smooth: true,
            itemStyle: { color: '#C4B5FD' },
            lineStyle: { type: 'dashed' }
          }
        ]
      };
      echartsInit(borrowYearChart, 'thisBorrow', option);
    },
    initChartFive() {
      let option = {
        grid: {
          left: '1%',
          right: '1%',
          bottom: '0%',
          height: '60%',
          containLabel: true
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'none',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        xAxis: {
          type: 'category',
          data: Object.keys(this.settleYear).slice(-6),
          show: false
        },
        yAxis: {
          type: 'value',
          axisLabel: { show: false },
          splitLine: { show: false }
        },
        series: [
          {
            min: 0,
            data: Object.values(this.settleYear).slice(-6),
            type: 'line',
            smooth: true,
            itemStyle: {
              color: '#E74C3C'
            }
          }
        ]
      };
      echartsInit(settleYearChart, 'thisSettle', option);
    },
    getSettleYearSub(year) {
      let arr = Object.values(year).slice(-2);
      this.settleSubYear = Number(arr[1]) - Number(arr[0]);
      this.settleNum = Number(arr[1])
      if (this.settleSubYear < 0) {
        this.settleSubYear = - this.settleSubYear;
        this.isSettleUp = false
      } else {
        this.isSettleUp = true
      }
    }
  },
}
</script>

<style lang="scss" scoped>
.item-wapper {
  height: 134px;
  width: 100%;
  display: flex;
}

.titles {
  font-family: 'puhuiti';
  font-size: 16px;
  margin-bottom: 16px;
}

.item-box:hover {
  box-shadow: 0 0 15px #e7e5e5;
}

.item-box {
  flex: 1;
  margin: 0 10px;
  height: 100%;
  padding: 13px;
  display: flex;
  cursor: pointer;

  .data-left {
    flex: 1;

    .data-title {
      font-family: 'puhuiti45';
      font-weight: 500;
      margin-bottom: 16px;
      font-size: 16px;
    }

    .compare-row {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
    }

    .compare-gap {
      margin-left: 8px;
    }

    .number {
      font-size: 24px;
      font-family: 'puhuiti45';
      font-weight: 700;
    }

    .text-1 {
      color: #4E5969;
      font-size: 12px;
      margin-right: 10px;
    }

    .text-2 {
      font-size: 14px;
      font-family: 'puhuiti45';
      font-weight: 700;
      margin-right: 5px;
    }
  }

  .chart-box {
    flex: 1;

    div {
      width: 100%;
      height: 100%;
    }
  }

}

.one {
  background-color: #F2F9FE;
}

.two {
  background-color: #F5FEF2;
}

.three {
  background-color: #F2F9FE;
}

.four {
  background-color: #F6F6FF;
}

.five {
  background-color: #FFF0F5;
}

.upColor {
  color: #F44C4C;
}

.dowColor {
  color: #00B42A
}
</style>