<template>
    <div>
        <a-row :gutter="24" style="margin-bottom: 20px">
            <a-col :sm="18" :md="18" :xl="18" class="keep-manage-col">
                <a-card class="card-content echarts-card">
                    <div slot="title">
                        <span style="font-weight: bolder">数据总览</span>
                        <!-- &nbsp;&nbsp; <span style="font-size:13px;">更新时间：{{updateAccountEchart | formatDate}}</span>  -->
                    </div>

                    <div class="person-content-title" slot="extra">
                        <div class="content-title-acount"></div>
                        <div class="content-title-checkout">
                            <span class="title-checkout-select" style="margin-right: 10px">
                                <a-select v-model="mediaId" style="width: 100px" @change="selectMediaIdChange">
                                    <a-select-option value="1">头条</a-select-option>
                                    <a-select-option value="2">快手</a-select-option>
                                </a-select>
                            </span>
                            <span class="title-checkout-select" style="margin-right: 10px">
                                <a-select v-model="selectValue" style="width: 100px" @change="selectValueChange">
                                    <a-select-option value="1">汇总</a-select-option>
                                    <a-select-option value="2">运营个人</a-select-option>
                                </a-select>
                            </span>
                            <span class="title-checkout-time">
                                <a-range-picker
                                    v-model="dateEchart"
                                    format="YYYY-MM-DD"
                                    :range="dateRanges"
                                    @change="dateEchartChange"
                                />
                            </span>
                        </div>
                    </div>
                    <a-spin :spinning="spinning">
                        <div
                            v-if="yestadyNum == 1"
                            id="accountIndexEchart"
                            ref="accountIndexEchart"
                            style="width: 90%; height: 315px; margin: 0 auto"
                            :style="{ width: clientWidth * 0.75 - 48 - 24 + 'px' }"
                        >
                            <a-empty />
                        </div>

                        <div
                            v-else
                            id="acctowecharts"
                            ref="acctowecharts"
                            style="width: 90%; height: 315px; margin: 0 auto"
                            :style="{ width: clientWidth * 0.75 - 48 - 24 + 'px' }"
                        >
                            <a-empty />
                        </div>
                    </a-spin>
                </a-card>
            </a-col>

            <a-col :sm="6" :md="6" :xl="6" class="keep-manage-col">
                <a-card class="card-content">
                    <div slot="title">
                        <span style="font-weight: bolder">运营组数据</span>
                    </div>
                    <a-spin :spinning="spinningGroup">
                        <div style="width: 100%; height: 315px">
                            <ul class="group-keep-ul">
                                <li>
                                    今日消耗: <span style="font-weight: bold">{{ todayCost | formatNum }}</span>
                                </li>
                                <li v-if="!!compare">
                                    <span style="margin-left: 20%" v-if="compare.indexOf('-') == 0">
                                        <img
                                            style="width: 25px; height: 25px"
                                            class="title-radio-img"
                                            src="@/assets/greendown.png"
                                            alt=""
                                        />
                                        <span style="color: green">{{ compare }}</span>
                                    </span>
                                    <span style="margin-left: 20%" v-else-if="compare.indexOf('-') == -1">
                                        <img
                                            style="width: 25px; height: 25px"
                                            class="title-radio-img"
                                            src="@/assets/upred.png"
                                            alt=""
                                        />
                                        <span style="color: red">{{ compare }}</span>
                                    </span>

                                    <a-tooltip placement="top">
                                        <template slot="title">
                                            <span>今天截止此时的消耗跟昨天截止同个时段的消耗变化</span>
                                        </template>
                                        <a-icon style="margin-left: 10px" type="question-circle" />
                                    </a-tooltip>
                                </li>
                                <li><span style="margin-left: 31px">消耗:</span> {{ sectionCost | formatNum }}</li>
                                <li>人均带户: {{ userAverageAccount | formatNum }}</li>
                                <li>人均消耗: {{ userAveragecost | formatNum }}</li>
                                <li>在投项目数量：{{ projectNum }}</li>
                            </ul>
                        </div>
                    </a-spin>
                </a-card>
            </a-col>
        </a-row>
        <a-row :gutter="24" style="margin-bottom: 20px">
            <a-col>
                <a-card>
                    <div slot="title">
                        <span style="font-weight: bolder">运营数据详情</span>
                    </div>
                    <div class="person-content-title" slot="extra">
                        <div class="content-title-acount"></div>
                        <div class="content-title-checkout">
                            <span style="margin-right: 15px">
                                <a-range-picker
                                    v-model="dateMiddle"
                                    format="YYYY-MM-DD"
                                    :ranges="dateRanges"
                                    @change="dateMiddleChange"
                                />
                            </span>
                            <span style="margin-right: 15px">
                                <a-button @click="exportClick">导 出</a-button>
                            </span>
                            <span>
                                <a-radio-group v-model="mediaIdDetail" @change="dateMiddleChange">
                                    <a-radio-button value="2"> 快手 </a-radio-button>
                                    <a-radio-button value="1"> 头条 </a-radio-button>
                                </a-radio-group>
                            </span>
                        </div>
                    </div>
                    <a-table
                        size="middle"
                        :dataSource="echartsDataoperate"
                        :columns="columnsprojectoperate"
                        bordered
                        id="outTable"
                        :pagination="echartsIpagination"
                        :loading="echartsLoadingYun"
                        @change="sortDataoperate"
                        ref="accountTable"
                    >
                        <a slot="userName" slot-scope="text, record" @click="userNameClick(record)">{{ text }}</a>
                        <span slot="newEffectNum" slot-scope="text">
                            <span v-if="text">{{ text }}</span>
                            <span v-else>0</span>
                        </span>
                        <span slot="newCampaignNum" slot-scope="text">
                            <span v-if="text">{{ text }}</span>
                            <span v-else>0</span>
                        </span>
                        <span slot="newUnitNum" slot-scope="text">
                            <span v-if="text">{{ text }}</span>
                            <span v-else>0</span>
                        </span>
                    </a-table>
                </a-card>
            </a-col>
        </a-row>
        <a-row :gutter="24" style="margin-bottom: 20px">
            <a-col>
                <a-card>
                    <div slot="title">
                        <span style="font-weight: bolder">运营组数据</span>
                    </div>
                    <div class="person-content-title" slot="extra">
                        <div class="content-title-acount"></div>
                        <div class="content-title-checkout">
                            <span style="margin-right: 15px">
                                <a-range-picker
                                    v-model="dateMiddleGroup"
                                    format="YYYY-MM-DD"
                                    :ranges="dateRanges"
                                    @change="dateMiddleChangeGroup"
                                />
                            </span>
                            <span style="margin-right: 15px">
                                <a-button @click="exportClickGroup">导 出</a-button>
                            </span>
                            <span>
                                <a-radio-group v-model="mediaIdGroup" @change="changeGetGroupList">
                                    <a-radio-button value="2"> 快手 </a-radio-button>
                                    <a-radio-button value="1"> 头条 </a-radio-button>
                                </a-radio-group>
                            </span>
                        </div>
                    </div>
                    <a-table
                        size="middle"
                        :dataSource="groupList"
                        :columns="columnGroup"
                        bordered
                        id="outTable"
                        :pagination="groupIpagination"
                        :loading="groupLoading"
                        ref="accountTable"
                    >
                        <a slot="userName" slot-scope="text, record" @click="userNameClick(record)">{{ text }}</a>
                        <span slot="newEffectNum" slot-scope="text">
                            <span v-if="text">{{ text }}</span>
                            <span v-else>0</span>
                        </span>
                        <span slot="newCampaignNum" slot-scope="text">
                            <span v-if="text">{{ text }}</span>
                            <span v-else>0</span>
                        </span>
                        <span slot="newUnitNum" slot-scope="text">
                            <span v-if="text">{{ text }}</span>
                            <span v-else>0</span>
                        </span>
                    </a-table>
                </a-card>
            </a-col>
        </a-row>
        <a-row :gutter="24">
            <a-col>
                <a-card>
                    <div slot="title">
                        <span style="font-weight: bolder">{{ titleList }}</span>
                    </div>
                    <div class="person-content-title" slot="extra">
                        <div class="content-title-checkout" style="margin-right: 10px">
                            <!-- <span class="title-checkout-custom"
                                ><a @click="exportExcel" :loading="visibleLoading">导出数据</a></span
                            > -->
                        </div>
                        <div class="content-title-checkout">
                            <!-- <span style="margin-right: 20px">
                                <a-button type="link" @click="customColumn"> 自定义列 </a-button>
                            </span> -->
                            <span style="margin-right: 15px">
                                <a-range-picker
                                    v-model="dateMiddleProject"
                                    :ranges="dateRanges"
                                    @change="dateMiddleProjectChange"
                                />
                            </span>
                            <a-button @click="exportExcel" :loading="visibleLoading" style="margin-right: 15px">
                                导 出
                            </a-button>
                            <span>
                                <a-radio-group v-model="mediaIdAccount" @change="projectAccountChange">
                                    <a-radio-button value="2"> 快手 </a-radio-button>
                                    <a-radio-button value="1"> 头条 </a-radio-button>
                                </a-radio-group>
                            </span>
                        </div>
                    </div>
                    <a-table
                        size="middle"
                        :dataSource="echartsDataProject"
                        :columns="columnsProject"
                        bordered
                        id="outTable"
                        :pagination="echartsIpaginationProject"
                        :loading="echartsLoading"
                        @change="sort"
                        ref="accountTable"
                        :scroll="{ x: scrollX }"
                    >


                        <span slot="yearOnYear" slot-scope="text, records">
                            {{ text }}
                            <a-icon v-if="text && parseFloat(text) > 0" type="caret-up" style="color: #f00" />
                            <a-icon v-else type="caret-down" style="color: green" />
                        </span>
                        <span slot="equallyRate" slot-scope="text, records">
                            {{ text }}
                            <a-icon v-if="text && parseFloat(text) > 0" type="caret-up" style="color: #f00" />
                            <a-icon v-else type="caret-down" style="color: green" />
                        </span>
                        <div slot="jl" slot-scope="text, record">
                            {{
                                record.adSceneDate.findIndex((item) => {
                                    return item.adSceneName == '激励视频广告'
                                }) > -1
                                    ? record.adSceneDate.find((item) => {
                                          return item.adSceneName == '激励视频广告'
                                      }).adSceneCost
                                    : '-'
                            }}
                        </div>
                        <div slot="kp" slot-scope="text, record">
                            {{
                                record.adSceneDate.findIndex((item) => {
                                    return item.adSceneName == '开屏广告'
                                }) > -1
                                    ? record.adSceneDate.find((item) => {
                                          return item.adSceneName == '开屏广告'
                                      }).adSceneCost
                                    : '-'
                            }}
                        </div>
                        <div slot="ss" slot-scope="text, record">
                            {{
                                record.adSceneDate.findIndex((item) => {
                                    return item.adSceneName == '搜索广告'
                                }) > -1
                                    ? record.adSceneDate.find((item) => {
                                          return item.adSceneName == '搜索广告'
                                      }).adSceneCost
                                    : '-'
                            }}
                        </div>
                        <div slot="lm" slot-scope="text, record">
                            {{
                                record.adSceneDate.findIndex((item) => {
                                    return item.adSceneName == '联盟'
                                }) > -1
                                    ? record.adSceneDate.find((item) => {
                                          return item.adSceneName == '联盟'
                                      }).adSceneCost
                                    : '-'
                            }}
                        </div>
                        <div slot="sxh" slot-scope="text, record">
                            {{
                                record.adSceneDate.findIndex((item) => {
                                    return item.adSceneName == '上下滑大屏广告'
                                }) > -1
                                    ? record.adSceneDate.find((item) => {
                                          return item.adSceneName == '上下滑大屏广告'
                                      }).adSceneCost
                                    : '-'
                            }}
                        </div>
                        <div slot="xxl" slot-scope="text, record">
                            {{
                                record.adSceneDate.findIndex((item) => {
                                    return item.adSceneName == '信息流广告'
                                }) > -1
                                    ? record.adSceneDate.find((item) => {
                                          return item.adSceneName == '信息流广告'
                                      }).adSceneCost
                                    : '-'
                            }}
                        </div>
                        <div slot="inventory" slot-scope="text,record">
                            <div v-if="text">
                                <p v-for="(item, index) in text.split(',')" :key="index" style="margin-bottom:0">
                                    {{ item }}
                                </p>
                            </div>
                            <div v-else>-</div>
                        </div>
                    </a-table>
                </a-card>
            </a-col>
        </a-row>

        <customColumnProject
            :visible="visible"
            :listNum="listNum"
            :fiexColumn="columnsFixd"
            :mediaType="2"
            @closeCustomColumn="closeCustomColumn"
            @changeColumn="changeColumn"
        />
    </div>
