<template>
  <div class="p_all_20" v-if="isBuySaleRank === true">
    <el-tabs v-model="activeTop" type="card" @tab-click="handleClick">
      <el-tab-pane label="品牌销售排行" name="1">
        <template>
          <el-backtop :right="150" >
            <img style="width: 60px;border-radius: 50%" src="@/assets/img/totop.png" alt="">
          </el-backtop>
        </template>
        <el-tabs v-model="activeName" @tab-click="jump" :class="{ tabbox: true, fixedTop: fixedTop }">
          <el-tab-pane label="我的品牌数据" name="selfBrandData"></el-tab-pane>
          <!--<el-tab-pane label="E淘宝活跃趋势图" name="activeTrend"></el-tab-pane>-->
          <!--<el-tab-pane label="品牌销量排行" name="brandSaleRank"></el-tab-pane>-->
        </el-tabs>
        <div class="infobox" v-loading="loadingChart">
          <div class="title2 do-jump" id="selfBrandData">我的品牌数据</div>
          <div class="chartbox">
            <div class="title">E淘宝浏览量</div>
            <div class="notice">
              <v-chart :option="view.polar" class="chart" />
              <div class="chart_btn">
                <el-radio-group v-model="view.radio" size="mini" @change="getBrandRecord">
                  <el-radio-button label="7">最近7天</el-radio-button>
                  <el-radio-button label="30">最近30天</el-radio-button>
                </el-radio-group>
              </div>
            </div>
          </div>
          <div class="flex_x_between">
            <div class="chartbox half">
              <div class="title">{{ money.radio == '7' ? '近7天' : '近30天' }}销售金额</div>
              <div class="notice">
                <v-chart :option="money.polar" class="chart" />
                <div class="chart_btn">
                  <el-radio-group v-model="money.radio" size="mini" @change="getBrandRecord">
                    <el-radio-button label="7">最近7天</el-radio-button>
                    <el-radio-button label="30">最近30天</el-radio-button>
                  </el-radio-group>
                </div>
              </div>
            </div>
            <div class="chartbox half">
              <div class="title">{{ num.radio == '7' ? '近7天' : '近30天' }}销售数量</div>
              <div class="notice">
                <v-chart :option="num.polar" class="chart" />
                <div class="chart_btn">
                  <el-radio-group v-model="num.radio" size="mini" @change="getBrandRecord">
                    <el-radio-button label="7">最近7天</el-radio-button>
                    <el-radio-button label="30">最近30天</el-radio-button>
                  </el-radio-group>
                </div>
              </div>
            </div>
          </div>
        </div>
        <template v-if="false">
          <div class="hr"></div>
          <div class="infobox" v-loading="loadingChart2">
            <div class="title2 do-jump" id="activeTrend">
              E淘宝活跃趋势图
              <span class="subtitle">（同风格品牌）</span>
            </div>
            <div class="chartbox" @mouseover="hoverChart(true)" @mouseout="hoverChart(false)">
              <div class="notice">
                <!-- 这个echart有问题，是echart自己的问题，但是并不影响使用(console里报错) -->
                <v-chart :option="activeTrend.polar" class="chart scroll-bars" />
                <div class="chart_btn">
                  <el-radio-group v-model="activeTrend.radio" size="mini" @change="activeTrendChartChange">
                    <el-radio-button label="1">昨天</el-radio-button>
                    <el-radio-button label="7">最近7天</el-radio-button>
                    <el-radio-button label="30">最近30天</el-radio-button>
                  </el-radio-group>
                </div>
              </div>
            </div>
          </div>
          <div class="hr"></div>
          <div class="infobox" v-loading="loadingChart1">
            <div class="title2 do-jump" id="brandSaleRank">
              品牌销量排行
              <span class="subtitle">（同风格品牌）</span>
            </div>
            <div>
              <el-table :data="[]" :default-sort="{ prop: 'salesAmount', order: 'descending' }" @sort-change="sortChange"
                        max-height="480">
                <el-table-column prop="rank" label="名次" align="center" width="110">
                  <template slot-scope="scope">
                    <span v-if="scope.row.rank == -1" style="color: grey">未上榜</span>
                    <span v-else>{{ scope.row.rank }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="brandName" label="品牌名称" align="center">
                  <template slot-scope="scope">
                    <div class="flex_x_left" style="margin-left:80px;">
                      <img v-if="scope.row.isVip" :src="scope.row.icon" style="margin-right: 5px;height:22px" alt />
                      <span v-if="!scope.row.mark">{{ scope.row.brandName }}</span>
                      <span style="color: red;font-weight: bold;">{{ scope.row.mark }}</span>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="salesAmount" sortable="custom" :sort-orders="['ascending', 'descending']"
                                 label="近30天销售金额" align="center">
                  <template slot-scope="scope">
                    <div class="flex_x_left" style="margin-left:60px;">
                      <el-progress :percentage="scope.row.proportion * 100" :show-text="false"
                                   style="width: 90px;margin-right: 15px" />
                      <span>{{ scope.row.salesAmount }}</span>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="sales" label="在售商品数" align="center" width="250" />
              </el-table>
              <DynamicScroller ref="scroller" :items="monthSales" :min-item-size="45" key-field="rank" class="scroller">
                <template v-slot="{ item, index, active }">
                  <DynamicScrollerItem :item="item" :active="active" :data-index="index">
                    <el-row class="text-center row-item">
                      <el-col :span="3">
                        <span v-if="item.rank == -1" style="color: grey">未上榜</span>
                        <span v-else>{{ item.rank }}</span>
                      </el-col>
                      <el-col :span="9">
                        <div class="flex_x_left" style="text-align: left;padding-left: 40px;">
                          <img v-if="item.isVip" :src="item.icon" style="margin-right: 5px;height:22px" alt />
                          <span v-if="item.mark" style="color: red;font-weight: bold;">{{ item.brandName }}</span>
                          <span v-else-if="item.brandName">{{ item.brandName }}</span>
                          <span v-else>&nbsp;</span>
                        </div>
                      </el-col>
                      <el-col :span="6">
                        <div class="flex_x_left">
                          <el-progress :percentage="item.proportion * 100" :show-text="false"
                                       style="width: 90px;margin-right: 15px" />
                          <span>{{ item.salesAmount }}</span>
                        </div>
                      </el-col>
                      <el-col :span="6">
                        {{ item.sales }}
                      </el-col>
                    </el-row>
                  </DynamicScrollerItem>
                </template>
              </DynamicScroller>
            </div>
          </div>
        </template>
      </el-tab-pane>
      <el-tab-pane label="商品销售排行" name="2">
        <template>
          <el-backtop :right="150" >
            <img style="width: 60px;border-radius: 50%" src="@/assets/img/totop.png" alt="">
          </el-backtop>
        </template>
        <div style="color: #f60;margin-bottom: 10px">注意：仅展示前100名销售数量高的商品</div>
        <div>
          <el-table v-loading="loading" :data="tableData" tooltip-effect="dark">
            <el-table-column label="名次" prop="rank" align="center" width="80px" />
            <el-table-column label="商品信息" align="center">
              <template slot-scope="scope">
                <div class="flex_x_left">
                  <img class="good_img" :src="scope.row.imgPath" alt />
                  <div class="good_info">
                    <div>{{ scope.row.skuModel }}</div>
                    <div v-if="scope.row.isVip">
                      <img class="good_tag" :src="scope.row.icon" alt />
                    </div>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="salesAmount" label="近30天销售金额" align="left" width="270px">
              <template slot-scope="scope">
                <div class="flex_x_left">
                  <el-progress :percentage="scope.row.proportion * 100" :show-text="false" :stroke-width="10"
                    style="width: 120px;margin: 7px 15px 8px 0" />
                  <span>{{ scope.row.salesAmount }}</span>
                </div>
                <div class="blueColor" @click="showSkuDetail(scope.row.productId)">趋势图></div>
              </template>
            </el-table-column>
            <el-table-column label="近30天销售数量" prop="salesVolume" align="center" width="140px" />
            <el-table-column label="E淘宝浏览量" width="120px">
              <template slot-scope="scope">
                <p>昨日：{{ scope.row.yesterdayViews }}</p>
                <p>本月：{{ scope.row.thisMonthViews }}</p>
                <p>上月：{{ scope.row.lastMonthViews }}</p>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
    </el-tabs>
    <!-- 规格弹窗 -->
    <el-dialog :visible.sync="visible" title="单品趋势图" :close-on-click-modal="false" width="963px">
      <div class="chartbox" style="margin-top: -20px">
        <div class="title">E淘宝浏览量</div>
        <div class="notice">
          <v-chart :option="viewSku.polar" class="chart" />
          <div class="chart_btn">
            <el-radio-group v-model="viewSku.radio" size="mini" @change="getSkuRecord">
              <el-radio-button label="7">最近7天</el-radio-button>
              <el-radio-button label="30">最近30天</el-radio-button>
            </el-radio-group>
          </div>
        </div>
      </div>
      <div class="flex_x_between">
        <div class="chartbox half">
          <div class="title">{{ moneySku.radio == '7' ? '近7天' : '近30天' }}销售金额</div>
          <div class="notice">
            <v-chart :option="moneySku.polar" class="chart" />
            <div class="chart_btn">
              <el-radio-group v-model="moneySku.radio" size="mini" @change="getSkuRecord">
                <el-radio-button label="7">最近7天</el-radio-button>
                <el-radio-button label="30">最近30天</el-radio-button>
              </el-radio-group>
            </div>
          </div>
        </div>
        <div class="chartbox half">
          <div class="title">{{ numSku.radio == '7' ? '近7天' : '近30天' }}销售数量</div>
          <div class="notice">
            <v-chart :option="numSku.polar" class="chart" />
            <div class="chart_btn">
              <el-radio-group v-model="numSku.radio" size="mini" @change="getSkuRecord">
                <el-radio-button label="7">最近7天</el-radio-button>
                <el-radio-button label="30">最近30天</el-radio-button>
              </el-radio-group>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
  <div v-else-if="isBuySaleRank === false" class="d_flex flex_row flex_justify_cont no_buy">
    <div class="tip_box">
      <img :src="'/static/img/index/smile_face.png'" alt="">
      <div class="tip_title">温馨提示</div>
      <div class="tip_detail">您尚未开通销售排行付费服务，<br />如需使用，请前往付费。</div>
      <el-button :disabled="!showInfo" type="primary" @click="goto('/marketing/salerankad')">1元开通体验<i class="el-icon-arrow-right"></i> </el-button>
    </div>
  </div>
</template>

<script>
import ECharts from 'vue-echarts'
import * as echarts from "echarts"
import { _getStorage, _deepClone } from '@/utils/utils'
import pagination from "@/components/common/pagination"
import { DynamicScroller, DynamicScrollerItem } from 'vue-virtual-scroller'
import 'vue-virtual-scroller/dist/vue-virtual-scroller.css'
export default {
  components: {
    // 传入组件
    'v-chart': ECharts,
    pagination,
    DynamicScrollerItem,
    DynamicScroller
  },
  data() {
    return {
      activeName: 'selfBrandData',
      activeTop: '1',
      brandId: undefined,
      money: { polar: {}, radio: 7, },
      num: { polar: {}, radio: 7 },
      view: { polar: {}, radio: 7 },
      moneySku: { polar: {}, radio: 7, },
      numSku: { polar: {}, radio: 7 },
      viewSku: { polar: {}, radio: 7 },
      activeTrend: { polar: {}, radio: 1 },
      finalOption: {
        tooltip: { trigger: 'axis' },
        grid: { left: '10', top: '40', right: '50', bottom: '10', containLabel: true },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          axisLine: { lineStyle: { color: '#8A8A8A' } },
          axisTick: { show: false }
        },
        yAxis: {
          axisTick: { show: false },
          axisLine: { show: true, lineStyle: { color: '#8A8A8A' } },
          splitLine: { show: false }
        },
        series: []
      },
      finalBarOption: {
        tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
        grid: { left: '150', top: '30', right: '30', bottom: '30' },
        dataZoom: [{
          type: 'slider',
          yAxisIndex: 0,
          showDataShadow: false,
          zoomLock: true,
          backgroundColor: '#f2f2f2',
          fillerColor: '#b4bbc5',
          borderColor: 'none',
          showDetail: false,
          brushSelect: false,
          maxValueSpan: 8,
          minValueSpan: 8,
          width: 8,
          start: 100
        },
        {
          type: 'inside',
          yAxisIndex: 0,
          moveOnMouseMove: false,
          zoomOnMouseWheel: false,
          moveOnMouseWheel: true
        }],
        yAxis: {
          type: 'category',
          axisTick: { show: false },
          axisLabel: {
            margin: 140
          }
        },
        xAxis: { axisLine: { show: true }, splitLine: { show: false }, axisTick: { show: false } },
        series: []
      },
      monthSales: [],
      monthSalesSortType: 1,
      params: {
        brandId: ''
      },
      tableData: [],
      loadingChart: false,
      loadingChart1: false,
      loadingChart2: false,
      loading: false,
      visible: false,
      productId: undefined,
      fixedTop: false,
      isBuySaleRank: undefined,
      endDate: '',
      showInfo: true
    }
  },
  created() {
    const initList = [
      { name: 'num', xAxis: '日期', yAxis: '数量' },
      { name: 'money', xAxis: '日期', yAxis: '金额' },
      { name: 'view', xAxis: '日期', yAxis: '浏览量' },
      { name: 'numSku', xAxis: '日期', yAxis: '数量' },
      { name: 'moneySku', xAxis: '日期', yAxis: '金额' },
      { name: 'viewSku', xAxis: '日期', yAxis: '浏览量' }
    ]
    initList.forEach(item => {
      var option = _deepClone(this.finalOption)
      option.xAxis.name = item.xAxis
      option.yAxis.name = item.yAxis
      this[item.name].polar = option
    })
    const initBarList = [
      { name: 'activeTrend' }
    ]
    initBarList.forEach(item => {
      var option = _deepClone(this.finalBarOption)
      this[item.name].polar = option
    })
  },
  mounted() {
    this.getSaleRankInfo()
  },
  methods: {
    init() {
      let { brandId } = _getStorage('info');
      this.brandId = brandId
      this.loadingChart = true
      // this.getSaleRank()
      this.getBrandRecord()
      // this.activeTrendChartChange()
      this.handleClick()
      window.addEventListener('scroll', this.onScroll, true)
    },
    onScroll: function (e) {
      if (!e.target.scrollingElement) return
      const scrollTop = e.target.scrollingElement.scrollTop
      if (scrollTop > 140) { this.fixedTop = true }
      else { this.fixedTop = false }
      var sections = document.getElementsByClassName('do-jump');
      for (var i = sections.length - 1; i >= 0; i--) {
        if (scrollTop >= sections[i].offsetTop - 400) {
          if (i == 0) {
            this.activeName = "selfBrandData";
          } else if (i == 1) {
            this.activeName = "activeTrend"
          } else if (i == 2) {
            this.activeName = "brandSaleRank"
          }
          break;
        }
      }
    },
    handleClick() {
      if (this.activeTop == '2') {
        this.getList();
      }
    },
    jump(e) {
      var index = e.index;
      var id = e.name;
      document.getElementById(id).scrollIntoView({ block: "center", behavior: "smooth" });
    },
    checkEndDate() {
      if (!this.isBuySaleRank) return false
      if (new Date(this.endDate) < new Date()) {
        this.isBuySaleRank = false
        this.$message.warning("“一元体验”已过期");
        return false
      }
      return true
    },
    async getBrandRecord() {
      if (!this.checkEndDate()) return
      this.loadingChart = true
      try {
        const res = await this.$axios.get('/brandrecord/brief', {
          params: {
            brandId: this.brandId,
            brandPriceType: this.money.radio,
            brandCountType: this.num.radio,
            brandViewsType: this.view.radio,
          }
        })
        if (res.data.code != 200 || !res.data.data) throw Error('/brandrecord/brief code: ' + res.data.code);
        this.numChartChange(res.data.data.salesVolume)
        this.moneyChartChange(res.data.data.salesAmount)
        this.viewChartChange(res.data.data.views)
      } finally {
        this.loadingChart = false
      }
    },
    numChartChange(data) {
      if (!data) return;
      var num = this.num
      if (this.visible) num = this.numSku
      num.polar.xAxis.data = Object.keys(data);
      num.polar.series = [{
        name: "销售数量",
        type: 'line',
        data: Object.values(data)
      }];
    },
    moneyChartChange(data) {
      if (!data) return;
      var money = this.money
      if (this.visible) money = this.moneySku
      money.polar.xAxis.data = Object.keys(data);
      money.polar.series = [{
        name: "销售金额",
        type: 'line',
        data: Object.values(data)
      }];
    },
    viewChartChange(data) {
      if (!data) return;
      var view = this.view
      if (this.visible) view = this.viewSku
      view.polar.xAxis.data = Object.keys(data);
      view.polar.series = [{
        name: "浏览量",
        type: 'line',
        data: Object.values(data)
      }];
    },
    sortChange(obj) {
      this.monthSalesSortType = obj.order == "ascending" ? 0 : 1
      if (this.$refs.scroller) {
        this.$refs.scroller.scrollToItem(0)
      }
      this.getSaleRank()
    },
    async getSaleRank() {
      if (!this.checkEndDate()) return
      this.loadingChart1 = true
      try {
        const r = await this.$axios.get("/brandrecord/brandMonthlySales", {
          params: {
            brandId: this.brandId,
            rankType: this.monthSalesSortType
          }
        })
        let { code, data } = r.data
        if (code == 200) {
          this.monthSales = data;
        }
      } finally {
        this.loadingChart1 = false
      }
    },
    async activeTrendChartChange() {
      if (!this.checkEndDate()) return
      this.loadingChart2 = true
      let { brandId } = _getStorage('info');
      try {
        const r = await this.$axios.get('/brandrecord/allViewsRank', {
          params: {
            type: this.activeTrend.radio,
            brandId
          }
        })
        let { code, data } = r.data
        if (code == 200) {
          this.activeTrend.polar.yAxis.data = data.map((item, index) => {
            const space = 15 > item.brandName.length ? (15 - item.brandName.length) : 0
            return {
              value: item.rank + ' ' + item.brandName,
              textStyle: {
                color: index == 0 ? 'red' : 'black',
                fontWeight: index == 0 ? 'bold' : 'normal',
                align: 'left'
              }
            }
          }).reverse();
          this.activeTrend.polar.series = [{
            name: '浏览量',
            type: 'bar',
            barWidth: '60%',
            itemStyle: {
              color: new echarts.graphic.LinearGradient(1, 0, 0, 0, [
                {
                  offset: 0,
                  color: '#ff6600'
                },
                {
                  offset: 1,
                  color: '#ff9700'
                }
              ])
            },
            data: data.map(item => item.views).reverse()
          }]
        }
      } finally {
        this.loadingChart2 = false
      }
    },
    getList() {
      if (!this.checkEndDate()) return
      this.loading = true
      let { brandId } = _getStorage('info');
      this.params.brandId = brandId
      this.$axios.get("/brandrecord/skuRank", {
        params: this.params
      }).then(r => {
        this.loading = false
        let { code, data } = r.data;
        if (code == 200) {
          this.tableData = data
        }
      }).catch(() => {
        this.loading = false
      })
    },
    async getSkuRecord() {
      let { brandId } = _getStorage("info");
      const res = await this.$axios.get('/brandrecord/skuDetail', {
        params: {
          productId: this.productId,
          brandId,
          skuPriceType: this.moneySku.radio,
          skuCountType: this.numSku.radio,
          skuViews: this.viewSku.radio,
        }
      })
      if (res.data.code != 200 || !res.data.data) throw Error('/brandrecord/brief code: ' + res.data.code);
      this.numChartChange(res.data.data.salesVolume)
      this.moneyChartChange(res.data.data.salesAmount)
      this.viewChartChange(res.data.data.skuViews)
    },
    showSkuDetail(id) {
      if (!this.checkEndDate()) return
      this.productId = id
      this.numSku.radio = 7
      this.moneySku.radio = 7
      this.viewSku.radio = 7
      this.getSkuRecord()
      this.visible = true
    },
    hoverChart(hover) {
      if (hover) {
        document.body.style = 'overflow: hidden'
      } else {
        document.body.style = ''
      }
    },
    goto(url) {
      if (url) {
        if (/^http/.test(url)) {
          window.open(url)
        } else {
          this.$router.push(url)
        }
      }
    },
    // 先查询权限
    getSaleRankInfo () {
      let { brandId } = _getStorage("info");
      this.$axios.get('/extra/saleRankInfo',{
        params: {
          brandId
        },
      }).then((res)=>{
        if(res.data.code == 200){
          var data = res.data.data;
          this.isBuySaleRank = (data.status == 1)
          this.endDate = data.endDate
          this.showInfo = (data.showInfo == 1)
          this.init()
        }
      })
    }
  },
  beforeDestroy() {
    window.removeEventListener('scroll', this.onScroll)
  },
}
</script>

