<style>
.materialReport .chart-card-content {
    display: none !important;
}
</style>
<style scoped>
.bg {
    width: 100%;
    height: 100%;
}
.bg:after {
    content: '';
    width: 110%;
    height: 110%;
    position: absolute;
    left: -5%;
    top: -5%;
    background: inherit;
    filter: blur(10px);
    z-index: 2;
    background: rgba(0, 0, 0, 0.8);
}
.top-ul-style {
    width: 100%;
    padding-left: 0;
}
.top-ul-style li {
    height: 100px;
    border: 1px solid #f2f2f2;
    margin-bottom: 5px;
    padding: 10px;
    display: flex;
    justify-content: space-between;
}
.li-cost {
    display: flex;
    flex-flow: column;
    justify-content: center;
    align-content: flex-end;
}
.li-cost span {
    font-size: 16px;
    font-weight: 500;
    min-width: 50px;
    text-align: right;
}
</style>
<template>
    <div class="materialReport">
        <div class="card-containers">
            <div class="option" style="justify-content: space-between">
                <div class="option" style="padding: 0">
                    <div class="item">
                        <span>日期选择</span>
                        <a-range-picker
                            v-model="dateValue"
                            :ranges="dateRanges"
                            :disabled-date="(current) => disabledDate(dateValue, current)"
                            style="width: 300px"
                        />
                    </div>
                    <div class="item">
                        <span>媒体维度</span>
                        <a-radio-group v-model="mediaDimension" @change="mediaDimensionChange">
                            <a-radio-button value="b">快手</a-radio-button>
                            <a-radio-button
                                value="a"
                                :disabled="
                                    roleCode == 'CompanyManager' &&
                                    !dataDimensionList.filter((item) => item.companyId == dataDimensionValue)[0]
                                        .ttDesignId
                                "
                                >头条</a-radio-button
                            >
                        </a-radio-group>
                    </div>
                    <div class="item">
                        <span>公司</span>
                        <a-select
                            v-model="dataDimensionValue"
                            style="width: 300px; margin-left: 10px"
                            :filterOption="filterOption"
                            showSearch
                            allowClear
                            :disabled="roleCode == 'CompanyManager'"
                        >
                            <a-select-option
                                v-for="(item, index) in dataDimensionList"
                                :key="index + 1"
                                :value="item.companyId"
                                :disabled="mediaDimension == 'a' && !item.ttDesignId"
                            >
                                {{ item.companyName }}
                            </a-select-option>
                        </a-select>
                    </div>
                </div>
                <div class="item" style="float: right">
                    <a-button :loading="searchLoading" type="primary" @click="handleSubmit"> 搜索 </a-button>
                    <a-button
                        :disabled="spinning"
                        :loading="resetLoading"
                        style="margin-left: 15px"
                        @click="resetSubmit"
                    >
                        重置
                    </a-button>
                    <a-button type="primary" style="margin-left: 15px" @click="dataKanBan">数据看板</a-button>
                </div>
            </div>
        </div>

        <a-row :gutter="24" style="margin-top: 20px">
            <a-col :span="16">
                <a-row :gutter="24">
                    <a-col :span="12">
                        <a-spin :spinning="spinning">
                            <a-card class="material-report-card">
                                <span slot="title"> 素材产出数量 </span>
                                <div v-if="materialManyVisible">
                                    <div
                                        id="accountIndexEchartOnePie"
                                        ref="accountIndexEchartOnePie"
                                        style="width: 90%; height: 300px; margin-right: 20px"
                                        :style="{ width: clientWidth / 3 - 48 - 24 + 'px' }"
                                    ></div>
                                </div>
                                <a-list v-else :data-source="[]" />
                            </a-card>
                        </a-spin>
                    </a-col>
                    <a-col :span="12">
                        <a-spin :spinning="spinningChart">
                            <a-card class="material-report-card">
                                <span slot="title"> 运营消耗情况 </span>
                                <div style="width: 100%; display: flex">
                                    <div style="width: 100%">
                                        <div v-if="operateVisible && barTotal > 0">
                                            <div
                                                id="operateEchartBar"
                                                ref="operateEchartBar"
                                                style="width: 100%; height: 240px; margin-right: 20px"
                                                :style="{ width: clientWidth / 3 - 48 - 24 + 'px' }"
                                            ></div>
                                        </div>
                                        <a-list v-else :data-source="[]" />
                                    </div>
                                </div>
                            </a-card>
                        </a-spin>
                    </a-col>
                </a-row>
                <a-row :gutter="24" style="margin-top: 24px">
                    <a-col :span="12">
                        <a-spin :spinning="spinningChartPie">
                            <a-card class="material-report-card">
                                <span slot="title"> 素材产出消耗 </span>
                                <div v-if="materialPieVisible">
                                    <div
                                        id="materialPie"
                                        ref="materialPie"
                                        style="width: 90%; height: 300px; margin-right: 20px"
                                        :style="{ width: clientWidth / 3 - 48 - 24 + 'px' }"
                                    ></div>
                                </div>
                                <a-list v-else :data-source="[]" />
                            </a-card>
                        </a-spin>
                    </a-col>
                    <a-col :span="12">
                        <a-spin :spinning="spinningTarget">
                            <a-card class="material-report-card">
                                <span slot="title"> 本月消耗完成度 </span>
                                <div style="width: 100%; display: flex">
                                    <div style="width: 50%">
                                        <div v-if="completeEchart">
                                            <div
                                                style="
                                                    width: 90%;
                                                    height: 300px;
                                                    margin-right: 20px;
                                                    display: flex;
                                                    justify-content: center;
                                                    align-items: center;
                                                "
                                            >
                                                <a-tooltip :title="totalConsume" slot="action">
                                                    <a-progress
                                                        type="dashboard"
                                                        :percent="completePercent"
                                                        :width="160"
                                                        style="margin-top: -40px"
                                                    />
                                                </a-tooltip>
                                            </div>
                                        </div>
                                        <a-list v-else :data-source="[]" />
                                    </div>
                                    <div
                                        style="width: 50%; display: flex; justify-content: center; align-items: center"
                                    >
                                        <a-input
                                            addon-before="本月目标"
                                            style="margin-top: -40px"
                                            v-model="completeEchartValue"
                                        >
                                            <a slot="addonAfter" @click="okValue">确定</a>
                                        </a-input>
                                    </div>
                                </div>
                            </a-card>
                        </a-spin>
                    </a-col>
                </a-row>
                <a-row :gutter="24" style="margin-top: 24px">
                    <a-col :span="24">
                        <a-spin :spinning="spinningMedio">
                            <a-card class="material-report-card">
                                <span slot="title"> 分媒体投放数据 </span>
                                <div v-if="medioDataVisible && medioKsData.length > 0">
                                    <div
                                        id="medioDataLine"
                                        ref="medioDataLine"
                                        style="width: 90%; height: 300px; margin-right: 20px"
                                        :style="{ width: clientWidth * 0.6 - 48 - 24 + 'px' }"
                                    ></div>
                                </div>
                                <a-list v-else :data-source="[]" />
                            </a-card>
                        </a-spin>
                    </a-col>
                </a-row>
            </a-col>
            <a-col :span="8">
                <a-row :gutter="24">
                    <a-col :span="24">
                        <a-spin :spinning="spinningAllData">
                            <a-card class="material-report-card" style="height: 492px">
                                <span slot="title"> 整体数据概览 </span>
                                <div v-if="allData" style="margin-top: 10px">
                                    <h4>今日消耗</h4>
                                    <p
                                        style="
                                            width: 90%;
                                            display: flex;
                                            justify-content: space-between;
                                            font-weight: bold;
                                            margin-left: 5%;
                                        "
                                    >
                                        <span style="font-size: 36px; color: rgb(245, 178, 62)">{{
                                            allData.cost | decimalsHandle
                                        }}</span
                                        ><span style="position: relative; top: 20px" v-if="allData.costRatio">
                                            <img
                                                style="width: 20px; position: absolute; right: 70px"
                                                src="./assets/shang.png"
                                                alt=""
                                                v-if="allData.costRatio > 0"
                                            />

                                            <!-- TODO 这个是下降的样式，后续优化  -->

                                            <img
                                                style="width: 20px; position: absolute; right: 70px"
                                                src="./assets/xia.png"
                                                alt=""
                                                v-else
                                            />
                                            
                                            {{ allData.costRatio ? allData.costRatio + '%' : '-' }}</span
                                        >
                                    </p>
                                    <h4>今日基建数</h4>
                                    <p
                                        style="
                                            width: 90%;
                                            display: flex;
                                            justify-content: space-between;
                                            font-weight: bold;
                                            margin-left: 5%;
                                        "
                                    >
                                        <span style="font-size: 24px; color: rgb(33, 105, 254)">{{
                                            allData.groupNum + '个'
                                        }}</span
                                        ><span style="position: relative; top: 20px" v-if="allData.unitRatio">
                                            <img
                                                style="width: 20px; position: absolute; right: 70px"
                                                src="./assets/shang.png"
                                                alt=""
                                                v-if="allData.unitRatio > 0"
                                            />

                                            <!-- TODO 这个是下降的样式，后续优化  -->

                                            <img
                                                style="width: 20px; position: absolute; right: 70px"
                                                src="./assets/xia.png"
                                                alt=""
                                                v-else
                                            />
                                             {{ allData.unitRatio ? allData.unitRatio + '%' : '-' }}</span
                                        >
                                    </p>
                                    <h4>今日素材产出</h4>
                                    <p
                                        style="
                                            width: 90%;
                                            display: flex;
                                            justify-content: space-between;
                                            font-weight: bold;
                                            margin-left: 5%;
                                        "
                                    >
                                        <span style="font-size: 24px; color: rgb(232, 84, 65)">{{
                                            allData.materialNum + '个'
                                        }}</span
                                        ><span style="position: relative; top: 20px" v-if="allData.materialRatio">
                                            <img
                                                style="width: 20px; position: absolute; right: 70px"
                                                src="./assets/shang.png"
                                                alt=""
                                                v-if="allData.materialRatio > 0"
                                            />

                                            <!-- TODO 这个是下降的样式，后续优化  -->

                                            <img
                                                style="width: 20px; position: absolute; right: 70px"
                                                src="./assets/xia.png"
                                                alt=""
                                                v-else
                                            />{{ allData.materialRatio ? allData.materialRatio + '%' : '-' }}</span
                                        >
                                    </p>
                                    <h4>人效比</h4>
                                    <p
                                        style="
                                            width: 90%;
                                            display: flex;
                                            justify-content: space-between;
                                            font-weight: bold;
                                            margin-left: 5%;
                                        "
                                    >
                                        <span style="font-size: 24px; color: rgb(132, 119, 246)">{{
                                            allData.renXiao
                                        }}</span>
                                    </p>
                                </div>
                                <a-list v-else :data-source="[]" />
                            </a-card>
                        </a-spin>
                    </a-col>
                    <a-col :span="24" style="margin-top: 24px">
                        <a-spin :spinning="spinningTop">
                            <a-card class="material-report-card" style="height: 492px">
                                <span slot="title"> 项目消耗Top10 </span>
                                <a-radio-group v-model="topType" @change="topTypeChange" slot="extra">
                                    <a-radio-button value="b">柱形图</a-radio-button>
                                    <a-radio-button value="a">表格</a-radio-button>
                                </a-radio-group>
                                <div style="margin-top: 10px">
                                    <div v-if="topType == 'b'">
                                        <div v-if="topVisible && topData.length > 0">
                                            <div
                                                id="topEcharts"
                                                ref="topEcharts"
                                                style="width: 100%; height: 380px; margin-right: 20px"
                                                :style="{ width: clientWidth / 3 - 48 - 24 + 'px' }"
                                            ></div>
                                        </div>
                                        <a-list v-else :data-source="[]" />
                                    </div>
                                    <a-table
                                        bordered
                                        :columns="columns"
                                        :data-source="topData"
                                        v-else
                                        :pagination="false"
                                        :scroll="{ y: 300 }"
                                    >
                                    </a-table>
                                </div>
                            </a-card>
                        </a-spin>
                    </a-col>
                </a-row>
            </a-col>
        </a-row>
    </div>
