<template>
  <div class="mediaReport">
    <div class="mediaReport_header">
      <div class="option-top">
        <span class="item">
          <span class="title">
            公司
            <a-tooltip class="tipinfo">
              <template slot="title">
                不选时，默认查询全部公司(包括渠道)。
              </template>

              <a-icon type="question-circle" />
            </a-tooltip>
          </span>
          <span>：</span>
          <a-select placeholder="请选择公司" style="width: 120px" v-model="company">
            <a-select-option value="">全部</a-select-option>
            <a-select-option v-for="item in companyArr" :key="item.companyId" :value='item.companyId'>
              {{item.area}}
            </a-select-option>
          </a-select>

        </span>
        <span class="item">
          <span class="title">
            广告主
            <a-tooltip class="tipinfo">
              <template slot="title">
                不选时，默认查询全部广告主。不选择公司时，不可选择广告主。
              </template>
              <a-icon type="question-circle" />
            </a-tooltip>

          </span>
          <span>：</span>
          <!-- @focus="handleFocus" @blur="handleBlur" @change="advertisersChange" -->
          <a-select show-search placeholder='请选择或搜索广告主' option-filter-prop="children" style="width: 300px"
            :filter-option="filterOption" v-model="advertiser" @change="advertisersChange">
            <a-select-option value="">全部</a-select-option>
            <a-select-option v-for="item in advertisersArr" :key="item.id" :value='item.id'>
              {{item.name}}
            </a-select-option>
          </a-select>

        </span>
        <span class="item">
          <span class="title">
            产品
            <a-tooltip class="tipinfo">
              <template slot="title">
                不选时，默认查询全部产品
              </template>
              <a-icon type="question-circle" />
            </a-tooltip>
          </span>
          <span>：</span>
          <a-select show-search option-filter-prop="children" :filter-option="filterOption" @focus="handleFocus"
            @blur="handleBlur" placeholder='请选择或搜索产品' style="width: 200px" @change="projectChange" v-model="project">
            <a-select-option value="">全部</a-select-option>
            <a-select-option v-for="item in projectArr" :key="item.id" :value='item.id'>
              {{item.productName}}
            </a-select-option>
          </a-select>

        </span>

      </div>
      <div class="option-bot">
        <!-- <span class="item">
          <span class="title">
            媒体
            <a-tooltip class="tipinfo">
              <template slot="title">
                不选时，默认查询全部媒体。
              </template>
              <a-icon type="question-circle" />
            </a-tooltip>
          </span>
          <span>：</span>
          <a-select placeholder="请选择媒体" style="width: 120px" v-model="mediaType">
            <a-select-option value="">全部</a-select-option>
            <a-select-option :value='1'>头条</a-select-option>
            <a-select-option :value='2'>快手</a-select-option>
            <a-select-option :value='3'>头条内广</a-select-option>
            <a-select-option :value='4'>快手内广</a-select-option>
          </a-select>
        </span> -->

        <span class="item">
          <span class="title">
            日期
            <a-tooltip class="tipinfo">
              <template slot="title">
                将以选择的日期为准，消耗差值=当天-前一天；
              </template>
              <a-icon type="question-circle" />
            </a-tooltip>

          </span>
          <span>：</span>
          <a-date-picker @change="onChange" v-model="dateValue" :allowClear="false" placeholder='请选择日期'
            :disabled-date="disabledDate" />

        </span>

      </div>
      <a-button type='primary' class="option-btn" @click="searchHandle">搜索</a-button>
    </div>
    <div class="tableBox">
      <a-card style="width:100%" :tab-list="tabListNoTitle" :active-tab-key="noTitleKey"
        @tabChange="key => onTabChange(key, 'noTitleKey')">
        <div class="tableBody">
          <a-table size="middle" :columns="columns" :dataSource="tableData" bordered id="tableBody"
            :pagination="ipagination" :loading="loading" @change="tableChange"
            style="word-break: break-all;font-size:16px;font-weight:600">
            <span slot="mediaType" slot-scope="text">
              <span v-if="text==1">头条</span>
              <span v-if="text==2">快手</span>
              <span v-if="text==3">头条内广</span>
              <span v-if="text==4">快手内广</span>
              <span v-if="text=='-'">-</span>
            </span>
            <!-- <span slot="yesterdayCost" slot-scope="yesterdayCost,record">
              <span v-if="record.mediaType == 1">{{yesterdayCost | decimalsHandle}}</span>
              <span v-else>{{yesterdayCost | decimalsHandleThree}}</span>
            </span>
            <span slot="todayCost" slot-scope="todayCost,record">
              <span v-if="record.mediaType == 1">{{todayCost | decimalsHandle}}</span>
              <span v-else>{{todayCost | decimalsHandleThree}}</span>
            </span>
            <span slot="diffCost" slot-scope="diffCost,record">
              <span v-if="record.mediaType == 1">{{diffCost | decimalsHandle}}</span>
              <span v-else>{{diffCost | decimalsHandleThree}}</span>
            </span> -->
            <span slot="operatorManger" slot-scope="operatorManger">{{ operatorManger | blankHandle}}</span>
            <span slot="operator" slot-scope="operator">{{ operator | blankHandle}}</span>
            <span slot="sale" slot-scope="sale">{{ sale | blankHandle}}</span>
            <span slot="plan" slot-scope="plan">{{ plan | blankHandle}}</span>
            <span slot="shot" slot-scope="shot">{{ shot | blankHandle}}</span>
            <span slot="clip" slot-scope="clip">{{ clip | blankHandle}}</span>
          </a-table>
        </div>
        <!-- <a slot="tabBarExtraContent" href="#">More</a> -->
        <a-button slot="tabBarExtraContent" type='primary' class="export" @click="exportExcel">导出报表</a-button>
      </a-card>
      <!-- <div class="tableOption">
        
      </div> -->

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