</template>

<script>
import customColumnProject from './customColumnProject.vue'
import keepPersonData from './new-keep-data.js'
import moment from 'moment'
import { getAction, postAction, downFile, downFilePost } from '@/api/manage'
// 引入基本模板
var echarts = require('echarts')
// 引入折线图组件
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')
import { mapGetters } from 'vuex'
export default {
    components: { customColumnProject },
    data() {
        return {
            spinning: false,
            spinningGroup: false,
            mediaId: '2',
            mediaIdGroup: '2',
            mediaIdAccount: '2',
            mediaIdDetail: '2',
            visibleLoading: false,
            scrollX: 1500,
            visible: false,
            titleList: '项目列表',
            listNum: [],
            columnsFixd: keepPersonData.setNoDeleteColumns(),
            selectValue: '1',
            dateEchart: [moment(), moment()],
            updateAccountEchart: '',
            clientWidth: 0,
            personData: -2,
            dateMiddle: [moment(), moment()],
            dateRanges: keepPersonData.setTimeRange(),
            echartsDataoperate: [],
            echartsLoadingYun: true,
            echartsLoading: false,
            echartsDataProject: [],
            projectAccount: 'a',
            dateMiddleProject: [moment(), moment()],
            dateMiddleGroup: [moment(), moment()],
            echartsIpagination: {
                current: 1,
                pageSize: 5,
                //   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.echartsIpagination.current = current
                    this.echartsIpagination.pageSize = pageSize
                },
            },
            echartsIpaginationProject: {
                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.echartsIpaginationProject.current = current
                    this.echartsIpaginationProject.pageSize = pageSize
                },
            },
            columnsprojectoperate: [
                {
                    title: '运营人员',
                    align: 'center',
                    dataIndex: 'userName',
                    scopedSlots: { customRender: 'userName' },
                },
                {
                    title: '项目数量',
                    align: 'center',
                    dataIndex: 'projectNum',
                },
                {
                    title: '账户数量',
                    align: 'center',
                    dataIndex: 'accountNum',
                },
                {
                    title: '花费',
                    align: 'center',
                    dataIndex: 'totalCost',
                    sorter: true,
                    sorter: (a, b) => a.totalCost - b.totalCost,
                },
                {
                    title: '花费环比',
                    align: 'center',
                    dataIndex: 'rate',
                },
                {
                    title: '新上计划数',
                    align: 'center',
                    dataIndex: 'newCampaignNum',
                    sorter: true,
                    sorter: (a, b) => a.newCampaignNum - b.newCampaignNum,
                    scopedSlots: { customRender: 'newCampaignNum' },
                },
                {
                    title: '新上组数',
                    align: 'center',
                    dataIndex: 'newUnitNum',
                    sorter: true,
                    sorter: (a, b) => a.newUnitNum - b.newUnitNum,
                    scopedSlots: { customRender: 'newUnitNum' },
                },
            ],
            groupList: [],
            groupLoading: false,
            groupIpagination: {
                current: 1,
                pageSize: 5,
                //   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.groupIpagination.current = current
                    this.groupIpagination.pageSize = pageSize
                    this.getGroupList()
                },
            },
            columnGroup: [
                {
                    title: '运营经理',
                    align: 'center',
                    dataIndex: 'realname',
                    scopedSlots: { customRender: 'realname' },
                },
                {
                    title: '运营数量',
                    align: 'center',
                    dataIndex: 'operationNum',
                },
                {
                    title: '日均消耗',
                    align: 'center',
                    dataIndex: 'averageDayCost',
                },
                {
                    title: '人均消耗',
                    align: 'center',
                    dataIndex: 'averagePeopleCost',
                },
                {
                    title: '花费',
                    align: 'center',
                    dataIndex: 'totalCost',
                    sorter: true,
                    sorter: (a, b) => a.totalCost - b.totalCost,
                },
                {
                    title: '花费环比',
                    align: 'center',
                    dataIndex: 'yearOnYearCost',
                },
                {
                    title: '项目数',
                    align: 'center',
                    dataIndex: 'projectNum',
                    scopedSlots: { customRender: 'projectNum' },
                },
                {
                    title: '账户数',
                    align: 'center',
                    dataIndex: 'accountNum',
                    scopedSlots: { customRender: 'accountNum' },
                },
                {
                    title: '平均账户消耗',
                    align: 'center',
                    dataIndex: 'averageAccountCost',
                    scopedSlots: { customRender: 'averageAccountCost' },
                },
                {
                    title: '基建数量',
                    align: 'center',
                    dataIndex: 'unitNum',
                    scopedSlots: { customRender: 'unitNum' },
                },
            ],
            columnsProject: keepPersonData.setNoDeleteColumns(),
            echartsData: [],
            timeData: [],
            lengthData: [],
            todayList: [],
            yesterdayList: [],
            yestadyNum: 1,
            dataName: '',
            todayCost: '',
            projectNum: '',
            compare: '',
            sectionCost: '',
            userAverageAccount: '',
            userAveragecost: '',
            projectId: '',
        }
    },
    filters: {
        formatDate: function (value) {
            if (value) {
                let date = new Date(value)
                let y = date.getFullYear()
                let MM = date.getMonth() + 1
                MM = MM < 10 ? '0' + MM : MM
                let d = date.getDate()
                d = d < 10 ? '0' + d : d
                let h = date.getHours()
                h = h < 10 ? '0' + h : h
                let m = date.getMinutes()
                m = m < 10 ? '0' + m : m
                let s = date.getSeconds()
                s = s < 10 ? '0' + s : s
                return y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s
            } else {
                return '-'
            }
        },
        formatNum: function (value) {
            if (!value) {
                return '暂无数据'
            } else if (value == '暂无数据') {
                return '暂无数据'
            }
            return Number(value)
                .toFixed(3)
                .toString()
                .replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')
        },
    },
    mounted() {

        if(this.userInfo().id == '4afe739502ae4258a18c36a000d7ff20'||this.userInfo().roleName == '头条运营经理'){
            this.mediaId= '1'
            this.mediaIdGroup= '1'
            this.mediaIdAccount= '1'
            this.mediaIdDetail= '1'
            this.projectAccountChange();
        }
        this.getQueryNewlyData()
        // this.showColumn()
        this.getOperationGroupData()
        this.getOperateDetails()
        this.getGroupList()
        this.getItemList()
        this.clientWidth = document.documentElement.clientWidth - 224
    },
    activated() {
        this.$nextTick(() => {
            this.clientWidth = document.documentElement.clientWidth - 224
        })
    },
    methods: {
        ...mapGetters(['userInfo']),
        exportExcel(exportType) {
            this.visibleLoading = true

            var getUrl = ''
            var params = {}
            // if (this.projectAccount == 'a') {
            getUrl =
                process.env.VUE_APP_BASE_STARE_URL +
                '/kuaiShouOpreate/kuaiShouMaterialStareController/exportKuaiShouOperateProjectInfo'
            params.startTime = this.dateMiddleProject[0].format('YYYY-MM-DD')
            params.endTime = this.dateMiddleProject[1].format('YYYY-MM-DD')
            params.userId = this.userInfo().id
            params.mediaType = this.mediaIdAccount
            // } else {
            //     getUrl =
            //         process.env.VUE_APP_BASE_STARE_URL +
            //         '/kuaiShouOpreate/kuaiShouMaterialStareController/exportKuaiShouOperateAccountInfo'
            //     params.startTime = this.dateMiddleProject[0].format('YYYY-MM-DD')
            //     params.endTime = this.dateMiddleProject[1].format('YYYY-MM-DD')
            //     params.userId = this.userInfo().id
            //     params.projectId = this.projectId
            // }

            //   项目 /material/kuaiShouOpreate/kuaiShouMaterialStareController/exportKuaiShouOperateProjectInfo?startTime=2022-04-27&endTime=2022-04-27&userId=e9ca23d68d884d4ebb19d07889727dae
            //   账户 /material/kuaiShouOpreate/kuaiShouMaterialStareController/exportKuaiShouOperateAccountInfo?projectId=8220885&startTime=2022-04-27&endTime=2022-04-27&userId=e9ca23d68d884d4ebb19d07889727dae
            downFile(getUrl, params).then((res) => {
                this.visibleLoading = 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 = `${this.dateMiddleProject[0].format(
                    'YYYY-MM-DD'
                )}~${this.dateMiddleProject[1].format('YYYY-MM-DD')}报表.xlsx` //下载后文件名
                document.body.appendChild(downloadElement)
                downloadElement.click() //点击下载
                document.body.removeChild(downloadElement) //下载完成移除元素
                window.URL.revokeObjectURL(href) //释放掉blob对象
            })
        },
        // 项目列表
        getItemList() {
            this.echartsLoading = true
            let params = {
                startTime: this.dateMiddleProject[0].format('YYYY-MM-DD'),
                endTime: this.dateMiddleProject[1].format('YYYY-MM-DD'),
                userId: this.userInfo().id,
                mediaType: this.mediaIdAccount,
                pageNum: this.echartsIpaginationProject.current,
                pageSize: this.echartsIpaginationProject.pageSize,
            }
            this.getAction(
                process.env.VUE_APP_BASE_STARE_URL +
                    '/kuaiShouOpreate/kuaiShouMaterialStareController/getKuaiShouOperateProjectInfo2',
                params
            ).then((res) => {
                this.echartsLoading = false
                if (res.code == 0) {
                    // columnsProject
                    this.echartsDataProject = res.result.list
                    this.echartsIpaginationProject.total = res.result.total
                } else {
                    this.echartsDataProject = []
                    this.echartsIpaginationProject.total = 0
                }
            })
        },
        dateMiddleProjectChange() {
            this.echartsLoading = true
            this.echartsIpaginationProject.current = 1
            if (this.projectAccount == 'a') {
                this.getItemList()
            } else {
                this.getAccountData()
            }
        },
        sort(pagination, filters, sorter, { currentDataSource }) {
            this.echartsLoading = true
            // console.log(pagination, filters, sorter)
            this.echartsIpaginationProject.current = pagination.current
            this.echartsIpaginationProject.pageSize = pagination.pageSize
            this.getItemList()
            // if (this.projectAccount == 'a') {
            //     this.getItemList()
            // } else {
            //     this.getAccountData()
            // }
        },
        getAccountData() {
            this.echartsLoading = true
            let params = {
                startTime: this.dateMiddleProject[0].format('YYYY-MM-DD'),
                endTime: this.dateMiddleProject[1].format('YYYY-MM-DD'),
                userId: this.userInfo().id,
                mediaType: this.mediaIdAccount,
                pageNum: this.echartsIpaginationProject.current,
                pageSize: this.echartsIpaginationProject.pageSize,
                projectId: this.projectId,
            }
            this.getAction(
                process.env.VUE_APP_BASE_STARE_URL +
                    '/kuaiShouOpreate/kuaiShouMaterialStareController/getKuaiShouOperateAccountInfo',
                params
            ).then((res) => {
                this.echartsLoading = false
                if (res.code == 0) {
                    this.echartsDataProject = res.result.list
                    this.echartsIpaginationProject.total = res.result.total
                }
            })
        },
        projectNameClick(row) {
            this.titleList = '账户列表'
            this.columnsFixd = keepPersonData.setNoDeleteProjectColumns()
            this.listNum = keepPersonData.setNoDeleteProjectColumns()
            this.projectAccount = 'b'
            this.projectId = row.projectId
            this.echartsIpaginationProject.current = 1
            // this.showColumn()
            this.$nextTick(() => {
                this.echartsLoading = true
                this.getAccountData()
            })
        },
        changeGetGroupList() {
            this.groupIpagination.current = 1
            this.getGroupList()
        },
        projectAccountChange(ent) {
            if (this.mediaIdAccount == 2) {
                this.scrollX = 1500
                this.columnsProject = keepPersonData.setNoDeleteColumns()
            } else {
                this.scrollX = 0
                this.columnsProject = keepPersonData.setNoTtDeleteColumns()
            }
            this.echartsIpaginationProject.current = 1
            this.getItemList()
            // this.echartsLoading = true
            // if (ent.target.value == 'a') {
            //     this.titleList = '项目列表'
            //     this.columnsFixd = keepPersonData.setNoDeleteColumns()
            //     this.listNum = keepPersonData.setNoDeleteColumns()
            //     this.projectId = ''
            //     this.columnsProject = [...this.columnsFixd]
            //     this.echartsIpaginationProject.current = 1
            //     // this.showColumn()
            //     this.getItemList()
            // } else {
            //     this.titleList = '账户列表'
            //     this.columnsFixd = keepPersonData.setNoDeleteProjectColumns()
            //     this.listNum = keepPersonData.setNoDeleteProjectColumns()
            //     console.log(this.columnsFixd)
            //     this.columnsProject = [...this.columnsFixd]
            //     // this.showColumn()
            //     this.echartsIpaginationProject.current = 1
            //     this.getAccountData()
            // }
            // this.projectAccount = ent.target.value
            // this.showColumn();
        },
        accountNameClick(row) {
            sessionStorage.setItem('personalaccountId', row.accountId)
            this.$router.push({ path: '/modules/stockWatch/modules/new-keepManage/account-newkeepManage' })
        },
        userNameClick(row) {
            sessionStorage.setItem('personalUserId', row.userId)
            this.$router.push({ path: '/modules/stockWatch/modules/new-keepManage/personal-keepManage' })
        },
        // 运营组数据
        getOperationGroupData() {
            this.cancel()
            this.spinningGroup = true
            let params = {
                startTime: this.dateEchart[0].format('YYYY-MM-DD'),
                endTime: this.dateEchart[1].format('YYYY-MM-DD'),
                mediaType: this.mediaId,
                userId: this.userInfo().id,
            }
            this.getAction(
                process.env.VUE_APP_BASE_STARE_URL +
                    '/kuaiShouOpreate/kuaiShouMaterialStareController/kuaiShouOperateDateTotal',
                params
            ).then((res) => {
                this.spinningGroup = false
                if (res.code == 0) {
                    if (res.result.todayCost) {
                        this.todayCost = res.result.todayCost
                    } else {
                        this.todayCost = '暂无数据'
                    }

                    this.compare = res.result.compare
                    if (res.result.sectionCost) {
                        this.sectionCost = res.result.sectionCost
                    } else {
                        this.sectionCost = '暂无数据'
                    }
                    if (res.result.userAverageAccount) {
                        this.userAverageAccount = res.result.userAverageAccount
                    } else {
                        this.userAverageAccount = '暂无数据'
                    }
                    if (res.result.userAveragecost) {
                        this.userAveragecost = res.result.userAveragecost
                    } else {
                        this.userAveragecost = '暂无数据'
                    }
                    if (res.result.projectNum) {
                        this.projectNum = res.result.projectNum
                    } else {
                        this.projectNum = '暂无数据'
                    }
                }
            })
        },
        // 运营数据详情
        getOperateDetails() {
            let params = {
                startTime: this.dateMiddle[0].format('YYYY-MM-DD'),
                endTime: this.dateMiddle[1].format('YYYY-MM-DD'),
                userId: this.userInfo().id,
                pageNum: this.echartsIpagination.current,
                pageSize: this.echartsIpagination.pageSize,
                mediaType: this.mediaIdDetail,
            }
            this.getAction(
                process.env.VUE_APP_BASE_STARE_URL +
                    '/kuaiShouOpreate/kuaiShouMaterialStareController/getKuaiShouOperateInfo',
                params
            ).then((res) => {
                if (res.code == 0) {
                    this.echartsDataoperate = res.result.list
                    this.echartsIpagination.total = res.result.total
                    this.echartsLoadingYun = false
                }
            })
        },

        // 运营组数据
        getGroupList() {
            this.groupLoading = true
            this.groupList = []
            let params = {
                startTime: this.dateMiddleGroup[0].format('YYYY-MM-DD'),
                endTime: this.dateMiddleGroup[1].format('YYYY-MM-DD'),
                mediaType: this.mediaIdGroup,
                userId: this.userInfo().id,
                pageNum: this.groupIpagination.current,
                pageSize: this.groupIpagination.pageSize,
            }
            this.getAction(
                process.env.VUE_APP_BASE_STARE_URL +
                    '/kuaiShouOpreate/kuaiShouMaterialStareController/getOperationGroupData',
                params
            ).then((res) => {
                this.groupLoading = false
                if (res.code == 0) {
                    this.groupList = res.result.list
                    this.groupIpagination.total = res.result.total
                } else {
                    this.groupList = []
                    this.groupIpagination.total = 0
                }
            })
        },

        sortDataoperate(pagination, filters, sorter, { currentDataSource }) {
            this.echartsLoadingYun = true
            // console.log(pagination, filters, sorter)
            this.echartsIpagination.current = pagination.current
            this.echartsIpagination.pageSize = pagination.pageSize
            this.getOperateDetails()
        },

        dateMiddleChange() {
            this.echartsLoadingYun = true
            this.echartsIpagination.current = 1
            this.getOperateDetails()
        },
        dateMiddleChangeGroup() {
            this.groupLoading = true
            this.groupIpagination.current = 1
            this.getGroupList()
        },
        // 导出
        exportClick() {
            let params = {
                startTime: this.dateMiddle[0].format('YYYY-MM-DD'),
                endTime: this.dateMiddle[1].format('YYYY-MM-DD'),
                userId: this.userInfo().id,
                pageNum: this.echartsIpagination.current,
                pageSize: this.echartsIpagination.pageSize,
                mediaType: this.mediaIdDetail,
            }
            window.location.href = `${
                process.env.VUE_APP_BASE_STARE_URL
            }${'/kuaiShouOpreate/kuaiShouMaterialStareController/exportKuaiShouOperateInfo'}?startTime=${
                params.startTime
            }&endTime=${params.endTime}&userId=${params.userId}&pageNum=${params.pageNum}&pageSize=${params.pageSize}&mediaType=${params.mediaType}`
        },
        exportClickGroup() {
            let params = {
                startTime: this.dateMiddleGroup[0].format('YYYY-MM-DD'),
                endTime: this.dateMiddleGroup[1].format('YYYY-MM-DD'),
                userId: this.userInfo().id,
                pageNum: this.groupIpagination.current,
                pageSize: this.groupIpagination.pageSize,
                mediaType: this.mediaIdGroup,
            }
            window.location.href = `${
                process.env.VUE_APP_BASE_STARE_URL
            }${'/kuaiShouOpreate/kuaiShouMaterialStareController/exportOperationGroupData'}?startTime=${
                params.startTime
            }&endTime=${params.endTime}&userId=${params.userId}&pageNum=${params.pageNum}&pageSize=${
                params.pageSize
            }&mediaType=${params.mediaType}`
        },
        getQueryNewlyData() {
            this.spinning = true
            let params = {
                startTime: this.dateEchart[0].format('YYYY-MM-DD'),
                endTime: this.dateEchart[1].format('YYYY-MM-DD'),
                mediaType: this.mediaId,
                type: this.selectValue,
                userId: this.userInfo().id,
            }
            this.getAction(
                process.env.VUE_APP_BASE_STARE_URL + '/kuaiShouOpreate/kuaiShouMaterialStareController/kuaiShousumData',
                params
            ).then((res) => {
                this.spinning = false
                if (res.code == 0) {
                    this.updateAccountEchart = res.timestamp
                    if (this.selectValue == '1') {
                        this.todayList = res.result.todayList.map((item) => {
                            return item.totalCost
                        })
                        this.yesterdayList = res.result.yesterdayList.map((item) => {
                            return item.totalCost
                        })

                        this.timeData = [
                            '0:00',
                            '2:00',
                            '4:00',
                            '6:00',
                            '8:00',
                            '10:00',
                            '12:00',
                            '14:00',
                            '16:00',
                            '18:00',
                            '20:00',
                            '22:00',
                        ]
                        this.timeData = res.result.yesterdayList.map((itemdate) => {
                            return itemdate.hour
                        })
                        this.lengthData = ['今天', '昨天']
                        let consumptionSummary = []
                        this.initEchart(
                            'accountIndexEchart',
                            this.initAccountIndexEchart(
                                this.todayList,
                                this.yesterdayList,
                                consumptionSummary,
                                this.timeData,
                                this.lengthData,
                                this.yestadyNum
                            )
                        )
                    } else if (this.selectValue == '3') {
                        let consumptionSummary = []
                        consumptionSummary = res.result.map((itemday) => {
                            return itemday.totalCost
                        })
                        this.todayList = []
                        this.yesterdayList = []
                        this.timeData = res.result.map((itemdate) => {
                            return itemdate.dateTime
                        })
                        this.lengthData = ['消耗汇总']
                        this.initEchart(
                            'accountIndexEchart',
                            this.initAccountIndexEchart(
                                this.todayList,
                                this.yesterdayList,
                                consumptionSummary,
                                this.timeData,
                                this.lengthData,
                                this.yestadyNum
                            )
                        )
                    } else if (this.selectValue == '2') {
                        this.lengthData = res.result.map((i) => {
                            return i.userName
                        })
                        this.timeData = [
                            '0:00',
                            '2:00',
                            '4:00',
                            '6:00',
                            '8:00',
                            '10:00',
                            '12:00',
                            '14:00',
                            '16:00',
                            '18:00',
                            '20:00',
                            '22:00',
                        ]
                        let series = []
                        let array = []
                        this.timeData = res.result[0].data.map((element) => {
                            if (element.hour) {
                                return element.hour
                            } else {
                                return element.dateTime
                            }
                        })
                        console.log(this.timeData)
                        series = res.result.map((item) => {
                            return {
                                name: item.userName,
                                type: 'line',
                                smooth: true,
                                symbol: 'circle',
                                data: item.data.map((i) => {
                                    return i.totalCost
                                }),
                            }
                        })
                        this.initEchart('acctowecharts', this.acctowecharts(this.lengthData, this.timeData, series))
                    } else {
                        this.lengthData = res.result.map((i) => {
                            return i.userName
                        })
                        res.result.map((o) => {
                            this.timeData = o.data.map((tt) => {
                                return tt.dateTime
                            })
                        })
                        console.log(this.timeData)
                        let series = []
                        let array = []
                        series = res.result.map((item) => {
                            return {
                                name: item.userName,
                                type: 'line',
                                smooth: true,
                                symbol: 'circle',
                                data: item.data.map((i) => {
                                    return i.totalCost
                                }),
                            }
                        })
                        // res.result.forEach(element => {
                        //     element.data.forEach(item => {

                        //         array.push(item.totalCost)
                        //         series.push({
                        //             name: element.userName,
                        //             type: 'line',
                        //             smooth: true,
                        //             symbol: 'circle',
                        //             data: array,
                        //             lineStyle: {
                        //             color: '#00BFFF',
                        //             width: 2,
                        //             },
                        //             itemStyle:{
                        //             color:'#00BFFF',
                        //             borderWidth:2,
                        //             borderColor:'#00BFFF'
                        //             },
                        //         })
                        //     });
                        // });

                        //     for(var i=0; i<series.length; i++){
                        //     for(var j=i+1; j<series.length; j++){
                        //         if(series[i].name==series[j].name){         //第一个等同于第二个，splice方法删除第二个
                        //             series.splice(j,1);
                        //             j--;
                        //         }
                        //     }
                        // }
                        this.initEchart('acctowecharts', this.acctowecharts(this.lengthData, this.timeData, series))
                    }
                }
            })
        },
        selectMediaIdChange() {
            this.dateEchartChange()
        },
        selectValueChange() {
            if (this.selectValue == 1) {
                this.yestadyNum = 1
            } else {
                this.yestadyNum = 2
            }
            this.getQueryNewlyData()
        },
        dateEchartChange() {
            this.getQueryNewlyData()
            this.getOperationGroupData()
        },
        //获取echart的值
        initEchart(idName, optionName) {
            let that = this
            const chart = this.$refs[idName]
            //   // console.log(res);(chart)
            if (chart) {
                console.log(chart)
                const myChart = echarts.init(document.getElementById(idName))
                // myChart.showLoading({
                //     text: "图表数据正在努力加载..."
                // });
                myChart.clear()
                myChart.setOption(optionName)
                window.addEventListener('resize', function () {
                    that.clientWidth = document.documentElement.clientWidth - 224
                    myChart.resize()
                })
            }
        },
        //趋势图echarts配置
        initAccountIndexEchart(todayList, yesterdayList, consumptionSummary, timeData, lengthData) {
            // this.clientWidth  =  document.documentElement.clientWidth - 224
            // var myChart = echarts.init(document.getElementById('accountIndexEchart'))
            var iconNone = require('../../../../../assets/nodata.png')
            let option = {
                tooltip: {
                    trigger: 'axis',
                },
                title: {
                    x: 'center',
                    y: 'center',
                    text: timeData.length == 0 ? `{a| ${''}}` : '',
                    show: true,
                    textStyle: {
                        rich: {
                            a: {
                                height: 200,
                                width: 280,
                                backgroundColor: {
                                    image: iconNone,
                                },
                            },
                        },
                    },
                },
                legend: {
                    data: lengthData,
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true,
                },
                // toolbox: {
                //     feature: {
                //         saveAsImage: {}
                //     }
                // },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: timeData,
                },
                yAxis: {
                    type: 'value',
                },
                series: [
                    {
                        name: '今天',
                        type: 'line',
                        smooth: true,
                        symbol: 'circle',
                        data: todayList,
                        lineStyle: {
                            color: '#00BFFF',
                            width: 2,
                        },
                        itemStyle: {
                            color: '#00BFFF',
                            borderWidth: 2,
                            borderColor: '#00BFFF',
                        },
                    },
                    {
                        name: '昨天',
                        type: 'line',
                        smooth: true,
                        symbol: 'circle',
                        data: yesterdayList,
                        lineStyle: {
                            color: '#00FF7F',
                            width: 2,
                        },
                        itemStyle: {
                            color: '#00FF7F',
                            borderWidth: 2,
                            borderColor: '#00FF00',
                        },
                    },
                    {
                        name: '消耗汇总',
                        type: 'line',
                        smooth: true,
                        symbol: 'circle',
                        data: consumptionSummary,
                        lineStyle: {
                            color: '#00BFFF',
                            width: 2,
                        },
                        itemStyle: {
                            color: '#00BFFF',
                            borderWidth: 2,
                            borderColor: '#00BFFF',
                        },
                    },
                ],
            }
            return option
        },
        acctowecharts(lengthData, timeData, series) {
            // this.clientWidth  =  document.documentElement.clientWidth - 224
            // var myChart = echarts.init(document.getElementById('accountIndexEchart'))
            var iconNoneAcc = require('../../../../../assets/nodata.png')
            let option = {
                tooltip: {
                    trigger: 'axis',
                },
                title: {
                    x: 'center',
                    y: 'center',
                    text: timeData.length == 0 ? `{a| ${''}}` : '',
                    show: true,
                    textStyle: {
                        rich: {
                            a: {
                                height: 200,
                                width: 280,
                                backgroundColor: {
                                    image: iconNoneAcc,
                                },
                            },
                        },
                    },
                },
                legend: {
                    data: lengthData,
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true,
                },
                // toolbox: {
                //     feature: {
                //         saveAsImage: {}
                //     }
                // },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: timeData,
                },
                yAxis: {
                    type: 'value',
                },
                series: series,
            }
            return option
        },

        // 自定义列
        customColumn() {
            this.visible = true
            console.log(this.columnsProject)
            this.listNum = [...this.columnsProject]
        },
        //自定义列相关
        closeCustomColumn() {
            this.visible = false
        },
        showColumn() {
            this.postDataAction('/toutiao/videoReportDaily/getColumnJson', {
                columnType: this.projectAccount === 'a' ? 101 : 102,
            }).then((res) => {
                // console.log(res)
                if (res.success) {
                    // console.log(JSON.parse(res.result))
                    if (res.result) {
                        let columns = JSON.parse(res.result)
                        console.log(columns)
                        if (columns.length) {
                            if (columns.length >= this.columnsFixd.length) {
                                columns.map((item, index) => {
                                    if (index > this.columnsFixd.length - 1) {
                                        item.sorter = function (a, b) {}
                                    }
                                })
                                columns = columns.slice(this.columnsFixd.length - 1)
                                this.columnsProject = [...this.columnsFixd, ...columns]
                                // this.columnsProject = [...new Set(this.columnsProject.filter(item=>item.dataIndex))]
                                var obj = {}
                                this.columnsProject = this.columnsProject.reduce(function (item, next) {
                                    obj[next.dataIndex] ? '' : (obj[next.dataIndex] = true && item.push(next))
                                    return item
                                }, [])
                                console.log(this.columnsProject)
                                this.changeColumn(this.columnsProject)
                            }
                        }
                    } else {
                        this.changeColumn(this.columnsProject)
                    }
                }
            })
        },

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

            //     this.scrollX = 0
            // } else if (this.columnsProject.length > this.columnsFixd.length) {
            //     this.columnsProject.forEach((element, index) => {
            //         if (index < this.columnsFixd.length) {
            //             if (element.dataIndex == 'accountNum') {
            //                 element.width = 100
            //                 element.fixed = 'left'
            //             } else if (element.dataIndex == 'userNum') {
            //                 element.width = 100
            //                 element.fixed = 'left'
            //             } else if (element.dataIndex == 'yearOnYear') {
            //                 element.width = 100
            //                 element.fixed = 'left'
            //             } else if (element.dataIndex == 'equallyRate') {
            //                 element.width = 100
            //                 element.fixed = 'left'
            //             } else {
            //                 // element.width = 150
            //                 // element.fixed = 'left'
            //             }
            //         } else {
            //             element.width = 'auto'
            //             element.fixed = false
            //         }
            //     })

            //     this.scrollX = 1500 + 200 * (this.columnsProject.length - this.columnsFixd.length)
            // } else if (this.columnsProject.length == this.columnsFixd.length) {
            //     this.columnsProject.forEach((element, index) => {
            //         element.width = 'auto'
            //         element.fixed = false
            //     })
            //     this.scrollX = false
            // } else {
            //     this.scrollX = 0
            //     this.columnsProject.forEach((element) => {
            //         element.width = 'auto'
            //         element.fixed = false
            //     })
            // }

            let arr = JSON.stringify(this.columnsProject)
            this.postDataAction('/toutiao/videoReportDaily/saveOrUpdateColumnJson', {
                json: arr,
                columnType: this.projectAccount === 'a' ? 101 : 102,
            }).then((res) => {
                // console.log(res)
            })
        },
    },
}
</script>
<style lang="less" scoped>
@import '../keep-manage/keep-manage.less';

.group-keep-ul li {
    margin-bottom: 20px;
    font-size: 16px;
}
</style>
