<style lang="scss" scoped>
.search-bar {
  display: flex;
  align-items: center;
}
.search-box p {
  display: inline-block;
  border: 1px solid #f2f2f2;
  border-radius: 5px;
  margin-right: 10px;
  padding: 5px 10px;
  cursor: pointer;
}
</style>
<style>
/* .data-display-statistics .ant-card-body {
  padding: 0 15px;
} */
.data-display-statistics .ant-col-6 {
  margin: 10px 0;
}
.data-display-statistics .ant-col-6 .ant-card-body {
  display: flex;
  justify-content: center;
}
.data-display-statistics .ant-col-6 p,
.data-display-statistics .ant-col-6 span {
  text-align: center;
  line-height: 40px;
  font-size: 30px;
  font-weight: 600;
  color: red;
  margin: 0;
}
.search-box .ant-card-body {
  padding: 5px 15px;
}
.data-display-statistics .ant-col-6 .ant-card-body .styleElse {
  line-height: 60px;
  height: 40px;
  font-size: 16px;
  font-weight: 400;
  margin-left: 10px;
}
.ant-modal-wrap .yincang .ant-modal-content .ant-modal-footer {
  display: none !important;
}
.yincang .ant-col-6 p {
  text-align: left;
  color: red;
  font-size: 16px;
  font-weight: 500;
}
.ant-table-thead div {
  font-weight: 700;
}
.tool-tip {
  position: absolute;
  top: 65px;
  right: 10px;
}
th div {
  white-space: nowrap;
}
</style>
<template>
  <div class="data-statistics">
    <a-row class="image-list-heading vm-panel">
      <a-row type="flex" align="middle" justify="space-between" class="panel-body">
        <div class="search-bar" style="width:100%">
          <span>账户选择：</span>
          <treeselect :appId.sync="appId" />
          <span style="margin-left:10px">返点比例：</span>
          <a-input-number
            :min="1"
            :max="10"
            :step="0.1"
            v-model="discount"
            placeholder="请输入折扣"
            style="width:100px"
          />
          <a-button type="primary" style="margin:10px" @click="addUser">搜索</a-button>

          <a-button
            type="primary"
            icon="reload"
            @click="getDataReset"
            style="background-color:#67c23a;border-color:#67c23a"
            >刷新</a-button
          >
          <a-button type="primary" @click="getDataResetAll" style="color:white;margin-left:10px">重置</a-button>
        </div>
      </a-row>
      <a-row>
        <a-col :span="24">
          <a-card :bordered="false" class="search-box">
            <time-check
              @getAdd="getAdd"
              :startValue.sync="startValue"
              ref="timeCheck"
            ></time-check>
          </a-card>
        </a-col>
      </a-row>
    </a-row>
    <a-row :gutter="16" v-if="kuaishou">
      <a-col :sm="24" :md="12" :xl="12" :xxl="5">
        <lifting
          :kuaishou.sync="kuaishou"
          :active.sync="active"
          title="总消耗"
          typeName="cost"
          typeThan="costProportion"
        ></lifting>
      </a-col>
      <a-col :sm="24" :md="12" :xl="12" :xxl="5">
        <lifting
          :kuaishou.sync="kuaishou"
          :active.sync="active"
          title="折后消耗"
          typeName="discountCost"
          typeThan="discountCostProportion"
        ></lifting>
      </a-col>
      <a-col :sm="24" :md="12" :xl="12" :xxl="5">
        <lifting
          :kuaishou.sync="kuaishou"
          :active.sync="active"
          title="封面点击数"
          typeName="photoClick"
          typeThan="photoClickProportion"
        ></lifting>
      </a-col>
      <a-col :sm="24" :md="12" :xl="12" :xxl="5">
        <lifting
          :kuaishou.sync="kuaishou"
          :active.sync="active"
          title="封面曝光数"
          typeName="photoShow"
          typeThan="showProportion"
        ></lifting>
      </a-col>
      <a-col :sm="24" :md="12" :xl="12" :xxl="4">
        <lifting
          :kuaishou.sync="kuaishou"
          :active.sync="active"
          title="素材曝光数"
          typeName="aclick"
          typeThan="aClickProportion"
        ></lifting>
      </a-col>
    </a-row>
    <a-row :gutter="10">
      <a-col :span="24">
        <a-card
          style="width:100%"
          :tabList="tabListNoTitle"
          :activeTabKey="noTitleKey"
          @tabChange="key => onTabChange(key, 'noTitleKey')"
        >
          <div id="chart" style="width:100%;height:500px"></div>
        </a-card>
      </a-col>
    </a-row>
    <a-row :gutter="10" style="margin-top:10px">
      <a-col :span="24">
        <a-card style="width:100%;">
          <div
            style="display:flex;margin-bottom:15px"
            v-show="
              role.roleCode == 'operator' ||
                role.roleCode == 'kuaishouOperationManager' ||
                role.roleCode == 'admin' ||
                role.roleCode == 'operationAssistant' ||
                role.roleCode == 'touTiaoOperationManager'
            "
          >
            <a-select
              style="width: 120px"
              v-model="statHour"
              @change="getElseData"
              allowClear
              v-if="active == 1 || active == 2"
            >
              <a-select-option v-for="item of 24" :key="item - 1" :value="item - 1">{{ item - 1 }}</a-select-option>
            </a-select>
            <a-button type="primary" @click="exportExcel" style="margin-left:15px">导出</a-button>
          </div>
          <a-table
            :columns="columns"
            :dataSource="data"
            bordered
            id="outTable"
            :pagination="false"
            :scroll="{ x: 1900 }"
          ></a-table>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script>
