<template>
  <div class="vsummary">
      <div class="tabspane">
        <a-tabs v-model="tabKeys" @change="tabChange">
            <a-tab-pane :key="1" tab="头条">           
            </a-tab-pane>
            <a-tab-pane :key="2" tab="快手" >               
            </a-tab-pane>
        </a-tabs>
      </div>
    <div class="xiangmuxuanze">
      <span>项目选择：</span>
       
        <a-tree-select
            v-model="accountIds"
            show-search
            style="width: 600px;height:30px"
            :dropdownMatchSelectWidth='true'
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"              
            tree-checkable
            searchPlaceholder='请输入账户关键字搜索'
            :show-checked-strategy="SHOW_PARENT"
            placeholder="请选择项目和账户或搜索账户关键字"
            treeNodeFilterProp="title"
            :allowClear="true"
            @change="treeChange"                               
            :maxTagCount='1'    
            :tree-data="treeData"
            :filterOption='filterOption'
        >
        
        </a-tree-select>
        
    </div>
    <div class="timeDiv">
      <div style="margin-right:30px">
        <span>时间范围：</span>

        <a-range-picker
          :disabled-date="disabledDate"
          format="YYYY-MM-DD"
          style="width: 250px;"
          @change="dateChange"
          v-model="dateRange"
        />
        
      </div>
      <div>
        <span>图片ID：</span>
        <a-input class="myinput" v-model="videoID" style="width:250px" :allowClear='true' />
      </div>

      <a-button type="primary" style="position:absolute;right:0" @click="searchRes">查询</a-button>
    </div>

    <div style="display:flex;margin:15px 0" class="btndiv">
      <a-button type="primary" @click="exportExcel" id="mybtn" :loading="exportExcelIsOk">导出报表</a-button>
    </div>

   
    <div class="tableBody">

        <a-table
        size="middle"
        :columns="columns"
        :dataSource="data"
        bordered
        id="outTable"
        :pagination="ipagination"
        :scroll="{ x: scrollX }"
        :loading="loading"
        @change="sort"
        style="word-break: break-all;"
        >
        <div slot="imageUrl" slot-scope="text,records">
            <img
            :src="text"
            alt
            style="width:80px"
            @click="openVideo(records.imageUrl)"
            @load="loadShow"
            />
        </div>
        <span slot="cost" slot-scope="text">{{ text | decimalsHandle }}</span>
        <span slot="charge" slot-scope="text">{{ text | decimalsHandle }}</span>
        <span slot="activation" slot-scope="text">{{ text | decimalsHandle }}</span>
        <span slot="eventRegister" slot-scope="text">{{ text | decimalsHandle }}</span>
        <span slot="eventPay" slot-scope="text">{{ text | decimalsHandle }}</span>
        <span slot="formCount" slot-scope="text">{{ text | decimalsHandle }}</span>
        <span slot="eventJinJianApp" slot-scope="text">{{ text | decimalsHandle }}</span>
        <span slot="eventCreditGrantApp" slot-scope="text">{{ text | decimalsHandle }}</span>
        <span slot="photoClick" slot-scope="text">{{ text | formatCurrency }}</span>
        <span slot="photoShow" slot-scope="text">{{ text | formatCurrency }}</span>
        <span slot="click" slot-scope="text">{{ text | formatCurrency }}</span>
        <span slot="showNum" slot-scope="text">{{ text | formatCurrency }}</span>
        <span slot="convert" slot-scope="text">{{ text | formatCurrency }}</span>
        
        <p slot="operation" slot-scope="text">
          平面：{{ text || '未绑定' }}
        </p>
        

        </a-table>
    
    </div>
    <a-modal v-model="relevantPeopleVisible" title="相关人员" :footer="null" :centered='true'>
        <p>编导：{{relevantPeopleData.planName || '无'}}</p>
        <p>剪辑：{{relevantPeopleData.clipName || '无'}}</p>
        <p>拍摄：{{relevantPeopleData.shotName || '无'}}</p>
    </a-modal>
    <a-modal v-model="Videovisible" title="图片展示" @ok="videoOk" :footer="null" width="800px" style="text-align:center">
      <img
        @click.stop
        class="video"
        :src="videoUrl"
        controls="controls"
        style="height:400px;width:auto"
      />
    </a-modal>
  </div>
