<style>
.materialReport .chart-card-content {
  display: none !important;
}
</style>
<style scoped>
.top-ul-style {
  width: 100%;
  padding-left: 0;
}
.top-ul-style li {
  height: 100px;
  border: 1px solid #f2f2f2;
  margin-bottom: 5px;
  padding: 10px;
  display: flex;
  justify-content: space-between;
}
.li-cost {
  display: flex;
  flex-flow: column;
  justify-content: center;
  align-content: flex-end;
}
.li-cost span {
  font-size: 16px;
  font-weight: 500;
  min-width: 50px;
  text-align: right;
}
</style>
<template>
  <div class="materialReport">
    <div class="card-container">
      <div class="option" style="justify-content: space-between">
        <div class="option" style="padding: 0">
          <div class="item">
            <span>素材ID</span>
            <a-input style="width: 300px" v-model="md5"></a-input>
          </div>
        </div>

        <div class="item" style="float: right">
          <a-button @click="handleSubmit" type="primary" :loading="spinning">搜索</a-button>
          <a-button @click="resetSubmit" style="margin-left: 15px" :loading="spinning">重置</a-button>
        </div>
      </div>
    </div>
    <a-row :gutter="24" style="margin-top: 20px">
      <a-col :xl="24">
        <a-card title="数据列表" style="width: 100%; min-height: 700px" :bordered="false">
          <div class="tableTop" style="text-align: end; margin: 0 0 15px 0">
            <!-- <a-button type="primary" class="export" @click="exportExcel">导出报表</a-button> -->
            <a-button type="primary" class="add" @click="customColumns">自定义列</a-button>
          </div>
          <a-table
            size="middle"
            :columns="columns"
            :dataSource="tableData"
            bordered
            id="outTable"
            :pagination="ipagination"
            :scroll="{ x: scrollX }"
            :loading="loading"
            ref="accountTable"
            :width="tableWidth"
            :customRow="rowClick"
            @change="sort"
            style="word-break: break-all; font-size: 16px; font-weight: 600"
          >
            <span slot="coverUrl" slot-scope="text, records">
              <img :src="text || noImg" alt="" style="width: 100%; height: auto" />
            </span>
            <span slot="ctr" slot-scope="ctr">{{ ctr | toPercentage }}</span>
            <span slot="cost" slot-scope="cost">{{ cost | decimalsHandle }}</span>
            <span slot="clickMaterial" slot-scope="clickMaterial">{{ clickMaterial | formatCurrency }}</span>
            <span slot="showMaterial" slot-scope="showMaterial">{{ showMaterial | formatCurrency }}</span>
            <span slot="convertMaterial" slot-scope="convertMaterial">{{ convertMaterial | formatCurrency }}</span>
            <span slot="play25FeedBreak" slot-scope="play25FeedBreak">{{ play25FeedBreak | formatCurrency }}</span>
            <span slot="play50FeedBreak" slot-scope="play50FeedBreak">{{ play50FeedBreak | formatCurrency }}</span>
            <span slot="play75FeedBreak" slot-scope="play75FeedBreak">{{ play75FeedBreak | formatCurrency }}</span>
            <span slot="play100FeedBreak" slot-scope="play100FeedBreak">{{ play100FeedBreak | formatCurrency }}</span>
            <span slot="nextDayOpen" slot-scope="nextDayOpen">{{ nextDayOpen | formatCurrency }}</span>
            <span slot="downloadFinish" slot-scope="downloadFinish">{{ downloadFinish | formatCurrency }}</span>
            <span slot="downloadStart" slot-scope="downloadStart">{{ downloadStart | formatCurrency }}</span>
            <span slot="likeMaterial" slot-scope="likeMaterial">{{ likeMaterial | formatCurrency }}</span>
            <span slot="shareMaterial" slot-scope="shareMaterial">{{ shareMaterial | formatCurrency }}</span>
            <span slot="register" slot-scope="register">{{ register | formatCurrency }}</span>
            <span slot="follow" slot-scope="follow">{{ follow | formatCurrency }}</span>
            <span slot="formCount" slot-scope="formCount">{{ formCount | formatCurrency }}</span>
            <span slot="formCountCost" slot-scope="formCountCost">{{ formCountCost | decimalsHandle }}</span>
            <span slot="aClick" slot-scope="aClick">{{ aClick | formatCurrency }}</span>
            <span slot="photoShow" slot-scope="photoShow">{{ photoShow | formatCurrency }}</span>
            <span slot="photoClick" slot-scope="photoClick">{{ photoClick | formatCurrency }}</span>
            <span slot="bClick" slot-scope="bClick">{{ bClick | formatCurrency }}</span>
            <span slot="active" slot-scope="active">{{ active | formatCurrency }}</span>
            <span slot="submit" slot-scope="submit">{{ submit | formatCurrency }}</span>
            <span slot="nextDayOpen" slot-scope="nextDayOpen">{{ nextDayOpen | formatCurrency }}</span>
            <span slot="eventCreditGrantLandingPage" slot-scope="eventCreditGrantLandingPage">{{
              eventCreditGrantLandingPage | formatCurrency
            }}</span>
            <span slot="submitCost" slot-scope="submitCost">{{ submitCost | decimalsHandle }}</span>
            <span slot="eventCreditGrantLandingPageCost" slot-scope="eventCreditGrantLandingPageCost">{{
              eventCreditGrantLandingPageCost | decimalsHandle
            }}</span>
            <span slot="submitRate" slot-scope="submitRate">{{ submitRate | toPercentage }}</span>
            <span slot="eventCreditGrantLandingPageRate" slot-scope="eventCreditGrantLandingPageRate">{{
              eventCreditGrantLandingPageRate | toPercentage
            }}</span>
            <span slot="play25FeedBreakRate" slot-scope="play25FeedBreakRate">{{
              play25FeedBreakRate | toPercentage
            }}</span>
            <span slot="playOverRate" slot-scope="playOverRate">{{ playOverRate | toPercentage }}</span>
            <!-- 新加数据 -->

            <span slot="convertRate" slot-scope="convertRate">{{ convertRate | toPercentage }}</span>
            <span slot="nextDayOpenRate" slot-scope="nextDayOpenRate">{{ nextDayOpenRate | toPercentage }}</span>
            <span slot="ctr" slot-scope="ctr">{{ ctr | toPercentage }}</span>
            <span slot="cpc" slot-scope="cpc">{{ cpc | decimalsHandle }}</span>
            <span slot="cpm" slot-scope="cpm">{{ cpm | decimalsHandle }}</span>
            <span slot="activeRate" slot-scope="activeRate">{{ activeRate | toPercentage }}</span>
            <span slot="installFinishRate" slot-scope="installFinishRate">{{ installFinishRate | toPercentage }}</span>
            <span slot="validPlayRate" slot-scope="validPlayRate">{{ validPlayRate | toPercentage }}</span>
            <span slot="activePayCost" slot-scope="activePayCost">{{ activePayCost | decimalsHandle }}</span>
            <span slot="nextDayOpenCost" slot-scope="nextDayOpenCost">{{ nextDayOpenCost | decimalsHandle }}</span>
            <span slot="validPlayCost" slot-scope="validPlayCost">{{ validPlayCost | decimalsHandle }}</span>
            <span slot="activeCost" slot-scope="activeCost">{{ activeCost | decimalsHandle }}</span>
            <span slot="nextDayOpenCost" slot-scope="nextDayOpenCost">{{ nextDayOpenCost | decimalsHandle }}</span>
            <span slot="gameAddictionCost" slot-scope="gameAddictionCost">{{
              gameAddictionCost | decimalsHandle
            }}</span>
            <span slot="downloadFinishCost" slot-scope="downloadFinishCost">{{
              downloadFinishCost | decimalsHandle
            }}</span>
            <span slot="downloadStartCost" slot-scope="downloadStartCost">{{
              downloadStartCost | decimalsHandle
            }}</span>
            <span slot="installFinishCost" slot-scope="installFinishCost">{{
              installFinishCost | decimalsHandle
            }}</span>
            <span slot="convertCost" slot-scope="convertCost">{{ convertCost | decimalsHandle }}</span>

            <!--  -->
            <span slot="downloadStartRate" slot-scope="downloadStartRate">{{ downloadStartRate | toPercentage }}</span>
            <span slot="downloadFinishRate" slot-scope="downloadFinishRate">{{
              downloadFinishRate | toPercentage
            }}</span>
            <span slot="activeRate" slot-scope="activeRate">{{ activeRate | toPercentage }}</span>
            <span slot="activeRegisterRate" slot-scope="activeRegisterRate">{{
              activeRegisterRate | toPercentage
            }}</span>
            <span slot="gameAddictionRate" slot-scope="gameAddictionRate">{{ gameAddictionRate | toPercentage }}</span>
            <span slot="nextDayOpenRate" slot-scope="nextDayOpenRate">{{ nextDayOpenRate | toPercentage }}</span>
            <!-- <span slot="nextDayOpenRate" slot-scope="nextDayOpenRate">{{ nextDayOpenRate | toPercentage }}</span> -->
          </a-table>
        </a-card>
      </a-col>
    </a-row>
    <a-modal title="查看视频" v-model="visibleVideo" :width="400" :footer="null">
      <video class="video" :src="videoUrlShow" controls="controls" style="width: 100%">
        您的浏览器不支持 video 标签。
      </video>
    </a-modal>
    <customColumn
      :visible="visible"
      :listNum="listNum"
      :fiexColumn="columnsFixd"
      :mediaType="2"
      @closeCustomColumn="closeCustomColumn"
      @changeColumn="changeColumn"
    />
  </div>