import ARow from 'ant-design-vue/es/grid/Row'
import ACol from 'ant-design-vue/es/grid/Col'
import countTo from 'vue-count-to'
import moment from 'moment'
import { getAdvertiserList, getReportList, getStatistics } from '@api/statistics'
import axios from 'axios'
import lifting from './components/lifting'
import timeCheck from './components/timeCheck'
import Treeselect from './components/Treeselect.vue'

import { getAction, postAction, postFile } from '@/api/manage'
import { mapGetters } from 'vuex'

// 引入基本模板
let echarts = require('echarts/lib/echarts')
// 引入柱状图组件
require('echarts/lib/chart/bar')
require('echarts/lib/chart/pie')
require('echarts/lib/chart/line')
// 引入提示框和title组件
require('echarts/lib/component/tooltip')
require('echarts/lib/component/title')
require('echarts/lib/component/graphic')
require('echarts/lib/component/toolbox')
require('echarts/lib/component/legend')
var length = 0
var active = 1
const columns = [
  {
    title: '时间',
    dataIndex: 'date',
    align: 'center',
    width: 150,
    customRender: function(text, record, index) {
      const obj = {
        children: text,
        attrs: {}
      }
      for (let i = 0; i < length; i++) {
        if (index == 0 && i == 0) {
          obj.attrs.rowSpan = length
        } else {
          if (index == i) {
            obj.attrs.rowSpan = 0
          }
        }
      }
      return obj
    }
  },
  {
    title: '账户Id',
    dataIndex: 'accountId',
    align: 'center',
    width: 150,
    customRender: function(text, record, index) {
      const obj = {
        children: text,
        attrs: {}
      }
      if (active == 1) {
        for (let i = 0; i < length; i++) {
          if (index >= length - 3) {
            obj.attrs.colSpan = 2
          }
        }
      } else {
        for (let i = 0; i < length; i++) {
          if (index >= length - 1) {
            obj.attrs.colSpan = 2
          }
        }
      }
      return obj
    }
  },
  {
    title: '账户昵称',
    dataIndex: 'accountName',
    scopedSlots: { customRender: 'cost' },
    align: 'center',
    width: 150,
    customRender: function(text, record, index) {
      const obj = {
        children: text,
        attrs: {}
      }
      if (active == 1) {
        for (let i = 0; i < length; i++) {
          if (index >= length - 3) {
            obj.attrs.colSpan = 0
          }
        }
      } else {
        for (let i = 0; i < length; i++) {
          if (index >= length - 1) {
            obj.attrs.colSpan = 0
          }
        }
      }

      return obj
    }
  },
  {
    title: '消耗(￥)',
    dataIndex: 'cost',
    scopedSlots: { customRender: 'cost' },
    align: 'center'
  },
  {
    title: '折后消耗(￥)',
    dataIndex: 'costY',
    align: 'center'
  },
    {
    title: '次留数',
    dataIndex: 'eventNextDayStay',
    scopedSlots: { customRender: 'eventNextDayStay' },
    align: 'center'
  },
  {
    title: '次留率',
    dataIndex: 'eventNextDayStayRatio',
    align: 'center'
  },
  {
    title: '封面展示',
    dataIndex: 'photoShow',
    align: 'center'
  },
  {
    title: '封面点击',
    dataIndex: 'photoClick',
    align: 'center'
  },
  {
    title: '素材曝光数',
    dataIndex: 'aclick',
    align: 'center'
  },
  {
    title: '封面点击率',
    dataIndex: 'photoClickRatio',
    align: 'center'
  },
  {
    title: 'cvr',
    dataIndex: 'cvr',
    align: 'center'
  },
  {
    title: 'cpm(￥)',
    dataIndex: 'cpm',
    align: 'center'
  },
  {
    title: '行为数',
    dataIndex: 'bClick',
    align: 'center'
  },
  {
    title: '转化数',
    dataIndex: 'formCount',
    align: 'center'
  },
  {
    title: '折前转化单价(￥)',
    dataIndex: 'beforeFormPrice',
    align: 'center'
  },
  {
    title: '折后转化单价(￥)',
    dataIndex: 'afterFormPrice',
    align: 'center'
  },

  {
    title: '注册数',
    dataIndex: 'eventRegister',
    align: 'center'
  },
  {
    title: '注册成本(￥)',
    dataIndex: 'eventRegisterCost',
    align: 'center'
  },
  {
    title: '单价区间',
    dataIndex: 'price',
    align: 'center',
    customRender: function(text, record, index) {
      const obj = {
        children: text,
        attrs: {}
      }
      for (let i = 0; i < length; i++) {
        if (index == 0 && i == 0) {
          obj.attrs.rowSpan = length
        } else {
          if (index == i) {
            obj.attrs.rowSpan = 0
          }
        }
      }
      return obj
    }
  }
]