</template>

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

import { TreeSelect } from 'ant-design-vue';
const SHOW_PARENT = TreeSelect.SHOW_PARENT;

// import selectComponent from './selectComponent'
// import Treeselect from '../components/Treeselect'
const TTcolumns = [
  {
    title: '图片',
    dataIndex: 'imageUrl',
    align: 'center',
    width: 100,
    fixed: 'left',
    key: 'imageUrl',
    scopedSlots: { customRender: 'imageUrl' }
  },
  {
    title: '图片ID',
    dataIndex: 'signature',
    align: 'center',
    width: 150,
    fixed: 'left'
  },
  {
    title: '项目名称',
    dataIndex: 'projectName',
    align: 'center',
    width: 200,
    fixed: 'left'
  },
    {
    title:'相关人员',
    dataIndex:'operation',
    key:'operation',
    scopedSlots: { customRender: 'operation' },
    align: 'center',
    width:150,
    fixed: 'left'
  },
  
  {
    title: '消耗',
    dataIndex: 'cost',

    scopedSlots: { customRender: 'cost' },
    align: 'center',
    sorter: () => {}
  },
  {
    title: '点击数',
    dataIndex: 'click',
    align: 'center',

    scopedSlots: { customRender: 'click' },
    sorter: () => {}
    // (a, b) => a.clickMaterial - b.clickMaterial
  },
  {
    title: '展示数',
    dataIndex: 'showNum',
    align: 'center',

    scopedSlots: { customRender: 'showNum' },
    sorter: () => {}
  },   
  {
    title: '转化数',
    dataIndex: 'convert',
    align: 'center',

    scopedSlots: { customRender: 'convert' },
    sorter: () => {}
  },
  // {
  //   title: '上传时间',
  //   dataIndex: 'statDate',
  //   scopedSlots: { customRender: 'statDate' },
  //   align: 'center',
  //   sorter: () => {}
  // },
]
const KScolumns = [
  {
    title: '图片',
    dataIndex: 'imageUrl',
    align: 'center',
    width: 100,
    fixed: 'left',
    key: 'imageUrl',
    scopedSlots: { customRender: 'imageUrl' }
  },
  {
    title: '图片ID',
    dataIndex: 'signature',
    align: 'center',
    width: 150,
    fixed: 'left'
  },
  {
    title: '项目名称',
    dataIndex: 'projectName',
    align: 'center',
    width: 200,
    fixed: 'left'
  },
    {
    title:'相关人员',
    dataIndex:'operation',
    key:'operation',
    scopedSlots: { customRender: 'operation' },
    align: 'center',
    width:150,
    fixed: 'left'
  },
  
  {
    title: '消耗',
    dataIndex: 'charge',

    scopedSlots: { customRender: 'charge' },
    align: 'center',
    sorter: () => {}
  },
  {
    title: '点击数',
    dataIndex: 'photoClick',
    align: 'center',

    scopedSlots: { customRender: 'photoClick' },
    sorter: () => {}
    // (a, b) => a.clickMaterial - b.clickMaterial
  },
  {
    title: '展示数',
    dataIndex: 'photoShow',
    align: 'center',

    scopedSlots: { customRender: 'photoShow' },
    sorter: () => {}
  },   
  {
    title: '激活成本',
    dataIndex: 'activation',
    align: 'center',

    scopedSlots: { customRender: 'activation' },
    sorter: () => {}
  },
  {
    title: '注册成本',
    dataIndex: 'eventRegister',
    align: 'center',

    scopedSlots: { customRender: 'eventRegister' },
    sorter: () => {}
  },
  {
    title: '付费成本',
    dataIndex: 'eventPay',
    align: 'center',

    scopedSlots: { customRender: 'eventPay' },
    sorter: () => {}
  },
  {
    title: '表单提交成本',
    dataIndex: 'formCount',
    align: 'center',

    scopedSlots: { customRender: 'formCount' },
    sorter: () => {}
  },
  {
    title: '完件成本',
    dataIndex: 'eventJinJianApp',
    align: 'center',

    scopedSlots: { customRender: 'eventJinJianApp' },
    sorter: () => {}
  },
  {
    title: '授信成本',
    dataIndex: 'eventCreditGrantApp',
    align: 'center',

    scopedSlots: { customRender: 'eventCreditGrantApp' },
    sorter: () => {}
  },
  // {
  //   title: '上传时间',
  //   dataIndex: 'materialUploadTime',
  //   scopedSlots: { customRender: 'materialUploadTime' },
  //   align: 'center',
  //   sorter: () => {}
  // },
]