</template>

<script>
import moment from 'moment'
import { getAction, postAction, downFile, downFilePost } from '@/api/manage'
import YoutTable from '@/components/youtTable/YoutTable'
import ChartCard from '@/components/ChartCard'
import Trend from '@/components/Trend'
import { mapGetters } from 'vuex'
import { stopOtherVideo, closeAllVideoFun } from '@/utils/videoControl' // 停止除当前外的其他视频播放，及停止所有视频播放的方法
import customColumn from '../components/customColumn.vue'
var echarts = require('echarts')

const columnsFixd = [
  {
    title: '素材',
    dataIndex: 'coverUrl',
    scopedSlots: { customRender: 'coverUrl' },
    align: 'center',
    key: 'date',
    width: 200,
    fixed: 'left',
  },
  {
    title: '素材名称',
    dataIndex: 'materialName',
    align: 'center',
    width: 200,
    fixed: 'left',
    customRender: function (text) {
      if (text) {
        return text
      } else {
        return '-'
      }
    },
  },
  {
    title: '所属项目',
    dataIndex: 'projectName',
    align: 'center',
    width: 200,
    fixed: 'left',
  },
]

const initVariableColimns = [
  {
    title: '消耗（元）',
    dataIndex: 'cost',
    scopedSlots: { customRender: 'cost' },
    align: 'center',
    sorter: (a, b) => {},
  },
  {
    title: '点击数',
    dataIndex: 'clickMaterial',
    align: 'center',
    scopedSlots: { customRender: 'clickMaterial' },
    sorter: (a, b) => {},
    // (a, b) => a.clickMaterial - b.clickMaterial
  },
  {
    title: '点击率',
    dataIndex: 'ctr',
    align: 'center',
    scopedSlots: { customRender: 'ctr' },
    sorter: (a, b) => {},
  },

  {
    title: '展示数',
    dataIndex: 'showMaterial',
    align: 'center',

    scopedSlots: { customRender: 'showMaterial' },
    sorter: (a, b) => {},
  },
  {
    title: '平均千次展现费用(元)',
    dataIndex: 'cpm',
    tip: '广告平均每一千次展现所付出的费用，计算公式是：总花费/展示数*1000',
    align: 'center',

    scopedSlots: { customRender: 'cpm' },
    sorter: (a, b) => {},
  },
  {
    title: '平均点击单价(元)',
    dataIndex: 'cpc',
    tip: '广告主为每次点击付出的费用成本，计算公式是：总花费/点击数',
    align: 'center',
    scopedSlots: { customRender: 'cpc' },
    sorter: (a, b) => {},
  },
]
export default {
  components: {
    YoutTable,
    ChartCard,
    Trend,
    customColumn,
  },
  data() {
    return {
      tableData: [],
      designTopLoading: false,
      noImg: require('@/assets/noImg.png'),
      visibleVideo: false,
      videoUrlShow: '',
      cost: '0',
      costLink: 0,
      videoTotal: '0',
      newVideo: 0,
      hotTotal: '0',
      xiaoTotal: '0',
      spinning: false,
      loading: false,
      chartList: [],
      videoList: [],
      designTopList: [],
      columns: [...columnsFixd, ...initVariableColimns], //table的表头
      columnsFixd,
      ipagination: {
        current: 1,
        pageSize: 10,
        //   pageSizeOptions: ['10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        // showSizeChanger: true,
        // pageSizeOptions: ['10', '30', '50'],
        total: 0,
        onChange: (current, pageSize) => {
          // 切换分页时的回调，
          // 当在页面定义change事件时，切记要把此处的事件清除，因为这两个事件重叠了，可能到时候会导致一些莫名的bug
          this.ipagination.current = current
          this.ipagination.pageSize = pageSize
        },
      },

      dateRanges: {
        今天: [moment(), moment()],
        昨天: [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
        近一周: [moment().subtract(7, 'days'), moment()],
        近一月: [moment().subtract(1, 'months'), moment()],
        近半年: [moment().subtract(6, 'months'), moment()],
        近一年: [moment().subtract(12, 'months'), moment()],
      },
      dateValue: [moment().subtract(7, 'days'), moment()],
      dataDimension: 'a',
      mediaDimension: 'b',
      dataDimensionValue: [],
      dataDimensionList: [],
      specificLoading: false,
      order: null,
      target: null,
      materialData: null,
      md5: '',
      visible: false,
      listNum: [],
      scrollX: 1000,
      tableWidth: '', //设置表格的列宽
    }
  },
  watch: {
    visibleVideo(n, o) {
      if (!n) {
        stopOtherVideo()
        closeAllVideoFun()
      }
    },
    'ipagination.current': function (n, o) {
      if (n != o) {
        this.getMoreVideoList({
          ...this.materialData,
        })
      }
    },
  },
  methods: {
    rowClick(record, index) {
      return {
        on: {
          click: (e) => {
            this.$router.push({
              path: '/materialReport/marterialDetail?md5=' + record.signature + '&mediaId=1',
            })
          },
        },
      }
    },

    moment,
    closeCustomColumn() {
      this.visible = false
    },
    changeColumn(val) {
      this.columns = [...val]
      if (this.columns.length > this.columnsFixd.length && this.columns.length < 8) {
        this.columns.forEach((element, index) => {
          if (index < this.columns.length - 1) {
            element.width = 'auto'
            element.fixed = false
          }
        })

        // this.scrollX=2000+200*(this.columns.length-this.columnsFixd.length)
      } else if (this.columns.length >= 8) {
        this.columns.forEach((element, index) => {
          if (index < this.columnsFixd.length) {
            element.width = 200
            element.fixed = 'left'
          }
        })

        this.scrollX = 1000 + 200 * (this.columns.length - this.columnsFixd.length)
      } else {
        this.scrollX = 0
        this.columns.forEach((element) => {
          element.width = 'auto'
          element.fixed = false
        })
      }
    },
    customColumns() {
      this.visible = true
      this.listNum = [...this.columns]
    },
    ...mapGetters(['userInfo']),
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    sort(pagination, filters, sorter, { currentDataSource }) {
      // console.log(pagination, filters, sorter)
      this.ipagination.current = pagination.current
      this.ipagination.pageSize = pagination.pageSize
      if (sorter.order) {
        this.order = sorter.order ? sorter.order : 'descend'
        this.target = sorter.columnKey
        this.getMoreVideoList({
          ...this.materialData,
          target: sorter.columnKey,
          order: sorter.order ? sorter.order : 'descend',
        })
      } else {
        this.order = null
        this.target = null
      }
    },
    getData() {
      var data = { ...this.materialData, md5: this.md5 }
      this.getMoreVideoList(data)
    },

    getMoreVideoList(data) {
      this.loading = true
      var params = { ...data }
      params.channelType = null

      if (data.target) {
        params.target = data.target
        if (data.order == 'descend') {
          params.order = 'desc'
        } else {
          params.order = 'asc'
        }
      } else {
        params.target = this.target
        params.order = this.order == 'descend' ? 'desc' : this.order == null ? null : 'asc'
      }

      params.pageSize = this.ipagination.pageSize
      params.pageNo = this.ipagination.current
      this.postDataAction('/overView/materialTopViewMore', params).then((res) => {
        this.loading = false
        if (res.success) {
          this.tableData = res.result.list
          this.ipagination.total = res.result.total
        }
      })
    },
    getDesignTopList(data) {
      this.designTopLoading = true
      return new Promise((resolve, reject) => {
        var params = {
          // startDate: this.dateValue.length == 2 ? moment(this.dateValue[0]).format('YYYY-MM-DD') : null,
          // endDate: this.dateValue.length == 2 ? moment(this.dateValue[1]).format('YYYY-MM-DD') : null,
          // userId: this.userInfo().id,
          // pageSize: this.ipagination.pageSize,
          // pageNo: this.ipagination.current,
          // target: 'cost',
          // order: 'desc',
        }
        params.startDate = this.dateValue.length == 2 ? moment(this.dateValue[0]).format('YYYY-MM-DD') : null
        params.endDate = this.dateValue.length == 2 ? moment(this.dateValue[1]).format('YYYY-MM-DD') : null
        params.userId = this.userInfo().id
        params.pageSize = this.ipagination.pageSize
        params.pageNo = this.ipagination.current

        if (data) {
          params.target = data.target
          if (data.order == 'descend') {
            params.order = 'desc'
          } else {
            params.order = 'asc'
          }
        } else {
          params.target = this.target
          params.order = this.order == 'descend' ? 'desc' : 'asc'
        }
        this.postDataAction('/overView/designTop', params).then((res) => {
          this.designTopLoading = false
          if (res.success) {
            this.designTopList = res.result.list
            this.ipagination.total = res.result.total
            resolve(res.result)
          } else {
            reject(res.message)
          }
        })
      })
    },

    handleSubmit() {
      this.ipagination.current = 1
      this.getData()
    },
    resetSubmit() {
      this.dateValue = [moment().subtract(7, 'days'), moment()]
      this.dataDimension = 'a'
      this.mediaDimension = 'b'
      this.dataDimensionValue = []
      this.ipagination.current = 1
      this.md5 = ''
      this.getData()
    },
    //导出报表
    exportExcel() {
      let column = this.columns.map((item, index) => {
        return item.dataIndex
      })
      let columns = column.splice(3)
      // console.log(columns)
      downFilePost('/ctop/kuaishou/dailyPage/report/excel', {
        mediaId: this.mediaId,
        discount: this.discount,
        accountIds: this.accountId,
        startDate: this.dateValue[0].format('YYYY-MM-DD'),
        endDate: this.dateValue[1].format('YYYY-MM-DD'),
        hour: this.timeSelectValue,
        target: this.target,
        order: this.order,
        columns,
      }).then((res) => {
        let blob = new Blob([res], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        })
        let downloadElement = document.createElement('a')
        let href = window.URL.createObjectURL(blob) //创建下载的链接
        downloadElement.href = href
        downloadElement.download = moment().format('YYYY-MM-DD') + '账户报表.xlsx' //下载后文件名
        document.body.appendChild(downloadElement)
        downloadElement.click() //点击下载
        document.body.removeChild(downloadElement) //下载完成移除元素
        window.URL.revokeObjectURL(href) //释放掉blob对象
      })
    },
    tableChange(data) {
      console.log(data)
    },
    //获取echart的值
    initEchart(idName, optionName) {
      const chart = this.$refs[idName]
      //   console.log(chart)
      if (chart) {
        const myChart = echarts.init(document.getElementById(idName))
        // myChart.showLoading({
        //     text: "图表数据正在努力加载..."
        // });

        myChart.setOption(optionName)
        window.addEventListener('resize', function () {
          myChart.resize()
        })
      }
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.materialData = JSON.parse(localStorage.getItem('materialParams'))
      this.getMoreVideoList(this.materialData)
    })
  },
}
</script>

