<template>
  <div>
    <div>当前登录人：{{user.name}}</div>
    <div class="statistics">
      <panel-group :totaldata="list" />
    </div>
    <div>
      <el-row :gutter="32">
        <el-col :xs="24" :sm="24" :lg="24">
          <div class="chart-wrapper">
            <div class="chart-title">
              <span>出入库统计</span>
              <el-date-picker @change="changeDate" v-model="dateRange" value-format="yyyy-MM-dd" type="daterange"
                :picker-options="pickerOptions" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
                align="right">
              </el-date-picker>
            </div>
            <line-chart :height="'500px'" :chartData="lineArr" />
          </div>
        </el-col>
      </el-row>
    </div>


  </div>
</template>

<script>
  import LineChart from './components/LineChart'
  import PanelGroup from './components/PanelGroup'
  import {
    getChartsHome
  } from "../../api/dashboard.js"
  import {
    stocksCharts
  } from "@/api/charts.js"
  import {
    outboundsCharts
  } from "@/api/charts.js"
  import {
    getInfo
  } from '../../api/user.js'
  import {
    setWzglUser
  } from '@/utils/auth.js'

  export default {
    components: {
      PanelGroup,
      LineChart
    },
    data() {
      return {
        user:{},
        start_time: '',
        end_time: '',
        dateRange:[],
        pickerOptions: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
        list: {},
        lineArr: {
          xArr: [],
          legendArr: ["入库", "出库"],
          series: [{
              name: '入库',
              type: 'line',
              stack: 'Total',
              data: []
            },
            {
              name: '出库',
              type: 'line',
              stack: 'Total',
              data: []
            }
          ]
        }
      }
    },
    watch: {

    },
    methods: {
      changeDate(e) {
        var that = this;
        this.dateRange = e;
        that.start_time = e[0];
        that.end_time = e[1];
        this.loadChart();
      },
      async loadData() {
        await getChartsHome().then((res) => {
          console.log(res);
          this.list = res;
        }).catch()
      },
      async loadChart(){
        let that = this
        await stocksCharts({
          start_time: this.start_time,
          end_time: this.end_time
        }).then((res) => {
          for (var m of res) {
            that.lineArr.xArr.push(m.date.split('-')[1] + "-" + m.date.split('-')[2]);
            that.lineArr.series[0].data.push(m.total);
          }
        }).catch()
        await outboundsCharts({
          start_time: this.start_time,
          end_time: this.end_time
        }).then((res) => {
          for (var m of res) {
            that.lineArr.series[1].data.push(m.total);
          }
        }).catch()
      },
      getNowDate() {
        const timeOne = new Date()
        const year = timeOne.getFullYear()
        let month = timeOne.getMonth() + 1
        let day = timeOne.getDate()
        month = month < 10 ? '0' + month : month
        day = day < 10 ? '0' + day : day
        const NowDate = `${year}-${month}-${day}`
        return NowDate
      },
      recentTime(day, fmt, time) {
        //获取当前时间的毫秒值
        let now = (time ? new Date(time) : new Date()).getTime();
        // 获取前后n天时间
        let recent = new Date(now + day * 24 * 60 * 60 * 1000);

        // key：正则匹配表达式，value：对应的时间、日期
        let fmtObj = {
          'M+': recent.getMonth() + 1, //月份
          'd+': recent.getDate(), //日
          'h+': recent.getHours(), //时
          'm+': recent.getMinutes(), //分
          's+': recent.getSeconds(), //秒
        };
        // 获取匹配年份替换
        if (/(y+)/.test(fmt)) {
          //RegExp.$1 匹配结果，替换成对应的长度。如：yyyy就替换成整个年份2021，yy就替换成后两位21，以此类推
          fmt = fmt.replace(RegExp.$1, (recent.getFullYear() + '').substr(4 - RegExp.$1.length));
        }
        for (let key in fmtObj) {
          if (new RegExp(`(${key})`).test(fmt)) {
            //日期，时、分、秒替换，判断fmt是否需要补0，如：yyyy-M-d h:m:s 不补0,yyyy-MM-dd hh:mm:ss 则自动补0
            fmt = fmt.replace(
              RegExp.$1,
              RegExp.$1.length == 1 ?
              fmtObj[key] :
              ('00' + fmtObj[key]).substr(('' + fmtObj[key]).length),
            );
          }
        }
        return fmt;
      }
    },
    created() {
      getInfo().then(response => {
        console.log(response)
        this.user = response
        setWzglUser(this.user)
      }).catch(error => {})
      this.start_time = this.recentTime(-14, 'yyyy-MM-dd')
      this.end_time = this.getNowDate()
      this.dateRange = [this.start_time,this.end_time]
      this.loadData();
      this.loadChart()
    },
    mounted() {
      window.onresize = () => {
        this.col.resize()
        this.line.resize()
      }

    },
    destroyed() {
      window.onresize = null
    }
  }
</script>

<style lang="scss" scoped>
  .chart-wrapper{
    background:#fff;
    padding:10px;
    font-size:20px;
    color:#0077CC;
    .chart-title{
      display: flex;
      justify-content: space-between;
    }
  }
  .statistics {
    display: flex;

    margin-top: 20px;

    &-title {

      padding-left: 6px;
    }

    &-content {
      text-align: center;
      font-size: 13px;

      &-top {

        &__num {
          font-weight: 600;
        }

        &__name {
          font-size: 10px;
          color: rgb(140, 140, 140);
        }
      }

      &-bottom {
        display: flex;
        justify-content: space-between;

        &-left {

          &__num {
            font-weight: 600;
          }

          &__name {
            font-size: 10px;
            color: rgb(140, 140, 140);
          }
        }

        &-right {

          &__num {
            font-weight: 600;
          }

          &__name {
            font-size: 10px;
            color: rgb(140, 140, 140);
          }
        }
      }
    }

    &>div {
      flex: 1;
      margin-right: 20px;

      &:last-child {
        margin-right: 0;
      }
    }
  }

  .chart {
    display: flex;

    margin-top: 20px;


    .chartItem {

      width: 49%;

      .chartItemTitle {
        font-size: 16px;
        margin-bottom: 20px;
      }

      #col-chart {
        background: #fff;
        border-radius: 10px;
        flex: 1;
        margin-right: 20px;
        padding: 20px;
        box-sizing: border-box;
        min-height: 400px;
        width: 100%;
      }

      #line-chart {
        background: #fff;
        border-radius: 10px;
        flex: 1;
        padding: 20px;
        box-sizing: border-box;
        min-height: 400px;
      }
    }


  }
</style>
