<template>
  <div class="home">
    <div class="report-page">
      <!-- 查询条件 -->
      <a-row>
        <a-card class="search-panel">
          <div class="toolsBar">
            <a-form ref="searchForm" :model="searchForm" layout="inline">
              <a-form-item props="queryWord" label="统计区间">
                <a-range-picker style="width: 220px;" @change="dateChange" v-model.trim="searchForm.queryWord" :disabledDate="disabledDate" />
              </a-form-item>
              <a-form-item props="storeIds" label="清运网点">
                <a-select
                  allowClear
                  mode="multiple"
                  placeholder="选择网点"
                  v-model="searchForm.storeIdList"
                  style="width: 200px"
                  option-filter-prop="children"
                  :filter-option="filterOption"
                >
                  <a-select-option :disabled="!isStationAll && searchForm.storeIdList.length > 0" value="all" key="all">全部</a-select-option>
                  <a-select-option :disabled="isStationAll" v-for="item in stationList" :value="item.stationNo" :key="item.id">{{ item.name }}</a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item>
                <a-button type="primary" class="search-btn" @click="handleSearch()">查询</a-button>
                <a-button type="" style="margin-left: 10px;" @click="handleReset()">重置</a-button>
              </a-form-item>
              <a-form-item>
                快捷筛选：
                <span :class="['searchItem', curentType == item.type ? 'active' : '']" v-for="(item, index) in tabList" :key="index" @click="getCurentSearchTime(item)">
                  {{ item.name }}
                </span>
              </a-form-item>
            </a-form>
          </div>
        </a-card>
      </a-row>
      <!-- 清运量数据 -->
      <a-card class="panel" title="清运量趋势">
        <!-- 清运量趋势图表展示 -->
        <chart-line
          style="height: 300px;"
          ref="chartLine"
          yUnit="kg"
          :xAxisRotate="resize"
          :xAxisData="XdaysData"
          :seriesData="clearnChartData"
          :color="washTypePieColor"
          text=""
        />
        <span v-if="isNoData" class="noData">暂无数据</span>
      </a-card>
      <!-- 各回收物类型数据 -->
      <a-card class="panel " title="各回收物类型清运数据">
        <a-row :gutter="24">
          <a-col :md="24" :lg="24">
            <div style="display: flex;align-items: center;flex-wrap: wrap;">
              <div v-for="(item, index) in qyTotalPieData" :key="index" class="module-list" :style="{ background: washTypePieColor[index] }">
                <div>{{ item.name }}</div>
                <span>{{ item.value }} kg</span>
              </div>
            </div>
          </a-col>
        </a-row>
        <!-- 各回收物类型数据图表展示 -->
        <a-row :gutter="24">
          <a-col class="tab-card">
            <span :class="['tab-card-item', currentTabChart == 'tab1' ? 'checked-item' : '']" @click="currentTabChart = 'tab1'">详情数据</span>
            <span :class="['tab-card-item', currentTabChart == 'tab2' ? 'checked-item' : '']" @click="currentTabChart = 'tab2'">变化趋势</span>
          </a-col>
          <!-- 详情数据 -->
          <a-col span="24" v-if="currentTabChart == 'tab1'">
            <chart-bar
              ref="ChartBar"
              style="height: 300px;"
              :xAxisRotate="resize"
              yUnit="kg"
              :xAxisData="XdaysData1"
              :seriesData="hswTypeBarData"
              :color="washTypePieColor" />
            <span v-if="isNoData1" class="noData">暂无数据</span>
          </a-col>
          <!-- 变化趋势 -->
          <a-col span="24" v-if="currentTabChart == 'tab2'">
            <chart-line
              ref="ChartLine"
              style="height: 300px;"
              yUnit="kg"
              :xAxisRotate="resize"
              :xAxisData="XdaysData1"
              :seriesData="hswTypeLineData"
              :color="washTypePieColor" />
            <span v-if="isNoData1" class="noData">暂无数据</span>
          </a-col>
        </a-row>
      </a-card>
      <a-row :gutter="24">
        <a-col span="12">
          <a-card class="panel chart-pie" title="各回收物类型占比">
            <chart-pie
              ref="chartPie"
              class="chartPie-box"
              :value="qyTotalPieData"
              title="清运总量(kg)"
              :total="totalGroupRubbiData.cleanWeight"
              :color="washTypePieColor"
              :xAxisRotate="resize"
              text=""
            />
          </a-card>
        </a-col>
        <a-col span="12">
          <a-card class="panel chart-pie" title="各清运司机占比">
            <!-- 各清运司机占比 百分比展示 -->
            <chart-pie
              ref="serverChartPie"
              class="chartPie-box"
              :value="sjTotalPieData"
              title="清运总量(台)"
              :total="totalGroupUserData.cleanWeight"
              :color="couponColor"
              :xAxisRotate="resize"
              text=""
            />
          </a-card>
        </a-col>
      </a-row>
    </div>
  </div>