<style lang="scss" scoped>
.materialReport {
  .option {
    background: white;
    padding: 20px;
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
    .item {
      margin-right: 15px;
      margin-bottom: 15px;
      height: 32px;
      line-height: 32px;
      flex-shrink: 0;
      span {
        margin-right: 10px;
      }
    }
  }
  .echart {
    margin-top: 20px;
    padding: 0 20px 20px;
    background: white;
    .echart-header {
      padding: 20px 0;
      font-size: 15px;
      font-weight: 600;
    }
  }
  .tableBody {
    margin-top: 20px;
  }
}
</style>
<style>
.card-container {
  overflow: hidden;
  /* padding: 24px; */
}
.card-container > .ant-tabs-card > .ant-tabs-content {
  /* height: 120px; */
  margin-top: -16px;
}

.card-container > .ant-tabs-card > .ant-tabs-content > .ant-tabs-tabpane {
  background: #fff;
  /* padding: 16px; */
}

.card-container > .ant-tabs-card > .ant-tabs-bar {
  border-color: #fff;
}

.card-container > .ant-tabs-card > .ant-tabs-bar .ant-tabs-tab {
  border-color: transparent;
  background: transparent !important;
}

.card-container > .ant-tabs-card > .ant-tabs-bar .ant-tabs-tab-active {
  border-color: #fff;
  background: #fff !important;
}
</style>