<template>
  <div class="app-container" ref="searchBar">
    <el-date-picker v-model="inputDatetime" :clearable="false" class="inputDatetime filter-item" type="daterange"
      range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" style="width: 250px;margin-right: 10px;"
      :picker-options="pickerOptions" />
    <el-button class="el-icon-arrow-left elIconArrowLeft" :disabled="Beforedisabled" @click="handleBefore" />
    <el-button class="el-icon-arrow-right elIconArrowRight" :disabled="Nextdisabled" @click="handleNext" />
    <el-button class="successBorder" @click="form_search">查询</el-button>
    <h3 style="text-align: center;">每日拌料车次</h3>
    <div id="chartLine1" :style="{height:height,width:width}" />
  </div>

</template>

<script>
  import echarts from 'echarts'

  require('echarts/theme/macarons')
  import Cookies from 'js-cookie'
  import {
    parseTime
  } from '@/utils/index.js'
  import {
    GetDataByName,
    postJson,
    GetReportform,
    whichWeek
  } from '@/api/common'
  export default {
    name: 'FormulaStatistics',
    data() {
      return {
        width: '100%',
        height: document.documentElement.clientHeight - 85 - 150 + 'px',
        startTime: parseTime(new Date(), '{y}-{m}-{d}'),
        endTime: parseTime(new Date(), '{y}-{m}-{d}'),
        inputDatetime: [new Date(), new Date()],
        Beforedisabled: false,
        Nextdisabled: false,
        pickerOptions: {
          onPick: ({
            maxDate,
            minDate
          }) => {
            this.pickerMinDate = minDate.getTime()
            if (maxDate) {
              this.pickerMinDate = ''
            }
          },
          // 限制不能选择明天之后的日期
          disabledDate: (time) => {
            if (this.pickerMinDate !== '') {
              const one = 31 * 24 * 3600 * 1000
              const minTime = this.pickerMinDate - one
              let maxTime = this.pickerMinDate + one

              // console.log(minTime, 'minTime')
              // console.log(maxTime, 'maxTime')
              // console.log(new Date(), 'new Date()')
              // console.log(Date.now(), 'Date.now()')
              // console.log(time.getTime(), 'time.getTime()')
              if (maxTime > new Date()) {
                maxTime = Date.now() + 8.64e7
              }

              return time.getTime() < minTime || time.getTime() > maxTime
            }
            return time.getTime() > Date.now() + 8.64e7
          }
        },
        chart1: {
          chartLine: null,
          chartLine_data: {},

          tableKey: 1,
          list: [],
          total: 0,
          listLoading: true,
          statisticsList: [],
          chart1Data1: [],
          isChart: true,
          isTable: false,
          table: {
            tableKey: 1,
            list: [],
            total: 0,
            listLoading: false
          }
        }
      }
    },

    created() {
      // this.getChart1()
      this.getChart1()
    },

    methods: {
      handleBefore() {
        if (this.inputDatetime !== '' && this.inputDatetime !== null) {
          var start = new Date(this.inputDatetime[0].setDate(this.inputDatetime[0].getDate() - 1))
          var stop = new Date(this.inputDatetime[1].setDate(this.inputDatetime[1].getDate() - 1))
          if (stop > Date.now()) {
            this.Nextdisabled = true
            this.Beforedisabled = false
          } else {
            this.Nextdisabled = false
            this.Beforedisabled = false
          }
          this.inputDatetime.length = 0
          this.inputDatetime.push(start, stop)
          this.$forceUpdate()
        }
        this.startTime = parseTime(this.inputDatetime[0], '{y}-{m}-{d}')
        this.endTime = parseTime(this.inputDatetime[1], '{y}-{m}-{d}')
        this.getList()
      },
      handleNext() {
        if (this.inputDatetime !== '' && this.inputDatetime !== null) {
          var start2 = new Date(this.inputDatetime[0].setDate(this.inputDatetime[0].getDate() + 1))
          var stop2 = new Date(this.inputDatetime[1].setDate(this.inputDatetime[1].getDate() + 1))
          if (stop2 > Date.now()) {
            this.Nextdisabled = true
            this.Beforedisabled = false
          } else {
            this.Nextdisabled = false
            this.Beforedisabled = false
          }
          this.inputDatetime.length = 0
          this.inputDatetime.push(start2, stop2)
          this.$forceUpdate()
        }
        this.startTime = parseTime(this.inputDatetime[0], '{y}-{m}-{d}')
        this.endTime = parseTime(this.inputDatetime[1], '{y}-{m}-{d}')
        this.getChart1()
      },
      form_search() {
        this.getChart1()
      },
      getChart1() {
        this.chart1.listLoading = true
        const url = 'authdata/formulastatistics'
        const data = {}
        // data.parammaps = {}
        data.pastureId = Cookies.get('pastureid')
        data.startTime = parseTime(this.inputDatetime[0], '{y}-{m}-{d}')
        data.endTime = parseTime(this.inputDatetime[1], '{y}-{m}-{d}')
        postJson(url, data).then(response => {
          if (response.data !== null) {
            this.chart1.chartLine_data = {}
            this.chart1.chartLine_data = response.data
            // this.chart1.chartLine_data.xdata = ['业务系统1', '业务系统2', '业务系统3', '业务系统4', '业务系统5', '业务系统6', '业务系统7']
            // // this.chart1.chartLine_data.data1 = ['高危', '中低', '低危','']
            // this.chart1.chartLine_data.data1 = ['高危', '中低', '低危']
            // this.chart1.chartLine_data.data2 = [
            //   [50, 60, 59, 50, 50, 50, 50],
            //   [70, 70, 70, 70, 70, 70, 0],
            //   [70, 70, 70, 70, 70, 70, 70]
            // ]
          } else {
            this.chart1.chartLine_data = []
          }
          this.roadChartLine1(this.chart1.chartLine_data)
          setTimeout(() => {
            this.chart1.listLoading = false
          }, 100)
        })
      },
      roadChartLine1(chartLine_data) {
        if (this.chart1.chartLine != null) {
          this.chart1.chartLine.dispose()
        }
        this.chart1.chartLine = echarts.init(document.getElementById('chartLine1'))
        var option = {
          tooltip:{
            // trigger: 'axis'
            formatter: (param, ticket, callback) => {
              var str = ''
              str +=  param.name + '<br>' + param.marker + ' ' + param.seriesName +':' +param.value
              console.log(ticket,'ticket')
              return str
            }
          },
          grid: {
            top: '30%',
            left: '3%',
            right: '10%',
            // bottom: '3%',
            containLabel: true
          },
          legend: {
            data:chartLine_data.data1
          },
          xAxis: {
            data: chartLine_data.xdata,
            type: 'category',
            axisLabel: {
              showMaxLabel: true
            }
          },
          yAxis: {
            type: 'value',
            max: function(value) {
              return (value.max+1)
            }
          },
          series: (function() {
            var serie = []
            if (chartLine_data.data2 !== null) {
              for (var i = 0; i < chartLine_data.data2.length; i++) {
                var item = {
                  name: chartLine_data.data1[i],
                  type: 'bar',
                  stack: '总量',
                  label: {
                    show: true,
                    formatter: function(params) {
                      const a = params.value
                      if (a > 0) {
                        return a
                      } else {
                        return ''
                      }
                    },
                    color: 'black'
                  },
                  emphasis: {
                    focus: 'series'
                  },
                  data: chartLine_data.data2[i]
                }
                serie.push(item)
              }
              var item2 = {
                name: '',
                type: 'bar',
                stack: '总量',
                label: {
                  show: true,
                  position: 'top',
                  formatter: function(params) {
                    const a = params.value
                    if (a > 0) {
                      return a
                    } else {
                      return ''
                    }
                  }
                },
                emphasis: {
                  focus: 'series'
                },
                data: chartLine_data.data2[chartLine_data.data2.length -1]
              }
              serie.push(item2)
            }
            return serie
          }())
        };
        var series = option.series

        function getSum(params) {
          var datavalue = 0
          for (var i = 0; i < series.length; i++) {
            datavalue += series[i].data[params.dataIndex]
          }
          return datavalue
        }
        series[series.length - 1].label.formatter = getSum
        this.chart1.chartLine.setOption(option, true);

        this.chart1.chartLine.on('legendselectchanged', (obj) => {
               function getSum (params) {
                 var datavalue = 0
                 for (var i = 0; i < series.length; i++) {
                   if (obj.selected[series[i].name]) {
                     datavalue += series[i].data[params.dataIndex]
                   }
                 }
                 return datavalue
               }
               series[series.length - 1].label.formatter = getSum
               this.chart1.chartLine.setOption(option)
             })
        // this.chart1.chartLine.setOption(option, true);
      },
    }
  }
</script>