<script>
  import moment from 'moment';
  import {
    getAction,
    postAction,
    downFile,
    downFilePost
  } from '@/api/manage';
  import {
    JeecgListMixin
  } from '@/mixins/ipagination'

  export default {
    mixins: [JeecgListMixin],
    data() {
      return {
        moment,
        tabListNoTitle: [{
            key: '1',
            tab: '头条',
          },
          {
            key: '2',
            tab: '快手',
          }
        ],
        noTitleKey: '1',
        company: undefined, //公司的默认值
        mediaType: '1', // 媒体类型
        advertiser: undefined, //广告主
        project: undefined, //项目
        dateValue: moment(), //
        advertisersArr: [], //广告主数组
        projectArr: [], //项目数组
        companyArr: [], //公司数组
        mediaTypeArr: [],
        tableData: [],
        loading: false,
        dateString1: moment().subtract(1, 'days').format('YYYY-MM-DD'),
        dateString2: moment().format('YYYY-MM-DD'),
        columns: [{
            title: '媒体',
            dataIndex: 'mediaType',
            align: 'center',
            scopedSlots: {
              customRender: 'mediaType'
            },
            width: 50
          },
          {
            title: '广告主',
            dataIndex: 'advertiserName',
            align: 'center',
            scopedSlots: {
              customRender: 'advertiserName'
            }
          },
          {
            title: '产品',
            dataIndex: 'productName',
            align: 'center',
            scopedSlots: {
              customRender: 'productName'
            },
            width: 80
          },
          {
            title: moment().subtract(1, 'days').format('YYYY-MM-DD'),
            dataIndex: 'yesterdayCost',
            align: 'center',
            scopedSlots: {
              customRender: 'yesterdayCost'
            }
          },
          {
            title: moment().format('YYYY-MM-DD'),
            dataIndex: 'todayCost',
            align: 'center',
            scopedSlots: {
              customRender: 'todayCost'
            }
          },
          {
            title: '消耗差值',
            dataIndex: 'diffCost',
            align: 'center',
            scopedSlots: {
              customRender: 'diffCost'
            }
          },
          {
            title: '公司',
            dataIndex: 'companyName',
            align: 'center',
            scopedSlots: {
              customRender: 'companyName'
            },
            width: 200
          },
          {
            title: '运营',
            dataIndex: 'operator',
            align: 'center',
            scopedSlots: {
              customRender: 'operator'
            },
            width: 120
          },
          {
            title: '销售',
            dataIndex: 'sale',
            align: 'center',
            scopedSlots: {
              customRender: 'sale'
            },
            width: 80
          },
          // {
          //     title: '策划',
          //     dataIndex: 'plan',
          //     align: 'center',
          //     scopedSlots: { customRender: 'plan' },
          //     width:120
          // },
          // {
          //     title: '拍摄',
          //     dataIndex: 'shot',
          //     align: 'center',
          //     scopedSlots: { customRender: 'shot' },
          //     width:120
          // },
          // {
          //     title: '剪辑',
          //     dataIndex: 'clip',
          //     align: 'center',
          //     scopedSlots: { customRender: 'clip' },
          //     width:120
          // },

        ]
      }
    },
    methods: {
      onTabChange(key, type) {
        console.log(key, type);
        this[type] = key;
        this.mediaType = key
        this.ipagination.current = 1
        this.searchHandle()
        this.project = undefined;
        this.getPruduct()
      },
      companyChange(value) {
        if (this.company == '' || this.company == undefined) {
          this.advertisersArr = [];
          this.projectArr = [];
          this.advertiser = undefined;
          this.project = undefined;
        } else {
          //网络请求获取广告主数据
          this.advertisersArr = [];
          this.projectArr = [];
          this.advertiser = undefined;
          this.project = undefined;
          getAction('/ctop/product/advertiserList').then(res => {
            if (res.success) {
              console.log(res)
              this.advertisersArr = res.result
            }
          })
        }
      },
      //广告主改变
      advertisersChange(value) {
        console.log(`selected ${value}`);
        if (this.advertiser == '' || this.advertiser == undefined) {

          this.project = undefined;
		  this.projectArr = [];
		  this.getPruduct()
        } else {
          this.project = undefined;
          this.projectArr = [];
          this.getPruduct()
        }
      },
      projectChange(value) {
        console.log(`selected ${value}`);
        if (this.project == '') {
          // this.project=undefined
        }
      },
      //日期改变
      onChange(date, dateString) {
        // console.log(date, dateString,this.dateValue);
        let addCol = [{
            title: moment(date).subtract(1, 'days').format('YYYY-MM-DD'),
            dataIndex: 'yesterdayCost',
            align: 'center',
            scopedSlots: {
              customRender: 'accountId'
            }
          },
          {
            title: dateString,
            dataIndex: 'todayCost',
            align: 'center',
            scopedSlots: {
              customRender: 'accountId'
            }
          },
        ];

        this.columns.splice(3, 2, addCol[0], addCol[1]);
        this.searchHandle();
      },

      //搜索
      searchHandle() {
        let company = '';
        let advertiser = '';
        let project = '';
        let mediaType = ''
        if (this.company == undefined) {
          company = ''
        } else {
          company = this.company
        }
        if (this.advertiser == undefined) {
          advertiser = ''
        } else {
          advertiser = this.advertiser
        }
        if (this.project == undefined) {
          project = ''
        } else {
          project = this.project
        }
        if (this.mediaType == undefined) {
          mediaType = ''
        } else {
          mediaType = this.mediaType
        }

        this.tableHttp({
          companyId: company,
          advertiserId: advertiser,
          productId: project,
          mediaType,
          todayDate: this.dateValue.format('YYYY-MM-DD'),
          yesterdayDate: moment(this.dateValue).subtract(1, "days").format('YYYY-MM-DD'),
        })
      },
      //table的改变（页码改变请求数据，也可以写排序）
      tableChange(pagination, filters, sorter, {
        currentDataSource
      }) {

        this.searchHandle();
      },
      //table的网络请求
      tableHttp(params) {
        this.loading = true;
        this.tableData = []
        postAction(`/ctop/media/report/mediaReport/${this.ipagination.current}/${this.ipagination.pageSize}`, params)
          .then(res => {
            if (res.success) {
              // console.log(res)
              this.loading = false;
              this.ipagination.total = res.result.total
              if (res.success) {
                res.result.list.map((item, index) => {
                  item.key = index
                })
                this.tableData = res.result.list
              }
            }
          })
      },
      //导出报表
      exportExcel() {
        let company = '';
        let advertiser = '';
        let project = '';
        let mediaType = ''
        if (this.company == undefined) {
          company = ''
        } else {
          company = this.company
        }
        if (this.advertiser == undefined) {
          advertiser = ''
        } else {
          advertiser = this.advertiser
        }
        if (this.project == undefined) {
          project = ''
        } else {
          project = this.project
        }
        if (this.mediaType == undefined) {
          mediaType = ''
        } else {
          mediaType = this.mediaType
        }


        downFilePost('/ctop/media/report/exportMediaReportExcel', {
          //   companyId: company,
          //   advertiserId: advertiser,
          //   projectId: project,
          mediaType,
          todayDate: this.dateValue.format('YYYY-MM-DD'),
          //   yesterdayDate: moment(this.dateValue).subtract(1, "days").format('YYYY-MM-DD'),
        }).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对象
        })
      },

      handleBlur() {
        // console.log('blur');
      },
      handleFocus() {
        // console.log('focus');
      },
      filterOption(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        );
      },
      disabledDate(current) {
        // console.log(current)
        return current && current > moment()
      },
      getPruduct() {
        postAction('/ctop/media/report/getAllProductList', {
          "mediaType": this.noTitleKey,
          advertiserId: this.advertiser==""?null:this.advertiser
        }).then(res => {
          if (res.success) {
            console.log(res)
            this.projectArr = res.result
          }
        })
      }
    },
    mounted() {
      getAction('/ctop/media/report/getCompany', {}).then(res => {
        if (res.success) {
          this.companyArr = res.result
        }
      });
      getAction('/ctop/product/advertiserList').then(res => {
        if (res.success) {
          console.log(res)
          this.advertisersArr = res.result
        }
      })
      this.getPruduct()

      this.tableHttp({
        companyId: '',
        advertiserId: '',
        productId: '',
        mediaType: '1',
        todayDate: this.dateValue.format('YYYY-MM-DD'),
        yesterdayDate: moment(this.dateValue).subtract(1, 'days').format('YYYY-MM-DD'),
      })


    },
    filters: {
      toPercentage(val) {
        if (val) {
          if (typeof val != 'string') {
            return (val * 100).toFixed(2) + '%'
          } else {
            return val
          }
        } else if (typeof val == 'string') {
          return val
        } else {
          return 0
        }
      },
      //保留两位小数并且变成货币格式
      decimalsHandle(val) {

        if (val && typeof val != 'string') {
          if (val >= 0) {
            val = parseFloat(val).toFixed(2);
            let numberStr = val.toString()
            let str = numberStr.split('.')

            let str0 = str[0].split('').reverse();
            for (let i = 0; i < str0.length; i++) {
              if ((i + 1) % 4 === 0) {
                str0.splice(i, 0, ',')
              }
            }
            str0.reverse()
            let handleResult = ''
            for (let j = 0; j < str0.length; j++) {
              handleResult += str0[j]
            }

            return handleResult + '.' + str[1]
          } else {
            val = parseFloat(val).toFixed(2);
            let numberStr = val.toString()
            let str = numberStr.split('.')

            let str0 = str[0].substr(1).split('').reverse();
            for (let i = 0; i < str0.length; i++) {
              if ((i + 1) % 4 === 0) {
                str0.splice(i, 0, ',')
              }
            }
            str0.reverse()
            let handleResult = ''
            for (let j = 0; j < str0.length; j++) {
              handleResult += str0[j]
            }

            return '-' + handleResult + '.' + str[1]
          }

        } else if (typeof val == 'string') {
          return val
        } else {
          return 0
        }
      },
      //保留两位小数并且变成货币格式
      decimalsHandleThree(val) {

        if (val && typeof val != 'string') {
          if (val >= 0) {
            val = parseFloat(val).toFixed(3);
            let numberStr = val.toString()
            let str = numberStr.split('.')

            let str0 = str[0].split('').reverse();
            for (let i = 0; i < str0.length; i++) {
              if ((i + 1) % 4 === 0) {
                str0.splice(i, 0, ',')
              }
            }
            str0.reverse()
            let handleResult = ''
            for (let j = 0; j < str0.length; j++) {
              handleResult += str0[j]
            }

            return handleResult + '.' + str[1]
          } else {
            val = parseFloat(val).toFixed(3);
            let numberStr = val.toString()
            let str = numberStr.split('.')

            let str0 = str[0].substr(1).split('').reverse();
            for (let i = 0; i < str0.length; i++) {
              if ((i + 1) % 4 === 0) {
                str0.splice(i, 0, ',')
              }
            }
            str0.reverse()
            let handleResult = ''
            for (let j = 0; j < str0.length; j++) {
              handleResult += str0[j]
            }

            return '-' + handleResult + '.' + str[1]
          }

        } else if (typeof val == 'string') {
          return val
        } else {
          return 0
        }
      },
      //变成货币格式
      formatCurrency(val) {
        if ((val || val == 0) && typeof val != 'string') {
          let numberStr = val.toString()
          let str = numberStr.split('').reverse()
          for (let i = 0; i < str.length; i++) {
            if ((i + 1) % 4 === 0) {
              str.splice(i, 0, ',')
            }
          }
          str.reverse()
          let handleResult = ''
          for (let j = 0; j < str.length; j++) {
            handleResult += str[j]
          }
          return handleResult
        } else if (typeof val == 'string') {
          return val
        } else {
          return '-'
        }

      },

      //处理空白为 --
      blankHandle(val) {
        if (val) {
          return val
        } else {
          return '-'
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
  .mediaReport {
    padding: 0 10px;

    .mediaReport_header {
      padding: 15px 10px;
      background: #fff;
      position: relative;

      .option-top,
      .option-bot {
        .item {
          margin-right: 20px;
          display: inline-block;

          .title {
            display: inline-block;
            position: relative;
            padding-right: 15px;
            margin-right: 5px;
          }

          .tipinfo {
            position: absolute;
            font-size: 12px;
            right: 0px;
            top: 0;
          }
        }

      }

      .option-top {
        margin-bottom: 15px;
      }

      .option-btn {
        position: absolute;
        top: 15px;
        right: 10px;
      }

    }

    .mediaReport_header:hover {
      border-radius: 5px;
      box-shadow: 0 0 15px rgba(0, 0, 0, .2);
    }

    .tableBox {
      margin-top: 30px;
      background: #fff;
      padding: 10px 10px;

      .tableOption {
        margin-bottom: 10px;
        text-align: right;
      }
    }
  }
</style>
<style lang="scss">
  .ant-tooltip-inner,
  .ant-tooltip,
  .ant-tooltip-arrow::before {
    background-color: #fff;
    color: #666;
    font-size: 12px;
  }
</style>