</template>
<script>
import moment from 'moment'
import YoutTable from '@/components/youtTable/YoutTable'
import ChartCard from '@/components/ChartCard'
import Trend from '@/components/Trend'
import { mapGetters } from 'vuex'
import { stopOtherVideo, closeAllVideoFun } from '@/utils/videoControl' // 停止除当前外的其他视频播放，及停止所有视频播放的方法

var echarts = require('echarts')
const columns = [
    {
        title: '项目名称',
        dataIndex: 'projectName',
    },
    {
        title: '消耗',
        dataIndex: 'allCost',
    },
    {
        title: '基建数',
        dataIndex: 'adNum',
    },
]
function getDaysBetween(dateString1, dateString2) {
    var startDate = Date.parse(dateString1)
    var endDate = Date.parse(dateString2)
    if (startDate > endDate) {
        return 0
    }
    if (startDate == endDate) {
        return 1
    }
    var days = (endDate - startDate) / (1 * 24 * 60 * 60 * 1000)
    return days + 1
}
function getArrayValue(array, key) {
    var key = key || 'value'
    var res = []
    if (array) {
        array.forEach(function (t) {
            res.push(t[key])
        })
    }
    return res
}

function array2obj(array, key) {
    var resObj = {}
    for (var i = 0; i < array.length; i++) {
        resObj[array[i][key]] = array[i]
    }
    return resObj
}