<style lang="scss" scoped>
.hr {
  height: 2px;
  background: #f0f0f0;
}

.title2 {
  font-size: 16px;
  font-weight: bold;
  padding-bottom: 15px;
}

.subtitle {
  font-size: 12px;
  color: gray;
}

.infobox {
  padding: 20px;
}

.chartbox {
  box-sizing: border-box;
  position: relative;
  background-color: #fff;
  border: 1px solid #e7e7e7;
  border-radius: 8px;
  padding: 20px 20px 10px;
  margin-top: 20px;
  min-height: 60px;

  &.half {
    width: 450px;
  }

  .title {
    color: rgb(255, 102, 0);
  }

  .chart {
    width: 100%;
    height: 200px;
    padding-top: 5px;

    &.scroll-bars {
      height: 300px;
    }
  }

  .notice {
    .chart_btn {
      display: inline-block;
      position: absolute;
      top: 15px;
      right: 15px;
    }
  }
}

.good_img {
  width: 80px;
  height: 80px;
  margin: 20px;
}

.good_info {
  text-align: left;
}

.good_tag {
  width: 30px;
}

.search-wrap {
  .search-box {
    overflow: hidden;
    flex-wrap: wrap;
    display: flex;
    transition: max-height 0.15s ease-in-out;

    .search-item {
      margin-right: 15px;
      margin-bottom: 15px;

      .label {
        font-size: 14px;
      }

      .input {
        width: 250px;
      }
    }
  }

  .search-btn-box {
    // margin-top: 15px;

    display: flex;
    align-items: center;

    .icon-arrow {
      margin-left: 4px;
      transition: transform 0.25s ease-in-out;
    }

    .more {
      color: #46b791;
      margin-left: 10px;
      cursor: pointer;
      line-height: 33px;
    }
  }
}

.fixedTop {
  position: fixed;
  top: 110px;
  width: 978px;
  z-index: 4;
  background-color: #fff;
}

/deep/ .el-progress-bar__inner {
  background: linear-gradient(45deg, #ff9700, #ff6600);
}

.scroller {
  height: 480px;
  overflow: auto;
  z-index: 2;
  margin-top: -60px;

  .row-item {
    background: #fff;
    border-bottom: 1px solid #ebeef5;
    text-align: center;
    height: 45px;
    line-height: 45px;

    &:hover {
      background: #f5f7fa;
    }
  }
}

.no_buy {
  height: 600px;

  .tip_box {
    width: 300px;
    text-align: center;

    .tip_title {
      font-size: 24px;
      color: #333333;
      padding: 20px;
    }

    .tip_detail {
      font-size: 16px;
      line-height: 20px;
      color: #666666;
      padding-bottom: 35px;
    }
  }
}
</style>
