<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>
.showNumBox{
  margin: 10px 0;
}
.showNumBox .ant-card-body {
  display: flex;
  justify-content: center;
}
.showNumBox p,
.showNumBox 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;
}
.showNumBox .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;
}
</style>
<style lang='less'>
.ant-card-head .ant-tabs-bar{
  padding: 0;
}
.search-box .ant-card-body {
  padding: 5px 15px;

}
.search-box{
  padding: 15px 10px;
}
.search-box p {
  display: inline-block;
  border: 1px solid #f2f2f2;
  border-radius: 5px;
  margin-right: 10px;
  padding: 5px 10px;
  cursor: pointer;
}
.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;
}
.statistics{
  .ant-card-bordered {
     border: none; 
  }
  .ant-card-head .ant-tabs {
    clear: both;
    margin-bottom: -13px;
    color: rgba(0, 0, 0, 0.65);
    font-weight: normal;
    font-size: 14px;
}
.duibi{
  position: absolute;
  right: 24px;
  top: 15px;
}
  p{
    margin-bottom: 0;
  }
}

</style>

<style lang="less">
.newPlanStatic{
  .divider{
      height: 62px;
  }
  .showNumBox{
    background: white;
    overflow: hidden;
    margin: 15px 0;
    padding: 30px 0;
    text-align: center;
    .ant-card-body{
      padding-top: 0;
    }
    .title{     

      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #999999;
      line-height: 22px;
      display: inline-block;
    }
  }
  .tabbody{
    background: white;
    padding: 0 24px;
    margin-bottom: 15px;
    .ant-tabs-bar {
      margin: 0;
    }
  }
  .chartBox{
    background: white;
    padding: 20px 0;
  }
  .tableBody{
    background: white;
    padding: 20px ;
  }
}
</style>

<template>
  <div class="newPlanStatic">
    <div class="tabbody">
      <a-tabs v-model="tabKey" @change="tabChange">
        <a-tab-pane :key="1" tab="头条">        
        </a-tab-pane>
        <a-tab-pane :key="2" tab="快手">       
        </a-tab-pane>
      </a-tabs>
    </div>
    
    <a-row>
      <a-col :span="24">
        
        <a-card :bordered="false" class="search-box">
          <div style="margin-bottom:20px">
            <span>项目选择：</span>
            <a-tree-select
                v-model="treeValue"
                show-search
                style="width: 580px;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"
                @search="treeSearch"
                @select="treeSelect"                        
                :maxTagCount='1'    
                :tree-data="treeData"
                :filterOption='filterOption'
                :disabled='accountDisabled'
            >
             </a-tree-select>

            <span style="margin-left:20px">运营：</span>
            <a-select
              v-model="operate"
              show-search
              placeholder="请输入名字"
              option-filter-prop="children"
              style="width: 200px"
              :filter-option="filterOption"
              @change="operateChange"
              :disabled='operateDisabled'
              allowClear
            >
              <a-select-option v-for="item in operateList" :key="item.user_id" :value="item.user_id">
                {{item.user_name}}
              </a-select-option>
            </a-select> 
            <a-button type='primary' style="position:absolute;right:20px" @click="search">查询</a-button>
          </div>
          <div style="margin-bottom:20px">
              <span>数据维度：</span>
                <a-radio-group v-model="value" @change="dataTypeChange">
                    <a-radio :value="1">
                        广告计划
                    </a-radio>
                    <a-radio :value="2" v-show="tabKey==2">
                        广告组
                    </a-radio>
                    
                </a-radio-group>
          </div>
          <div class="time"  @click="opendate" >
            <datePick  :dateValue.sync='dateValue'   :type.sync='type'   />
            
          </div>
          <!-- <p>对比</p> -->
          
        </a-card>
      </a-col>
    </a-row>
    <a-row >
      <div class="showNumBox">
          <a-col :sm="24" :md="10" :xl="10" :xxl="10">
            <span class="title">
              
              <template v-if="tabKey==1 || tabKey==2&&value==1 ">新上计划数</template>
               <template v-else-if="tabKey==2&&value==2">新上推广组</template>
            </span>
            <div>
              <countTo
                :startVal="0"
                :endVal="newPlan"
                :duration="duration"
                :decimals="0"
                style="overflow:auto"
              ></countTo>
            </div>
            
          </a-col>
          <a-col :sm="24" :md="2" :xl="2" :xxl="2">
            <a-divider type="vertical" class="divider" />
          </a-col>
          
          <a-col :sm="24" :md="10" :xl="10" :xxl="10">
            <span class="title">
               <template v-if="tabKey==1 || tabKey==2&&value==1 ">有效计划数</template>
               <template v-else-if="tabKey==2&&value==2">有效推广组</template>
            </span>
           <div>
              <countTo
                :startVal="0"
                :endVal="effectPlan"
                :duration="duration"
                :decimals="0"
                style="overflow:auto"
              ></countTo>
            </div>
          </a-col>
      </div>
      
    </a-row>
    <a-row :gutter="10">
      <a-col :span="24"> 
        <div class="chartBox">
          <a-spin :spinning="echartSpinning">
           <div id="chart" style="width:100%;height:320px" ref="sectionChart"></div>
          </a-spin>
        </div>
         
      </a-col>
    </a-row>
    
    <a-row style="margin-bottom:15px;margin-top:12px">
      <a-col :span="24">
        <div class="tableBody">
          <a-tabs v-model="tableTab" @change="tableTabChange">
            <a-tab-pane :key="1" :tab="(tabKey==1||tabKey==2&&value==1)?'新上计划数':'新上推广组'">        
            </a-tab-pane>
            <a-tab-pane :key="2" :tab="(tabKey==1||tabKey==2&&value==1)?'有效计划数':'有效推广组'">       
            </a-tab-pane>

            <a-button slot="tabBarExtraContent" @click="exportExcel" :loading="exportloading" v-show="tabKey==2">
              导出报表
            </a-button>
          </a-tabs>
          <a-table :columns="columns" :dataSource="dataTable" :pagination="false" :loading="loading" bordered>             
          </a-table> 
        </div>
               
      </a-col>
    </a-row>
  </div>