let show = 0

export default {
  data() {
    return {
        tabKeys:1,
        
        accountIds:[],
        treeData:[],
        SHOW_PARENT,
        KSaccountList:[],
        TTaccountList:[],
        accountID:undefined,
        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;
            }
        },



        relevantPeopleVisible:false,
      relevantPeopleData:{},
      roleCode: localStorage.getItem('roleCode'),
       //下拉选择框的数据
      projectArr:[],
      selectValue:'',
      appId:[],
      //设置表格的列宽
      tableWidth: '',

      //gudinglie
  

      //是否打开视频
      Videovisible: false,
      videoUrl: '',

      //是否显示导出按钮
      exportExcelIsOk: false,
      consumeValue: 0,

      columns: [...TTcolumns],
      TTcolumns,
      KScolumns,
      data: [],
      totalSelect: 0,
      daysFlag: false,
      dateRange: [],
      dataElse: [],
      loading: false,
      visible: false,
      //自定义列的搜索框
      searchInput: '',
      //弹出框中现实的选中列数
      scrollX: 0,
      listNum: [],
      //
      form: [],
      videoID: '',
      timedata: []
    }
  },
  // mixins: [JeecgListMixin],
  components: {
    // selectComponent,
    // Treeselect
  },
    methods: {
        tabChange(val){
          this.accountIds=[];
          this.data=[]
          if(this.tabKeys==1){
                this.treeData=this.TTaccountList;
                this.columns=this.TTcolumns;
                this.HttpPost('/image/bytedance/cost')
            }else if (this.tabKeys==2){
                this.treeData=this.KSaccountList;
                this.columns=this.KScolumns
                this.HttpPost('/image/kuaishou/cost')
            } 
        },
        treeChange(val) {
        // console.log(this.treeData)
            console.log(val)
            this.accountIds = [];
            
            if(val){
                val.forEach((ele,index)=>{
                if(ele*1){
                    this.accountIds.push(ele)
                }else{              
                    let projectArr=this.treeData.filter((item)=>{
                        return item.value==ele
                    });
                    // console.log(projectArr)
                    projectArr[0].children.forEach((element)=>{
                        this.accountIds.push(element.value)
                    })
                }


                })       
            }
            
            console.log(this.accountIds);
            

        
        },
        
        
        filterOption(input, option){
            console.log(input, option)
            return (
                option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
                );
        },

        // 查看相关人员
        showRelevantPeople(record){
        this.relevantPeopleVisible=true;
        console.log(record)
        getAction('/ctop/materialAscription/getDetail',{
            code:record.signature
        }).then(res=>{
            console.log(res);
            this.relevantPeopleData=[];
            if(res.result&&res.success){
            this.relevantPeopleData=res.result
            }
            
        })
        },
        sort(pagination, filters, sorter, { currentDataSource }){
            console.log(pagination, filters, sorter)
            if(sorter.order == 'ascend'){
                this.HttpPost(sorter.columnKey+'+')
                return 
            }else if(sorter.order == 'descend'){
                this.HttpPost(sorter.columnKey+'-')
                return 
            }
            this.ipagination.current=pagination.current
            // this.HttpPost()
        },
        moment,
        //select切换---项目
        selectChange(key){
            this.selectValue=key;
        },
        //打开视频
        openVideo(val) {
          this.Videovisible = true
          this.videoUrl = val
        },
        videoOk() {
          this.Videovisible = false
        },

        disabledDate(current) {
        // console.log(current)
          return current && current > moment()
        },

        consumeOnChange() {},
        //查询按钮
        searchRes() {
            this.data=[];
            if(this.tabKeys==1){               
                this.HttpPost('/image/bytedance/cost')
            }else if (this.tabKeys==2){
                this.HttpPost('/image/kuaishou/cost')
            } 
        },
        loadShow(){
            show++
            if(this.data.length>0){
                if(show == (this.data.length*2)){
                    this.data = [...this.data]
                }
            }
        },
        //网络请求table数据函数
        HttpPost(url){
          this.loading=true;
          show = 0
          postAction(url, {
              startDate: this.timedata[0],
              endDate: this.timedata[1],        
              code: this.videoID,
              pageNumber:this.ipagination.current,
              pageSize:this.ipagination.pageSize,
              accountList:this.accountIds,
              // sort:sort?sort:''
          }).then(res => {
              let resArr = []
              this.loading=false;
              if (res.success) {
              //   let result = res.result
              //   this.data.push({ ...result, key: 1 })
              //   result.map((item, index) => {
              //     item.key = index
              //   })
              this.data = res.data.list.map((item,index)=>{
                  return {
                      ...item,
                      key:index
                  }
              })
              this.ipagination.total = res.data.total
              this.loading = false
              
              }else{
                  this.loading = false
              }
          })
        },
        //导出报表
        exportExcel() {
          this.exportExcelIsOk=true;
        
        // let column = this.columns.map((item, index) => {
        //     return item.dataIndex
        // })
        //     let columns=['url',...column]
        let url=''
        if(this.tabKeys==1){
          url='/image/bytedance/cost/export'
        }else{
          url='/image/kuaishou/cost/export'
        }
            
        downFilePost(url, {
            startDate: this.timedata[0],
              endDate: this.timedata[1],        
              code: this.videoID,
              accountList:this.accountIds,
        }).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 =  '图片消耗.xlsx' //下载后文件名
            document.body.appendChild(downloadElement)
            downloadElement.click() //点击下载
            document.body.removeChild(downloadElement) //下载完成移除元素
            window.URL.revokeObjectURL(href) //释放掉blob对象
            this.exportExcelIsOk=false;
        })
        },

        //日期选择回调
        dateChange(data, dataString) {
        if (data.length) {
            this.timedata = dataString
            this.dateRange[0] = data[0]
            this.totalSelect = (data[1]._d - data[0]._d) / (24 * 60 * 60 * 1000) + 1
            this.daysFlag = true
            if (this.totalSelect > 92) {
            this.$message.error('时间跨度太长啦，选小一点好嘛？')
            this.daysFlag = false
            this.dateRange = []
            }
        } else {
            this.daysFlag = false
            this.dateRange = []
        }
        },

        //请求项目和账户内容
        accountHttp(type){
            this.accountID=undefined;
            getAction(`/ctop/projectMember/getProjectAccountByUserId?mediaType=${type}`, {}).then(res => {
                if(res.success){                   
                    if(res.result){
                        res.result.forEach((element,index) => {
                        if(element){
                            if(type==1){
                                this.TTaccountList.push({});
                                this.TTaccountList[index].title=element.project.projectName +'_('+ element.project.advertiserName +')';
                                this.TTaccountList[index].value='project'+element.project.projectId;
                                this.TTaccountList[index].key=element.project.projectId;
                                this.TTaccountList[index].mediaId=element.project.mediaId;
                                this.TTaccountList[index].children=[];

                                if(element.account.length){
                                    element.account.forEach((ele,i)=>{
                                        this.TTaccountList[index].children.push({});
                                        this.TTaccountList[index].children[i].title=ele.userName+'_'+ele.authName;
                                        this.TTaccountList[index].children[i].value=ele.accountId;
                                        this.TTaccountList[index].children[i].key=ele.accountId;
                                    })

                                }
                                this.treeData=this.TTaccountList
                            }else if(type==2){
                                this.KSaccountList.push({});
                                this.KSaccountList[index].title=element.project.projectName +'_('+ element.project.advertiserName +')';
                                this.KSaccountList[index].value='project'+element.project.projectId;
                                this.KSaccountList[index].key=element.project.projectId;
                                this.KSaccountList[index].mediaId=element.project.mediaId;
                                this.KSaccountList[index].children=[];

                                if(element.account.length){
                                    element.account.forEach((ele,i)=>{
                                        this.KSaccountList[index].children.push({});
                                        this.KSaccountList[index].children[i].title=ele.userName+'_'+ele.authName;
                                        this.KSaccountList[index].children[i].value=ele.accountId;
                                        this.KSaccountList[index].children[i].key=ele.accountId;
                                    })

                                }
                                this.treeData=this.KSaccountList
                            }
                            
                        }
                        });
                        // console.log(this.treeData)

                    }
                }
            })
        },
  },
  // watch:{
  //     'ipagination.current':function(n,o){
  //         console.log(n,o)
  //         this.HttpPost()
  //     }
  // },
 
  filters: {
    
    toshowTime(val) {
      // console.log(val, this.timedata)
      // return this.timedata[0] + '~' + this.timedata[1]
      return val
    },
    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
          }           
      },
      //变成货币格式
      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 '-'
        }
          
      }
  },


  mounted() {
    
    //进入页面默认展示昨天到今天的数据
    this.dateRange=[moment().subtract(1,'days'),moment()]
    this.timedata=[moment().subtract(1
    ,'days').format('YYYY-MM-DD'),moment().format('YYYY-MM-DD')]
    // this.loading=true;
   
    this.HttpPost('/image/bytedance/cost')
    this.accountHttp(1);
    this.accountHttp(2);
    
    
  }
}
</script>
<style lang="less">
// .ant-table .ant-table-fixed-left .ant-table-thead {
//   height: 108px !important ;
// }
.vsummary{
  .ant-table .ant-table-thead .ant-table-header-column .ant-table-column-title {
    // display:block;
    white-space: normal;
    word-break: break-all;
  }
}

