<template>
  <tf-page :isActive="isActive" :gutter="false">
    <template v-slot:action>
      <QueryForm
        :loading="loading"
        @query="onQuery"
        :points="points"
        @point-change="onPointChange"
        @standard-change="standards = $event"
        :fetching-point="dataLoading.base"
      />
    </template>
    <div class="content">
      <el-row type="flex" justify="center" align="center" class="title">
        {{ baseData.siteName ? `【${baseData.siteName}】` : '' }} 统计分析结果
      </el-row>
      <el-row type="flex" justify="center" align="center" class="base">
        <span>监测天数：{{ baseData.days || '-' }}天</span>
        <span>数据时间：{{ getIntervalValue(baseData.beginDate, baseData.endDate, '-') }} </span>
      </el-row>
      <el-row :gutter="15" type="flex">
        <el-col :span="12" style="height: 400px">
          <QuerySummary :info="baseData" :siteId="query.siteId" @refresh="fetchBaseData" v-loading="dataLoading.base" />
        </el-col>
        <el-col :span="12">
          <el-row :gutter="15">
            <el-col :span="12">
              <ChartItem
                type="year"
                :data="data"
                item-key="yearData"
                v-loading="dataLoading.base"
                :standards="standards"
              >
                <tf-title slot="title">按年度统计</tf-title>
              </ChartItem>
            </el-col>
            <el-col :span="12">
              <ChartItem
                type="season"
                :data="data"
                item-key="quarterData"
                v-loading="dataLoading.base"
                :standards="standards"
              >
                <tf-title slot="title">按季度统计</tf-title>
              </ChartItem>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
      <ChartItem
        type="month"
        class="full"
        :data="data"
        item-key="monthData"
        v-loading="dataLoading.base"
        :standards="standards"
      >
        <tf-title slot="title">按月统计</tf-title>
      </ChartItem>
      <DayAndHourChart
        type="day"
        class="full"
        :data="dayData"
        v-loading="dataLoading.day"
        :standards="standards"
        rainfallKey="rfallTotal"
      >
        <tf-title slot="title">
          <el-row type="flex" align="middle">
            <span style="margin-right: 3em">按天统计</span>
            <el-radio-group v-model="day.type" size="small" @change="onDayTypeChange">
              <el-radio label="day">近30天</el-radio>
              <el-radio label="custom">自定义时间</el-radio>
            </el-radio-group>
            <el-date-picker
              v-model="day.datetime"
              type="daterange"
              :picker-options="getDefaultDateTimePickerProp()"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              align="right"
              size="small"
              value-format="yyyy-MM-dd"
              style="margin-left: 2em; width: 250px"
              :disabled="day.type === 'day'"
              @change="onDayChange"
            />
          </el-row>
        </tf-title>
      </DayAndHourChart>
      <DayAndHourChart
        type="day"
        class="full"
        :data="hourData"
        v-loading="dataLoading.hour"
        :standards="standards"
        rainfallKey="maxFall"
      >
        <tf-title slot="title">
          <el-row type="flex" align="middle">
            <span style="margin-right: 3em">按小时统计</span>
            <el-radio-group v-model="hour.type" size="small" @change="onHourTypeChange">
              <el-radio label="hour">近24小时</el-radio>
              <el-radio label="custom">自定义时间</el-radio>
            </el-radio-group>
            <el-date-picker
              v-model="hour.datetime"
              type="daterange"
              :picker-options="getDefaultDateTimePickerProp()"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              align="right"
              size="small"
              value-format="yyyy-MM-dd"
              style="margin-left: 2em; width: 250px"
              :disabled="hour.type === 'hour'"
              @change="onHourChange"
            />
          </el-row>
        </tf-title>
      </DayAndHourChart>
    </div>
  </tf-page>
</template>