</template>

<script>

import datePick from '../components/datePick'
import { TreeSelect } from 'ant-design-vue';
const SHOW_PARENT = TreeSelect.SHOW_PARENT;
import ARow from 'ant-design-vue/es/grid/Row'
import ACol from 'ant-design-vue/es/grid/Col'
import moment from 'moment'
import countTo from 'vue-count-to'
import lifting from '../components/lifting'
import {  getKsAccountReport, getKsDetail, getReportList } from '@api/video.js'
import { getAction, postAction ,downFile, downFilePost } from '@/api/manage'

import timeCheck from '../components/timeCheck'

var upDate

// 引入基本模板
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')

let TTcolumns=[
  {
    title: '账户名称',
    dataIndex: 'authName',
    scopedSlots: { customRender: 'authName' },
    align: 'center',
    key:'authName'
    
  },
  {
    title: '账户ID',
    dataIndex: 'accountId',
    scopedSlots: { customRender: 'accountId' },
    align: 'center',
    key:'accountId'
    
  },
  {
    title: '账户所属人',
    dataIndex: 'userName',
    scopedSlots: { customRender: 'userName' },
    align: 'center',
    key:'userName'
    
  },
  {
    title: '新上计划数',
    dataIndex: 'new',
    scopedSlots: { customRender: 'new' },
    align: 'center',
    key:'new'
    
  },
  {
    title: '最近上新',
    dataIndex: 'maxCreateTime',
    scopedSlots: { customRender: 'maxCreateTime' },
    align: 'center',
    key:'maxCreateTime'
    
  },
]
let TTcolumnsVaild=[
  {
    title: '账户名称',
    dataIndex: 'authName',
    scopedSlots: { customRender: 'authName' },
    align: 'center',
    key:'authName'
    
  },
  {
    title: '账户ID',
    dataIndex: 'accountId',
    scopedSlots: { customRender: 'accountId' },
    align: 'center',
    key:'accountId'
    
  },
  {
    title: '账户所属人',
    dataIndex: 'userName',
    scopedSlots: { customRender: 'userName' },
    align: 'center',
    key:'userName'
    
  },
  {
    title: '有效计划数',
    dataIndex: 'valid',
    scopedSlots: { customRender: 'valid' },
    align: 'center',
    key:'valid'
    
  },
  {
    title: '最近上新',
    dataIndex: 'maxCreateTime',
    scopedSlots: { customRender: 'maxCreateTime' },
    align: 'center',
    key:'maxCreateTime'
    
  },
]