</style>

<style lang="scss" scoped>
.vsummary {
  width: 100%;
  height: 100%;
  background:  #fff;
  padding: 20px;
  box-sizing: border-box;
}
.tableBody{
   margin-top: 20px;
}
.xiangmuxuanze{
  margin-bottom: 20px;;
}
.timeDiv {
  display: flex;
  justify-content: flex-start;
  position: relative;
}
span {
  margin-left: 5px;
}
.myinput {
  width: 40%;
}

.addlist {
  float: left;
  width: 70%;
  border: 1px solid #eee;
  .selectionList {
    padding: 10px 15px;
    height: 450px;
    overflow: auto;
    .leibie {
      .leiName {
        font-size: 26px;
        text-align: left;
      }
    }
    .jutixiang {
      display: inline-block;
      width: 32%;
      box-sizing: border-box;
      padding: 10px 3px;
    }
  }
}
.listNum {
  float: right;
  width: 28%;
  border: 1px solid #eee;
  position: relative;
}
.zhuti {
  margin-top: 15px;
  overflow: hidden;

  p {
    height: 40px;
    line-height: 20px;
    padding: 10px 15px;

    background: rgb(249, 250, 253);
    border-bottom: 1px solid #eee;
  }
  #btn {
    position: absolute;
    right: 0;
    top: 5px;
  }
  .selectlist {
    width: 100%;
    list-style: none;
    margin: 0;
    height: 450px;
    padding: 0 15px 10px;
    overflow: auto;

    li {
      width: 100%;
      padding: 5px 8px;
      margin: 6px 0;
      border-radius: 10px;
      background: rgb(248, 248, 248);
      height: 32px;
      position: relative;
      span {
        width: 80%;
        height: 100%;
        display: inline-block;
        margin: 0 10px;
        // overflow:hidden;
        // text-overflow:ellipsis;
        // white-space: nowrap;
      }
      .listText {
        position: absolute;
        top: 2;
        left: 10;
        width: 40%;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
      #closeStyle {
        position: absolute;
        top: 9px;
        right: 7px;
      }
    }
  }
}
</style>