<template>
  <div class="app-container">
    <div class="app-container-search main-bgcolor main-radius">
      <h1 class="">销售趋势</h1>
      <br />
      <!-- 搜索工作栏 -->
      <StatsForm
        ref="searchForm"
        :searchFormParam="{ queryParams, dataSource }"
        :showSearch.sync="showSearch"
        @handleQuery="handleQuery"
        @selectChage="selectChage"
      ></StatsForm>
        </div>
        <div
          class="echart"
          id="mychart"
          :style="{ float: 'left', width: '100%', height: '400px' }"
      ></div>
      </div>
</template>

<script>
    import * as echarts from "echarts";
    import { getBusinessNameList } from '@/api/basic/businessInfo'
    import StatsForm from '@/components/Customer/SearchForm'
    import StatsTable from '@/components/EmptyTable'
    import { getGoodsNameList } from '@/api/basic/goodsInfo'
    import { getScanCountToday } from '@/api/identity/scanRecord'
    export default {
      name: 'DiversionStats',
      components: {
        StatsForm,
        StatsTable,
      },
    data() {
      return {
        //展示层
        foldBoole: false,
        // 遮罩层
        loading: true,
        // 导出遮罩层
        exportLoading: false,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 窜货统计列表
        list: [],
        // 弹出层标题
        title: '',
        // 是否显示弹出层
        open: false,
        scanCountToday: {},
        chartOption:{},
        myChart: null,
        // 查询参数

        queryParams: {
          pageNo: 1,
          pageSize: 10,
          dealerId: null,
          dealerName: null,
          batchId: null,
          goodsId: null,
          goodsName: null,
          num: null,
          belongBusinessId: null,
          belongBusinessName: null,
          businessName: null,
          timeHorizon: null,
          scanCount: null,
          createTime: [],
        },
        //表对象
        dataSource: [
          {
            key: 'belongBusinessName', //商户名称
            itemType: 'select',
            label: '商户名称',
            placeholder: '请选择品牌',
            onEnterKeyUp: this.handleQuery,
            options: [],
            isNet: true,
          },
          {
            key: 'goodsName', //商品名称
            itemType: 'select',
            label: '商品',
            placeholder: '请输入',
            onEnterKeyUp: this.handleQuery,
            options: [],
          },
          {
            key: 'timeHorizon', //时间范围
            itemType: 'datePicker',
            label: '时间范围',
            placeholder: '请选择',
            onEnterKeyUp: this.handleQuery,
          },
        ],
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          businessName: [
            { required: true, message: '商户名称不能为空', trigger: 'blur' },
          ],
          goodsName: [
            { required: true, message: '商品名称不能为空', trigger: 'blur' },
          ],
        },
        datalist: this.$route.query

      }
    },
    mounted() {
      if( this.datalist && this.datalist.params ){
        let params = JSON.parse( this.datalist.params );
        console.log('params',params);
        this.queryParams = {
          ...this.queryParams,
          ...params,
        };
        let obj = {
          value : params.belongBusinessId,
          type: 'goodsName',
          book: true,
        };
        this.selectChage(obj);
        this.handleQuery();
      }
      this.initEcharts();

    },
    created() {
      this.getBusinessNameList()
    },
    methods: {
      initEcharts() {
        console.log(this.datalist,"aaaaaaaaaaaaaaaaaa")
        const option = {
          title: {
            text: "当月统计"
          },
          tooltip: {},
          legend: {
            show: true,
            right: '5%',
            bottom: '18%',
            itemWidth: 16,
            itemHeight: 6,
            icon: 'rect',
            textStyle: {
              padding: [0 , 0 , 0 , 10 ],
            },
          },
          xAxis:{
            type: 'category',
            data: [],
            axisTick: {
              alignWithLabel: true,
            },
            axisLabel: {
              interval: 10,
            },
          },
          yAxis: {
            type: 'value',
            minInterval: 1,
            splitLine : {
              lineStyle: {
                type: 'dotted' //设置网格线类型 dotted：虚线 solid:实线
              },
              show: true,
            },
          },
          series: [
            {
              data: [],
              type: 'line',
              symbol: 'none',
            }
          ]
        };
        let that = this
        this.chartOption = option
        this.myChart = echarts.init(document.getElementById("mychart"));// 图标初始化
        this.myChart.setOption(option);// 渲染页面

        //随着屏幕大小调节图表
        window.addEventListener("resize",function() {
          that.myChart.resize();
        });
      },
      selectChage({ value, type, book }) {
        console.log('选择',value, type, book);
        if (type != 'goodsName') {
          this.queryParams.goodsName = ''
        }
        if (!book) {
          return
        }
        getGoodsNameList({
          ids: value,
        }).then((res) => {
          console.log(res, 'res')
          this.$nextTick(() => {
            this.dataSource[1].options = res.data.map((el) => {
              let obj = {
                label: el.goodsName,
                value: el.id,
                key: el.id,
              }
              return obj
            })
          })
        })
      },
      /** 查询列表 */
      getList() {
        // this.loading = true
        // 执行查询
        getScanCountToday(this.queryParams).then((response) => {
           console.log("response",response,this.queryParams, this.dataSource[1].options);
          let data = response, dataList = [],dateList = []
          for(let date in data){
            dateList.push(date)
          }
          dateList = dateList.sort((a,b) => new Date(a).getTime()- new Date(b).getTime())
          dateList.forEach(key => {
            dataList.push(data[key])
          })
          console.log('查询', this.queryParams.goodsName );
          let name = this.dataSource[1].options.find(item => item.label === this.queryParams.goodsName).label;
          // this.chartOption.legend.data = [name]
          this.chartOption.xAxis.data = dateList
          this.chartOption.series[0].name = name
          this.chartOption.series[0].data = dataList

          this.myChart.setOption(this.chartOption);// 渲染页面
          console.log(this.myChart,this.chartOption)
        })
      },
      //获取商户名称
      async getBusinessNameList() {
        const res = await getBusinessNameList()
        console.log('res', res)
        this.$nextTick(() => {
          this.dataSource[0].options = res.data.map((el) => {
            let obj = {
              label: el.businessName,
              value: el.id,
              key: el.id,
            }
            return obj
          })
        })
      },
      //获取商品名称
      async getGoodsNameList() {
        const res = await getGoodsNameList()
        console.log('res', res)
        this.$nextTick(() => {
          this.dataSource[1].options = res.data.map((el) => {
            let obj = {
              label: el.goodsName,
              value: el.id,
              key: el.id,
            }
            return obj
          })
        })
      },
      /** 取消按钮 */
      cancel() {
        this.open = false
        this.reset()
      },
      /** 表单重置 */
      reset() {
        this.form = {
          businessName: undefined,
          goodsName: undefined,
          timeHorizon: undefined,
        }
        this.resetForm('form')
      },
      /** 搜索按钮操作 */
      handleQuery() {
        if( !this.queryParams.belongBusinessName || !this.queryParams.goodsName || !this.queryParams.timeHorizon || this.queryParams.timeHorizon.length == 0 ){
          this.$message.error("搜索栏所有参数不能为空");
          return false;
        }
        this.queryParams.pageNo = 1
        this.getList()
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm('queryForm')
        this.handleQuery()
      },
    },
  }
  </script>