let KScolumns=[
  // {
  //   title: '项目名称',
  //   dataIndex: 'projectName',
  //   scopedSlots: { customRender: 'projectName' },
  //   align: 'center',
  //   key:'projectName'
    
  // },
  {
    title: '账户名称',
    dataIndex: 'authName',
    scopedSlots: { customRender: 'authName' },
    align: 'center',
    key:'authName'
    
  },
  {
    title: '账户ID',
    dataIndex: 'accountId',
    scopedSlots: { customRender: 'accountId' },
    align: 'center',
    key:'accountId'
    
  },
  {
    title: '账户所属人',
    dataIndex: 'userName',
    scopedSlots: { customRender: 'userName' },
    align: 'center',
    key:'userName'
    
  },
  {
    title: '新上推广组',
    dataIndex: 'new',
    scopedSlots: { customRender: 'new' },
    align: 'center',
    key:'new'
    
  },
  {
    title: '最近上新',
    dataIndex: 'maxCreateTime',
    scopedSlots: { customRender: 'maxCreateTime' },
    align: 'center',
    key:'maxCreateTime'
    
  },
]
let KScolumnsVaild=[
  // {
  //   title: '项目名称',
  //   dataIndex: 'projectName',
  //   scopedSlots: { customRender: 'projectName' },
  //   align: 'center',
  //   key:'projectName'
    
  // },
  {
    title: '账户名称',
    dataIndex: 'authName',
    scopedSlots: { customRender: 'authName' },
    align: 'center',
    key:'authName'
    
  },
  {
    title: '账户ID',
    dataIndex: 'accountId',
    scopedSlots: { customRender: 'accountId' },
    align: 'center',
    key:'accountId'
    
  },
  {
    title: '账户所属人',
    dataIndex: 'userName',
    scopedSlots: { customRender: 'userName' },
    align: 'center',
    key:'userName'
    
  },
  {
    title: '有效推广组',
    dataIndex: 'valid',
    scopedSlots: { customRender: 'valid' },
    align: 'center',
    key:'valid'
    
  },
  {
    title: '最近上新',
    dataIndex: 'maxCreateTime',
    scopedSlots: { customRender: 'maxCreateTime' },
    align: 'center',
    key:'maxCreateTime'
    
  },
]

let KScolumnsPlan=[
  // {
  //   title: '项目名称',
  //   dataIndex: 'projectName',
  //   scopedSlots: { customRender: 'projectName' },
  //   align: 'center',
  //   key:'projectName'
    
  // },
  {
    title: '账户名称',
    dataIndex: 'authName',
    scopedSlots: { customRender: 'authName' },
    align: 'center',
    key:'authName'
    
  },
  {
    title: '账户ID',
    dataIndex: 'accountId',
    scopedSlots: { customRender: 'accountId' },
    align: 'center',
    key:'accountId'
    
  },
  {
    title: '账户所属人',
    dataIndex: 'userName',
    scopedSlots: { customRender: 'userName' },
    align: 'center',
    key:'userName'
    
  },
  {
    title: '新上计划数',
    dataIndex: 'new',
    scopedSlots: { customRender: 'new' },
    align: 'center',
    key:'new'
    
  },
  {
    title: '最近上新',
    dataIndex: 'maxCreateTime',
    scopedSlots: { customRender: 'maxCreateTime' },
    align: 'center',
    key:'maxCreateTime'
    
  },
]
let KScolumnsPlanVaild=[
  // {
  //   title: '项目名称',
  //   dataIndex: 'projectName',
  //   scopedSlots: { customRender: 'projectName' },
  //   align: 'center',
  //   key:'projectName'
    
  // },
  {
    title: '账户名称',
    dataIndex: 'authName',
    scopedSlots: { customRender: 'authName' },
    align: 'center',
    key:'authName'
    
  },
  {
    title: '账户ID',
    dataIndex: 'accountId',
    scopedSlots: { customRender: 'accountId' },
    align: 'center',
    key:'accountId'
    
  },
  {
    title: '账户所属人',
    dataIndex: 'userName',
    scopedSlots: { customRender: 'userName' },
    align: 'center',
    key:'userName'
    
  },
  {
    title: '有效计划数',
    dataIndex: 'valid',
    scopedSlots: { customRender: 'valid' },
    align: 'center',
    key:'valid'
    
  },
  {
    title: '最近上新',
    dataIndex: 'maxCreateTime',
    scopedSlots: { customRender: 'maxCreateTime' },
    align: 'center',
    key:'maxCreateTime'
    
  },
]


