<template>

  <div style="background-color:#f7f7f7;padding:10px 10px;">
    <div class="history">
      <div style="height:58px;line-height:58px;">
        <div style="color:#0006"> <span>渠道额统计分析</span> <span style="padding:0 5px;">></span> <span
            style="color:#000000e6">销售总额统计</span></div>
      </div>
     <div >

         <!-- 顶部搜索 -->
         <div class="toolbar">
           <el-form  :inline="true" :model="pageIndex">
             <el-form-item label="渠道">
             <el-select  placeholder="全部"
               v-model="pageIndex.ticketChannel"
               style="width: 120px;margin-right: 15px">
            <el-option v-for="(item,index) in type" :label="item==1?'有赞':'其他'" :value="item" />
             </el-select>
             </el-form-item>
             <el-form-item label="票种">
             <el-select  placeholder="全部"   v-model="pageIndex.ticketType"
               style="width: 120px;margin-right: 15px">
              <el-option v-for="(item,index) in listType" :label="item" :value="item" />
             </el-select>
             </el-form-item>
             <el-form-item label="日期">
               <el-date-picker
                 v-model="pageIndex.list"
                 type="daterange"

                 range-separator="至"
                 start-placeholder="开始时间"
                 end-placeholder="结束时间"
                 value-format="yyyy-MM-dd"
               />
             </el-form-item>

             <el-form-item label-width="0">
               <el-button   @click="search" style="background-color: #3F9B6A;color: #fff">查询</el-button>
               <el-button  @click="clear" class="buttonHover"
              style="color: #606266;border: 1px solid #dddfe5;background-color: #fff;">重置</el-button>
             </el-form-item>
           </el-form>
         </div>
         <div style="margin-bottom: 20px;">
           <el-button  style="background-color: #3F9B6A;color: #fff" @click="daochu">导出</el-button>
         </div>
     </div>
        <!-- 表格 -->
        <div class="content_table" style="padding: 15px 10px 10px 20px;background-color:#F2F3F5">
          <div style="background-color: #fff;padding: 10px;margin-bottom: 20px;text-algin:center">
          <div style='padding:20px 10px;background-color:#fff;'>
            <div style="display:flex;font-size:14px;justify-content: space-evenly">
              <div style="width:10%;border-right:1px solid #F2F2F2">
                <div style="margin-bottom: 10px;font-weight: 600;">总销售额(元)</div>
                <div style="font-weight: 600;">{{moyeOne}}</div>
              </div>
              <div style="width:10%;border-right:1px solid #F2F2F2"  v-for="(item,index) in tongList">
                <div style="margin-bottom: 10px;font-weight: 600;">{{item.ticketChannel==1?'有赞':''}}销售总额(元)</div>
                <div style="font-weight: 600;">{{item.sum}}</div>
              </div>
 
            </div>
          </div>
       </div>
       <!-- 图表 -->
               <div style="display: flex;">
                      <div style="background-color: #fff;padding: 10px;margin-right: 10px;width: 32%;">
                        <div style="display: flex;border-bottom:1px solid #F2F2F2;justify-content: space-between;padding: 5px; 0 15px 0;text-align: center;">
                          <div style="line-height: 200%;">总销售额趋势表</div>
                          <!-- <el-button  style="background-color: #3F9B6A;color: #fff">导出</el-button> -->
                        </div>
                        <!-- <div style="margin:10px 0 15px 0">
                           <el-date-picker

                                v-model="value1"
                                value-format="yyyy-mm-dd"
                                type="daterange"
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期">
                              </el-date-picker>
                        </div> -->
                        <div style="color:#000;padding: 5px;">单位：张</div>
                        <!--    折线图-->
                          <div ref="container1" style="width: 400px; height: 400px;"></div>

                      </div>
                      <div style="background-color: #fff;padding: 10px;margin-right: 10px;width: 32%;">
                        <div style="display: flex;border-bottom:1px solid #F2F2F2;justify-content: space-between;padding: 5px; 0 15px 0">
                          <div style="line-height: 200%;">渠道销售情况表</div>
                          <!-- <el-button  style="background-color: #3F9B6A;color: #fff">导出</el-button> -->
                        </div>
                        <!-- <div style="margin:10px 0 15px 0">
                             <el-radio-group v-model="radio1">
                                 <el-radio-button label="全部"></el-radio-button>
                                 <el-radio-button label="美团"></el-radio-button>
                                 <el-radio-button label="大麦"></el-radio-button>
                                 <el-radio-button label="携程"></el-radio-button>
                               </el-radio-group>
                        </div> -->
                         <div style="color:#000;padding: 5px;">单位：元</div>
                        <!--    柱状图-->
                          <div ref="container2" style="width: 400px; height: 400px;"></div>

                      </div>
                      <div style="background-color: #fff;padding: 10px;width: 32%;">
                        <div style="display: flex;border-bottom:1px solid #F2F2F2;justify-content: space-between;padding: 5px; 0 15px 0">
                          <div style="line-height: 200%;">票种销售额情况表</div>
                          <!-- <el-button  style="background-color: #3F9B6A;color: #fff">导出</el-button> -->
                        </div>
                        <!-- <div style="margin:10px 0 15px 0">
                           <el-radio-group v-model="radio2">
                               <el-radio-button label="全部"></el-radio-button>
                               <el-radio-button label="票种1"></el-radio-button>
                               <el-radio-button label="票种2"></el-radio-button>
                               <el-radio-button label="票种3"></el-radio-button>
                             </el-radio-group>
                        </div> -->
                         <div style="color:#000;padding: 5px;">单位：元</div>
                        <!--    柱状图-->
                          <div ref="container3" style="width: 400px; height: 400px;"></div>

                      </div>
               </div>
        </div>

    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import {getTotalSales,excelToTotalSales} from '@/api/piaowu'