const columnsWu = [
  {
    title: '时间',
    dataIndex: 'date',
    align: 'center',
    width: 150,
    customRender: function(text, record, index) {
      const obj = {
        children: text,
        attrs: {}
      }
      for (let i = 0; i < length; i++) {
        if (index == 0 && i == 0) {
          obj.attrs.rowSpan = length
        } else {
          if (index == i) {
            obj.attrs.rowSpan = 0
          }
        }
      }
      return obj
    }
  },
  {
    title: '账户Id',
    dataIndex: 'accountId',
    align: 'center',
    width: 150,
    customRender: function(text, record, index) {
      const obj = {
        children: text,
        attrs: {}
      }
      if (active == 1) {
        for (let i = 0; i < length; i++) {
          if (index >= length - 3) {
            obj.attrs.colSpan = 2
          }
        }
      } else {
        for (let i = 0; i < length; i++) {
          if (index >= length - 1) {
            obj.attrs.colSpan = 2
          }
        }
      }
      return obj
    }
  },
  {
    title: '账户昵称',
    dataIndex: 'accountName',
    scopedSlots: { customRender: 'cost' },
    align: 'center',
    width: 150,
    customRender: function(text, record, index) {
      const obj = {
        children: text,
        attrs: {}
      }
      if (active == 1) {
        for (let i = 0; i < length; i++) {
          if (index >= length - 3) {
            obj.attrs.colSpan = 0
          }
        }
      } else {
        for (let i = 0; i < length; i++) {
          if (index >= length - 1) {
            obj.attrs.colSpan = 0
          }
        }
      }

      return obj
    }
  },
  {
    title: '消耗(￥)',
    dataIndex: 'cost',
    scopedSlots: { customRender: 'cost' },
    align: 'center'
  },
  {
    title: '折后消耗(￥)',
    dataIndex: 'costY',
    align: 'center'
  },
  {
    title: '封面展示',
    dataIndex: 'photoShow',
    align: 'center'
  },
  {
    title: '封面点击',
    dataIndex: 'photoClick',
    align: 'center'
  },
  {
    title: '素材曝光数',
    dataIndex: 'aclick',
    align: 'center'
  },
  {
    title: '封面点击率',
    dataIndex: 'photoClickRatio',
    align: 'center'
  },
  {
    title: 'cvr',
    dataIndex: 'cvr',
    align: 'center'
  },
  {
    title: 'cpm(￥)',
    dataIndex: 'cpm',
    align: 'center'
  },
  {
    title: '行为数',
    dataIndex: 'bClick',
    align: 'center'
  },
  {
    title: '转化数',
    dataIndex: 'formCount',
    align: 'center'
  },
  {
    title: '折前转化单价(￥)',
    dataIndex: 'beforeFormPrice',
    align: 'center'
  },
  {
    title: '折后转化单价(￥)',
    dataIndex: 'afterFormPrice',
    align: 'center'
  },

  {
    title: '注册数',
    dataIndex: 'eventRegister',
    align: 'center'
  },
  {
    title: '注册成本(￥)',
    dataIndex: 'eventRegisterCost',
    align: 'center'
  },
  {
    title: '单价区间',
    dataIndex: 'price',
    align: 'center',
    customRender: function(text, record, index) {
      const obj = {
        children: text,
        attrs: {}
      }
      for (let i = 0; i < length; i++) {
        if (index == 0 && i == 0) {
          obj.attrs.rowSpan = length
        } else {
          if (index == i) {
            obj.attrs.rowSpan = 0
          }
        }
      }
      return obj
    }
  }
]
export default {
  name: 'data-display-statistics',
  components: {
    ACol,
    ARow,
    countTo,
    lifting,
    timeCheck,
    Treeselect
  },

  data: function() {
    return {
      title: '账户数据展示',
      show: true,
      data: [],
      columns:columnsWu,
      options: [],
      list: [],
      appId: [],
      statHour: null,
      keyValue: null,
      keyValueData: [],
      active: 1,
      startValue: [],
      allValue: [],
      discount: 1,
      duration: 1000,
      kuaishou: {
        aclick: 0,
        aClickProportion: 0,
        cost: 0,
        costProportion: 0,
        photoClick: 0,
        photoClickroportion: 0,
        photoShow: 0,
        showProportion: 0,
        discountCost: 0,
        discountCostProportion: 0
      },
      timeList: [
        // { label: '今天', value: 1, show: true },
        { label: '昨天', value: 2, show: true },
        { label: '近一周', value: 3, show: true },
        { label: '近十五天', value: 4, show: true },
        { label: '近一月', value: 5, show: true },
        { label: '近三月', value: 6, show: true },
        { label: '近半年', value: 7, show: true },
        { label: '所有', value: 8, show: true }
      ],
      dataDetail: [],
      tabListNoTitle: [
        {
          key: 'cost',
          tab: '总消耗'
        },
        {
          key: 'discountCost',
          tab: '折后总消耗'
        },
        {
          key: 'photoClick',
          tab: '封面点击数'
        },
        {
          key: 'photoShow',
          tab: '封面曝光数'
        },
        {
          key: 'aclick',
          tab: '素材曝光数'
        }
      ],
      noTitleKey: 'cost',
      role: { roleCode: '' },
      statDate: ''
    }
  },
  filters: {
    formatDate: function(value) {
      let date = new Date(value)
      let y = date.getFullYear()
      let MM = date.getMonth() + 1
      MM = MM < 10 ? '0' + MM : MM
      let d = date.getDate()
      d = d < 10 ? '0' + d : d
      let h = date.getHours()
      h = h < 10 ? '0' + h : h
      let m = date.getMinutes()
      m = m < 10 ? '0' + m : m
      let s = date.getSeconds()
      s = s < 10 ? '0' + s : s
      return y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s
    }
  },
  methods: {
    moment,
    ...mapGetters(['nickname', 'avatar', 'userInfo']),
    disabledDate(current) {
      return current && current > moment().endOf('day')
    },
    handleChange(value) {
      console.log(value)
      //   this.appId = value
    },
    getElseData(value) {
      if(value){
        this.columns = columnsWu
      }else{
        this.columns = columns
      }
      this.getStatistics()
    },
    handleBlur() {
      console.log('blur')
    },
    handleFocus() {
      console.log('focus')
      if (this.appId.length > 0) {
        this.options = []
        for (let i = 0; i < this.list.length; i++) {
          for (let j = 0; j < this.appId.length; j++) {
            if (this.list[i].accountId == this.appId[j]) {
              this.options.push(this.list[i])
            }
          }
        }
      } else {
        this.options = this.list
      }
    },
    search(value) {
      //   console.log(value)
      this.options = []
      if (value != '') {
        this.options = this.list.filter(item => {
          var data = item.accountId + ' ' + item.authName + ' ' + item.advertiserName + ' ' + item.operationName
          return data.toLowerCase().indexOf(value.toLowerCase()) > -1
        })
        this.options = [...this.options]
        console.log(this.options)
      } else {
        if (this.appId.length > 0) {
          this.options = []
          for (let i = 0; i < this.list.length; i++) {
            for (let j = 0; j < this.appId.length; j++) {
              if (this.list[i].accountId == this.appId[j]) {
                this.options.push(this.list[i])
              }
            }
          }
        } else {
          this.options = this.list
        }
      }
    },
    getDataReset() {
      this.active = 1
      this.allValue = []
      this.$refs.timeCheck.active = 1
      this.addUser()
    },
    getDataResetAll() {
      this.active = 1
      this.allValue = []
      this.$refs.timeCheck.active = 1
      var that = this
      that.kuaishou.aclick = 0
      that.kuaishou.cost = 0
      that.kuaishou.photoClick = 0
      that.kuaishou.photoShow = 0
      that.kuaishou.discountCost = 0
      this.data = []
      this.appId = []
      this.drawPie(1, [])
    },
    addUser() {
      var that = this
      if (this.appId.length > 0) {
          if(that.active == 1){
            that.columns = columnsWu
          }else{
            that.columns = columns
          }
        var params = {}
        params.accountIds = JSON.stringify(that.appId)
        params.type = that.active
        params.discount = that.discount
        if (that.active == 9) {
          params.startDate = this.allValue[0]
          params.endDate = this.allValue[1]
        }

        getReportList(params).then(res => {
          if (res.success) {
            if (res.result) {
              that.kuaishou = res.result.summary
              that.dataDetail = res.result.trend
              that.drawPie(that.noTitleKey, res.result.trend)
            } else {
              that.kuaishou.aclick = 0
              that.kuaishou.cost = 0
              that.kuaishou.photoClick = 0
              that.kuaishou.photoShow = 0
              that.kuaishou.discountCost = 0
            }
          }
        })
        that.getStatistics()
      } else {
        this.$message.error('请选择账户')
      }
    },
    getStatistics() {
      var params = {}
      params.accountIds = JSON.stringify(this.appId)
      params.type = this.active
      params.statHour = this.statHour
      params.discount = this.discount
      if (this.active == 9) {
        params.startDate = this.allValue[0]
        params.endDate = this.allValue[1]
      }
            
      this.data = []
      getStatistics(params).then(res => {
        console.log(res)
        if (res.success) {

          if (res.result.accountDetail) {
            this.statDate = res.result.statDate
            this.data = res.result.accountDetail.map((item, index) => {
              return {
                key: index,
                ...item,
                photoClickRatio: item.photoClickRatio ? (item.photoClickRatio * 100).toFixed(2) + '%' : 0 + '%',
                cpm: item.cpm ? item.cpm.toFixed(2) : 0,
                cost: item.cost.toFixed(2),
                cvr: item.cvr ? (item.cvr * 100).toFixed(2) + '%' : 0 + '%',
                costY: (item.cost / this.discount).toFixed(2),
                beforeFormPrice: item.formPrice
                  ? item.formPrice.toFixed(2)
                  : item.activationPrice
                  ? item.activationPrice.toFixed(2)
                  : 0,
                afterFormPrice: item.formPrice
                  ? (item.formPrice / this.discount).toFixed(2)
                  : item.activationPrice
                  ? (item.activationPrice / this.discount).toFixed(2)
                  : 0,
                date: this.statHour ? res.result.statDate + '  ' + this.statHour : res.result.statDate,
                formCount: item.formCount > 0 ? item.formCount : item.activationCount,
                eventRegister: item.eventRegister,
                eventRegisterCost: item.eventRegisterCost.toFixed(2),
                eventNextDayStayRatio:item.eventNextDayStayRatio?(item.eventNextDayStayRatio*100).toFixed(2) + '%' : 0 + '%'
              }
            })
            var index = this.data.length
            if (this.active == 1) {
              var allNow = {
                key: index + 1,
                ...res.result.now,
                photoClickRatio: res.result.now.photoClickRatio
                  ? (res.result.now.photoClickRatio * 100).toFixed(2) + '%'
                  : 0 + '%',
                cpm: res.result.now.cpm ? res.result.now.cpm.toFixed(2) : 0,
                cost: res.result.now.cost.toFixed(2),
                cvr: res.result.now.cvr ? (res.result.now.cvr * 100).toFixed(2) + '%' : 0 + '%',
                costY: (res.result.now.cost / this.discount).toFixed(2),
                accountId: '总计',
                beforeFormPrice: res.result.now.formPrice
                  ? res.result.now.formPrice.toFixed(2)
                  : res.result.now.activationPrice
                  ? res.result.now.activationPrice.toFixed(2)
                  : 0,
                afterFormPrice: res.result.now.formPrice
                  ? (res.result.now.formPrice / this.discount).toFixed(2)
                  : res.result.now.activationPrice
                  ? (res.result.now.activationPrice / this.discount).toFixed(2)
                  : 0,
                formCount: res.result.now.conversionNum,
                eventRegister: res.result.now.eventRegister,
                eventRegisterCost: res.result.now.eventRegisterCost.toFixed(2)
              }
              var allYesterday = {
                key: index + 2,
                ...res.result.yesterday,
                photoClickRatio: res.result.yesterday.photoClickRatio
                  ? (res.result.yesterday.photoClickRatio * 100).toFixed(2) + '%'
                  : 0 + '%',
                cpm: res.result.yesterday.cpm ? res.result.yesterday.cpm.toFixed(2) : 0,
                cost: res.result.yesterday.cost.toFixed(2),
                cvr: res.result.yesterday.cvr ? (res.result.yesterday.cvr * 100).toFixed(2) + '%' : 0 + '%',
                costY: (res.result.yesterday.cost / this.discount).toFixed(2),
                accountId: '昨日总计',
                beforeFormPrice: res.result.yesterday.formPrice
                  ? res.result.yesterday.formPrice.toFixed(2)
                  : res.result.yesterday.activationPrice
                  ? res.result.yesterday.activationPrice.toFixed(2)
                  : 0,
                afterFormPrice: res.result.yesterday.formPrice
                  ? (res.result.yesterday.formPrice / this.discount).toFixed(2)
                  : res.result.yesterday.activationPrice
                  ? (res.result.yesterday.activationPrice / this.discount).toFixed(2)
                  : 0,
                formCount:res.result.yesterday.conversionNum,
                eventRegister: res.result.yesterday.eventRegister,
                eventRegisterCost: res.result.yesterday.eventRegisterCost.toFixed(2)
              }
              var chainRatio = {
                key: index + 3,
                cost: (res.result.chainRatio.costProportion * 100).toFixed(2) + '%',
                photoShow: (res.result.chainRatio.showProportion * 100).toFixed(2) + '%',
                photoClick: (res.result.chainRatio.photoClickProportion * 100).toFixed(2) + '%',
                aclick: (res.result.chainRatio.aClickProportion * 100).toFixed(2) + '%',
                photoClickRatio: res.result.chainRatio.photoClickRatioProportion
                  ? (res.result.chainRatio.photoClickRatioProportion * 100).toFixed(2) + '%'
                  : 0.0 + '%',
                cvr: (res.result.chainRatio.cvrProportion * 100).toFixed(2) + '%',
                cpm: (res.result.chainRatio.cpmProportion * 100).toFixed(2) + '%',
                bClick: (res.result.chainRatio.bClickProportion * 100).toFixed(2) + '%',
                formCount: (res.result.chainRatio.nowConversionNumProportion* 100).toFixed(2) + '%',
                beforeFormPrice: (res.result.chainRatio.beforeConversionPriceProportion*100).toFixed(2) + '%',
                afterFormPrice: (res.result.chainRatio.afterConversionPriceProportion*100).toFixed(2) + '%',
                costY: (res.result.chainRatio.costProportion * 100).toFixed(2) + '%',
                eventRegister: (res.result.chainRatio.eventRegisterProportion * 100).toFixed(2) + '%',
                eventRegisterCost: (res.result.chainRatio.eventRegisterCostProportion * 100).toFixed(2) + '%',
                accountId: '环比'
              }
              this.data.push(allNow)
              this.data.push(allYesterday)
              this.data.push(chainRatio)
            } else {
              var allNow = {
                key: index + 1,
                ...res.result.ratioJson,
                photoClickRatio: res.result.ratioJson.photoClickRatio
                  ? (res.result.ratioJson.photoClickRatio * 100).toFixed(2) + '%'
                  : 0 + '%',
                cpm: res.result.ratioJson.cpm ? res.result.ratioJson.cpm.toFixed(2) : 0,
                cost: res.result.ratioJson.cost?res.result.ratioJson.cost.toFixed(2):0,
                cvr: res.result.ratioJson.cvr ? (res.result.ratioJson.cvr * 100).toFixed(2) + '%' : 0 + '%',
                costY: (res.result.ratioJson.cost / this.discount).toFixed(2),
                accountId: '总计',
                beforeFormPrice: res.result.ratioJson.formPrice
                  ? res.result.ratioJson.formPrice.toFixed(2)
                  : res.result.ratioJson.activationPrice
                  ? res.result.ratioJson.activationPrice.toFixed(2)
                  : 0,
                afterFormPrice: res.result.ratioJson.formPrice
                  ? (res.result.ratioJson.formPrice / this.discount).toFixed(2)
                  : res.result.ratioJson.activationPrice
                  ? (res.result.ratioJson.activationPrice / this.discount).toFixed(2)
                  : 0,
                formCount: res.result.ratioJson.conversions,
                beforeFormPrice: res.result.ratioJson.conversionPrice.toFixed(2),
                afterFormPrice: res.result.ratioJson.discountConversionPrice.toFixed(2),
                eventRegister: res.result.ratioJson.eventRegister,
                eventRegisterCost: res.result.ratioJson.eventRegisterCost.toFixed(2),
                eventNextDayStayRatio:res.result.ratioJson.eventNextDayStayRatio?(res.result.ratioJson.eventNextDayStayRatio*100).toFixed(2) + '%' : 0 + '%'
              }
              this.data.push(allNow)
              this.statDate = res.result.statDate
            }

            length = this.data.length
          } else {
            this.$message.error('暂无数据')
          }
        }
      })
    },
    getAdd(checked) {
      if (checked == 9) {
        if (this.startValue.length > 0 && this.startValue[0]) {
          this.allValue[1] = moment(this.startValue[0]._d).format('YYYY-MM-DD')
          this.allValue[0] = moment(this.startValue[1]._d).format('YYYY-MM-DD')
        }
      } else {
        this.startValue = []
        this.allValue = []
      }
      this.active = checked
      active = checked
      if(this.active == 1){
        this.columns = columnsWu
      }else{
        this.columns = columns
      }
      this.addUser(checked)
    },
    onTabChange(key, type) {
      console.log(key, type)
      this[type] = key
      if (type == 'noTitleKey') {
        this.drawPie(key, this.dataDetail)
      }
    },
    drawPie(type, data) {
      console.log(type)
      var dataLegend = []
      var dataLength = []
      var dataElse = []
      var dataDate = []
      var that = this
      if (this.active == 1 || this.active == 2) {
        dataDate = data.map(item => {
          return item.statHour
        })
      } else {
        dataDate = data.map(item => {
          return item.statDate
        })
      }
      dataLength = data.map(item => {
        return item[type]
      })
      if (type == 'cost') {
        dataLegend = ['总消耗']
        dataElse = data.map(item => {
          if (item.now) {
            return { proportion: (item.now.costProportion * 100).toFixed(2) + '%', statHour: item.statHour }
          } else {
            return { proportion: 0, statHour: item.statHour }
          }
        })
      } else if (type == 'photoClick') {
        dataLegend = ['封面点击数']
        dataElse = data.map(item => {
          if (item.now) {
            return { proportion: (item.now.photoClickProportion * 100).toFixed(2) + '%', statHour: item.statHour }
          } else {
            return { proportion: 0, statHour: item.statHour }
          }
        })
      } else if (type == 'photoShow') {
        dataLegend = ['封面曝光数']
        dataElse = data.map(item => {
          if (item.now) {
            return { proportion: (item.now.showProportion * 100).toFixed(2) + '%', statHour: item.statHour }
          } else {
            return { proportion: 0, statHour: item.statHour }
          }
        })
      } else if (type == 'aclick') {
        dataLegend = ['素材曝光数']
        dataElse = data.map(item => {
          if (item.now) {
            return { proportion: (item.now.aClickProportion * 100).toFixed(2) + '%', statHour: item.statHour }
          } else {
            return { proportion: 0, statHour: item.statHour }
          }
        })
      } else if (type == 'discountCost') {
        dataLegend = ['折后总消耗']
        dataElse = data.map(item => {
          if (item.now) {
            return { proportion: (item.now.discountCostProportion * 100).toFixed(2) + '%', statHour: item.statHour }
          } else {
            return { proportion: 0, statHour: item.statHour }
          }
        })
        dataLength = data.map(item => {
          return (item.cost / this.discount).toFixed(2)
        })
      }

      console.log(dataLength, 134123)
      var series
      if (this.active == 1) {
        dataLegend = ['今天', '昨天']
        series = [
          {
            name: dataLegend[0],
            type: 'line',
            color: '#9933ff',
            smooth: true,
            symbol: 'circle',
            symbolSize: 1,
            lineStyle: {
              normal: {
                width: 2,
                color: '#9933ff'
              }
            },
            itemStyle: {
              borderColor: '#ffffff',
              borderWidth: 3
            },
            data: data.map(item => {
              if (item.now) {
                return item.now[type]
              } else {
                return 0
              }
            })
          },
          {
            name: dataLegend[1],
            type: 'line',
            color: '#0bcd74',
            smooth: true,
            symbol: 'circle',
            symbolSize: 1,
            lineStyle: {
              normal: {
                width: 2,
                color: '#0bcd74'
              }
            },
            itemStyle: {
              borderColor: '#ffffff',
              borderWidth: 3
            },
            data: dataLength
          }
        ]
      } else {
        series = [
          {
            name: dataLegend[0],
            type: 'line',
            color: '#0bcd74',
            smooth: true,
            symbol: 'circle',
            symbolSize: 1,
            lineStyle: {
              normal: {
                width: 2,
                color: '#0bcd74'
              }
            },
            itemStyle: {
              borderColor: '#ffffff',
              borderWidth: 3
            },
            data: dataLength
          }
        ]
      }

      var option = {
        backgroundColor: '#fff',
        toolbox: {
          show: true,
          feature: {
            dataView: { readOnly: false }
          }
        },
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            var index = dataElse.findIndex(v => v.statHour == params[0].name)
            var da = null
            if (index >= 0) {
              da = dataElse[index].proportion
            }
            if (that.active == 1) {
              if (params.length > 1) {
                return `${params[0].marker}今天${params[0].name}时:${params[0].data}  <br/>
              ${params[1].marker}昨天${params[1].name}时:${params[1].data} <br/>
            环比:${da} <br/> `
              } else {
                return `${params[0].marker}时间:${params[0].name} <br/>
            数值:${params[0].data} `
              }
            } else {
              return `${params[0].marker}时间:${params[0].name} <br/>
            数值:${params[0].data} `
            }
          }
        },
        legend: {
          data: dataLegend
        },
        grid: {
          left: '2%',
          right: '2%',
          bottom: '2%',
          containLabel: true
        },

        xAxis: {
          type: 'category',
          data: dataDate,
          boundaryGap: false,
          // 坐标轴线
          axisLine: {
            show: false,
            lineStyle: {
              color: '#999'
            }
          },
          // 分割线
          splitLine: {
            show: true,
            lineStyle: {
              type: 'dashed',
              color: '#e5e5e5'
            }
          }
        },
        yAxis: {
          type: 'value',
          axisLine: {
            show: false,
            lineStyle: {
              color: '#999'
            }
          },
          splitLine: {
            lineStyle: {
              type: 'dashed',
              color: '#e5e5e5'
            }
          }
        },
        series: series
      }
      var chart = echarts.init(document.getElementById('chart'))
      chart.clear()
      chart.setOption(option, true)
      window.onresize = function() {
        chart.resize()
      }
    },
    getDate() {
      let date = new Date()
      let y = date.getFullYear()
      let MM = date.getMonth() + 1
      MM = MM < 10 ? '0' + MM : MM
      let d = date.getDate()
      d = d < 10 ? '0' + d : d
      let h = date.getHours() - 1
      h = h < 10 ? '0' + h : h
      if (this.active == 1) {
        if (this.statHour) {
          return y + '-' + MM + '-' + d
        } else {
          return y + '-' + MM + '-' + d + '  ' + h
        }
      } else {
        return y + '-' + MM + '-' + (d - 1)
      }
    },
    exportExcel() {
      var title = ''
      if (this.active == 1) {
        if (this.statHour) {
          title = this.getDate() + '  ' + this.statHour + '时数据报表'
        } else {
          title = this.getDate() + '时数据报表'
        }
      } else if (this.active == 2) {
        title = this.getDate() + '数据报表'
      } else {
        title = this.statDate + '数据报表'
      }
      const borderAll = {
        //单元格外侧框线
        top: {
          style: 'thin'
        },
        bottom: {
          style: 'thin'
        },
        left: {
          style: 'thin'
        },
        right: {
          style: 'thin'
        }
      }
      //   var opt = {
      //     rowIndex: 4
      //   } //开头空4行
      var sheet = XLSX2.utils.table_to_sheet(document.getElementById('outTable'))
      var sheetName = ['D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O']
      //   sheet['A2'].s = {
      //     alignment: {
      //       horizontal: 'center',
      //       vertical: 'center'
      //     }
      //     // fill: {
      //     //   fgColor: {rgb: "008000"},
      //     // },
      //   }
      //   for (let i = 0; i < 3; i++) {
      //     sheet['B' + (length + 1 - i)].s = {
      //       alignment: {
      //         horizontal: 'center',
      //         vertical: 'center'
      //       }
      //     }
      //   }
      //   for (let i = 0; i < sheetName.length; i++) {
      //     for (let j = 2; j < length + 2; j++) {
      //       console.log(sheetName[i] + j + '')
      //       var a = sheetName[i] + j + ''
      //       console.log(a)
      //       sheet[a].t = 'n'
      //     }
      //   }
      for (var i in sheet) {
        if (i == '!ref' || i == '!merges' || i == '!cols') {
        } else {
          sheet[i + ''].s = {
            border: borderAll,
            alignment: {
              horizontal: 'center',
              vertical: 'center'
            }
            // fill: {
            //   fgColor: { rgb: 'FFFF00' }
            // }
          }
          sheet[i + ''].t = 'n'
        }
      }
      //["!merges"]这个属性是专门用来进行单元格合并的
      //   sheet['!merges'].push({
      //     //如果不为空push 为空 = 赋值
      //     //合并单元格 index都从0开始
      //     s: {
      //       //s开始
      //       c: 0, //开始列
      //       r: 0 //开始行
      //     },
      //     e: {
      //       //e结束
      //       c: 12, //结束列
      //       r: 3 //结束行
      //     }
      //   })

      sheet['!cols'] = [
        {
          wpx: 100
        },
        {
          wpx: 100
        },
        {
          wpx: 100
        },
        {
          wpx: 100
        },
        {
          wpx: 100
        },
        {
          wpx: 100
        },
        {
          wpx: 100
        },
        {
          wpx: 100
        },
        {
          wpx: 100
        },
        {
          wpx: 100
        },
        {
          wpx: 100
        },
        {
          wpx: 100
        },
        {
          wpx: 100
        },
        {
          wpx: 100
        },
        {
          wpx: 100
        },
        {
          wpx: 100
        }
      ] //单元格列宽

      openDownloadDialog(sheet2blob(sheet), title + '.xlsx')
    }
  },
  watch: {},
  distoryed() {},
  mounted: function() {
    this.$nextTick(() => {
      getAction('/sys/user/getRoleInfo', { userId: this.userInfo().id }).then(res => {
        this.role = res
      })
    })
  }
}
</script>