<script lang="ts">
  import { Vue, Component, Prop } from 'vue-property-decorator'
  import QueryForm from './QueryForm.vue'
  import ChartItem from './ChartItem.vue'
  import DayAndHourChart from './DayAndHourChart.vue'
  import QuerySummary from './QuerySummary.vue'
  import { getDefaultDateTimePickerProp, getDefaultPagination, getIntervalValue } from '@/utils/constant'
  import { dataQueryCols } from '../utils'
  import { IPagination } from '@/api/common'
  import { IPoint, IPointTarget } from '../../configuration/api/common'
  import { pointPage } from '../../configuration/api/point'
  import { fetchData, fetchDayData, fetchBaseData, fetchHourData, IQueryParam } from '../api/statistics'
  import { IStatisticsBase, IStatisticsData, IStatisticsDayNHour } from '../api/common'
  import moment from 'moment'

  const format = 'YYYY-MM-DD'
  const get30Days = () => [moment().add(-1, 'month').format(format), moment().format(format)]
  const get24Hours = () => [moment().add(-1, 'day').format(format), moment().format(format)]

  @Component({ name: 'Statistics', components: { QueryForm, ChartItem, QuerySummary, DayAndHourChart } })
  export default class Statistics extends Vue {
    @Prop({ type: Boolean, default: false }) isActive!: boolean
    dataQueryCols = dataQueryCols
    getIntervalValue = getIntervalValue
    standards: IPointTarget['showVos'] = []

    visible = false

    loading = { query: false, export: false }
    dataLoading = { base: false, data: false, day: false, hour: false }

    pagination: IPagination = getDefaultPagination()
    getDefaultDateTimePickerProp = getDefaultDateTimePickerProp

    points: IPoint[] = []

    point: Partial<IPoint> = {}

    query: Partial<IQueryParam> = {}
    day = { type: 'day', datetime: get30Days() }
    hour = { type: 'hour', datetime: get24Hours() }

    data: Partial<IStatisticsData>[] = []
    baseData: Partial<IStatisticsBase> = {}
    dayData: Partial<IStatisticsDayNHour> = {}
    hourData: Partial<IStatisticsDayNHour> = {}

    get isReady() {
      return !!this.query.siteId && !!this.query.checkCode && this.query.checkCode.length > 0
    }

    onQuery(query: Partial<IQueryParam>) {
      this.query = { ...query }
      this.baseData = {}
      const point = this.points.find((item) => item.id === query.siteId)
      this.point = point || {}
      this.doQuery()
    }

    async fetchBaseData() {
      this.dataLoading.base = true
      try {
        const { result: baseData } = await fetchBaseData(this.query.siteId)
        this.baseData = baseData
      } catch (error) {
        console.log(error)
      }
      this.dataLoading.base = false
    }
    async fetchData() {
      this.dataLoading.data = true
      try {
        const { result: data } = await fetchData(this.query)
        this.data = data
      } catch (error) {
        console.log(error)
      }
      this.dataLoading.data = false
    }
    async fetchDayData() {
      this.dataLoading.day = true
      try {
        const [beginDate, endDate] = this.day.datetime || []
        const { result: dayData } = await fetchDayData({ ...this.query, beginDate, endDate })
        this.dayData = dayData
      } catch (error) {
        console.log(error)
      }
      this.dataLoading.day = false
    }
    async fetchHourData() {
      this.dataLoading.hour = true
      try {
        const [beginDate, endDate] = this.hour.datetime || []
        const { result: hourData } = await fetchHourData({ ...this.query, beginDate, endDate })
        this.hourData = hourData
      } catch (error) {
        console.log(error)
      }
      this.dataLoading.hour = false
    }

    async doQuery() {
      this.loading.query = true
      await Promise.all([this.fetchBaseData(), this.fetchData(), this.fetchDayData(), this.fetchHourData()])
      this.loading.query = false
    }

    onPageChange(pagination) {
      this.pagination = { ...this.pagination, ...pagination }
      this.doQuery()
    }

    onPointChange(point) {
      this.point = { ...point }
    }

    async getAllPoints() {
      try {
        const {
          result: { records }
        } = await pointPage({ current: 1, size: 9999, ...this.$store.getters['project/id'] })
        this.points = (records || []).filter((item) => !!item.deviceType)
      } catch (error) {
        console.log(error)
      }
    }

    onDayTypeChange(type) {
      if (type === 'day') this.day.datetime = get30Days()
      if (this.isReady) this.fetchDayData()
    }
    onDayChange() {
      if (this.isReady) this.fetchDayData()
    }
    onHourTypeChange(type) {
      if (type === 'hour') this.hour.datetime = get24Hours()
      if (this.isReady) this.fetchHourData()
    }
    onHourChange() {
      if (this.isReady) this.fetchHourData()
    }

    preparing() {
      this.getAllPoints()
    }

    mounted() {
      this.preparing()
    }
  }
</script>
<style lang="scss" scoped>
  .content {
    padding: $gutter;
    background-color: $--color-white;
    height: 100%;

    .title {
      font-size: $--font-size-medium;
      font-weight: bold;
      margin-bottom: 1em;
    }
    .base {
      font-size: $--font-size-base;
      color: $--color-info;
      span + span {
        margin-left: $gutter * 2;
        margin-bottom: $gutter * 2;
      }
    }
  }
  .full {
    margin-top: $gutter;
  }
</style>