function getData(data, sumValue) {
    var res = {
        series: [],
        yAxis: [],
    }
    for (let i = 0; i < data.length; i++) {
        res.series.push({
            type: 'pie',
            clockWise: false, //顺时加载
            hoverAnimation: false, //鼠标移入变大
            radius: [73 - i * 15 + '%', 65 - i * 15 + '%'],
            center: ['25%', '55%'],
            label: {
                show: false,
            },
            itemStyle: {
                label: {
                    show: false,
                },
                labelLine: {
                    show: false,
                },
                borderWidth: 5,
            },
            data: [
                {
                    value: (data[i].value * 0.75).toFixed(3),
                    name: data[i].name,
                },
                {
                    value: sumValue - (data[i].value * 0.75).toFixed(3),
                    name: '',
                    itemStyle: {
                        color: 'rgba(0,0,0,0)',
                        borderWidth: 0,
                    },
                    tooltip: {
                        show: false,
                    },
                    hoverAnimation: false,
                },
            ],
        })
        res.series.push({
            name: '',
            type: 'pie',
            silent: true,
            z: 1,
            clockWise: false, //顺时加载
            hoverAnimation: false, //鼠标移入变大
            radius: [73 - i * 15 + '%', 65 - i * 15 + '%'],
            center: ['25%', '55%'],
            label: {
                show: false,
            },
            itemStyle: {
                label: {
                    show: false,
                },
                labelLine: {
                    show: false,
                },
                borderWidth: 5,
            },
            data: [
                {
                    value: 7.5,
                    itemStyle: {
                        color: '#E3F0FF',
                        borderWidth: 0,
                    },
                    tooltip: {
                        show: false,
                    },
                    hoverAnimation: false,
                },
                {
                    value: 2.5,
                    name: '',
                    itemStyle: {
                        color: 'rgba(0,0,0,0)',
                        borderWidth: 0,
                    },
                    tooltip: {
                        show: false,
                    },
                    hoverAnimation: false,
                },
            ],
        })
        res.yAxis.push(((data[i].value / sumValue) * 100).toFixed(2) + '%')
    }
    return res
}
export default {
    components: {
        YoutTable,
        ChartCard,
        Trend,
    },
    data() {
        return {
            userInfoId: false,
            roleCode: localStorage.getItem('roleCode'),
            noImg: require('@/assets/noImg.png'),
            spinning: false,
            spinningChart: false,
            spinningChartPie: false,
            spinningTarget: false,
            spinningMedio: false,
            spinningAllData: false,
            spinningTop: false,
            loading: false,
            columns,
            materialManyVisible: true, //素材产出数量饼图展示
            pieData: [], //素材产出数量饼图数据
            pieTotal: null, //素材产出数量饼图总数
            operateVisible: true, //运营消耗情况
            barData: [],
            barTotal: null,
            materialPieVisible: false,
            materialPieData: [],
            materialPieTotal: null,
            completeEchart: true,
            completeEchartValue: 0,
            completePercent: 0,
            totalConsume: 0,
            medioDataVisible: false,
            medioKsData: [],
            medioTtData: [],
            allData: null,
            topVisible: false,
            topType: 'b',
            topData: [],
            dateRanges: {
                昨天: [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                近三天: [moment().subtract(3, 'days'), moment().subtract(1, 'days')],
                近一周: [moment().subtract(7, 'days'), moment().subtract(1, 'days')],
                近14天: [moment().subtract(14, 'days'), moment().subtract(1, 'days')],
                近一月: [moment().subtract(1, 'months'), moment().subtract(1, 'days')],
                近三月: [moment().subtract(3, 'months'), moment().subtract(1, 'days')],
            },
            dateValue: [moment(), moment()],
            dataDimension: 'a',
            mediaDimension: 'b',
            dataDimensionValue: undefined,
            dataDimensionList: [],
            specificLoading: false,
            clientWidth: 0,
            resetLoading: false,
            searchLoading: false,
            spinningPopularVideoList: false,
        }
    },
    watch: {},
    methods: {
        ...mapGetters(['userInfo']),
        filterOption(input, option) {
            return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        },
        dataKanBan() {
            const a = document.createElement('a')
            document.body.appendChild(a)
            a.style.display = 'none'
            a.href = 'http://adsp.c-top.com.cn/boss-data-kanban'
            a.target = '_blank'
            a.click()
            document.body.removeChild(a)
        },
        getData() {
            if (!!this.dataDimensionValue) {
                this.getMetarialList()
                this.getOperateList()
                this.getMaterialConsumeData()
                this.getMedioData()
                this.getTotalConsume()
                this.getRealTimeData()
                this.getRealTimeData()
                this.getTopTenData()
                this.searchLoading = false
                this.resetLoading = false
            } else {
                this.$message.error('请先选择公司')
            }
        },
        getProjectList() {
            this.specificLoading = true
            return new Promise((resolve, reject) => {
                this.getAction(process.env.VUE_APP_BASE_MATERIAL_URL + '/manager/company/getCompanyList').then(
                    (res) => {
                        this.specificLoading = false
                        if (res.success) {
                            this.dataDimensionList = res.result
                            resolve(res.result)
                        } else {
                            reject(res.message)
                        }
                    }
                )
            })
        },
        decimalsHandle(val, num) {
            if (val && typeof val != 'string') {
                if (val >= 0) {
                    val = parseFloat(val).toFixed(num)
                    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(num)
                    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
            }
        },
        handleSubmit() {
            if (!!this.dataDimensionValue) {
                this.searchLoading = true
                this.resetLoading = true

                if (this.dateValue.length == 2) {
                    var between = getDaysBetween(this.dateValue[0], this.dateValue[1])
                    if (between > 90) {
                        this.$message.error('时间选择不可超过90天')
                    } else {
                        this.topType = 'b'
                        this.getData()
                    }
                } else {
                    this.$message.error('时间未选择')
                }
            } else {
                this.$message.error('请先选择公司')
            }
        },
        resetSubmit() {
            this.dataDimension = 'a'
            this.mediaDimension = 'b'
            this.topType = 'b'
            this.resetLoading = true
            this.getUserCampany().then((res) => {
                this.dateValue = [moment(), moment()]
                this.getData()
            })
        },
        //获取echart的值
        initEchart(idName, optionName) {
            let that = this
            const chart = this.$refs[idName]
            if (chart) {
                const myChart = echarts.init(document.getElementById(idName))
                myChart.setOption(optionName)

                // if (idName === 'materialPie') {
                //     var i = 0
                //     // myChart.dispatchAction({ type: 'highlight', seriesIndex: 0, dataIndex: i }) //设置默认选中高亮部分
                //     setInterval(function () {
                //         i++
                //         if (i == optionName.series[0].data.length) {
                //             i = 0
                //         }
                //         myChart.dispatchAction({
                //             type: 'downplay',
                //             seriesIndex: 0,
                //             dataIndex: i == 0 ? optionName.series[0].data.length-2 : i - 1,
                //         })
                //         myChart.dispatchAction({ type: 'highlight', seriesIndex: 0, dataIndex: i == optionName.series[0].data.length ? 0 : i }) //设置默认选中高亮部分
                //     }, 1000)
                // }

                window.addEventListener('resize', function () {
                    that.clientWidth = document.documentElement.clientWidth - 224
                    myChart.resize()
                })
            }
        },

        disabledDate(dateValue, current) {
            // .subtract(1, 'days')
            var startDate = dateValue[0] ? dateValue[0]._d : ''
            return (current && current > moment()) || (current && current < moment(startDate).subtract(90, 'days'))
        },
        mediaDimensionChange(e) {
            if (this.roleCode == 'admin') {
                this.dataDimensionValue = ''
            }
        },
        getUserCampany() {
            var params = {}
            params.userId = this.userInfo().id
            return new Promise((resolve, reject) => {
                this.getAction('/system/userCompany/queryCompanyByUserId', params).then((res) => {
                    if (res.success) {
                        this.dataDimensionValue = res.result
                        resolve()
                    } else {
                        reject()
                    }
                })
            })
        },
        parameterData() {
            var params = {}
            params.startTime = params.startTime =
                this.dateValue.length === 2 ? moment(this.dateValue[0]).format('YYYY-MM-DD') : null
            params.endTime = this.dateValue.length === 2 ? moment(this.dateValue[1]).format('YYYY-MM-DD') : null
            params.companyId = this.dataDimensionValue
            params.mediaId = this.mediaDimension === 'a' ? 1 : 2
            return params
        },
        //素材产出数量
        getMetarialList() {
            // http://localhost:7006/material/manager/company/getMaterialProduce
            this.spinning = true
            this.getAction(process.env.VUE_APP_BASE_MATERIAL_URL + '/manager/company/getMaterialProduce', {
                ...this.parameterData(),
            }).then((res) => {
                this.spinning = false
                if (res.code == 200) {
                    if (res.result) {
                        var servicedata = res.result.list
                        if (servicedata.length > 0) {
                            this.materialManyVisible = true
                            this.pieData = []
                            let num = 0
                            for (var i = 0; i < servicedata.length; i++) {
                                var obj = new Object()
                                obj.name = servicedata[i].depart_name
                                obj.value = servicedata[i].count
                                this.pieData[i] = obj
                            }
                            this.pieTotal = res.result.total
                            this.$nextTick(() => {
                                this.initEchart(
                                    'accountIndexEchartOnePie',
                                    this.initPieOneData(this.pieData, this.pieTotal)
                                )
                            })
                        } else {
                            this.materialManyVisible = false
                        }
                    } else {
                        this.pieData = []
                        this.materialManyVisible = false
                    }
                }
            })
        },
        // 素材产出数量饼图
        initPieOneData(pieData, pieTotal) {
            const list = pieData
            let option = {
                tooltip: {
                    trigger: 'item',
                    formatter: function (obj) {
                        return (
                            obj.name +
                            ':' +
                            obj.value +
                            '(' +
                            Math.round(pieTotal == 0 ? 0 : (obj.value / pieTotal) * 100) +
                            '%)'
                        )
                    },
                },
                legend: {
                    top: '20%',
                    orient: 'vertical',
                    right: '0%',
                    textStyle: {
                        //图例文字的样式
                        fontSize: 12,
                    },
                    itemGap: 20,
                    itemWidth: 15,
                    itemHeight: 10,
                    padding: [-45, 0, 0, 80],
                    bottom: '55%',
                    formatter: function (name) {
                        //该函数用于设置图例显示后的百分比
                        var data = list
                        var total = 0
                        var value
                        list.forEach((item) => {
                            if (item.name == name) {
                                value = item.value
                            }
                        })
                        var p = pieTotal == 0 ? 0 : Math.round((value / pieTotal) * 100) //求出百分比
                        return p >= 10
                            ? p == 11
                                ? `${name} ${'|'} ${value} ${p}% `
                                : `${name} ${'|'} ${value} ${p}% `
                            : `${name} ${'|'} ${value} ${p}% ` //返回出图例所显示的内容是名称+百分比
                    },
                },
                color: ['#016DDA', '#23A0E4', '#51C0F0', '#6BE0E0', '#24DFBE', '#04E893'],
                series: [
                    {
                        name: '',
                        type: 'pie',
                        radius: ['65%', '75%'],
                        avoidLabelOverlap: false,
                        hoverAnimation: true,
                        silent: false,
                        itemStyle: {
                            borderRadius: 10,
                            borderColor: 'white',
                            borderWidth: 2,
                        },
                        label: {
                            show: true,
                            position: 'center',
                            fontSize: 16,
                            formatter: function (param) {
                                return pieTotal + '\r\n\r\n素材总数'
                            },
                            textStyle: {
                                fontSize: 16,
                                color: 'black',
                            },
                        },
                        left: 0,
                        right: '50%',
                        top: 0,
                        bottom: '20%',
                        animation: false,
                        labelLine: {
                            show: false,
                        },
                        data: list,
                    },
                    {
                        name: '',
                        type: 'pie',
                        radius: ['50%', '60%'],
                        avoidLabelOverlap: false,
                        hoverAnimation: false,
                        colorBy: 'series',
                        silent: false,
                        itemStyle: {
                            borderRadius: 10,
                            borderColor: 'white',
                            borderWidth: 2,
                            color: '#f2f2f2',
                            // normal: { color: '#f2f2f2' },
                            emphasis: { color: '#f2f2f2' },
                        },
                        label: {
                            show: true,
                            position: 'center',
                            fontSize: 16,
                            formatter: function (param) {
                                return pieTotal + '\r\n\r\n素材总数'
                            },
                            textStyle: {
                                fontSize: 16,
                                color: 'black',
                            },
                        },
                        left: 0,
                        right: '50%',
                        top: 0,
                        bottom: '20%',
                        animation: false,
                        labelLine: {
                            show: false,
                        },
                        data: list,
                    },
                ],
            }
            return option
        },
        //运营消耗情况
        getOperateList() {
            this.spinningChart = true
            this.operateVisible = false
            this.getAction(process.env.VUE_APP_BASE_MATERIAL_URL + '/manager/company/getOperaterConsume', {
                ...this.parameterData(),
            }).then((res) => {
                this.spinningChart = false
                if (res.code == 200) {
                    if (res.result) {
                        var servicedata = res.result.list
                        if (servicedata.length > 0) {
                            this.operateVisible = true
                            this.barData = []
                            let num = 0
                            for (var i = 0; i < servicedata.length; i++) {
                                var obj = new Object()
                                obj.name = servicedata[i].depart_name
                                obj.value = servicedata[i].charge
                                // obj.charge = servicedata[i].charge
                                this.barData[i] = obj
                            }
                            this.barTotal = res.result.totalCharge
                            this.$nextTick(() => {
                                this.initEchart(
                                    'operateEchartBar',
                                    this.initOperateEchartBarData(this.barData, this.barTotal)
                                )
                            })
                        } else {
                            this.operateVisible = false
                        }
                    } else {
                        this.operateVisible = false
                    }
                }
            })
        },
        //柱状图
        // operateEchartBar
        initOperateEchartBarData(barData, barTotal) {
            var data = barData
            var arrName = getArrayValue(data, 'name')
            var arrValue = getArrayValue(data, 'value')
            var sumValue = eval(arrValue.join('+'))
            var objData = array2obj(data, 'name')
            var optionData = getData(data, sumValue)

            var option = {
                backgroundColor: '#fff',
                legend: {
                    show: true,
                    top: 'center',
                    left: '55%',
                    itemGap: 20,
                    itemWidth: 15,
                    itemHeight: 10,
                    data: arrName,
                    padding: [0, 5],
                    formatter: function (name) {
                        return '{title|' + name + '} | {value|' + (objData[name].value / 10000).toFixed(2) + 'w}'
                    },
                    textStyle: {
                        rich: {
                            title: {
                                fontSize: 12,

                                color: 'rgba(0,0,0,.85)',
                            },
                            value: {
                                fontSize: 12,
                                color: 'rgba(0,0,0,.85)',
                            },
                        },
                    },
                },
                tooltip: {
                    show: true,
                    trigger: 'item',
                    formatter: function (name) {
                        return `${name.name}:${(name.value / 0.75).toFixed(3)}(${(
                            (name.value / 0.75 / sumValue) *
                            100
                        ).toFixed(2)}%)`
                    },
                },
                color: ['#016DDA', '#23A0E4', '#51C0F0', '#6BE0E0', '#24DFBE', '#04E893'],
                grid: {
                    top: '18%',
                    bottom:
                        barData.length == 5
                            ? '48%'
                            : barData.length == 3
                            ? '60%'
                            : barData.length == 4
                            ? '54%'
                            : barData.length == 2
                            ? '66%'
                            : barData.length == 1
                            ? '72%'
                            : '48%',
                    left: '25%',
                    containLabel: false,
                },
                yAxis: [
                    {
                        type: 'category',
                        inverse: true,
                        axisLine: {
                            show: false,
                        },
                        axisTick: {
                            show: false,
                        },
                        axisLabel: {
                            interval: 0,
                            inside: true,
                            textStyle: {
                                color: '#000',
                                fontSize: 10,
                            },
                            show: true,
                        },
                        data: optionData.yAxis,
                    },
                ],
                xAxis: [
                    {
                        show: false,
                    },
                ],
                series: optionData.series,
            }
            return option
        },
        //素材产出消耗
        getMaterialConsumeData() {
            this.spinningChartPie = true
            this.getAction(process.env.VUE_APP_BASE_MATERIAL_URL + '/manager/company/getMaterialProduceConsume', {
                ...this.parameterData(),
            }).then((res) => {
                this.spinningChartPie = false
                if (res.code == 200) {
                    if (res.result) {
                        var servicedata = res.result.list
                        if (servicedata.length > 0) {
                            this.materialPieVisible = true
                            this.materialPieData = []
                            let num = 0
                            for (var i = 0; i < servicedata.length; i++) {
                                var obj = new Object()
                                obj.name = servicedata[i].depart_name
                                obj.value = servicedata[i].charge
                                this.materialPieData[i] = obj
                            }
                            this.materialPieTotal = res.result.totalCharge
                            this.$nextTick(() => {
                                this.initEchart(
                                    'materialPie',
                                    this.initPieConsumeData(this.materialPieData, this.materialPieTotal)
                                )
                            })
                        } else {
                            this.materialPieVisible = false
                        }
                    } else {
                        this.materialPieVisible = false
                    }
                }
            })
        },
        // 素材产出消耗饼图
        initPieConsumeData(pieData, pieTotal) {
            const list = pieData
            let option = {
                tooltip: {
                    trigger: 'item',
                    formatter: function (obj) {
                        if (pieTotal == 0) {
                            return obj.name + ':' + obj.value + '(0%)'
                        } else {
                            return obj.name + ':' + obj.value + '(' + Math.round((obj.value / pieTotal) * 100) + '%)'
                        }
                    },
                },
                legend: {
                    top: '20%',
                    orient: 'vertical',
                    right: '0%',
                    textStyle: {
                        //图例文字的样式
                        fontSize: 12,
                    },
                    icon: 'circle',
                    itemStyle: {
                        borderCap: 'round',
                    },
                    itemGap: 20,
                    itemWidth: 15,
                    itemHeight: 10,
                    padding: [-45, 0, 0, 80],
                    bottom: '55%',
                    formatter: function (name) {
                        //该函数用于设置图例显示后的百分比
                        var data = list
                        var total = 0
                        var value
                        list.forEach((item) => {
                            total += item.value
                            if (item.name == name) {
                                value = item.value
                            }
                        })
                        var p = total == 0 ? 0 : Math.round((value / total) * 100) //求出百分比
                        return p >= 10
                            ? p == 11
                                ? `${name} ${'|'} ${p}% `
                                : `${name} ${'|'} ${p}% `
                            : `${name} ${'|'} ${p}% ` //返回出图例所显示的内容是名称+百分比
                    },
                },
                color: ['#FF3300', '#FFCC00', '#6600FF', '#3399FF', '#66FFFF', '#66CC99'],
                series: [
                    {
                        type: 'pie',
                        radius: ['65%', '75%'],
                        avoidLabelOverlap: false,
                        hoverAnimation: true,
                        itemStyle: {
                            borderRadius: 10,
                            borderColor: '#fff',
                            borderWidth: 2,
                        },
                        // label: {
                        //     show: false,
                        //     position: 'center',
                        //     formatter: function (name) {
                        //         return name.value
                        //     },
                        //     color: 'black',
                        // },
                        label: {
                            show: true,
                            position: 'center',
                            fontSize: 16,
                            formatter: function (param) {
                                return (pieTotal / 10000).toFixed(2) + 'w' + '\r\n\r\n素材总消耗'
                            },
                            textStyle: {
                                fontSize: 16,
                                color: 'black',
                            },
                        },
                        emphasis: {
                            label: {
                                show: true,
                                fontSize: '16',
                            },
                        },
                        left: 0,
                        right: '50%',
                        top: 0,
                        bottom: '20%',
                        labelLine: {
                            show: false,
                        },
                        data: list,
                    },
                ],
            }
            return option
        },
        getMedioData() {
            this.spinningMedio = true
            this.getAction(process.env.VUE_APP_BASE_MATERIAL_URL + '/manager/company/getMediaData', {
                companyId: this.parameterData().companyId,
            }).then((res) => {
                this.spinningMedio = false
                if (res.code == 200) {
                    if (res.result) {
                        this.medioDataVisible = true
                        this.medioKsData = res.result.ksdata
                        this.medioTtData = res.result.ttdate
                        this.$nextTick(() => {
                            this.initEchart('medioDataLine', this.initmedioData(this.medioKsData, this.medioTtData))
                        })
                    } else {
                        this.medioDataVisible = false
                    }
                }
            })
        },
        initmedioData(ksdata, ttdata) {
            let option = {
                title: {
                    text: '',
                },
                color: ['rgb(253,63,152)', 'rgb(102,128,255)', '#FBE6F3', '#E9EDFF', '#8A2BE2', '#3CB371'],
                tooltip: {},
                tooltip: {
                    trigger: 'axis',
                    position: function (pt) {
                        return [pt[0], '10%']
                    },
                },
                legend: {
                    data: ['快手', '头条'],
                    textStyle: {
                        fontSize: 12,
                        color: '#B0C4DE',
                    },
                    left: '0%',
                },
                grid: {
                    left: 0,
                    right: 0,
                    containLabel: true,
                },
                xAxis: {
                    type: 'category',

                    show: false,
                    data: ksdata.map((item) => {
                        return item.statDate
                    }),
                    axisLabel: {
                        show: true,
                        textStyle: {
                            color: '#B0C4DE',
                        },
                    },
                    axisLine: {
                        //x轴线
                        show: true,
                        lineStyle: {
                            color: '#B0C4DE',
                        },
                    },
                },
                yAxis: {
                    type: 'value',
                    show: false,
                    axisLabel: {
                        show: true,
                        textStyle: {
                            color: '#B0C4DE',
                        },
                    },
                    axisLine: {
                        //x轴线
                        show: true,
                        lineStyle: {
                            color: '#B0C4DE',
                        },
                    },
                    splitLine: {
                        show: true,
                        lineStyle: {
                            color: '#B0C4DE',
                        },
                    },
                },
                series: [
                    {
                        name: '快手',
                        type: 'line',
                        data: ksdata.map((item) => {
                            return item.allCost
                        }),
                        areaStyle: {
                            color: '#FBE6F3',
                        },
                        smooth: true,
                        symbol: 'circle',
                        symbolSize: 3,
                    },
                    {
                        name: '头条',
                        type: 'line',
                        data: ttdata.map((item) => {
                            return item.allCost
                        }),
                        areaStyle: {
                            color: '#E9EDFF',
                        },
                        smooth: true,
                        symbol: 'circle',
                        symbolSize: 3,
                    },
                ],
            }
            return option
        },
        //查询本月总消耗
        getTotalConsume() {
            this.spinningTarget = true
            this.getAction(process.env.VUE_APP_BASE_MATERIAL_URL + '/manager/company/getTotalConsume', {
                companyId: this.parameterData().companyId,
                mediaId: this.parameterData().mediaId,
            }).then((res) => {
                this.spinningTarget = false
                if (res.code == 200) {
                    if (res.result.targetValue) {
                        this.completeEchartValue = parseFloat(res.result.targetValue)
                        if (parseFloat(res.result.totalConsume) > parseFloat(res.result.targetValue)) {
                            this.completePercent = 100
                        } else {
                            this.completePercent =
                                ((parseFloat(res.result.totalConsume) / parseFloat(res.result.targetValue)).toFixed(2) *
                                100).toFixed(2)
                        }

                        this.totalConsume = parseFloat(res.result.totalConsume)
                    } else {
                        this.completePercent = 0
                        this.totalConsume = parseFloat(res.result.totalConsume)
                        this.completeEchartValue = 0
                    }
                }
            })
        },
        okValue() {
            this.getAction(process.env.VUE_APP_BASE_MATERIAL_URL + '/manager/company/setConsumeValue', {
                companyId: this.parameterData().companyId,
                mediaId: this.parameterData().mediaId,
                targetValue: this.completeEchartValue,
            }).then((res) => {
                if (res.code == 200) {
                    this.getTotalConsume()
                } else {
                    this.$message.error('设置失败')
                }
            })
        },
        getRealTimeData() {
            this.spinningAllData = true
            this.allData = null
            this.getAction(process.env.VUE_APP_BASE_MATERIAL_URL + '/manager/company/getRealTimeData', {
                companyId: this.parameterData().companyId,
                mediaId: this.parameterData().mediaId,
            }).then((res) => {
                this.spinningAllData = false
                if (res.code == 200) {
                    if (res.result) {
                        this.allData = res.result
                    } else {
                        this.allData = null
                    }
                } else {
                    this.$message.error(res.message)
                }
            })
        },
        //TOP10
        getTopTenData() {
            this.spinningTop = true
            this.getAction(process.env.VUE_APP_BASE_MATERIAL_URL + '/manager/company/getProjectConsumeTop', {
                ...this.parameterData(),
            }).then((res) => {
                this.spinningTop = false
                if (res.code == 200) {
                    var servicedata = res.result
                    // if (servicedata.length > 0) {
                    this.topVisible = true
                    this.topData = res.result
                    let num = 0

                    this.$nextTick(() => {
                        this.initEchart('topEcharts', this.initTopTenData(this.topData))
                    })
                    // } else {
                    //     this.topVisible = false
                    // }
                }
            })
        },
        initTopTenData(topDataAll) {
            var topData = JSON.parse(JSON.stringify(topDataAll))
            topData = topData.sort(function (a, b) {
                return a.allCost - b.allCost
            })
            var option = {
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow',
                    },
                },
                grid: {
                    left: '0%',
                    right: '3%',
                    bottom: '3%',
                    top: 0,
                    containLabel: true,
                },
                color: ['#009726', '#FFA500', '#8A2BE2', '#3CB371'],
                xAxis: {
                    type: 'value',
                    // boundaryGap: [0, 0.01],
                    nameTextStyle: {
                        width: 10,
                        overflow: 'truncate',
                    },
                    axisTick: {
                        interval: 2,
                    },
                    axisLabel: {
                        show: true,
                        interval: 2,
                        rotate: 45,
                    },
                },
                yAxis: {
                    type: 'category',
                    data: topData.map((item) => {
                        return item.projectName
                    }),
                    nameTextStyle: {
                        width: '10%',
                        overflow: 'truncate',
                    },
                    axisTick: {
                        interval: 2,
                    },
                },
                series: [
                    {
                        type: 'bar',
                        data: topData.map((item) => {
                            return item.allCost
                        }),
                        showBackground: true,
                        backgroundStyle: {
                            color: '#E6F5EA',
                        },
                        barWidth: 15,
                        itemStyle: {
                            borderRadius: 15,
                        },
                    },
                ],
            }
            return option
        },
        topTypeChange() {
            if (this.topType == 'b') {
                this.$nextTick(() => {
                    this.initEchart('topEcharts', this.initTopTenData(this.topData))
                })
            }
        },
    },
    mounted() {
        this.clientWidth = document.documentElement.clientWidth - 224
        this.$nextTick(() => {
            this.getProjectList()
            this.getUserCampany()
                .then((res) => {
                    this.getMetarialList()
                    this.getOperateList()
                    this.getMaterialConsumeData()
                    this.getMedioData()
                    this.getTotalConsume()
                    this.getRealTimeData()
                    this.getRealTimeData()
                    this.getTopTenData()
                })
                .catch(() => {
                    this.$message.error('未能获取到所属公司，请查看配置后重进页面！')
                })

            // this.getData()
        })
    },
    activated() {
        this.$nextTick(() => {
            this.clientWidth = document.documentElement.clientWidth - 224
        })
    },
}
</script>
<style lang="less" scoped>
.materialReport {
    .material-report-card-two {
        width: 25%;
    }

    .material-report-card {
        height: 320px;
        ::v-deep .ant-card-body {
            padding-top: 5px;
        }
        .report-card-result {
            height: 88px;
        }
        .report-card-money {
            font-size: 30px;
            font-weight: bold;
        }
        .report-card-msg {
            display: flex;
            justify-content: space-between;
            font-size: 14px;
            margin-top: 20px;
        }
        .report-card-line {
            width: 100%;
            height: 1px;
            margin-top: 20px;
            background: #e8e8e8;
        }
        .report-card-radio {
            display: flex;
            justify-content: space-between;
            margin-top: 12px;
            font-size: 14px;
        }
    }
    .option {
        background: white;
        padding: 20px;
        display: flex;
        justify-content: flex-start;
        flex-wrap: wrap;
        .item {
            margin-right: 15px;
            margin-bottom: 15px;
            height: 32px;
            line-height: 32px;
            flex-shrink: 0;
            span {
                margin-right: 10px;
            }
        }
    }
    .echart {
        margin-top: 20px;
        padding: 0 20px 20px;
        background: white;
        .echart-header {
            padding: 20px 0;
            font-size: 15px;
            font-weight: 600;
        }
    }
    .tableBody {
        margin-top: 20px;
    }
}
</style>
<style>
.materialReport .card-containers {
    overflow: hidden !important;
}
.materialReport .card-containers > .ant-tabs-card > .ant-tabs-content {
    margin-top: -16px !important;
}

.materialReport .card-containers > .ant-tabs-card > .ant-tabs-content > .ant-tabs-tabpane {
    background: #fff !important;
}

.materialReport .card-containers > .ant-tabs-card > .ant-tabs-bar {
    border-color: #fff !important;
}

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

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