<template>
    <div class="laborCostStatistics">
        <div class="laborCostStatistics-head">
            <el-row>
                <el-col :span="4">
                    <span class="mr-10" style="color: #999;">图表Y轴{{ parentDeptId }}</span>
                    <el-radio-group v-model="chartYAxis" size="small" @change="subtypeSwitching">
                        <el-radio-button label="workingHours" v-if="permissions.countHours">显示工时</el-radio-button>
                        <el-radio-button label="cost" v-if="permissions.countCost">显示成本</el-radio-button>
                    </el-radio-group>
                </el-col>
                <el-col :span="18">
                    <template v-if="user.timeType.fixMonthcost == 0">
                        <el-date-picker size="small" v-model="chartDate" class="mr-10" style="width: 260px;"
                            :editable="false" @change="filterConditionSwitching" format="yyyy-MM-dd"
                            value-format="yyyy-MM-dd" :clearable="false" :range-separator="$t('other.to')"
                            type="daterange" :start-placeholder="$t('time.startDate')"
                            :end-placeholder="$t('time.endDate')"></el-date-picker>
                    </template>
                    <template v-if="user.timeType.fixMonthcost == 1">
                        <el-date-picker v-model="chartDate" class="mr-10" style="width: 260px;" :editable="false"
                            size="small" format="yyyy-MM" value-format="yyyy-MM" :clearable="false" type="month"
                            @change="filterConditionSwitching"></el-date-picker>
                    </template>
                    <el-radio-group v-model="singleChoiceType" size="small" :disabled="radioLoading"
                        @change="filterConditionSwitching" style="margin-right: 10px;">
                        <el-radio-button :label="$t('other.project')"></el-radio-button>
                        <el-radio-button :label="$t('zhu-xiang-mu')"
                            v-if="user.timeType.mainProjectState"></el-radio-button>
                        <el-radio-button :label="$t('projectclassification')"
                            v-if="user.companyId != '1071'"></el-radio-button>
                        <el-radio-button :label="'设备'" v-if="devicePermissions"></el-radio-button>
                        <el-radio-button :label="$t('lable.department')"
                            v-if="(permissions.viewAllSummary || permissions.viewMagDeptSummary)"></el-radio-button>
                        <el-radio-button :label="$t('ren-yuan')" v-if="permissions.countPersonnel"></el-radio-button>
                        <el-radio-button label="工单" v-if="user.companyId == 7536"></el-radio-button>
                        <el-radio-button :label="namess"
                            v-if="jichu.customDegreeActive == 1 && !jichu.customDegreeMultiple"></el-radio-button>
                        <el-radio-button v-for="item in theCustomList" :key="item.id"
                            :label="item.name"></el-radio-button>
                    </el-radio-group>

                    <div v-show="singleChoiceType == '部门' && parentDeptId">
                        <el-button @click="backToParentDept" size="small">返回上级</el-button>
                    </div>

                    <el-select v-model="projectStatus" placeholder="请选择项目状态" clearable @change="filterConditionSwitching" v-if="singleChoiceType == '项目'" size="small" style="margin-right: 10px">
                        <el-option label="进行中" value="1"></el-option>
                        <el-option label="已完成" value="2"></el-option>
                        <el-option label="已撤销" value="3"></el-option>
                        <el-option label="暂停" value="4"></el-option>
                    </el-select>

                    <select-project v-model="chartProjectId" :size="'small'" :placeholder="'请选择项目'" clearable
                        v-if="singleChoiceType == '项目' || singleChoiceType == '设备' || singleChoiceType == namess"
                        @change="filterConditionSwitching"></select-project>
                    <select-personnel v-model="chartUserId" v-if="singleChoiceType == '人员'"
                        @change="filterPersonnel"></select-personnel>
                </el-col>
                <el-col :span="2" style="display: flex;justify-content: flex-end;">
                    <el-button @click="reportExportCustomization" size="small" :loading="reportExportLoading"
                        v-if="user.companyId == 7536">报表导出</el-button>
                    <el-button @click="exportTheCustomListFlg" size="small" :loading="theCustomListFlgBtnLoading"
                        v-else-if="theCustomListFlg">报表导出</el-button>
                    <el-button @click="showExportDialog" size="small" v-else>报表导出</el-button>
                </el-col>
            </el-row>
        </div>
        <div class="laborCostStatistics-con">
            <div ref="echartsRef" id="echartsRef" :style="`width: 100%; height: 100%; overflow-x: auto;`"
                v-loading="echartsLoading">
                <EchartsEchar :options="echartsEcharData" :widthHtval="widthHtval" clickOnTheEvent
                    @chartClickEvents="chartClickEvents"></EchartsEchar>
            </div>
        </div>
        <div class="laborCostStatistics-end">
            <div>
                <template v-if="singleChoiceType == '项目'">
                    <el-radio-group v-model="nameNumber" size="small" @change="subtypeSwitching">
                        <el-radio-button label="1">{{ $t('headerTop.projectName') }}</el-radio-button>
                        <el-radio-button label="2">{{ user.companyId == '7030' ? '项目令号' : '项目编号' }}</el-radio-button>
                    </el-radio-group>
                </template>
                <template v-if="singleChoiceType == '部门' && this.parentDeptId">
                    <el-radio-group v-model="departmentPersonnel" @change="departmentPersonnelSwitch" size="small">
                        <el-radio-button label="1">{{ $t('lable.department') }}</el-radio-button>
                        <el-radio-button label="2">{{ $t('ren-yuan') }}</el-radio-button>
                    </el-radio-group>
                </template>
            </div>
            <el-pagination :current-page="pageIndex" :page-sizes="[50]" :page-size="50"
                @current-change="echartsCurrentChange" layout="total, sizes, prev, pager, next" :total="pageTotal">
            </el-pagination>
        </div>

        <!-- 报表导出 -->
        <cost-report-export v-model="reportExportVisable" ref="reportExportDisRef" :singleChoiceType="singleChoiceType"
            :hasReportUserList="hasReportUserList" :chartDate="chartDate" :theCustomListId="theCustomListId"
            :theCustomListPlant="theCustomListPlant"></cost-report-export>
    </div>
