<template>
  <div class="content">
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>销售报表</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <el-card shadow="hover"> 
      <!-- 搜索 -->
      <el-form :inline="true" size="small" v-model="listQuery">
         <el-form-item label="城市">
          <el-select v-model="listQuery.city"  clearable placeholder="请选择城市" @change="cityChange">
            <el-option  v-for="(item,index) in cityList"
                            :key="index"
                            :label="item"
                            :value="item"
                        ></el-option>
          </el-select>
        </el-form-item>
          <el-form-item label="门店">
          <el-select v-model="listQuery.storeNames"  clearable placeholder="请选择门店" multiple>
            <el-option  v-for="(item,index) in stationList"
                            :key="index"
                            :label="item"
                            :value="item"
                        ></el-option>
          </el-select>
        </el-form-item>
           <el-form-item label="业务线">
          <el-select v-model="listQuery.bizline" value-key="id" placeholder multiple clearable @change='getbuzLine_levelone_1' >
           <el-option  v-for="item  in displayList"
                            :key="item.id"
                            :label="item.businessLine"
                            :value="item"
                        ></el-option>
          </el-select> 
        </el-form-item>  
         <el-form-item label="一级分类">
        <el-select v-model="listQuery.levelOnes"  value-key="id" clearable placeholder="请选择一级分类" multiple @change='getbuzLine_leveltwo_1'>
            <el-option  v-for="item  in levelOneList_a"
                            :key="item.id"
                            :label="item.businessLine+'—'+item.levelOne"
                            :value="item"
                        ></el-option>
          </el-select>
        </el-form-item>  
        <el-form-item label="二级分类">
          <el-select v-model="listQuery.levelTwos"  value-key="id"  clearable placeholder="请选择一级分类" multiple>
            <el-option  v-for="item  in levelTwoList_a"
                            :key="item.id"
                            :label="item.businessLine+'—'+item.levelOne+'-'+item.levelTwo"
                            :value="item"
                        ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="listQuery.createTime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            @change="dateChange"
          ></el-date-picker>
        </el-form-item>
       
        <el-form-item>
          <el-button icon="el-icon-search" type="primary" plan @click="getSaleReportData">查询</el-button>
        </el-form-item>
      </el-form>

      <div class="hello" style="overflow-x: auto;" >
        <div id="mainChart" :style="'width:'+mywidth_1+'px'"></div>
        <!-- <div id="main2" style="width: 600px;height:400px; margin:0 auto; padding:40px;"></div>
        <div id="main3" style="width: 600px;height:400px; margin:0 auto; padding:40px;"></div>-->
      </div>
    </el-card>

    <el-card shadow="hover">
      <!-- 搜索 -->
      <el-form :inline="true" size="small" v-model="listQuery">
         <el-form-item label="城市">
          <el-select v-model="listQuery1.city"  clearable placeholder="请选择城市" @change="cityChange1">
            <el-option  v-for="(item,index) in cityList"
                            :key="index"
                            :label="item"
                            :value="item"
                        ></el-option>
          </el-select>
        </el-form-item>
          <el-form-item label="门店">
          <el-select v-model="listQuery1.storeNames"  clearable placeholder="请选择门店" multiple>
            <el-option  v-for="(item,index) in stationList1"
                            :key="index"
                            :label="item"
                            :value="item"
                        ></el-option>
          </el-select>
        </el-form-item>
         <el-form-item label="业务线">
          <el-select v-model="listQuery1.bizline" value-key="id" placeholder multiple clearable @change='getbuzLine_levelone_2' >
           <el-option  v-for="item  in displayList"
                            :key="item.id"
                            :label="item.businessLine"
                            :value="item"
                        ></el-option>
          </el-select> 
        </el-form-item>  
         <el-form-item label="一级分类">
        <el-select v-model="listQuery1.levelOnes"  value-key="id" clearable placeholder="请选择一级分类" multiple @change='getbuzLine_leveltwo_2'>
            <el-option  v-for="item  in levelOneList_b"
                            :key="item.id"
                            :label="item.businessLine+'—'+item.levelOne"
                            :value="item"
                        ></el-option>
          </el-select>
        </el-form-item>  
        <el-form-item label="二级分类">
          <el-select v-model="listQuery1.levelTwos"  value-key="id"  clearable placeholder="请选择一级分类" multiple>
            <el-option  v-for="item  in levelTwoList_b"
                            :key="item.id"
                            :label="item.businessLine+'—'+item.levelOne+'-'+item.levelTwo"
                            :value="item"
                        ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="listQuery1.createTime"
            type="monthrange"
            range-separator="至"
            start-placeholder="开始月份"
            end-placeholder="结束月份"
            value-format="yyyy-MM"
             :picker-options="pickerOptions1"
            @change="dateChange1"
          ></el-date-picker>
        </el-form-item>
       
        <el-form-item>
          <el-button icon="el-icon-search" type="primary" plan @click="getMonthlySaleReportData">查询</el-button>
        </el-form-item>
      </el-form>

      <div class="hello">
        <div id="mainChart1" ></div>
        <!-- <div id="main2" style="width: 600px;height:400px; margin:0 auto; padding:40px;"></div>
        <div id="main3" style="width: 600px;height:400px; margin:0 auto; padding:40px;"></div>-->
      </div>
    </el-card>
  </div>
