<template>
  <div>
    <!--头部搜索区-->
    <el-row>
      <el-form :model="searchData" :rules="rules" ref="ruleForm">
        <el-col :span="5">
          <el-form-item prop="productId">
            <el-input clearable v-model="searchData.productId" placeholder="输入商品ID或商品链接"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4" :offset="1">
          <el-form-item prop="queryDate">
            <el-date-picker
              v-model="searchData.queryDate"
              align="right"
              type="date"
              placeholder="选择查询日期"
              :picker-options="pickerOptions"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              style="width: 100%;">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="3" :offset="1">
          <el-form-item>
            <el-button type="primary" :disabled="isDisabled" icon="el-icon-search" @click="submitForm('ruleForm')">查询
            </el-button>
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>
    <template>
      <!--商品信息-->
      <el-row>
        <el-col :span="18">
          <div class="goods-info">
            <div class="goods-cover">
              <img :src="goodsInfo.img" alt="">
            </div>
            <div class="goods-detail">
              <p><span>商品名称：</span>{{ goodsInfo.title }}<span></span>
              <p><span>店铺名称：</span><span>{{ goodsInfo.shopName }}</span></p>
              <p><span>近30天付费人数：</span><span>{{ goodsInfo.totalPayNum}}</span></p>
            </div>
          </div>
        </el-col>
        <el-row :span="6"
                type="flex"
                :justify="'end'">
          <el-button :type="numSelectDate === day ? 'primary' : ''" size="small" v-for="day in [7, 30]"
                     @click="funSelectDate(day)" :key="day">近{{ day }}日数据
          </el-button>
        </el-row>
      </el-row>
      <el-row>
        <el-col class="TT-title">
          <span>关键指标对比</span>
          <template v-if="myzhishuData.length">
            <span>{{ myzhishuData[0].time }}</span>
            <span> -{{ myzhishuData[myzhishuData.length - 1].time }}</span>
          </template>
        </el-col>

      </el-row>
      <!--折线图-->
      <el-row>
        <el-col :span="24">
          <div class="chart-box" ref="myChartLineBox"></div>
        </el-col>
      </el-row>
      <!--表格-->
      <el-row type="flex"
              justify="space-between">
        <el-col :span="12">
          <div class="TT-title-wrap">
            <p class="TT-title">
              <span>每日对比</span>
              <template v-if="myzhishuData.length">
                <span>{{ myzhishuData[0].time }}</span>
                <span> -{{ myzhishuData[myzhishuData.length - 1].time }}</span>
              </template>
            </p>
            <p>
              <el-button type="primary" size="small" @click="exportExcel('my-table0')">导出</el-button>
            </p>
          </div>
          <el-table
            id="my-table0"
            :data="myzhishuData"
            border
            :summary-method="getSummaries"
            :header-cell-style="{background: '#f5f7fa'}"
            show-summary
            style="width: 100%; margin-top: 20px;">
            <el-table-column
              align="center"
              prop="time"
              label="日期">
            </el-table-column>
            <el-table-column
              align="center"
              sortable
              prop="uvIndex"
              label="访客数">
            </el-table-column>
            <el-table-column
              align="center"
              sortable
              prop="tradeIndex"
              label="买家数">
            </el-table-column>
            <el-table-column
              width="120px"
              align="center"
              sortable
              prop="payByrCntIndex"
              label="交易金额">
            </el-table-column>
            <el-table-column
              width="120px"
              align="center"
              sortable
              prop="payRateIndex"
              label="支付转化率">
              <template slot-scope="scope">
                <span>{{ scope.row.payRateIndex }}%</span>
              </template>
            </el-table-column>
            <el-table-column
              width="120px"
              align="center"
              sortable
              prop="avgPrice"
              label="客单价">
            </el-table-column>
            <el-table-column
              align="center"
              sortable
              prop="avgUvPrice"
              label="UV值">
            </el-table-column>
          </el-table>
        </el-col>
        <el-col :span="11">
          <div class="TT-title-wrap">
            <p class="TT-title">
              <span>流量来源分析</span>
              <span v-if="myzhishuData.length">{{ myzhishuData[myzhishuData.length - 1].time }}</span>
            </p>
            <p>
              <el-button type="primary" size="small" @click="exportExcel('my-table1')">导出</el-button>
            </p>
          </div>
          <el-table
            id="my-table1"
            :data="liuliangSource"
            border
            :header-cell-style="{background: '#f5f7fa'}"
            style="width: 100%; margin-top: 20px;">
            <el-table-column
              align="center"
              prop="pageName"
              label="渠道">
            </el-table-column>
            <el-table-column
              align="center"
              sortable
              prop="uvIndex"
              label="访客数">
            </el-table-column>
            <el-table-column
              align="center"
              sortable
              prop="crtByrCntIndex"
              label="下单买家数">
            </el-table-column>
            <el-table-column
              width="120px"
              align="center"
              sortable
              prop="payRateIndex"
              label="支付买家数">
            </el-table-column>
            <el-table-column
              width="120px"
              align="center"
              sortable
              prop="payByrCntIndex"
              label="支付转化率">
              <template slot-scope="scope">
                <span>{{ scope.row.payByrCntIndex }}%</span>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </template>
  </div>