let sectionOption={
    backgroundColor: '#fff',
    tooltip: {
        trigger: 'axis',
       
        axisPointer: {
        // 坐标轴指示器，坐标轴触发有效
          type: 'line', // 默认为直线，可选为：'line' | 'shadow',
        
        }, 
    },
    legend: {
        data: ['新上推广组','有效推广组']
    },
    grid: {
        left: '2%',
        right: '2%',
        bottom: '0%',
        top: '12%',
        containLabel: true
    },
    xAxis: 
        {
            type: 'category',
            data: [],
            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: [
        {
            name: '新上推广组',
            type: 'line',
            smooth: true,
            data:  [],
            symbol: 'circle',
            symbolSize :8,
            color: '#0bcd74',
           
            lineStyle: {
              normal: {
                width: 2,
                color: '#0bcd74'
              }
            },
            itemStyle: {
              borderColor: '#fff',
              borderWidth: 3
            },
        },
        {
            name: '有效推广组',
            type: 'line',
            smooth: true,
            data:  [],           
            symbol: 'circle',
            color: '#9933ff',
            symbolSize: 8,
            lineStyle: {
              normal: {
                width: 2,
                color: '#9933ff'
              }
            },
            itemStyle: {
              borderColor: '#ffffff',
              borderWidth: 3
            },
        },
    ]
}

export default {
  
  components: {
    ACol,
    ARow,
    countTo,
    lifting,
    timeCheck,
     datePick
  },

  data() {
    return {
      exportloading:false,
      value:2,
      KSaccountList:[],
      TTaccountList:[],

      KSoperateList:[],
      TToperateList:[],

      accountDisabled:false,
      operateDisabled:false,
      userId:JSON.parse(localStorage.getItem('pro__Login_Userinfo')).value.id,
      duration: 1000,
    //treeselect的参数
      treeValue: [],
      treeData: [],
      SHOW_PARENT,

      type:3,
      dateValue:[moment().subtract(7, 'days'), moment().subtract(1, 'days')],

      operate:'',
      operateList:[],

      tabKey:2,
      sectionOption:JSON.parse(JSON.stringify(sectionOption)),

      loading: false,
      TTcolumns,
      KScolumns,
      columns:[...KScolumns],    
      dataTable: [],
     
      tableTab:1,

      newPlan:0,
      effectPlan:0,
     
      echartSpinning:false,

      openOptions:false,

      target:'',
      order:'desc',
    }
  },
  methods: {
    //导出报表
        exportExcel() {
            this.exportloading=true;
            let url='';
            let nameType=''
            if(this.value==2){
              url='/ctop/kuaishou/newGroup/report/excel'
            }else{
              url='/ctop/kuaishou/newPlan/report/excel'
            }
            if(this.value==2){
                nameType='广告组'
            }else if(this.value==1){
                nameType='广告计划'
            }
            downFilePost(url,{
              accountIds:this.accountId,
              userId:this.operate || '',
              startDate:this.dateValue[0].format('YYYY-MM-DD'),
              endDate:this.dateValue[1].format('YYYY-MM-DD'),
              target:this.tableTab=='1'?'new':'valid',
              order:this.order
            }).then(res => {
                this.exportloading=false;
                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') + nameType+'.xlsx' //下载后文件名
                document.body.appendChild(downloadElement)
                downloadElement.click() //点击下载
                document.body.removeChild(downloadElement) //下载完成移除元素
                window.URL.revokeObjectURL(href) //释放掉blob对象
            })
        },
    dataTypeChange(e){
      console.log(e.target.value)
        if(this.value==2){
          this.operateList=this.KSoperateList
          this.treeData=this.KSaccountList;
          this.columns=this.tableTab==1?[...KScolumns]:[...KScolumnsVaild];
          this.sectionOption.legend.data=['新上推广组','有效推广组']
        }else{
          this.operateList=this.KSoperateList
          this.treeData=this.KSaccountList;
          this.columns=this.tableTab==1?[...KScolumnsPlan]:[...KScolumnsPlanVaild];
          this.sectionOption.legend.data=['新上计划数','有效计划数']
        }
        this.getNewPlan()
    },
      //项目改变后的事件
    treeChange(val) {
      // console.log(this.treeData)
      console.log(val)
      this.accountId = [];
      //选择一个后禁用其他
      if(val.length==1){
        this.operateDisabled=true;
        this.opendate=''
          if(val[0]*1){
            let selectindex=0
              this.treeData.forEach((ele,index)=>{                   
                  if(ele.children){
                     ele.children.map((item,ind)=>{
                            if(item.value==val[0]){
                                selectindex=index;
                                this.mediaId=ele.mediaId
                            }
                      })
                  }                   
              });
              // console.log(selectindex)
              if(selectindex ||selectindex==0){
                this.treeData.forEach((ele,index)=>{
                    if(index!=selectindex){
                         ele.disableCheckbox = true;
                         if(ele.children){
                              ele.children.map((item,ind)=>{
                                   item.disableCheckbox = true;
                              })
                         }
                    }
                })
              }
              
          }else{
            //  console.log(1)
              this.treeData.forEach((ele,index)=>{
                    if(ele.value!=val[0]){
                         ele.disableCheckbox = true;
                         
                         if(ele.children){
                              ele.children.forEach((item,ind)=>{
                                   item.disableCheckbox = true;
                              })
                         }
                    }
                    if(ele.value==val[0]){
                        this.mediaId=ele.mediaId
                    }
              })
          }
          // console.log(this.mediaId)
          
      }

      if(val.length==0){
          this.treeData.forEach((ele,index)=>{              
                ele.disableCheckbox = false;
                this.mediaId=ele.mediaId;
                if(ele.children){
                    ele.children.forEach((item,ind)=>{
                          item.disableCheckbox = false;
                    })
                }
              
          });
        this.operateDisabled=false;
        this.operate=this.userId
        // this.accountDisabled=true
      }
      if(val){
        val.forEach((ele,index)=>{
          if(ele*1){
              this.accountId.push(ele)
          }else{              
              let projectArr=this.treeData.filter((item)=>{
                  return item.value==ele
              });
              // console.log(projectArr)
              projectArr[0].children.forEach((element)=>{
                 this.accountId.push(element.value)
              })
          }
        })       
      }
      
     console.log(this.accountId)
    },
    treeSearch(){
      console.log(arguments);
    },
    treeSelect(){
      // console.log(arguments);
      // this.treeValue=arguments[0].value
    },
    disabledDate(current) {
      // console.log(current)

      //  return  current && current > moment().add(1, 'day')
      return moment().endOf('day');
    },
    filterOption(input, option){
      console.log(input, option)
      return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        );
    },
     
    //打开日期框
    opendate(){
       this.openOptions=!this.openOptions;
      //  console.log(this.openOptions)
    },
    // 快手头条的切换
    tabChange(key){
      console.log(key);
      this.treeValue=[];
      this.operate=undefined;
      if(key==1){
        // toutiao
        this.treeData=this.TTaccountList;
        this.operateList=this.TToperateList
        this.columns=this.tableTab==1?[...TTcolumns]:[...TTcolumnsVaild]
        this.sectionOption.legend.data=['新上计划数','有效计划数']
      }else{
        // kuaishou
        if(this.value==2){
          this.operateList=this.KSoperateList
          this.treeData=this.KSaccountList;
          this.columns=this.tableTab==1?[...KScolumns]:[...KScolumnsVaild]
          this.sectionOption.legend.data=['新上推广组','有效推广组']
        }else{
          this.operateList=this.KSoperateList
          this.treeData=this.KSaccountList;
          this.columns=this.tableTab==1?[...KScolumnsPlan]:[...KScolumnsPlanVaild]
          this.sectionOption.legend.data=['新上计划数','有效计划数']
        }
        
      }
      
      this.getNewPlan()
    },
    operateChange(value){
      console.log(value);
      if(value){
        this.accountDisabled=true;
        this.accountId=''
      }else{
        this.accountDisabled=false
      }
    },

    //初始化chart
    getEchartData(idName, optionName) {
      const chart = this.$refs[idName]
        // console.log(chart)
      if (chart) {
        // const myChart = echarts.init(document.getElementById(idName))
        const myChart = echarts.init(chart)
        myChart.setOption(optionName)
        window.addEventListener('resize', function() {
          myChart.resize()
        })
      }
    },
  
    moment,
    // table区域的tab切换
    tableTabChange(key){
      if(key==1){
       
        this.columns=this.tabKey==1?[...TTcolumns]:[...KScolumns]
        this.target='new'
      }else{
        
        this.columns=this.tabKey==1?[...TTcolumnsVaild]:[...KScolumnsVaild]
        this.target='valid'
      }
      this.getNewPlan()
    },
    //处理echart
    sectionHttp(params) {
      this.loading = true;
      this.spinning=true;
      this.sectionOption=JSON.parse(JSON.stringify(sectionOption));
      return new Promise((resolve, reject) => {
        postAction('/ctop/byteDance/homePage/report/chart', params).then(res => {
          // console.log(res)
          if (res.success) {
            this.loading = false
            this.spinning=false;
            //处理今天
            if(res.result){

            
            
           this.getEchartData('sectionChart', this.sectionOption);


           //处理表格数据
           let total={
              statDate:'总计',
              cost:0,           
              click:0,
              clickRate:0,
              costProportion:'-',
              cp:0,
              cpm:0,
              showNum:0
          }
           

            var afterData=[];
           res.result.list.forEach((ele,index)=>{
             if(ele.afterData){
                if(!ele.afterData.costProportion){
                  ele.afterData.costProportion='-'
                }
                if(ele.afterData.statHour||ele.afterData.statHour==0){
                    ele.afterData.statHour=ele.afterData.statHour > 9 ? `${ele.afterData.statHour}:00` : ` 0${ele.afterData.statHour}:00`
                    ele.afterData.statDate=ele.afterData.statDate+' '+ele.afterData.statHour
                }
                ele.afterData.key=index+1
                total.click+=ele.afterData.click
                total.cost+=ele.afterData.cost
                total.showNum+=ele.afterData.showNum;
                afterData.push(ele.afterData)
             }else{
                if(!ele.costProportion){
                  ele.costProportion='-'
                }
                if(ele.statHour||ele.statHour==0){
                    ele.statHour=ele.statHour > 9 ? `${ele.statHour}:00` : ` 0${ele.statHour}:00`
                    ele.statDate=ele.statDate+' '+ele.statHour
                }
                ele.key=index+1
                total.click+=ele.click
                total.cost+=ele.cost
                total.showNum+=ele.showNum
             }
              
           })

              total.cost=(total.cost).toFixed(2)
              total.clickRate=(total.click/total.showNum*100).toFixed(2)+'%'
              total.cp=(total.cost/total.click).toFixed(2)
              total.cpm=(total.cost/total.showNum*1000).toFixed(2)
              if(afterData.length>0){
                this.tableData=[total,...afterData]
              }else{
                this.tableData=[total,...res.result.list]
              }
              
            }
          }
        })
      })
    },


     //请求项目和账户内容
    accountHttp(key){
      this.treeData=[]
      this.treeValue=[];
     getAction(`/ctop/projectMember/getProjectAccountByUserId?mediaType=${key}`, {}).then(res => {
       if(res.success){
            // console.log(res);
            
            if(res.result){
              res.result.forEach((element,index) => {
                if(element){
                    if(key==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+'_'+element.project.projectName;
                                this.TTaccountList[index].children[i].value=ele.accountId;
                                this.TTaccountList[index].children[i].key=ele.accountId;
                            })

                        }
                        
                    }else if(key==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+'_'+element.project.projectName;
                                this.KSaccountList[index].children[i].value=ele.accountId;
                                this.KSaccountList[index].children[i].key=ele.accountId;
                            })

                        }
                        
                    }
                    

                    if(this.tabKey==1){
                      this.treeData=this.TTaccountList
                    }else{
                      this.treeData=this.KSaccountList
                    }
                }
              });
                        // console.log(this.treeData)

                    }
       }
     })
    },

    // 运营数据获取
    operateHttp(){
      postAction('',{}).then(res=>{
        console.log(res)
      })
    },

    // 获取所有运营
    getAllOperator(key){
      let url=''
      this.operateList=[]
      if(key==1){
        // 头条
        url='/ctop/bytedance/newPlan/report/AllOperator'
      }else{
        // 快手
        url='/ctop/kuaishou/newGroup/report/AllOperator'
      }
      postAction(url,{}).then(res=>{
        console.log(res);
        if(res.success){
          if(key==1){
            this.TToperateList=res.result;
          }else{
            this.KSoperateList=res.result;
          }

          if(this.tabKey==1){
            this.operateList=this.TToperateList
          }else{
            this.operateList=this.KSoperateList
          }
          
        }
      })
    },


    // 获取展示数据
    getNewPlan(){
      let url=''
      if(this.tabKey==1){
        // 头条
        url='/ctop/bytedance/newPlan/report/data'
      }else{
        // 快手
        if(this.value==2){
          url='/ctop/kuaishou/newGroup/report/data'
        }else{
          url='/ctop/kuaishou/newPlan/report/data'
        }
        
      }
      // if(this.accountId){
      //   this.operate='';
      // }else if(this.operate){
      //   this.accountId=''
      // }
      this.loading=true;
      this.echartSpinning=true;
      this.sectionOption=JSON.parse(JSON.stringify(sectionOption));
      if(this.tabKey==1){
        this.sectionOption.legend.data=['新上计划数','有效计划数']
        this.sectionOption.series[0].name='新上计划数'
        this.sectionOption.series[1].name='有效计划数'
      }else{
        if(this.value==2){
          this.sectionOption.legend.data=['新上推广组','有效推广组']
          this.sectionOption.series[0].name='新上推广组'
          this.sectionOption.series[1].name='有效推广组'
        }else{
          this.sectionOption.legend.data=['新上计划数','有效计划数']
          this.sectionOption.series[0].name='新上计划数'
          this.sectionOption.series[1].name='有效计划数'
        }
        
      }
      
      postAction(url,{
        accountIds:this.accountId,
        userId:this.operate || '',
        startDate:this.dateValue[0].format('YYYY-MM-DD'),
        endDate:this.dateValue[1].format('YYYY-MM-DD'),
        target:this.tableTab=='1'?'new':'valid',
        order:this.order
      }).then(res=>{
        console.log(res);
        this.loading=false;
        this.echartSpinning=false;
        if(res.success){
          if(res.result){
              this.effectPlan=res.result.sumData.valid;
              this.newPlan=res.result.sumData.new;
              this.dataTable=res.result.listData;
              // 处理echar数据
              res.result.chartData.map(item=>{
                this.sectionOption.xAxis.data.push(item.statDate)
                this.sectionOption.series[0].data.push(item.new)
                this.sectionOption.series[1].data.push(item.valid)
              })
         

          }else{
              this.effectPlan=0;
              this.newPlan=0;
              this.dataTable=[];
          }
          

          

          this.getEchartData('sectionChart', this.sectionOption);

        }
      })
      this.getEchartData('sectionChart', this.sectionOption);
    },

    // 查询按钮
    search(){
      if(this.accountId || this.operate){
        this.echartSpinning=true;
        this.getNewPlan()
      }else{
        this.$message.error('请选择具体账户或者运营')
      }
      
    },
    
  },
  watch: {
    dateValue(newName,oldName){
      
        this.search()
    },
  },
  computed: {
    newDate() {
      var myDate = new Date()
      myDate.getYear() //获取当前年份(2位)
      var n = myDate.getFullYear() //获取完整的年份(4位,1970-????)
      var m = myDate.getMonth() //获取当前月份(0-11,0代表1月)
      var d = myDate.getDate() //获取当前日(1-31)
      var day = myDate.getHours()
      return day
    }
  },
  mounted() {
    this.accountHttp(1);
    this.accountHttp(2);
    this.getAllOperator(1)
    this.getAllOperator(2)
    this.accountDisabled=true
  },
  activated: function() {
    this.$nextTick(()=>{
      this.getEchartData('sectionChart', this.sectionOption);

      // this.tabChange(2)
      let userInfo=localStorage.getItem('pro__Login_Userinfo')
      if(userInfo){
        this.userId=JSON.parse(userInfo).value.id;
        this.operate=this.userId;
        this.getNewPlan()
      }
      // console.log(this.userId)

      
    })
     
  },
  
  filters: {
    toPercentage(val) {
      if(typeof val != 'string'){
          return (val * 100).toFixed(2) + '%'
      }else{
        return val
      }
      
    },
    //保留两位小数并且变成货币格式
    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){
          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
      }
        
    }
  }
}
</script>