export default {
  data() {
    return {
      value1:'',
      radio1:'',
      radio2:'',
      total: 0,
      pageSize: 10,
      currentPage: 1,
      tipsList: [],
       tableData: [],
              chart1:null,
              chart2:null,
              chart3:null,
 pageIndex:{
        list: [],
            page: 1,
            pageSize: 10,
            startTime:"",
            endTime:"",
            ticketChannel:"",
            ticketType:""
        },
numOne:0,
        moyeOne:0,
        numTwo:0,
        moyeTwo:0,
        meimoye:0,
        numthree:0,
        moyethree:0,
		type:[],
		listType:[],
		tongList:[]
    }
  },
  mounted() {
    this.getAll()
	getTotalSales(this.pageIndex).then(res=>{
		this.type = this.extractAndDeduplicateTicketChannels(res.data)
		this.listType = this.listype(res.data)
	})

  },

  methods: {
    async getAll(){
      let res =   await getTotalSales(this.pageIndex)
      this.tableData = res.data
      this.total = res.data.length
		this.tongList = this.calculatePriceByTicketType(res.data)
      // this.echar(res.data.list)
       let moyeOne =0

      this.tableData.map(item=>{
           moyeOne += Number(item.price)

      })
	  this.moyeOne = moyeOne

this.echar2(this.tableData)
this.echar3( this.tableData)
this.echar( this.tableData)
      },
	  extractAndDeduplicateTicketChannels(arr) {
	  	const ticketChannels = [];
	  	for (let i = 0; i < arr.length; i++) {
	  		if (arr[i].hasOwnProperty('ticketChannel')) {
	  			ticketChannels.push(arr[i].ticketChannel);
	  		}
	  	}
	  	return [...new Set(ticketChannels)];
	  },
	  listype(arr) {
	  	const ticketChannels = [];
	  	for (let i = 0; i < arr.length; i++) {
	  		if (arr[i].hasOwnProperty('ticketType')) {
	  			ticketChannels.push(arr[i].ticketType);
	  		}
	  	}
	  	return [...new Set(ticketChannels)];
	  },
	  calculatePriceByTicketType(data) {
	      const result = {};
	      // 遍历数组中的每个对象
	      data.forEach(item => {
	          const ticketChannel = item.ticketChannel;
	          if (!result[ticketChannel]) {
	              // 如果 result 对象中还没有该 ticketChannel 的记录，初始化 sum 为 0
	              result[ticketChannel] = {
	                  ticketChannel: ticketChannel,
	                  sum: 0
	              };
	          }
	          // 累加当前对象的 price 到对应的 ticketChannel 的 sum 中
	          result[ticketChannel].sum += item.price;
	      });
	      // 将 result 对象的属性值转换为数组并返回
	      return Object.values(result);
	  },
      search(){
        if(this.pageIndex.list.length !=0){
          this.pageIndex.startTime = this.pageIndex.list[0]
          this.pageIndex.endTime = this.pageIndex.list[1]
        }
        this.getAll()
      },
      clear(){
        this.pageIndex = {
          list: [],
              page: 1,
              pageSize: 10,
              startTime:"",
              endTime:"",
              ticketChannel:"",
              ticketType:""
          }
          this.getAll()
      },
    echar(datas) {
      let Dom = this.$refs.container1
      let myChart = echarts.init(Dom)
      // let processedData = datas.map(item => ({
      //   name: item.ticketChannel,
      //   value: item.num
      // }))
   let processedData = datas.reduce((accumulator, item) => {
     // 查找当前名称是否已经存在于累加器中
     let existingItemIndex = accumulator.findIndex(i => i.name === item.time);

     // 如果存在，则累加值
     if (existingItemIndex !== -1) {
       accumulator[existingItemIndex].value += item.num;
     } else {
       // 如果不存在，则添加新项
       accumulator.push({ name: item.time, value: item.num });
     }

     return accumulator;
   }, []); // 初始值为空数组
      console.log(processedData)
      // this.chart1 = echarts.init(diameter);
      // 指定图表的配置项和数据
      let option = {
         xAxis: {
            type: 'category',
      data:processedData.map(item => item.name),
      },
          yAxis: {
            type: 'value'
          },
          series: [
            {
             data:processedData.map(item => item.value),
              type: 'line',
                itemStyle: {
                      color: '#3f9b6a',
                    },
            }
          ]
        }

      // 使用刚指定的配置项和数据显示图表。
      option && myChart.setOption(option);
    },
	weiqi(val) {
	    switch (val) {
	        case '1':
	            return '有赞';
	        case 2:
	            return '';
	        case 3:
	            return '';
	        default:
	            return '';
	    }
	},
    echar2(datas) {
      let Dom = this.$refs.container2
      let myChart = echarts.init(Dom)
      let processedData = datas.reduce((accumulator, item) => {
        // 查找当前名称是否已经存在于累加器中
        let existingItemIndex = accumulator.findIndex(i => i.name === item.ticketChannel);

        // 如果存在，则累加值
        if (existingItemIndex !== -1) {
          accumulator[existingItemIndex].value += Number(item.price);
        } else {
          // 如果不存在，则添加新项
		 
          accumulator.push({ name: item.ticketChannel , value:Number(item.price)});
        }

        return accumulator;
      }, []); // 初始值为空数组
      // this.chart2= echarts.init(diameter);
     let  option = {
        xAxis: {
          type: 'category',
          data:processedData.map(item => this.weiqi(item.name)),
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
              data:processedData.map(item => item.value),
            type: 'bar',
              itemStyle: {
                    color: '#3f9b6a',
                  },
          },

        ],

      };
         option && myChart.setOption(option);
    },
    echar3(datas) {
      let Dom = this.$refs.container3
      let myChart = echarts.init(Dom)
      let processedData = datas.reduce((accumulator, item) => {
        // 查找当前名称是否已经存在于累加器中
        let existingItemIndex = accumulator.findIndex(i => i.name === item.ticketType);

        // 如果存在，则累加值
        if (existingItemIndex !== -1) {
          accumulator[existingItemIndex].value +=Number(item.price);
        } else {
          // 如果不存在，则添加新项
          accumulator.push({ name: item.ticketType, value: Number(item.price) });
        }

        return accumulator;
      }, []); // 初始值为空数组

      // this.chart3 = echarts.init(diameter);
      // 指定图表的配置项和数据
     let  option = {
        xAxis: {
          type: 'category',
          data:processedData.map(item => item.name),
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data:processedData.map(item => item.value),
            type: 'bar',
              itemStyle: {
                    color: '#3f9b6a',
                  },
          }
        ]
      };
      // 使用刚指定的配置项和数据显示图表。
      option && myChart.setOption(option)
    },
    getSummaries(param) {
            const { columns, data } = param;
            const sums = [];
            columns.forEach((column, index) => {
              if (index === 0) {
                sums[index] = '总价';
                return;
              }
              const values = data.map(item => Number(item[column.property]));
              if (!values.every(value => isNaN(value))) {
                sums[index] = values.reduce((prev, curr) => {
                  const value = Number(curr);
                  if (!isNaN(value)) {
                    return prev + curr;
                  } else {
                    return prev;
                  }
                }, 0);
                sums[index] += ' 元';
              } else {
                sums[index] = 'N/A';
              }
            });

            return sums;
          },

        handleCurrentChange(val) {
          this.currentPage = val
        },
        handleSizeChange(val) {
          this.pageSize = val
        },
       async daochu(){
          let res = await excelToTotalSales(this.pageIndex)
          if(!res){
            return
          }
          const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
          const fileName = '总销售额明细表.xls'
          if ('download' in document.createElement('a')) {
             // 非IE下载
             const elink = document.createElement('a')
             elink.download = fileName
             elink.style.display = 'none'
             elink.href = URL.createObjectURL(blob)
             document.body.appendChild(elink)
             elink.click()
             URL.revokeObjectURL(elink.href) // 释放URL 对象
             document.body.removeChild(elink)
           } else {
            // IE10+下载
            navigator.msSaveBlob(blob, fileName)
          }
          this.$message({
            message: '导出成功',
            type: 'success'
          })


        },
   }
 }
</script>

<style lang='scss' scoped>
.history{
 padding: 0 20px 20px 20px;
    min-height: calc(100vh - 50px - 20px);
    background-color: #Fff;

}
 ::v-deep .el-form-item__label{
        font-weight: normal;
         font-size: 14px;

       }
    ::v-deep .buttonHover:hover{
      color:#3f9b6a !important;
      border-color: #c5e1d2 !important;
      background-color: #ecf5f0 !important;
      outline: none;
    }

</style>
<style scoped>



</style>
<style>
.el-tooltip__popper {
  max-width: 50%;
}
</style>