</template>

<script>
import echarts from 'echarts'
import FileSaver from 'file-saver'
import XLSX from 'xlsx'

export default {
  name: 'toolsAnalyze',
  data () {
    return {
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() > Date.now() - 8.64e7
        },
        shortcuts: [{
          text: '今天',
          onClick (picker) {
            picker.$emit('pick', new Date())
          }
        }, {
          text: '昨天',
          onClick (picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', date)
          }
        }, {
          text: '一周前',
          onClick (picker) {
            const date = new Date()
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', date)
          }
        }]
      },
      searchData: {
        productId: '', // 602950702411
        queryDate: ''
      },
      rules: {
        productId: [{ required: true, message: '请输入需要查询的商品ID', trigger: 'blur' }],
        queryDate: [{ type: 'string', required: true, message: '选择查询日期', trigger: 'change' }]
      },
      numSelectDate: 30,
      isDisabled: false,
      goodsInfo: {
        title: '',
        shopName: '',
        img: '',
        totalPayNum: 0
      },
      liuliangSource: [],
      zhishuData: [],
      chartLine: null
    }
  },
  computed: {
    myzhishuData () {
      return this.zhishuData.slice(-this.numSelectDate)
    }
  },
  activated () {
    // 由于给echart添加了resize事件, 在组件激活时需要重新resize绘画一次, 否则出现空白bug
    if (this.chartLine) {
      this.chartLine.resize()
    }
  },
  methods: {
    submitForm (formName) {
      const postData = {
        ...this.searchData
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.isDisabled) {
            return
          }
          this.isDisabled = true
          this.$http({
            url: this.$http.adornUrl('/tb/exchangeProduct'),
            method: 'post',
            data: this.$http.adornData(postData)
          }).then(({ data }) => {
            this.isDisabled = false
            if (data.status) {
              const { liuliangSource, zhishuData, title, shopName, img, totalPayNum } = data.data
              this.liuliangSource = liuliangSource
              this.zhishuData = zhishuData
              this.goodsInfo = {
                title,
                shopName,
                img,
                totalPayNum
              }
              this.$nextTick(() => {
                this.initChartLine()
              })
              return
            }
            this.$message.error(data.msg)
          }).catch(() => {
            this.isDisabled = false
          })
        }
      })
    },
    funSelectDate (day) {
      this.numSelectDate = day
      if (!this.zhishuData.length) {
        return
      }
      this.$nextTick(() => {
        this.initChartLine()
      })
    },
    // 折线图
    initChartLine () {
      const option = {
        'title': {
          'text': '关键指标对比',
          show: false
        },
        'tooltip': {
          'trigger': 'axis'
        },
        'legend': {
          'data': ['访客数', '支付买家数', '交易金额', '支付转化率'],
          'selectedMode': 'single'
        },
        'grid': {
          'left': '3%',
          'right': '4%',
          'bottom': '3%',
          'containLabel': true
        },
        'toolbox': {
          'feature': {
            'saveAsImage': {}
          }
        },
        'xAxis': {
          'type': 'category',
          'boundaryGap': false,
          'data': this.myzhishuData.map(item => item.time)
        },
        'yAxis': {
          'type': 'value'
        },
        'series': [
          {
            'name': '访客数',
            'type': 'line',
            'stack': '总量',
            'data': this.myzhishuData.map(item => item.uvIndex)
          },
          {
            'name': '支付买家数',
            'type': 'line',
            'stack': '总量',
            'data': this.myzhishuData.map(item => item.tradeIndex)
          },
          {
            'name': '交易金额',
            'type': 'line',
            'stack': '总量',
            'data': this.myzhishuData.map(item => item.payByrCntIndex)
          },
          {
            'name': '支付转化率',
            'type': 'line',
            'stack': '总量',
            'data': this.myzhishuData.map(item => item.payRateIndex)
          }
        ]
      }
      if (!this.chartLine) {
        this.chartLine = echarts.init(this.$refs.myChartLineBox)
      }
      this.chartLine.setOption(option)
      window.addEventListener('resize', () => {
        this.chartLine.resize()
      })
    },
    getSummaries (param) {
      const { columns, data } = param
      const sums = []
      const label = ['', '总访客', '总买家', '总金额', '平均转化率', '平均客单价', '平均UV值']
      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))) {
          if (index > 0 && index < 4) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
          } else if (index === 4 || index === 6) {
            sums[index] = values.reduce((prev, curr, index) => {
              if (index !== values.length - 1) {
                return prev + curr * 100
              } else {
                return (((prev + curr * 100) / values.length) / 100).toFixed(2)
              }
            })
          } else {
            sums[index] = values.reduce((prev, curr, index) => {
              if (index !== values.length - 1) {
                return prev + curr
              } else {
                return ((prev + curr) / values.length).toFixed(2)
              }
            })
          }
          sums[index] = label[index] + '\n' + (index === 4 ? sums[index] + '%' : sums[index])
        } else {
          sums[index] = ''
        }
      })

      return sums
    },
    // 导出表格所用
    exportExcel (id) {
      var excelName = id === 'my-table0' ? '每日对比' : '流量来源分析'
      var wb = XLSX.utils.table_to_book(document.querySelector('#' + id))
      var wbout = XLSX.write(wb, {
        bookType: 'xlsx',
        bookSST: true,
        type: 'array'
      })
      try {
        FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), excelName + '.xlsx')
      } catch (e) {
        if (typeof console !== 'undefined') {
          console.log(e, wbout)
        }
      }
      return wbout
    }
  },
  beforeDestroy () {
    if (this.chartLine) {
      this.chartLine.dispose()
    }
  }
}
</script>

<style lang="scss" scoped>
.goods-info {
  display: flex;
  align-items: center;
  margin-top: 20px;
}

.goods-cover {
  width: 60px;
  height: 66px;
  overflow: hidden;

  img {
    display: block;
    width: 100%;
  }
}

.goods-detail {
  margin-left: 6px;

  p {
    &:nth-of-type(2) {
      margin: 4px 0;
    }
  }

  span {
    &:nth-of-type(1) {
      color: #888;
    }
  }
}

.TT-title {
  span {
    &:nth-of-type(1) {
      margin-right: 10px;
      font-weight: 700;
      color: #333;
    }
  }
}

.chart-box {
  min-height: 400px;
}

.TT-title-wrap {
  display: flex;
  justify-content: space-between;
}

/deep/ .el-table .cell {
  white-space: pre-line;
}
</style>