</template>

<script>
import { ChartPie, ChartBar, ChartLine } from '@/components/Echarts'
import _ from 'lodash'
import getDate from '@/libs/getDate'
import moment from 'moment'
import { findTotalGroupRubbi, findTotalGroupUser, findTotalGroupDate, findTotalGroupDateAndRubbishType } from '@/api/cleanManage.js'
import { stationList } from '@/api/releaseRecord.js'
import { getLookUpData } from '@/api/data'
export default {
  name: 'Home',
  components: {
    ChartPie,
    ChartBar,
    ChartLine
  },
  watch: {
    screenWidth (val) {
      // 为了避免频繁触发resize函数，使用定时器
      if (!this.timer) {
        this.screenWidth = val
        this.timer = true
        const that = this
        setTimeout(function () {
          // that.screenWidth = that.$store.state.canvasWidth
          console.log(that.screenWidth)
          that.timer = false
        }, 400)
      }
    }
  },
  computed: {
    isStationAll () {
      //  是否选择全部网点
      let boolean
      if (this.searchForm.storeIdList.length > 0) {
        if (this.searchForm.storeIdList.indexOf('all') >= 0) {
          boolean = true
        } else {
          boolean = false
        }
      } else {
        boolean = false
      }
      return boolean
    },
    resize () {
      if (this.screenWidth < 1640) {
        return 40
      } else {
        return 30
      }
    },
    // 各回收物类型占比
    qyTotalPieData () {
      const list = this.totalGroupRubbiData ? this.totalGroupRubbiData.cleanReportData : []
      const temp = []

      if (list && list.length) {
        this.rubbishType.map(item => {
          const has = list.find(obj => obj.rubbishType == item.code)
          temp.push({
            name: item.dispName,
            value: has ? Number(has.cleanWeight / 1000).toFixed(3) : 0
          })
        })
      }
      return temp
    },
    // 各清运司机占比
    sjTotalPieData () {
      const list = this.totalGroupUserData ? this.totalGroupUserData.cleanReportData : []
      const temp = []
      if (list) {
        list.map(item => {
          temp.push({
            name: item.operatorName,
            value: Number(item.cleanWeight / 1000).toFixed(3)
          })
        })
      }
      return temp
    }
  },
  data () {
    return {
      screenWidth: document.body.clientWidth, // 这里是给到了一个默认值
      timer: false,
      form: this.$form.createForm(this, { name: 'searchForm' }),
      isNoData: false, // 是否有每天营业额及进店量数据
      isNoData1: false,
      stationList: [], // 清运网点列表
      searchForm: {
        queryWord: null, // 时间查询条件，默认本周
        storeIdList: [] // 已选清运网点
      },
      // 快速删选tab
      tabList: [
        {
          name: '今天',
          type: 'today'
        },
        {
          name: '本周',
          type: 'thisWeek'
        },
        {
          name: '上周',
          type: 'lastWeek'
        },
        {
          name: '本月',
          type: 'thisMonth'
        }
      ],
      curentType: 'thisWeek', // 当前所选时间查询类型
      beginDate: null, // 开始时间
      endDate: null, // 结束时间
      // 各回收物类型占比
      totalGroupRubbiData: {
        cleanWeight: 0,
        cleanReportData: []
      },
      // 各清运司机占比
      totalGroupUserData: {
        cleanWeight: 0,
        cleanReportData: []
      },
      // 洗车类型数据
      currentTabChart: 'tab1', // 洗车类型详情数据与变化趋势的tab 默认展示详情数据
      XdaysData: [], // 图表X轴时间集合
      XdaysData1: [],
      // 各类型占比
      washTypePieColor: ['#ffaa00', '#aaaa00', '#00aaff', '#ff55ff', '#1dc5d4', '#8465c7', '#ff5500', '#00aa00'],
      couponColor: ['#ffaa00', '#ff5500', '#00aaff', '#ff55ff', '#1dc5d4', '#8465c7', '#55aa00', '#527aff'],
      // 清运量趋势
      clearnChartData: [
        {
          name: '投递量',
          type: 'line',
          data: []
        },
        {
          name: '清运量',
          type: 'line',
          data: []
        }
      ],
      hswTypeBarData: [],
      hswTypeLineData: [],
      rubbishType: []
    }
  },
  methods: {
    moment,
    // 时间改变
    dateChange (dates) {
      this.curentType = ''
    },
    // 不可选日期
    disabledDate (date) {
      return (date && date.valueOf() > Date.now()) || date.valueOf() < Date.now() - 90 * 24 * 60 * 60 * 1000
    },
    filterOption (input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    // 查询分类数据字典
    getTypeCode (params) {
      const _this = this
      getLookUpData({
        pageNo: 1,
        pageSize: 1000,
        lookupCode: 'RUBBISH_TYPE'
      }).then(res => {
        const list = res.data.list.filter(item => item.code != 'HARM')
        _this.rubbishType = list
        list.map(item => {
          // 柱状图
          _this.hswTypeBarData.push({
            name: item.dispName,
            code: item.code,
            type: 'bar',
            data: []
          })
          // 折线图
          _this.hswTypeLineData.push({
            name: item.dispName,
            code: item.code,
            type: 'line',
            data: []
          })
        })
        setTimeout(() => {
          _this.getGroupDateAndRubbishType(params)
        }, 100)
      })
    },
    // 查询网点列表
    getListStation () {
      stationList({ "deviceType":"BOX"}).then(res => {
        if (res.status == 200) {
          this.stationList = res.data || []
		  console.log(this.stationList, '------------网点')
        } else {
          this.stationList = []
        }
      })
    },
    // 页面初始化
    pageInit () {
      this.form.resetFields()
    },
    // 查询
    handleSearch () {
      this.showChart = false
      if (this.searchForm.queryWord != ',' && this.searchForm.queryWord.length) {
        const searchTime = this.searchForm.queryWord.toString().split(',')
        this.beginDate = this.exitTime(searchTime[0])
        this.endDate = this.exitTime(searchTime[1])
        this.XdaysData = []
        this.XdaysData1 = []
        this.getPageData()
      } else {
        this.$message.error('请选择统计区间')
      }
    },
    // 重置
    handleReset () {
      this.searchForm.storeIdList = []
      this.curentType = 'thisWeek'
      this.getCurentSearchTime()
    },
    // 格式化时间
    exitTime (time) {
      const D = new Date(time)
      const RES_DATE = D.getFullYear() + '-' + this.p(D.getMonth() + 1) + '-' + this.p(D.getDate())
      return RES_DATE
    },
    // p为不够10添加0的函数
    p (s) {
      return s < 10 ? '0' + s : s
    },
    // 获取快速查询时间 并 赋值到时间选择框中
    getCurentSearchTime (item) {
      this.curentType = item ? item.type : this.curentType
      const quickType = {
        lastMonth: [moment(getDate.getLastMonthDays().starttime), moment(getDate.getLastMonthDays().endtime)],
        thisMonth: [moment(getDate.getCurrMonthDays().starttime), moment(getDate.getCurrMonthDays().endtime)],
        lastWeek: [moment(getDate.getLastWeekDays().starttime), moment(getDate.getLastWeekDays().endtime)],
        thisWeek: [moment(getDate.getCurrWeekDays().starttime), moment(getDate.getCurrWeekDays().endtime)],
        yesterday: [moment(getDate.getYesterday().starttime), moment(getDate.getYesterday().endtime)],
        today: [moment(getDate.getToday().starttime), moment(getDate.getToday().endtime)]
      }
      console.log(quickType[this.curentType])
      this.searchForm.queryWord = quickType[this.curentType]
      this.beginDate = quickType[this.curentType][0].format('YYYY-MM-DD')
      this.endDate = quickType[this.curentType][1].format('YYYY-MM-DD')
      console.log(this.searchForm.queryWord, '1111111')
      this.getPageData()
    },
    // 重置图表数据
    resetChartsData () {
      this.XdaysData = [] // x轴置空
      this.XdaysData1 = [] // x轴置空
      // 各回收物类型占比
      this.totalGroupRubbiData = {
        cleanWeight: 0,
        cleanReportData: []
      }
      // 各清运司机占比
      this.totalGroupUserData = {
        cleanWeight: 0,
        cleanReportData: []
      }
      // 重置清运量趋势图表数据
      this.clearnChartData[0].data = []
      this.clearnChartData[1].data = []
      // 重置各回收物类型清运数据
      this.hswTypeBarData.map(item => (item.data = []))
      this.hswTypeLineData.map(item => (item.data = []))
    },
    // 根据查询条件获取所有数据
    getPageData () {
      this.resetChartsData()
      const params = {
        beginDate: this.beginDate + ' 00:00:00',
        endDate: this.endDate + ' 00:00:00',
        stationNoList: this.searchForm.storeIdList
      }
      // 各回收物类型占比
      findTotalGroupRubbi(params).then(res => {
        console.log(res, '各回收物类型占比')
        if (res.status == 200) {
          this.totalGroupRubbiData = res.data
        }
      })
      // 各清运司机占比
      findTotalGroupUser(params).then(res => {
        console.log(res, '各清运司机占比')
        if (res.status == 200) {
          this.totalGroupUserData = res.data
        }
      })
      // 清运量趋势
      findTotalGroupDate(params).then(res => {
        console.log(res, '清运量趋势')
        if (res.status == 200) {
          const a = res.data.deliveryReportData
          const b = res.data.cleanReportData
          for (const key in a) {
            const val = Number(a[key] / 1000).toFixed(3)
            this.clearnChartData[0].data.push(val)
          }
          for (const key in b) {
            this.XdaysData.push(key)
            const val = Number(b[key] / 1000).toFixed(3)
            this.clearnChartData[1].data.push(val)
          }
          this.isNoData = false
        } else {
          this.isNoData = true
        }
      })

      if (this.hswTypeBarData.length == 0) {
        this.getTypeCode(params)
      } else {
        this.getGroupDateAndRubbishType(params)
      }
    },
    // 各回收物类型清运数据柱状图
    getGroupDateAndRubbishType (params) {
      findTotalGroupDateAndRubbishType(params).then(res => {
        console.log(res, '各回收物类型清运数据柱状图')
        if (res.status == 200 && res.data.cleanReportData) {
          const data = res.data.cleanReportData
          // x 时间轴
          for (const key in data) {
            this.XdaysData1.push(key)
          }
          this.hswTypeBarData = this.formAtGroupDateAndRubbishType(data, this.hswTypeBarData)
          this.hswTypeLineData = this.formAtGroupDateAndRubbishType(data, this.hswTypeLineData)
          this.isNoData1 = false
        } else {
          this.isNoData1 = true
        }
      })
    },
    // 格式化数据
    formAtGroupDateAndRubbishType (data, obj) {
      obj.map(item => {
        const ret = []
        for (const key in data) {
          const leve2 = data[key]
          const row = leve2[item.code]
          const val = row ? Number(row.cleanWeight / 1000).toFixed(3) : 0
          ret.push(val)
        }
        item.data = ret
      })
      return obj
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      vm.pageInit()
      vm.getListStation() // 获取网点列表
      vm.curentType = 'thisWeek'
      vm.getCurentSearchTime()
    })
  },
  // 将 reisze 事件在 vue mounted 的时候 去挂载一下它的方法
  mounted () {
    const that = this
    window.onresize = () => {
      return (() => {
        window.screenWidth = document.body.clientWidth
        that.screenWidth = window.screenWidth
      })()
    }
  }
}
</script>
<style lang="less" scoped>
.home {
  width: 100%;
}
.report-page {
  margin-top: 10px;
  overflow-y: scroll;
  overflow-x: hidden;
  .search-panel {
    .ivu-card-body > div {
      display: inline-block;
      margin-right: 20px;
    }

    .desc {
      color: #999;
    }

    .searchItem {
      padding: 8px 20px;
      border: 1px dashed #eeeeee;
      margin: 0 5px;
      border-radius: 5px;
    }

    .active {
      background-color: #ff9900;
      color: #fff;
      border: none;
    }
  }
  .search-panel /deep/ .ant-select-selection {
    max-height: 150px;
    overflow: auto;
  }
  .panel {
    margin-top: 10px;
    background-color: #ffffff;

    .noData {
      background-color: rgba(50, 50, 50, 0.7);
      color: #fff;
      padding: 15px 30px;
      position: absolute;
      top: 40%;
      left: 40%;
    }
    .chartPie-box {
      height: 300px;
      max-width: 600px;
      margin: 0 auto;
    }
    .panel-title {
      font-size: 18px;
      color: #333;
      padding-bottom: 5px;
    }

    .tab-card {
      float: right;
      margin: 30px 0;
      .tab-card-item {
        padding: 5px 10px;
        border: 1px solid #eee;
        cursor: pointer;
      }
      .checked-item {
        border-color: #2d8cf0;
        color: #2d8cf0;
      }
    }
  }

  .module-list {
    color: #ffffff;
    padding: 10px;
    border-radius: 10px;
    display: flex;
    align-items: center;
    flex-direction: column;
    margin: 5px;
    min-width: 150px;
    span {
      font-weight: 600;
      font-size: 20px;
    }
  }

  .module-icon {
    width: 52px;
    height: 54px;
  }
}
</style>