</template>

<script>
import Service from "../script/api/service";
export default {
  name: "HelloWorld",
  data() {
    return {
      mywidth_1:900,
      cityList:[],
      stationList:[],
      allStationList:[],
      displayList:[], //业务线 接口返回
      levelOneList_a:[],//一级分类
      levelTwoList_a:[],//二级分类
      listQuery: {
        city:'',
        storeNames:[],
        bizline:[],
        levelOnes:[],
        levelTwos:[],
        createTime: ""
      },
      
       levelOneList_b:[],//一级分类
      levelTwoList_b:[],//二级分类
      stationList1:[],
      listQuery1: {
        city:'',
        storeNames:[],
         bizline:[],
        levelOnes:[],
        levelTwos:[],
        createTime: ""
      },
      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 * 15);
              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]);
            }
          }
        ]
      },
       pickerOptions1: {
          shortcuts: [{
            text: '今年至今',
            onClick(picker) {
              const end = new Date();
              const start = new Date(new Date().getFullYear(), 0);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近六个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setMonth(start.getMonth() - 6);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近一年',
            onClick(picker) {
             const end = new Date();
              const start = new Date();
              start.setMonth(start.getMonth() - 12);
              picker.$emit('pick', [start, end]);
            }
          }]
        },
    };
  },
  mounted() {
    let token = this.$route.query.token;
    // console.log(token);
    let currentTime = new Date().getTime();
    let currentDate = this.formateDay(
      new Date(currentTime - 3600 * 1000 * 24 * 1)
    );

    let startDate = this.formateDay(
      new Date(currentTime - 3600 * 1000 * 24 * 7)
    );
    let beginMonth=this.formateMonth(
      new Date(currentTime - 3600 * 1000 * 24 * 365)
    );
     let endMonth=this.formateMonth(
      new Date()
    );
    this.listQuery.createTime = [startDate, currentDate];
    this.listQuery1.createTime = [beginMonth, endMonth];
   
    this.getCityStation();
    this.getDisplay();
     this.getSaleReportData();
     this.getMonthlySaleReportData();
  },
  methods: {
    insertLog(requestParm,url){
           // 插入导出日志
           let userInfo= JSON.parse(window.localStorage.getItem("userInfo"));
         Service.$axiosExportLog({
           functionName:'报表统计-销售报表',
           systemName:'报表系统',
           requestParm:JSON.stringify(requestParm),
           requestUrl :process.env.baseUrl +url,
           userId:userInfo.id,
           userName:userInfo.userName
          })
            .then((res) => {
              // console.log('导出日志'+res.data);
 })
            .catch((err) => {
              // console.log(err);
            });
    },
    getbuzLine_levelone_1(e){
      // console.log(e);
      let temparr=[];
      if(e.length>0){
        e.forEach(function(d){
          temparr=temparr.concat(d.listchild);
        })
      }
      this.levelOneList_a=temparr;
      this.listQuery.levelOnes=[];
      this.listQuery.levelTwos=[];
      this.levelTwoList_a=[];
       
    },
    
    getbuzLine_leveltwo_1(e){
      //  console.log(e);
      let temparr=[];
      if(e.length>0){
        e.forEach(function(d){
          temparr=temparr.concat(d.listchild);
        })
      }
     this.levelTwoList_a=temparr;
       this.listQuery.levelTwos=[];
    },
    //--------------------------11
     getbuzLine_levelone_2(e){
      // console.log(e);
      let temparr=[];
      if(e.length>0){
        e.forEach(function(d){
          temparr=temparr.concat(d.listchild);
        })
      }
      this.levelOneList_b=temparr;
      this.listQuery1.levelOnes=[];
      this.listQuery1.levelTwos=[];
      this.levelTwoList_b=[];
       
    },
    getbuzLine_leveltwo_2(e){
      //  console.log(e);
      let temparr=[];
      if(e.length>0){
        e.forEach(function(d){
          temparr=temparr.concat(d.listchild);
        })
      }
     this.levelTwoList_b=temparr;
       this.listQuery1.levelTwos=[];
    },
    //-------------------------------22
    dateChange(e) {
      if (e != null) {
        let start = new Date(e[0]).getTime();
        let end = new Date(e[1]).getTime();
        let isOvertime = end - start - 3600 * 1000 * 24 * 30 > 0;
        if (isOvertime) {
          this.$message.warning("选中时间范围不能超过一个月");
          this.listQuery.createTime = null;
        }
      }
    },
    dateChange1(e) {
      // console.log(this.listQuery1.createTime);
      if (e != null) {
        let start = (new Date(e[0]).getFullYear())*12+new Date(e[0]).getMonth();
        let end = (new Date(e[1]).getFullYear())*12+new Date(e[1]).getMonth();
        let isOvertime = end - start - 12 > 0;
        if (isOvertime) {
          this.$message.warning("选中时间范围不能超过一年");
          this.listQuery1.createTime = null;
        }
      }
    },
    
    getCityStation(){
      Service.$axiosGetCityStation().then(res => {
        if (res.data.errno == "0") {
           this.cityList=res.data.data.city;
           this.allStationList=res.data.data.storeStation;
        } else {
          this.$message.warning(res.data.errmsg);
        }
      });
    },
     getDisplay(){
      Service.$axiosGetdisplay().then(res => {
        if (res.data.errno == "0") {
          this.displayList=res.data.data;
          // let businessLineList=[];
          // let levelOneList=[];
          // let levelTwoList=[];
          // this.displayList.forEach(item=>{
          //     // businessLineList.push(item.businessLine);
          //     levelOneList=levelOneList.concat(item.listchild);
          //     if(item.listchild){
          //          item.listchild.forEach(two=>{
          //      levelTwoList=levelTwoList.concat(two.listchild);
          //          });
          //     }

          // })
          // this.levelOneList=levelOneList;
          // this.levelTwoList=levelTwoList;
          // console.log(this.levelTwoList);
        } else {
          this.$message.warning(res.data.errmsg);
        }
      });
    },
    cityChange(value){
      this.listQuery.storeNames=[];
      let currentStation=this.allStationList.filter(item=>{return item.city==value});
      this.stationList=currentStation[0].childShop;

    },
     cityChange1(value){
      this.listQuery1.storeNames=[];
      let currentStation=this.allStationList.filter(item=>{return item.city==value});
      this.stationList1=currentStation[0].childShop;

    },
    querySearch() {
      // startTime: !this.isEmptyObjVue(this.listQuery.createTime) ? this.listQuery.createTime[0] + ' 00:00:00' : '',
      // endTime: !this.isEmptyObjVue(this.listQuery.createTime) ? this.listQuery.createTime[1] + ' 23:59:59' : '',
    },
    getSaleReportData() {

      let tempbusinessLine=[];
       let templevelOnes=[];
        let templevelTwos=[];
      this.listQuery.bizline.forEach(function(e){
        tempbusinessLine.push(e.businessLine);
      })
       this.listQuery.levelOnes.forEach(function(e){
        templevelOnes.push(e.levelOne);
      })
       this.listQuery.levelTwos.forEach(function(e){
        templevelTwos.push(e.levelTwo);
      })

      let params = {
        startTime: !this.isEmptyObjVue(this.listQuery.createTime)
          ? this.listQuery.createTime[0]+" 00:00:00"
          : "",
        endTime: !this.isEmptyObjVue(this.listQuery.createTime)
          ? this.listQuery.createTime[1]+" 23:59:59"
          : "",
        city: this.listQuery.city,
        storeNames:this.listQuery.storeNames.join(','),
        businessLine:tempbusinessLine.join(','),
        levelOnes:templevelOnes.join(','),
        levelTwos:templevelTwos.join(','),
      };
      Service.$axiosGetSaleReportData(params).then(res => {
        if (res.data.errno == "0") {
          this.initEchart(res.data.data,'mainChart','每日销售报表');
           // 插入日志
          
          this.insertLog(params,'/reportservice/report/getSaleReportData');
        } else {
          this.$message.warning(res.data.errmsg);
        }
      });
    },
    getMonthlySaleReportData(){
       let tempbusinessLine=[];
       let templevelOnes=[];
        let templevelTwos=[];
      this.listQuery1.bizline.forEach(function(e){
        tempbusinessLine.push(e.businessLine);
      })
       this.listQuery1.levelOnes.forEach(function(e){
        templevelOnes.push(e.levelOne);
      })
       this.listQuery1.levelTwos.forEach(function(e){
        templevelTwos.push(e.levelTwo);
      })

      let params = {
        beginMonth: !this.isEmptyObjVue(this.listQuery1.createTime)
          ? this.listQuery1.createTime[0]
          : "",
        endMonth: !this.isEmptyObjVue(this.listQuery1.createTime)
          ? this.listQuery1.createTime[1]
          : "",
        city: this.listQuery1.city,
        storeNames:this.listQuery1.storeNames.join(','),
        businessLine:tempbusinessLine.join(','),
        levelOnes:templevelOnes.join(','),
        levelTwos:templevelTwos.join(','),
      };
      Service.$axiosGetMonthlySaleReportData(params).then(res => {
        if (res.data.errno == "0") {
          this.initEchart(res.data.data,'mainChart1','月度销售报表');

          // 插入日志
         
          this.insertLog(params,'/reportservice/report/getMonthlySaleReportData');
        } else {
          this.$message.warning(res.data.errmsg);
        }
      });
    },
    initEchart(data,chartName,text) {
       var myChart = this.$echarts.init(document.getElementById(chartName)); 

      let dateList=[];
      if(chartName=='mainChart1'){
        dateList=data.months; 
      }else{
        dateList=data.timeList; 
        if(dateList.length>12){ 
          this.mywidth_1=900+(dateList.length*40);
          setTimeout(() => {
              myChart.resize();
          }, 500);
        } 
      }
      
      
      let pwaList = data.pwaList;
      let legendData=[];
      pwaList.forEach(item => {
         legendData.push(item.name);
        if (item.type == "line") {
          item.yAxisIndex = 1;
        }
      });
      // 指定图表的配置项和数据
      var colors = ["#5793f3", "#d14a61", "#675bba"];

      let option = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
            crossStyle: {
              color: "#999"
            }
          }
        },
        grid: {
          //  top:'20%',
          right: "20%"
        },
        toolbox: {
          feature: {
            dataView: { show: true, readOnly: false },
            magicType: { show: true, type: ["line", "bar"] },
            restore: { show: true },
            saveAsImage: { show: true }
          }
        },
       title: {
        left: 'center',
        text: text
    },
        legend: {
          //     type: 'scroll',
          orient: "vertical",
          right: 0,
          top: 150,
          // bottom: 20,
          data: legendData
        },
        xAxis: [
          {
            type: "category",
            data: dateList,
            axisPointer: {
              type: "shadow"
            }
          }
        ],
        yAxis: [
          {
            type: "value",

            splitLine: {
              show: true,
              lineStyle: {
                type: "dashed"
              }
            },

            name: "实销额（单位：元）",
            axisLine: {
              show:true,
              lineStyle: {
                color: colors[2]
              }
            },
            axisLabel: {
              formatter: "{value} 元"
            }
          },
          {
            type: "value",
            splitLine: {
              show: true,
              lineStyle: {
                type: "dashed"
              }
            },
            name: "单量计数（单位：个）",
            axisLine: {
              show:true,
              lineStyle: {
                color: colors[0]
              }
            },
            axisLabel: {
              formatter: "{value} 个"
            }
          }
        ],
        series: pwaList
      };

      // 使用刚指定的配置项和数据显示图表。
      myChart.setOption(option,true);
      myChart.resize();
    },
  
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.crumbs {
  margin: 10px 0;
}
h1,
h2 {
  font-weight: normal;
}
.el-card{
  overflow-x: scroll;
  min-width: 1200px;
}
#mainChart,#mainChart1 {
  width: 1200px;
  height: 600px;
  margin: 0 auto;
  padding: 40px;
}
</style>