</template>
<script>
import selectProject from "../../components/selectProject.vue";
import selectPersonnel from "../../components/selectPersonnel.vue";
import EchartsEchar from "../../components/echartsEchar.vue"
import costReportExport from "./costReportExport.vue";
import { barChartOptions } from "./project";
export default {
    components: {
        selectProject,
        selectPersonnel,
        EchartsEchar,
        costReportExport
    },
    data() {
        return {
            user: JSON.parse(sessionStorage.getItem("user")),
            permissions: JSON.parse(sessionStorage.getItem("permissions")),
            chartYAxis: 'workingHours',
            chartDate: [],
            singleChoiceType: sessionStorage.radio != null ? sessionStorage.radio : this.$t('other.project'),
            chartProjectId: '',
            chartUserId: '',
            chartDeptId: '',
            radioLoading: false,
            jichu: [],
            chartYAxisVal: { workingHours: '1', cost: '0' },
            theCustomList: [], // 自定义数据来源
            theCustomListFlg: false, // 判断是否点击的是自定义配置的数据来源
            theCustomListId: '',
            theCustomListPlantLIst: [],
            theCustomListPlant: '',
            pageIndex: 1,
            pageTotal: 0,
            nameNumber: 1, // 项目， 编号
            departmentPersonnel: 1, // 部门， 人员
            parentDeptId: '', // 部门详情的部门和人员切换显示
            echartsLoading: false,
            echartsEcharData: {}, // 图表数据源
            totalHours: 0, // 总小时
            allListData: [],
            personnelAll: [],
            personnelAllPlly: [],
            widthHtval: document.body.clientWidth - 230, // 图表宽度  
            params: null,
            jichu: '',
            namess: '',
            devicePermissions: false,
            chartDataSource: [], // 图表数据源
            parentDeptStack: [],
            reportExportVisable: false,
            hasReportUserList: [],
            theCustomListFlgBtnLoading: false,
            projectStatus: '',
        }
    },

    methods: {
        filterPersonnel(id, name) {
            this.pageIndex = 1
            if(!id) {
                this.filterConditionSwitching()
            }
            if (this.chartUserId) {
                let arrList = JSON.parse(JSON.stringify(this.personnelAllPlly))
                const arr = arrList.list.filter(item => item.name == name)
                arrList.list = arr
                this.allListData = arrList
                if (this.user.userNameNeedTranslate === 1) {
                    const dealWithList = arr.map(item => ({
                        type: item.type,
                        id: item.name
                    }));
                    this.dealWithTranslationPlone(dealWithList);
                } else {
                    this.initialChartData();
                }
            }
        },
        async exportTheCustomListFlg() {
            this.theCustomListFlgBtnLoading = true;
            try {
                await this.$refs['reportExportDisRef'].exportProjectData();
            } catch (error) {
                console.error("错误信息", error);
            } finally {
                this.theCustomListFlgBtnLoading = false;
            }
        },
        getEchart() { // 获取图表数据
            const { timeType: { fixMonthcost } } = this.user;
            sessionStorage.radio = this.singleChoiceType;
            this.radioLoading = true;
            const param = this.chartDate ? {
                startDate: fixMonthcost === 0 ? this.chartDate[0] : this.chartDate,
                endDate: fixMonthcost === 0 ? this.chartDate[1] : this.chartDate
            } : {};

            const urlMap = {
                ['项目']: {
                    url: this.port.project.listCost,
                    extraParams: { projectId: this.chartProjectId, type: this.chartYAxisVal[this.chartYAxis], status: this.projectStatus ? this.projectStatus : '0' }
                },
                ['主项目']: { url: '/project/getTimeCostByMainProject' },
                ['项目分类']: { url: '/project/getTimeCostByCategory' },
                ['部门']: {
                    url: this.port.project.depCost,
                    extraParams: { parentDeptId: this.parentDeptId },
                    callback: () => { this.departmentadio = '1'; }
                },
                ['人员']: {
                    callback: () => {
                        this.getUserCostList();
                        return true;
                    }
                },
                ['设备']: {
                    url: '/device-log/getDeviceTimeCost',
                    extraParams: { projectId: this.chartProjectId }
                },
                ['工单']: {
                    url: '/project/getTimeCostByWorkNum',
                    extraParams: { }
                },
                [this.namess]: {
                    url: '/project/getDegreeCost',
                    extraParams: { projectId: this.chartProjectId }
                }
            };

            const customConfig = {
                url: '/project/getTimeCostByUserCustom',
                extraParams: { customId: this.theCustomListId, fieldName: this.theCustomListPlant }
            };

            const config = this.theCustomListFlg ? customConfig : urlMap[this.singleChoiceType];

            if (config) {
                if (config.callback && config.callback()) {
                    return;
                }

                Object.assign(param, config.extraParams);
                const url = config.url;

                // 这里可以继续处理 url 和 param，例如发送请求等
                this.postData(url, param).then((res) => {
                    this.processingRequestData(res.data)
                }).finally(() => {
                    this.radioLoading = false
                })
            }
        },
        processingRequestData(data) { // 处理请求数据
            const { userNameNeedTranslate } = this.user

            // let accumulateNumbers = 0
            // if (this.singleChoiceType == '项目' || this.singleChoiceType == '主项目' || this.singleChoiceType == '项目分类') {
            //     for (let i in data.costList) {
            //         accumulateNumbers += parseFloat(data.costList[i].cost)
            //     }
            // } else if (this.singleChoiceType == '部门') {
            //     for (let i in data.costList) {
            //         accumulateNumbers += parseFloat(data.costList[i].costTime)
            //     }
            // } else if (this.singleChoiceType == this.namess) {
            //     for (let i in data) {
            //         accumulateNumbers += parseFloat(data[i].cost)
            //     }
            // } else if (this.theCustomListFlg) {
            //     for (let i in data.list) {
            //         accumulateNumbers += parseFloat(data.list[i].cost)
            //     }
            // }
            // this.totalHours = accumulateNumbers

            let accumulateNumbers = 0;
            const costList = data.costList || data.list || data;
            const costKey = this.singleChoiceType === '部门' ? 'costTime' : 'cost';

            if (Array.isArray(costList)) {
                accumulateNumbers = costList.reduce((sum, item) => sum + parseFloat(item[costKey] || 0), 0);
            } else if (typeof costList === 'object') {
                accumulateNumbers = Object.values(costList).reduce((sum, item) => sum + parseFloat(item[costKey] || 0), 0);
            }

            // additionName // 未转译的数据另外存储一份，用作 DOM 上渲染
            if (userNameNeedTranslate == 1) {
                for (var i in costList) {
                    costList[i].additionName = data.costList[i].departmentName
                }
            }

            this.totalHours = accumulateNumbers;
            this.allListData = data

            if (userNameNeedTranslate == 1 && this.singleChoiceType == '部门') {
                const arr = this.allListData.costList.map(item => ({
                    type: item.type,
                    id: item.departmentName
                }));
                this.dealWithTranslation(arr)
            } else {
                this.initialChartData()
            }
        },
        subtypeSwitching() {
            this.initialChartData()
        },
        departmentPersonnelSwitch() { // 部门人员切换显示
            const typeIndex = this.departmentPersonnel
            if (typeIndex == '1') {
                this.getEchart()
            } else {
                this.getUserCostList(this.parentDeptId)
            }
        },
        initialChartData() { // 初始图表数据
            let list = []
            let totalMoneyCost = ((this.singleChoiceType == '项目' || this.singleChoiceType == '项目分类') ? this.allListData.totalMoneyCost : this.allListData.totalCostMoney);
            let newBarChartOptions = { ...barChartOptions }

            // 先将数据置空，防止数据残留
            this.echartsEcharData = [{ data: [] }]
            
            // 分页数据
            if (this.singleChoiceType != '人员' && this.departmentPersonnel != 2) {
                this.pageTotal = this.allListData.costList ? this.allListData.costList.length : 0
                list = this.allListData.costList && this.allListData.costList.slice(0 + 10 * (this.pageIndex - 1), 49 + 50 * (this.pageIndex - 1))

                if (list && list.length > 20) {
                    this.widthHtval += Math.max(0, list.length - 20) * 40;
                } else {
                    this.widthHtval = document.body.clientWidth - 230
                }
            }
            if (this.singleChoiceType == '项目') {
                newBarChartOptions = this.processProjectChartData(list, totalMoneyCost, newBarChartOptions)
            } else if (this.singleChoiceType == '主项目') {
                newBarChartOptions = this.processingMainProjectChartData(list, totalMoneyCost, newBarChartOptions)
            } else if (this.singleChoiceType == '项目分类') {
                newBarChartOptions = this.projectClassificationChartData(list, totalMoneyCost, newBarChartOptions)
            } else if (this.singleChoiceType == '设备') {
                newBarChartOptions = this.equipmentChartData(list, totalMoneyCost, newBarChartOptions)
            } else if (this.singleChoiceType == '部门' && this.departmentPersonnel != 2) {
                newBarChartOptions = this.processDepartmentalChartData(list, totalMoneyCost, newBarChartOptions)
            } else if (this.singleChoiceType == '人员' || this.departmentPersonnel == 2) {
                newBarChartOptions = this.personnelChartData(totalMoneyCost)
            } else if (this.theCustomListFlg) {
                this.pageTotal = this.allListData.list ? this.allListData.list.length : 0
                list = this.pageTotal ? this.allListData.list.slice(0 + 50 * (this.pageIndex - 1), 49 + 50 * (this.pageIndex - 1)) : []
                newBarChartOptions = this.theCustomListFlgChartData(list, totalMoneyCost, newBarChartOptions)
            } else if (this.singleChoiceType == this.namess) {
                this.pageTotal = this.allListData ? this.allListData.length : 0
                list = this.allListData.slice(0 + 10 * (this.pageIndex - 1), 49 + 50 * (this.pageIndex - 1))
                newBarChartOptions = this.namessChartData(list, totalMoneyCost, newBarChartOptions)
            } else if (this.singleChoiceType == '工单') {
                newBarChartOptions = this.workOrderChartData(list, totalMoneyCost, newBarChartOptions)
            } 

            console.log({ ...newBarChartOptions }, '<==== 图表数据')
            this.echartsEcharData = { ...newBarChartOptions }
        },
        workOrderChartData(list, totalMoneyCost = 0, chartData) { // 工单图表数据
            let xList = [], yList = [], totalHours = 0;
            const yAxisValue = this.chartYAxisVal[this.chartYAxis]
            const { countCost, countHours } = this.permissions
            for (let i in list) {
                xList.push(this.nameNumber == '1' ? list[i].workNum : list[i].workNum);

                let item = {
                    "value": yAxisValue == 0 ? (list[i].costMoney ? list[i].costMoney.toFixed(2) : 0) || list[i].costMoney : (list[i].cost ? list[i].cost.toFixed(1) : 0),
                    "id": list[i].id || i,
                }
                if (countCost) {
                    item.money = (list[i].costMoney ? list[i].costMoney.toFixed(2) : 0)
                }
                if (countHours) {
                    item.cost = list[i].cost
                    totalHours += parseFloat(list[i].cost);
                }
                yList.push(item);
            }

            totalHours = this.totalHours.toFixed(1);
            totalMoneyCost = totalMoneyCost.toFixed(2)

            return { ...this.sameChartProcessing(xList, yList, totalHours, totalMoneyCost, chartData) }
        },
        equipmentChartData(list, totalMoneyCost = 0, chartData) { // 设备图表数据
            let xList = [], yList = [], totalHours = 0;
            const yAxisValue = this.chartYAxisVal[this.chartYAxis]
            const { countCost, countHours } = this.permissions

            for (let i in list) {
                xList.push(list[i].projectName);
                let item = {
                    "value": yAxisValue == 0 ? (list[i].costMoney ? list[i].costMoney.toFixed(2) : 0) || list[i].costMoney : (list[i].cost ? list[i].cost.toFixed(1) : 0),
                    "id": list[i].id || i,
                }
                if (countCost) {
                    item.money = (list[i].costMoney ? list[i].costMoney.toFixed(2) : 0)
                }
                if (countHours) {
                    item.cost = list[i].cost
                    totalHours += parseFloat(list[i].cost);
                }
                yList.push(item);
            }

            totalHours = this.totalHours.toFixed(1);
            totalMoneyCost = totalMoneyCost.toFixed(2)

            return { ...this.sameChartProcessing(xList, yList, totalHours, totalMoneyCost, chartData) }
        },
        theCustomListFlgChartData(list, totalMoneyCost = 0, chartData) { // 不知道啥东西
            let xList = [], yList = [], totalHours = 0;
            const yAxisValue = this.chartYAxisVal[this.chartYAxis]
            const { countCost, countHours } = this.permissions
            for (var i in list) {
                xList.push(list[i].name);
                let item = {
                    "value": yAxisValue == 0 ? list[i].costMoney : list[i].cost,
                    "id": list[i].id || i,
                }
                if (countCost) {
                    item.money = list[i].costMoney ? list[i].costMoney.toFixed(2) : 0
                    totalMoneyCost += parseFloat(list[i].costMoney);
                }
                if (countHours) {
                    item.cost = list[i].cost
                    totalHours += parseFloat(list[i].cost);
                }
                yList.push(item);
            }

            totalHours = this.totalHours.toFixed(1);
            totalMoneyCost = totalMoneyCost.toFixed(2);

            return { ...this.sameChartProcessing(xList, yList, totalHours, totalMoneyCost, chartData) }
        },
        namessChartData(list, totalMoneyCost = 0, chartData) { // namess 图表数据
            let xList = [], yList = [], totalHours = 0;
            const yAxisValue = this.chartYAxisVal[this.chartYAxis]
            const { countCost, countHours } = this.permissions
            for (var i in list) {
                xList.push(list[i].name);
                let item = {
                    "value": yAxisValue == 0 ? list[i].costMoney : list[i].cost,
                    "id": list[i].id || i,
                }
                if (countCost) {
                    item.money = list[i].costMoney ? list[i].costMoney.toFixed(2) : 0
                    totalMoneyCost += parseFloat(list[i].costMoney);
                }
                if (countHours) {
                    item.cost = list[i].cost
                    totalHours += parseFloat(list[i].cost);
                }
                yList.push(item);
            }

            totalHours = this.totalHours.toFixed(1);
            totalMoneyCost = totalMoneyCost.toFixed(2);

            return { ...this.sameChartProcessing(xList, yList, totalHours, totalMoneyCost, chartData) }
        },
        personnelChartData() { // 人员图表数据
            const { countCost, countHours } = this.permissions
            const { list, userList, totalCostMoney } = this.allListData;
            const startIndex = 50 * (this.pageIndex - 1);
            const endIndex = startIndex + 49;

            // 数量数据
            // list = [...list, ...list, ...list, ...list, ...list, ...list, ...list, ...list, ...list, ...list, ...list, ...list, ...list, ...list, ...list, ...list, ...list, ...list, ...list, ...list, ...list, ...list, ...list, ...list, ...list, ...list, ...list, ...list]

            const _this = this;
            const xList = [];
            const yList = [];
            const array = [];
            const series = [];
            const yAxisValue = this.chartYAxisVal[this.chartYAxis]
            const paginatedList = list.slice(startIndex, endIndex);

            let totalHours = this.totalHours.toFixed(1);
            let totalMoneyCost = totalCostMoney;

            this.hasReportUserList = userList;
            this.pageTotal = list ? list.length : 0;

            if (list && list.length > 20) {
                this.widthHtval += Math.max(0, list.length - 20) * 40;
            } else {
                this.widthHtval = document.body.clientWidth - 230
            }

            if (paginatedList.length > 0) {
                let num = paginatedList.length == 0 ? 0 : paginatedList[0].project.length;
                for (var i in paginatedList) {
                    xList.push(paginatedList[i].name);
                    var pro = paginatedList[i].project;
                    for (var j in pro) {
                        if (array.indexOf(pro[j].project) == -1) {
                            array.push(pro[j].project)
                        }
                    }
                }

                for (var i in array) {
                    yList.push(array[i]);
                    let dataList = [];
                    let nameObj = {}
                    list.forEach(item => {
                        let moneyTol = 0;
                        let timeTol = 0;
                        item.project.forEach((project, index) => {
                            moneyTol += +project.money;
                            timeTol += +project.time;
                        });
                        // 假设每个 item.project 都至少有一个元素
                        if (item.project.length > 0) {
                            const lastProject = item.project[item.project.length - 1];
                            nameObj[item.name] = { moneyTol: moneyTol, timeTol: timeTol }
                            lastProject.moneyTol = moneyTol;
                            lastProject.timeTol = timeTol;
                        }
                    });

                    for (var j in paginatedList) {
                        let project = paginatedList[j].project, num = 0;
                        if (project.length != 0) {
                            for (var k in project) {
                                if (project[k].project == array[i]) {
                                    let item = {
                                        "value": yAxisValue == 0 ? project[k].money : project[k].time,
                                    }
                                    if (countCost) {
                                        item.money = project[k].money
                                    }
                                    if (countHours) {
                                        item.cost = project[k].time
                                    }
                                    if (project[k].moneyTol) {
                                        item.moneyTol = project[k].moneyTol
                                        item.timeTol = project[k].timeTol
                                    }
                                    dataList.push(item)

                                } else {
                                    num++;
                                }
                                if (k == project.length - 1 && num != project.length - 1) {
                                    dataList.push({
                                        "value": 0,
                                        "cost": 0,
                                        "money": 0,
                                    })
                                }
                            }
                        } else {
                            dataList.push({
                                "value": 0,
                                "cost": 0,
                                "money": 0,
                            })
                        }
                    }

                    let cerName = array[array.length - 1] // 最后一个项目
                    series.push({
                        name: array[i],
                        type: 'bar',
                        stack: '1',
                        barMaxWidth: 30,
                        data: dataList,
                        label: {
                            normal: {
                                show: true,
                                position: 'top',
                                formatter: function (params) {
                                    const { seriesName, data, name } = params
                                    if (!name) {
                                        return ''
                                    }
                                    const unit = yAxisValue == 0 ? _this.$t('yuan') : 'h';
                                    const totalValue = yAxisValue == 0 ? nameObj[name] && nameObj[name].moneyTol : nameObj[name] && nameObj[name].timeTol;
                                    const dayValue = yAxisValue == 0 ? 0 : nameObj[name] && (nameObj[name].timeTol/_this.user.timeType.allday).toFixed(1);
                                    return seriesName === cerName ? `${totalValue ? totalValue.toFixed(1) : 0} ${unit}${yAxisValue == 0?'':('/'+dayValue+'人天')}` : '';
                                }
                            }
                        }
                    });
                }
            }

            let chartData = { ...barChartOptions }
            totalMoneyCost = totalMoneyCost.toFixed(2)
            chartData.title = {
                ...chartData.title,
                text: `工时成本总计：${countCost ? `成本 ${totalMoneyCost},` : ''} ${countHours ? `时长 ${totalHours} 小时` : ''}`
            }

            chartData.legend = {
                x: 80,
                y: 10,
                data: yList,
                show: true,
                top: "5%",
            }
            chartData.toolbox = {
                show: true,
                feature: {
                    saveAsImage: {
                        show: this.user.userNameNeedTranslate == 1 ? false : true
                    },
                    restore: {
                        show: true
                    },
                    magicType: {
                        type: ['line', 'bar']
                    }
                }
            }

            chartData.tooltip = {
                trigger: 'axis',
                formatter: function (params, ticket, callback) {
                    var totalTime = 0;
                    var totalCost = 0;
                    var res = "";
                    for (var i in params) {
                        if (params[i].data.value > 0) {
                            res += "<div style='margin-top:3px;font-size:12px;'><font color='#ddd'>" + _this.$t('headerTop.projectName') + "：" + params[i].seriesName
                                + "</font><br/>" +
                                ((_this.permissions.countCost) ? _this.$t('workcost') + ":" + params[i].data.money + _this.$t('yuan') + "</br>" : '') +
                                ((_this.permissions.countHours) ? _this.$t('screening.workTime') + ":" + params[i].data.cost + _this.$t('time.hour') + "</br>" : '') + "</div>";
                            totalTime += Number(params[i].data.cost);
                            totalCost += Number(params[i].data.money);
                        }
                    }
                    if (_this.user.userNameNeedTranslate != 1) {
                        res = res + '<br/>' + params[0].name + '<br/>' + _this.$t('zong-ji') + '：' +
                            ((_this.permissions.countHours) ? totalTime.toFixed(1) + _this.$t('time.hour') : '') +
                            ((_this.permissions.countCost) ? totalCost.toFixed(2) + _this.$t('yuan') : '') +
                            "<br/>";
                    } else {
                        res = res + '<br/>' + '' + '<br/>' + _this.$t('zong-ji') + '：' +
                            ((_this.permissions.countHours) ? totalTime.toFixed(1) + _this.$t('time.hour') : '') +
                            ((_this.permissions.countCost) ? totalCost.toFixed(2) + _this.$t('yuan') : '') +
                            "<br/>";
                    }

                    return res;
                }
            }

            chartData.xAxis = {
                data: xList,
                axisLabel: {
                    interval: 0, rotate: 20
                }
            }

            chartData.yAxis = {
                type: 'value',
                axisLabel: {
                    formatter: yAxisValue == 0 ? '{value} (' + this.$t('yuan') + ')' : '{value} (' + this.$t('time.hour') + ')'
                }
            }

            chartData.series = series;
            return { ...chartData }
            // return this.processingPersonnelChartData(totalHours, totalMoneyCost)
        },
        processDepartmentalChartData(list, totalMoneyCost = 0, chartData) { // 处理部门图表数据
            let xList = [], yList = [], totalHours = 0;
            const yAxisValue = this.chartYAxisVal[this.chartYAxis]
            const { countCost, countHours } = this.permissions

            for (let i in list) {
                xList.push(list[i].departmentName);
                let item = {
                    "value": yAxisValue == 0 ? (list[i].costMoney ? list[i].costMoney.toFixed(2) : 0) || list[i].costMoney : (list[i].costTime ? list[i].costTime.toFixed(1) : 0),
                    "id": list[i].departmentId,
                    "hasSubDept": list[i].hasSubDept,
                    "type": list[i].type
                }
                if (countCost) {
                    item.money = (list[i].costMoney ? list[i].costMoney.toFixed(2) : 0)
                }
                if (countHours) {
                    item.cost = list[i].costTime
                    totalHours += parseFloat(list[i].costTime);
                }
                yList.push(item);
            }

            totalHours = this.totalHours.toFixed(1);
            totalMoneyCost = totalMoneyCost.toFixed(2)
            console.log(xList, yList, list, '<==== xList, yList,')
            return { ...this.sameChartProcessing(xList, yList, totalHours, totalMoneyCost, chartData) }
        },
        projectClassificationChartData(list, totalMoneyCost = 0, chartData) { // 处理项目分类图表数据
            let xList = [], yList = [], totalHours = 0;
            const yAxisValue = this.chartYAxisVal[this.chartYAxis]
            const { countCost, countHours } = this.permissions
            for (let i in list) {
                xList.push(list[i].categoryName);
                let item = {
                    "value": yAxisValue == 0 ? (list[i].costMoney ? list[i].costMoney.toFixed(2) : 0) || list[i].costMoney : (list[i].cost ? list[i].cost.toFixed(1) : 0),
                    "id": list[i].id || i,
                }
                if (countCost) {
                    item.money = (list[i].costMoney ? list[i].costMoney.toFixed(2) : 0)
                }
                if (countHours) {
                    item.cost = list[i].cost
                    totalHours += parseFloat(list[i].cost);
                }
                yList.push(item);
            }

            totalHours = this.totalHours.toFixed(1);
            totalMoneyCost = totalMoneyCost.toFixed(2)

            return { ...this.sameChartProcessing(xList, yList, totalHours, totalMoneyCost, chartData) }
        },
        processingMainProjectChartData(list, totalMoneyCost = 0, chartData) { // 处理主项目图表数据
            let xList = [], yList = [], totalHours = 0;
            const yAxisValue = this.chartYAxisVal[this.chartYAxis]
            const { countCost, countHours } = this.permissions
            for (let i in list) {
                xList.push(list[i].mainProjectName);

                let item = {
                    "value": yAxisValue == 0 ? (list[i].costMoney ? list[i].costMoney.toFixed(2) : 0) || list[i].costMoney : (list[i].cost ? list[i].cost.toFixed(1) : 0),
                    "id": list[i].id || i,
                }
                if (countCost) {
                    item.money = (list[i].costMoney ? list[i].costMoney.toFixed(2) : 0)
                }
                if (countHours) {
                    item.cost = list[i].cost
                    totalHours += parseFloat(list[i].cost);
                }
                yList.push(item);
            }

            totalHours = this.totalHours.toFixed(1);
            totalMoneyCost = totalMoneyCost.toFixed(2)

            return { ...this.sameChartProcessing(xList, yList, totalHours, totalMoneyCost, chartData) }
        },
        processProjectChartData(list, totalMoneyCost = 0, chartData) { // 处理项目图表数据
            let xList = [], yList = [], totalHours = 0;
            const yAxisValue = this.chartYAxisVal[this.chartYAxis]
            const { countCost, countHours } = this.permissions
            for (let i in list) {
                xList.push(this.nameNumber == '1' ? list[i].project : list[i].projectCode);

                let item = {
                    "value": yAxisValue == 0 ? (list[i].costMoney ? list[i].costMoney.toFixed(2) : 0) || list[i].costMoney : (list[i].cost ? list[i].cost.toFixed(1) : 0),
                    "id": list[i].id || i,
                }
                if (countCost) {
                    item.money = (list[i].costMoney ? list[i].costMoney.toFixed(2) : 0)
                }
                if (countHours) {
                    item.cost = list[i].cost
                    totalHours += parseFloat(list[i].cost);
                }
                yList.push(item);
            }

            totalHours = this.totalHours.toFixed(1);
            totalMoneyCost = totalMoneyCost.toFixed(2)

            return { ...this.sameChartProcessing(xList, yList, totalHours, totalMoneyCost, chartData) }
        },
        sameChartProcessing(xList, yList, totalHours, totalMoneyCost, chartData) { // 项目，主项目，人员，项目分类，部门 等相同处理
            const _this = this
            const yAxisValue = this.chartYAxisVal[this.chartYAxis]
            const { countCost, countHours } = this.permissions
            const { userNameNeedTranslate } = this.user
            chartData.title = {
                text: `工时成本总计：${countCost ? `成本 ${totalMoneyCost},` : ''} ${countHours ? `时长 ${totalHours} 小时/${(totalHours/_this.user.timeType.allday).toFixed(1)}人天` : ''}`,
                left: 'left',
            }

            chartData.toolbox = {
                show: true,
                feature: {
                    saveAsImage: { show: userNameNeedTranslate == 1 ? false : true }, restore: { show: true }, magicType: { type: ['line', 'bar'] },
                }
            }

            chartData.tooltip = {
                trigger: 'axis',
                formatter: function (params, ticket, callback) {
                    _this.params = params;
                    var res
                    if (_this.user.userNameNeedTranslate != '1') {
                        var res = params[0].name + "<br/>" +
                            ((_this.permissions.countCost) ? _this.$t('workcost') + " : " + params[0].data.money
                                + _this.$t('yuan') + "<br/>" : '') +
                            ((_this.permissions.countHours) ? _this.$t('screening.workTime') + " : " + params[0].data.cost + _this.$t('time.hour') : '');
                    } else {
                        var res = "<TranslationOpenDataText type='departmentName' :openid='" + _this.allListData.costList[params[0].dataIndex].additionName + "'></TranslationOpenDataText>" + "<br/>" +
                            ((_this.permissions.countCost) ? _this.$t('workcost') + " : " + params[0].data.money
                                + _this.$t('yuan') + "<br/>" : '') +
                            ((_this.permissions.countHours) ? _this.$t('screening.workTime') + " : " + params[0].data.cost + _this.$t('time.hour') : '');
                    }

                    return res;
                }
            }

            chartData.xAxis = {
                data: xList,
                axisLabel: {
                    interval: 0, rotate: 20
                }
            }

            chartData.yAxis = {
                type: 'value',
                axisLabel: {
                    formatter: yAxisValue == 0 ? '{value} (' + '元' + ')' : ('{value}' + '小时')
                }
            }

            chartData.series = [{
                name: yAxisValue == 0 ? this.$t('workcost') + '（' + this.$t('yuan') + '）' : this.$t('screening.workTime') + '（' + this.$t('time.hour') + '）',
                type: 'bar',
                barMaxWidth: 30,
                data: yList,
                label: {
                    normal: {
                        show: true,
                        position: 'top',
                        // formatter: ` ${yAxisValue == 0 ? '{c}元' : '{c}小时/{{c}/8}人天'}`,

                        formatter: function(params) {
                            var dayValue = yAxisValue == 0?0:(params.value/_this.user.timeType.allday).toFixed(1);
                            return ` ${yAxisValue == 0 ? (params.value + '元') : (params.value + 'h/'+dayValue+'人天')}`; // params.value 等价于 {c}
                        }
                    }
                }
            }]

            return { ...chartData }
        },
        getUserCostList(departmentId) { // 获取人员成本列表
            const { timeType: { fixMonthcost } } = this.user;
            const urls = this.port.project.userCost;
            const params = {};

            if (this.chartDate) {
                const [start, end] = fixMonthcost === 0 ? this.chartDate : [this.chartDate, this.chartDate];
                params.startDate = start;
                params.endDate = end;
            }

            if (departmentId) {
                params.departmentId = departmentId;
            }

            this.postData(urls, params).then(res => {
                const { list = [] } = res.data;
                const alltime = list.reduce((total, item) =>
                    total + item.project.reduce((sum, proj) => sum + parseFloat(proj.time), 0), 0);

                this.totalHours = alltime;
                this.personnelAll = res.data;
                this.allListData = res.data;
                this.personnelAllPlly = JSON.parse(JSON.stringify(res.data));

                if (this.user.userNameNeedTranslate === 1) {
                    const dealWithList = list.map(item => ({
                        type: item.type,
                        id: item.name
                    }));
                    this.dealWithTranslationPlone(dealWithList, res.data.list);
                } else {
                    this.initialChartData();
                }
            }).finally(() => {
                this.radioLoading = false;
            })
        },
        dealWithTranslation(items) { // 部门译处理
            if (WWOpenData.initCanvas) {
                WWOpenData.initCanvas()
            }
            const myFunOne = async () => {
                const result = await new Promise((resolve, reject) => {
                    if (WWOpenData.prefetch) {
                        WWOpenData.prefetch({ items }, (err, data) => {
                            if (err) { return reject(err) }
                            resolve(data)
                        })
                    }

                })
                for (var i in this.allListData.costList) {
                    this.allListData.costList[i].departmentName = result.items[i].data
                }
                this.initialChartData()
            }

            myFunOne()
        },
        dealWithTranslationPlone(items) { // 人员转译处理
            if (WWOpenData.initCanvas) {
                WWOpenData.initCanvas()
            }
            const myFunOne = async () => {
                const result = await new Promise((resolve, reject) => {
                    if (WWOpenData.prefetch) {
                        WWOpenData.prefetch({ items }, (err, data) => {
                            if (err) { return reject(err) }
                            resolve(data)
                        })
                    }
                })
                for (var i in this.allListData.list) {
                    if (result.items[i]) {
                        this.allListData.list[i].name = result.items[i].data
                    }
                }
                this.initialChartData()
            }
            myFunOne()
        },
        filterConditionSwitching() { // 切换筛选条件
            this.theCustomListFlg = false
            let ints = null
            for (var i in this.theCustomList) {
                if (this.singleChoiceType == this.theCustomList[i].name) {
                    this.theCustomListId = this.theCustomList[i].id
                    this.theCustomListPlant = this.theCustomListPlantLIst[i]
                    this.theCustomListFlg = true
                    ints = i
                }
            }
            if (this.theCustomListFlg) {
                this.customList = this.theCustomList[ints].subUserCustomList
                this.customName = this.theCustomList[ints].subUserCustomList[0].name
            }
            this.getEchart()
        },
        // 图表点击事件
        chartClickEvents(data) {
            const { params, myChart } = data
            const { timeType: { fixMonthcost } } = this.user
            if (this.singleChoiceType == '部门' || this.singleChoiceType == '项目') {
                const pointInPixel = [params.offsetX, params.offsetY];
                if (myChart.containPixel('grid', pointInPixel)) {
                    if (this.singleChoiceType == '项目') {
                        if (this.chartDate != null) {
                            if (fixMonthcost == 0) {
                                this.$router.push("/cost/" + this.params[0].data.id + "/" + this.params[0].name
                                    + "?startDate=" + this.chartDate[0] + "&endDate=" + this.chartDate[1]);
                            } else {
                                this.$router.push("/cost/" + this.params[0].data.id + "/" + this.params[0].name
                                    + "?startDate=" + this.chartDate + "&endDate=" + this.chartDate);
                            }
                        } else {
                            this.$router.push("/cost/" + this.params[0].data.id + "/" + this.params[0].name);
                        }
                    }

                    if (this.singleChoiceType == '部门') {
                        if (this.params[0].data.type == 'departmentName') {
                            if (this.params[0].data.hasSubDept) {
                                if (this.parentDeptId != this.params[0].data.id) {
                                    this.parentDeptId = this.params[0].data.id;
                                    this.parentDeptStack.push(this.parentDeptId);
                                    this.getEchart()
                                }
                            } else {
                                if (this.departmentPersonnel == '2') {
                                    return
                                }
                                if (this.chartDate != null) {
                                    this.$router.push("/costDep/" + this.params[0].data.id + "/" + this.params[0].name
                                        + "?startDate=" + this.chartDate[0] + "&endDate=" + this.chartDate[1]);
                                } else {
                                    this.$router.push("/costDep/" + this.params[0].data.id + "/" + this.params[0].name);
                                }
                            }
                        }
                    }
                }
            }
        },
        backToParentDept() { // 返回上级
            if (this.singleChoiceType == '部门') {
                if (this.parentDeptStack.length > 0) {
                    this.parentDeptStack.pop();
                    if (this.parentDeptStack.length > 0) {
                        this.parentDeptId = this.parentDeptStack[this.parentDeptStack.length - 1];
                    } else {
                        this.parentDeptId = null;
                    }
                    this.getEchart();
                }
            }
        },
        // 获取自定义数据
        getCustomData() {
            this.postData(`/user-custom/getUserCustomTitle`, {}).then((res) => {
                this.theCustomList = res.data.result
                this.theCustomListPlantLIst = res.data.field
            })
        },
        jutishez() {
            this.postData(`/time-type/getCompanyTimeSetting`, { companyId: this.user.companyId }).then((res) => {
                this.jichu = res.data
                if (res.data.customDegreeActive == 1) {
                    this.namess = res.data.customDegreeName
                }
            })
        },
        processingInitialData() { // 处理初始数据
            const { countCost, countHours } = this.permissions;
            const { timeType: { fixMonthcost }, moduleList } = this.user;

            this.devicePermissions = moduleList.filter(item => item.name === '设备管理').length > 0;

            this.chartYAxis = countCost && !countHours ? 'cost' : 'workingHours';

            const { query } = this.$route;
            const today = this.dayjs();

            if (fixMonthcost === 0) {
                this.chartDate = query.startDate
                    ? [query.startDate, query.endDate]
                    : [today.startOf('month').format('YYYY-MM-DD'), today.format('YYYY-MM-DD')];
            } else if (fixMonthcost === 1) {
                this.chartDate = query.startDate || today.format('YYYY-MM');
            }

            // this.exportParam.dateRange = this.chartDate;

            if (query.endDate && query.startDate && query.financeAudit) {
                const lastDay = this.dayjs(`${query.endDate}-01`).endOf('month').format('YYYY-MM-DD');
                this.chartDate = [`${query.startDate}-01`, lastDay];
            }

            this.chartYAxis = 'workingHours'
        },
        echartsCurrentChange(val) {
            this.pageIndex = val
            this.processingRequestData(this.allListData)
        },
        // 左右滚动
        scrollFunction() {
            this.domObj = document.getElementById('echartsRef') // 通过id获取要设置的div
            if (this.domObj.attachEvent) { // IE
                this.domObj.attachEvent('onmousewheel', this.mouseScroll)
            } else if (this.domObj.addEventListener) {
                this.domObj.addEventListener('DOMMouseScroll', this.mouseScroll, false)
            }
            this.domObj.onmousewheel = this.domObj.onmousewheel = this.mouseScroll
        },
        mouseScroll(event) { // google 浏览器下
            let detail = event.wheelDelta || event.detail
            let moveForwardStep = -1
            let moveBackStep = 1
            let step = 0
            step = detail > 0 ? moveForwardStep * 100 : moveBackStep * 100
            event.preventDefault() // 阻止浏览器默认事件
            this.domObj.scrollLeft = this.domObj.scrollLeft + step
        },
        showExportDialog() { // 显示报表导出
            this.reportExportVisable = true
        },
        reportExportCustomization() { // 报表导出
            var url = '/project/exportTimeCostByWorkNum';
            var fileName = this.chartDate.join('至') + '工单统计表.xlsx';
            this.reportExportLoading = true;
            this.postData(url, {
                startDate: this.chartDate[0],
                endDate: this.chartDate[1],
            }).then((res) => {
                const aTag = document.createElement('a');
                aTag.download = fileName;
                aTag.href = res.data;
                aTag.click()
            }).finally(() => {
                this.reportExportLoading = false
            })
        },
        // 单独封装请求
        async postData(urls, param) {
            return new Promise((resolve, reject) => {
                this.http.post(urls, { ...param },
                    res => {
                        if (res.code == 'ok') {
                            resolve(res)
                        } else {
                            this.$message({
                                message: res.msg,
                                type: 'error'
                            })
                            reject(res)
                        }
                        resolve(res)
                    },
                    error => {
                        this.$message({
                            message: error,
                            type: "error"
                        });
                        reject(error)
                    }
                )
            });
        },
    },
    created() { },
    mounted() {
        const { timeType: { userCustomStatic } } = this.user;
        userCustomStatic && this.getCustomData(); // 获取自定义数据

        this.processingInitialData()
        this.jutishez()
        setTimeout(() => {
            this.getEchart()
            this.scrollFunction()
        }, 300)
    }
}
</script>

<style lang="scss" scoped>
* {
    box-sizing: border-box;
}

.laborCostStatistics {
    width: 100%;
    height: 100%;
    padding: 15px;
    display: flex;
    flex-direction: column;

    .laborCostStatistics-con {
        margin: 10px 0;
    }

    .laborCostStatistics-end {
        display: flex;
        justify-content: space-between;
    }

    .laborCostStatistics-con {
        flex: 1;
    }

    .el-col {
        display: flex;
        align-items: center;
    }

    .mr-10 {
        margin-right: 10px;
    }
}
</style>