// 清收年度统计
<template>
    <div>
        <!-- 清收工作完成统计 -->
        <div v-if="liquidate === '1'">
            <div class="mgt20 left-border fz-16"><p class="c-black mgl10">清收工作年度情况统计</p></div>
            <div class="mgt20 pdb20">
                <div class="mgtb20">
                    <div class="flex-center">
                        <el-button  type="primary" v-if="$router.currentRoute.meta.btn.includes('生成年度统计表')"  round @click="createList('new')">生成年度统计表</el-button>
                    </div>
                </div>
                <div class="shadow radius10 pdt20">
                    <el-table v-loading='loading' :data="data"  stripe header-align="center" class="mat20">
                        <el-table-column type="index" width="200" label="序号" align="center"></el-table-column>
                        <el-table-column label="年度" align="center">
                            <template slot-scope="scope">
                                {{scope.row}}
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="300" align="center">
                            <template slot-scope="scope">
                                <el-button type="text" v-if="$router.currentRoute.meta.btn.includes('人员选择')" @click="createList(scope.row)">人员选择</el-button>
                                <el-button type="text" v-if="$router.currentRoute.meta.btn.includes('统计查看')" @click="[(liquidate = '2'), edit(scope.row, 'watch')]">查看</el-button>
                                <el-button type="text" v-if="$router.currentRoute.meta.btn.includes('统计编辑')"  @click="edit(scope.row)">管理</el-button>
                                <el-button type="text" v-if="$router.currentRoute.meta.btn.includes('统计删除')"  @click="del(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>
        </div>
        <!-- 查看详细数据 -->
        <div v-if="liquidate === '2'">
            <div class="mgt20 left-border fz-16"><p class="c-black mgl10">条件筛选</p></div>
            <div class="mgt20 pdb20">
                <div class="flex-between mgtb20">
                    <div class="flex-center">
                        <p class="fz-16 mgr10 font-blue mgl20 nowrap">清收组</p>
                        <el-select v-model="searchStr.groupId" placeholder="请选择" clearable @change="search">
                            <el-option v-for="item in liquidateSelectArr" :key="item.id" :label="item.groupName" :value="item.id"></el-option>
                        </el-select>

                        <p class="fz-16 mgr10 font-blue mgl20 nowrap">完成比例</p>
                        <el-select v-model="searchStr.proportionSymbol" placeholder="请选择" clearable @change="search">
                            <el-option v-for="item in proportion" :key="item.id" :label="item.label" :value="item.id"></el-option>
                        </el-select>
                        <el-input
                            placeholder="请输入数值"
                            class="wd20 mglr10"
                            style="min-width: 200px"
                            :disabled="!searchStr.proportionSymbol"
                            v-model="searchStr.proportion"
                            clearable
                        ></el-input>
                        <p>%</p>
                        <p class="fz-16 mgr10 font-blue mgl20 nowrap">已清收总额</p>
                        <el-select @change="allAoumntSymbolChange" v-model="searchStr.allAoumntSymbol" placeholder="请选择" clearable>
                            <el-option v-for="item in proportion" :key="item.id" :label="item.label" :value="item.id"></el-option>
                        </el-select>
                        <el-input :disabled="!searchStr.allAoumntSymbol" class="wd20 mglr10" placeholder="请输入金额（元）" style="min-width: 200px" v-model="searchStr.allAoumnt" clearable></el-input>
                    </div>
                    <div class="flex-center">
                        <el-button v-preventReClick type="primary" size="small" round @click="clearOption">清空选项</el-button>
                        <el-button v-preventReClick type="primary" size="small" round @click="annualStatisticsList">搜索</el-button>
                    </div>
                </div>
                <div class="shadow radius10 pdt20">
                    <div class="flex-between mab20 mgl10">
                        <div class="flex-center">
                            <p class="hr_tag"></p>
                            <span class="hr_text">{{liquidateSearch.year}}年度清收工作完成情况统计表</span>
                        </div>
                    </div>

                    <div class="flex-between">
                        <div class="flex-center">
                            <el-button class="mgl20"  v-if="$router.currentRoute.meta.btn.includes('统计导出列表')"  v-preventReClick type="primary" size="small" round @click="statisticsSelection">导出列表</el-button>
                            <el-radio-group v-model="radio" class="mgl30" @change="radioChange">
                                <el-radio-button class="ht40" label="依据公司排名"></el-radio-button>
                                <el-radio-button class="ht40" label="依据小组排名"></el-radio-button>
                            </el-radio-group>
                        </div>
                        <div class="df">
                            <el-input
                                style="min-width: 250px"
                                class="ht40 mgl10 mgr10"
                                @keyup.enter.native="annualStatisticsList('search')"
                                v-model="searchStr.queryCondition"
                                placeholder="工号/清收负责人"
                                clearable
                            ><i slot="suffix" class="el-input__icon el-icon-search" @click="annualStatisticsList"></i></el-input>
                        </div>
                    </div> 
                    <!-- 
                        前端查询
                         :data="data.filter(data => !search || data.businessCode.toLowerCase().includes(search.toLowerCase()))"
                     -->
                    <div class="dataList" ref="table" @scroll="handleScroll">
                        <el-table
                            :data="statisticsData"
                            stripe
                            header-align="center"
                            v-loading="statisticsLoading"
                            class="mat20 "
                            :row-key="getRowKeys"
                            :key="1"
                        >
                            <el-table-column type="selection" width="55" align="center" :reserve-selection="true"></el-table-column>
                            <el-table-column prop="companyRanks" label="公司排名" align="center" width="70px"></el-table-column>
                            <el-table-column prop="TeamRanks" label="小组排名" align="center" width="70px"></el-table-column>
                            <el-table-column prop="groupName" label="清收组" align="center" width="150px"></el-table-column>
                            <el-table-column prop="personLiable" label="清收负责人" align="center" width="150px"></el-table-column>
                            <el-table-column prop="jobNumber" label="工号" align="center"></el-table-column>
                            <el-table-column prop="enterprise" label="清收企业" align="center" width="150px">
                                <template slot-scope="scope">
                                    <div class="multi-box" v-for="(item, index) in scope.row.enterprise" :key="index">
                                        {{ item.enterprise }}
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column prop="cash" label="清收现金（元）" align="center" width="150px">
                                <template slot-scope="scope">
                                    <div class="multi-box" v-for="(item, index) in scope.row.cash" :key="index">
                                        {{ item.cash }}
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column prop="asset" label="清收资产（元）" align="center" width="150px">
                                <template slot-scope="scope">
                                    <div class="multi-box" v-for="(item, index) in scope.row.assets" :key="index">
                                        {{ item.assets }}
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column prop="collectionTime" label="回款时间" align="center" width="200px">
                                <template slot-scope="scope">
                                    <div class="backTime static multi-box" v-for="(item, index) in scope.row.collectionTime" :key="index">
                                        <el-date-picker
                                            v-if="item.collectionTime"
                                            style="width:180px"
                                            v-model="item.collectionTime"
                                            type="date"
                                            value-format="yyyy-MM-dd"
                                            :disabled="!scope.row.edit"
                                        >
                                        </el-date-picker>
                                        <div v-else>-</div>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column prop="totalAmount" label="已清收总额（元）" align="center" width="150px">
                                <template slot-scope="scope" >
                                    <div class="multi-box" >
                                        {{ scope.row.totalAmount }}
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column prop="ratio" label="完成比例" align="center" width="150px">
                                <template slot-scope="scope">
                                    <div class="ratio" v-show="scope.row.edit">
                                        <div class="top">{{scope.row.totalAmount}}</div>
                                        <el-input :disabled="!scope.row.edit" placeholder="输入年度金额指标" v-model="scope.row.proportion"></el-input>
                                    </div>
                                    <div v-if="!scope.row.edit">
                                        {{scope.row.percent==="未填写年度指标"?"未填写年度指标":scope.row.percent+"%"}}
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column prop="remark" label="备注" align="center"  width="200px">
                                <template slot-scope="scope">
                                    <div class="backTime static multi-box"  v-for="(item, index) in scope.row.description" :key="index">
                                        <el-tooltip v-if="item.description&&item.description!='-'&&scope.row.description!=' '" class="item" effect="dark" :content="item.description" placement="top">
                                            <el-input :disabled="!scope.row.edit" v-model="item.description"></el-input>
                                        </el-tooltip>
                                        <div v-else>
                                            -
                                        </div>
                                    </div>
                                </template>
                            </el-table-column>
                            <!-- 判断是否为查看或者编辑 -->
                            <el-table-column v-if="!liquidWatch" label="操作" width="300" align="center">
                                <template slot-scope="scope">
                                    <el-button type="text" @click="yearEdit(scope.row)">{{scope.row.editStr}}</el-button>
                                    <el-button type="text" v-show="scope.row.edit" @click="[scope.row.edit = false,annualStatisticsList()]">取消</el-button>
                                    <!-- <el-button type="text" @click="history(scope.row)">查看</el-button> -->
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                    <el-button class="more-btn" v-show="moreBtn" type="primary" @click="clickMore" round>{{moreText}}</el-button>
                </div>
            </div>
        </div>

        <!-- 弹框--生成年度统计表 -->
        <el-dialog title="请选择" v-loading="treeLoading" width="40%" :visible.sync="showRank" center>
            <div class="ranking">
                <div class="top">
                    <div class="left-border fz-16"><p class="c-black mgl10">年份</p></div>
                    <el-date-picker
                        :disabled="changeStaffDisabled"
                        class="mgt10 mgl80 year"
                        v-model="chooisYear"
                        value-format="yyyy"
                        :picker-options="pickerOptions"
                        type="year"
                        placeholder="选择年"
                    >
                    </el-date-picker>
                </div>
                <div class="tree">
                    <div class="left-border fz-16 mgt20"><p class="c-black mgl10">参与本年度清收排名的人员</p></div>
                    <div class="mgl80 mgt20 mgr80" style="border: 1px solid #e6e6e6; border-radius: 15px; overflow: auto; padding: 15px">
                        <!-- <el-checkbox @change="allCheck" v-model="checked" class="mgl20" style="margin-left:23px">全选</el-checkbox> -->
                        <el-tree
                            :data="tree"
                            show-checkbox
                            default-expand-all
                            node-key="id"
                            ref="tree"
                            @check-change="checkBox"
                            :default-checked-keys="treeIds"
                            highlight-current
                            :props="defaultProps"
                        >
                        </el-tree>
                    </div>
                </div>
                <div class="flex-center fj-center mgt20">
                    <el-button type="primary" v-preventReClick round class="mgr20" @click="treeSure">确定</el-button>
                    <el-button round class="mgl20" @click="[chooisYear='',showRank=false]">取消</el-button>
                </div>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import { json } from 'mathjs';
import {collectionGroupList ,generateAnnualStatistics,annualList,annualStatisticsList,editAnnualStatistics,personnelSelection ,annualStatisticsDeleted,annualStatisticsListExport,liquidateList } from '../../../utils/api'
import core from '../../../utils/core'
export default {
    name: '',
    props: {},
    components:{
    },
    data() {
        return {
            showRank: false, // 弹框
            treeLoading:false,// 树弹框加载
            loading:false,// 列表加载
            statisticsLoading:false,// 统计列表加载
            defaultProps: {
                children: 'personnel',
                label: "name"
            },
            data: [],
            tree: [],
            treeIds:[],
            treeStatus:'',
            chooisYear: '',
            pageNo: 0,
            totals: 0,
            liquidateSelectArr: [{ label: '不限', id: '' }],
            proportion: [
                // 选择完成比例符号
                { label: '不限', id: '' },
                { label: '>', id: '>' },
                { label: '<', id: '<' },
                { label: '>=', id: '>=' },
                { label: '<=', id: '<=' },
                { label: '=', id: '=' }
            ],
            searchStr: {
                // 筛选条件
                year:'',
                groupId: '', // 清收组
                proportion: '', // 比例
                percent: '', // 比例整数百分比
                proportionSymbol: '', // 选择比例符号
            },
            radio: '依据公司排名',

            liquidateSelect: '0', // 选择筛选框
            originalData:[],// 记录原本data
            statisticsData: [// 统计表的数据
            ], 
            keyword: '', // 搜索绑定变量占位
            pickerOptions: {
                disabledDate(time) {
                    // 限制时间
                    let date = new Date();
                    let year = date.getFullYear();
                    return time.getFullYear() > year;
                }
            },
            moreBtn:false,
            moreText:'向下滚动查看更多',
            recordArr:[],// 记录用数组,加载更多
            changeStaffYear:'',
            changeStaffDisabled:false,
            checked:false,

        };
    },
    watch: {
        showRank(val){
            if(val){
                this.getTree()
            }else{
                this.tree = []
                this.treeIds = []
            }
        },
        liquidate(val){
            if(val==2){
                // console.log('判断为2')
                this.liquidateList()
                this.annualStatisticsList()
            }else{
                this.annualList()
            }
        }
    },
    computed: {
        liquidate:{
            get(){
                return this.$store.state.loan.liquidate
            },set(){}
        },
        liquidWatch:{
            get(){
                return this.$store.state.loan.liquidWatch
            },set(){}
        },
        liquidateSearch:{
            get(){
                this.searchStr = this.$store.state.loan.liquidateSearch
                return this.$store.state.loan.liquidateSearch
            },set(){}
        },
        percent(){
            // console.log(this.statisticsData,'statisticsData')
            // console.log(this.statisticsData.totalAmount,this.statisticsData.proportion,'计算百分比的值')
            return (+this.statisticsData.totalAmount/+this.statisticsData.proportion).toFixed(2)
        }
    },
    created() {
        this.searchStr = this.$store.state.loan.liquidateSearch
        this.annualList()
        // console.log(this.liquidate,this.searchStr,'li')
        if(this.liquidate=='2'){
            this.annualStatisticsList()
        }
    },
    mounted() {
       
    },
    methods: {
        liquidateList(){// 清收组
            liquidateList().then(res=>{
                this.liquidateSelectArr = res.data.groupList
                // console.log(this.liquidateSelectArr,'arr')
            })
        },
        handleScroll:core.debounce(function(){
            let box = this.$refs.table
            if(box.scrollTop+box.clientHeight+180>box.scrollHeight){
                this.moreBtn = true
            }else{
                this.moreBtn = false
            }
            if(box.scrollTop+box.clientHeight+50>=box.scrollHeight){
                
            }
        },10),
        async clickMore(){// 进行加载更多操作
            this.statisticsLoading = true
            await setTimeout(() => {
                this.statisticsLoading = false
            }, 500+Math.floor(Math.random(500)));
            this.statisticsData.push(...this.recordArr.slice(0,10))
            this.recordArr.splice(0,10)
            let box = this.$refs.table
            let st = box.scrollTop
            if(this.recordArr.length===0){
                this.moreText = "没有更多数据了！"
            }else{
                this.moreText = "点击加载更多数据"
                box.scrollTop = st
            }
        },
        annualList(){
            this.loading = true
            annualList().then(res=>{
                this.loading = false
                if(!res.data.list[0]) this.data = []
                this.data = res.data.list
            }).catch(()=>{
                this.loading = false
            })
        },
        /* TODO 按照有多组进行区分，再按组分人，后端传来按组区分的数组，进行切割区分。
         * 
         */
        annualStatisticsList(){
            if(this.searchStr.proportionSymbol&&!this.searchStr.proportion) return this.$message('请输入完成比例整数！')
            if(this.searchStr.allAoumntSymbol&&!this.searchStr.allAoumnt) return this.$message('请输入已清收总额！')
            this.searchStr = this.$store.state.loan.liquidateSearch
            let param = {
                year:this.searchStr.year,
                groupId:this.searchStr.groupId,
                // proportionSymbol:this.searchStr.proportionSymbol,
                // proportion:this.searchStr.proportion,
                queryCondition:this.searchStr.queryCondition,
            }
            this.statisticsLoading = true
            annualStatisticsList(param).then(res=>{
                // console.clear()
                // console.log('开始处理数据')
                this.statisticsLoading = false
                let arr = new Map() // 最后处理得到的map对象
                let data = res.data.list
                let groupArr= new Map()// 得到的组排序对象，仅取出多组和多组排名即可。
                let overArr = []// 最终处理出来的组排序的数组

                function compare(key){
                    return function(value1,value2){
                        let val1=value1[key];
                        let val2=value2[key];
                        return val2-val1;
                    }
                }
                // console.log(res.data.groupList.collect,'res.data.groupList.collect')
                // 按组分人进行处理，取得人的组排序值，以及对应的多组的值，取得这两个数据即可
                let collect = JSON.parse(JSON.stringify(res.data.groupList.collect))
                if(res.data.groupList.collect){

                    // console.log('开始处理组的数据')
                    for (let key in res.data.groupList.collect) {// 循环分组
                        // 每次取出一个组进行处理，并且在该次处理中，把人员组和名次取出来
                        let group = res.data.groupList.collect[key]
                        // console.log(group,'每个组的数据',key,'key')
                        let aloneMap = new Map() // 每个组独立的map对象处理
                        let aloneArr = []// 取出所有的已处理数据
                        group.forEach(e=>{// 进行相同数据处理叠加，需要注意组和排名的处理
                            // 进行各项数据叠加，然后根据叠加的totalAmount字段进行排序，且，组之间需要进行一次额外排序
                            if(aloneMap.has(e.jobNumber)){// 如果处理过，进行叠加处理
                                let obj = aloneMap.get(e.jobNumber)
                                obj.enterprise.push({enterprise:e.enterprise,id:e.id})
                                obj.totalAmount += ((+e.cash||0)+(+e.assets))
                                obj.cash.push({cash:e.cash,id:e.id})
                                obj.assets.push({assets:e.assets,id:e.id})
                                obj.collectionTime.push({collectionTime:e.collectionTime,id:e.id})
                                obj.description.push({description:e.description,id:e.id})
                                aloneMap.set(e.jobNumber,obj)
                                // console.log(e.groupName,'多次处理的组数据') 
                            }else{
                                e.groupName = [e.groupName]// 区别于公司人员处理，把组提取出来
                                // console.log(e.groupName,'e.groupName')
                                e.enterprise = [{enterprise:e.enterprise||'-',id:e.id}]
                                e.totalAmount = (+e.cash||0)+(+e.assets)
                                e.cash = [{cash:e.cash||'-',id:e.id}]
                                e.assets = [{assets:e.assets||'-',id:e.id}]
                                e.collectionTime = [{collectionTime:e.collectionTime,id:e.id}]
                                e.description = [{description:e.description||'-',id:e.id}]
                                // console.log(e.totalAmount,`首次加入的${e.personLiable}`)
                                aloneMap.set(e.jobNumber,e)// 根据工号进行标识储存
                            }
                        })
                        // console.log(aloneMap,'首次处理的alone')
                        // 处理完的map进行解构，并排序，以此取得每个组的排序对象数组
                        for(let [key,value] of aloneMap){
                            aloneArr.push(value)
                        }
                        // console.log('取得aloneArr的map对象',aloneArr)

                        aloneArr.sort(compare('totalAmount'))// 进行金额排序
                        aloneArr.forEach((e,i)=>{// 由此取得每个人在组内的排序
                            e.TeamRanks = [i+1]
                        })
                        groupArr.set(key,aloneArr)// 再把该数组存入组id标识的map对象中
                    }
                }
                let dispose = []
                // 处理完map对象后，需要再根据人进行合并,先取出所有的组对应数组
                for(let [key,value] of groupArr){
                    // 存在map中的是一个个组为标识的数组，先把数组解构出来，然后再需要进行一个一个对象的工号对比，若相同，则进行合并
                    dispose.push(...value)
                }
                // console.log(dispose,'取出所有的dispose值')

                if(dispose.length>0){
                    // 建立一个新的map进行合并操作，以工号为标识
                    let disposeMap = new Map()
                    dispose.forEach(e=>{// 循环，合并相同的数据，仅需取得对应的排序和复数组
                        if(disposeMap.has(e.jobNumber)){// 如果处理过，进行叠加处理
                            let obj = disposeMap.get(e.jobNumber)
                            // console.log(e.groupName,e.TeamRanks,'e的组和排名')
                            // console.log(obj.groupName,obj.TeamRanks,'obj的组和排名')
                            // console.log(obj.groupName.includes(e.groupName),'obj是否包含e的判断')
                            if(!obj.groupName.includes(e.groupName)){// 进行初步判重
                                obj.groupName.push(...e.groupName)// 把多组处理出来，无需判重
                                obj.TeamRanks.push(...e.TeamRanks)// 再把组排名取出来
                            }
                            // console.log(obj,'处理完的obj')
                            // 无需处理其他类型数据
                            disposeMap.set(e.jobNumber,obj)// 进行覆盖
                        }else{
                            // e.groupName = [...e.groupName]// 区别于公司人员处理，把组提取出来
                            // e.TeamRanks = 
                            disposeMap.set(e.jobNumber,e)// 根据工号进行标识储存
                        }
                    })
                    // 最后取得一个已处理完毕的数组
                    // console.log(disposeMap,'处理完毕的map对象')
                    for(let [key,value] of disposeMap){
                        overArr.push(value)// 取得对应数组，只需要赋值到公司排名那里即可
                    }
                }
                // console.log('取得overArr',overArr)
                // 然后再把组和排名拿到公司排名那里进行拼接
                

                data.forEach(e=>{// 数据处理为一条--需要额外取得多组和分组排名，按组排序将无法正常展示
                    if(arr.has(e.jobNumber)){
                        let obj = arr.get(e.jobNumber)
                        obj.enterprise.push({enterprise:e.enterprise,id:e.id})
                        obj.totalAmount += ((+e.cash||0)+(+e.assets))
                        obj.cash.push({cash:e.cash,id:e.id})
                        obj.assets.push({assets:e.assets,id:e.id})
                        obj.collectionTime.push({collectionTime:e.collectionTime,id:e.id})
                        obj.description.push({description:e.description,id:e.id})
                        arr.set(e.jobNumber,obj)
                        // console.log(e.totalAmount,`再次处理加入的${e.personLiable}`)

                    }else{
                        e.enterprise = [{enterprise:e.enterprise||'-',id:e.id}]
                        e.totalAmount = (+e.cash||0)+(+e.assets)
                        e.cash = [{cash:e.cash||'-',id:e.id}]
                        e.assets = [{assets:e.assets||'-',id:e.id}]
                        e.collectionTime = [{collectionTime:e.collectionTime,id:e.id}]
                        e.description = [{description:e.description||'-',id:e.id}]
                        // console.log(e.totalAmount,`首次加入的${e.personLiable}`)
                        arr.set(e.jobNumber,e)
                    }
                })
                // 取得初次处理的数据
                this.originalData = []
                for(let [key,value] of arr){
                    // 处理百分比展示文字
                    if(value.totalAmount&&value.proportion){
                        value.percent = ((value.totalAmount/value.proportion)*100).toFixed(2)
                    }else{
                        value.percent = '未填写年度指标'
                    }
                    // 把组和排名进行赋值,取得组排名和多组的值
                    overArr.forEach(e=>{
                        if(e.jobNumber==value.jobNumber){
                            value.groupName = e.groupName.join(",") // 多组处理的拼接
                            value.TeamRanks = e.TeamRanks.join(",") // 多组排名的拼接
                        }
                    })
                    this.originalData.push(value)
                }
                // console.log(this.originalData,'初始处理的数据')
                // 初始数据执行两次排名，分别取得组排名和公司排名
                // this.radioChange('依据小组排名')
                this.radioChange('依据公司排名')
                // 根据单选按钮，进行实际排序展示
                if(this.radio==='依据小组排名'){
                    // console.log('依据小组排名',collect,'chunazhi')
                    this.radioChange('依据小组排名',collect)
                }
                // console.log(this.searchStr.proportionSymbol,'this.searchStr.allAoumntSymbol')
                
                switch (this.searchStr.proportionSymbol) {
                    case '':
                        break;
                    case ">":
                        if(this.searchStr.proportion){
                            this.statisticsData = this.statisticsData.filter(e=>{
                                if(e.percent!=='未填写年度指标')
                                return +e.percent > this.searchStr.proportion
                            })
                        }
                        break;
                    case "<":
                        if(this.searchStr.proportion){
                            this.statisticsData = this.statisticsData.filter(e=>{
                                if(e.percent!=='未填写年度指标')
                                return +e.percent < this.searchStr.proportion
                            })
                        }
                        break;
                    case ">=":
                        if(this.searchStr.proportion){
                            this.statisticsData = this.statisticsData.filter(e=>{
                                if(e.percent!=='未填写年度指标')
                                return +e.percent >= this.searchStr.proportion
                            })
                        }
                        break;
                    case "<=":
                        if(this.searchStr.proportion){
                            this.statisticsData = this.statisticsData.filter(e=>{
                                if(e.percent!=='未填写年度指标')
                                return +e.percent <= this.searchStr.proportion
                            })
                        }
                        break;
                    case "=":
                        if(this.searchStr.proportion){
                            this.statisticsData = this.statisticsData.filter(e=>{
                                if(e.percent!=='未填写年度指标')
                                return +e.percent == this.searchStr.proportion
                            })
                        }
                        break;
                    default:
                        break;
                }
                // 查完成比例查询
                switch (this.searchStr.allAoumntSymbol) {
                    case '':
                        break;
                    case ">":
                        this.statisticsData = this.statisticsData.filter(e=>{
                            return e.totalAmount > this.searchStr.allAoumnt||0
                        })
                        break;
                    case "<":
                        this.statisticsData = this.statisticsData.filter(e=>{
                            return e.totalAmount < this.searchStr.allAoumnt||0
                        })
                        break;
                    case ">=":
                        this.statisticsData = this.statisticsData.filter(e=>{
                            return e.totalAmount >= this.searchStr.allAoumnt||0
                        })
                        break;
                    case "<=":
                        this.statisticsData = this.statisticsData.filter(e=>{
                            return e.totalAmount <= this.searchStr.allAoumnt||0
                        })
                        break;
                    case "=":
                        this.statisticsData = this.statisticsData.filter(e=>{
                            return e.totalAmount == this.searchStr.allAoumnt||0
                        })
                        break;
                    default:
                        break;
                }
                /* 分页改为无限滚动，暂时保留 */
                // // 长度大于10，开启滚动记录数组,切割当前数组
                // if (this.statisticsData.length>10) {
                //     this.recordArr = JSON.parse(JSON.stringify(this.statisticsData))
                //     this.recordArr.splice(0,10)
                //     this.statisticsData.splice(10,this.statisticsData.length-1)// 首次切割
                // }
            }).catch(err=>{
                this.statisticsLoading = false
            })
        },
        getTree(){// 取得统计树数据
            this.treeLoading = true
            collectionGroupList().then(res=>{
                this.treeLoading = false
                let data = res.data.list
                data.forEach((e,index)=>{
                    if(e.id.includes('group')&&e.personnel.length===0){
                        e.disabled = true
                    }
                })
                let allTree = [{
                    id:'全选group',
                    name:'全选',
                    personnel:[...data]
                }]
                this.tree = allTree 
                // console.log("取得树数据")
            }).catch(err=>{
                this.treeLoading = false
            })
        },
        // 勾选
        checkBox(data, checked, indeterminate){
            // console.log(checked,'dianjiindeterminate')

            this.treeIds = this.$refs.tree.getCheckedKeys()
            // console.log(this.treeIds,'ids')
            // if(checked){
            //     const fn = function(arr,ids,id){
            //         arr.forEach(el=>{
            //             if(el.id.includes(',')){
            //                 if(el.id.split(',').pop()==id&&!ids.includes(el.id)){
            //                     ids.push(el.id)
            //                 }
            //             }
            //             if(el.personnel&&el.personnel.length>0){
            //                 fn(el.personnel,ids,id)
            //             }
            //         })
            //     }
            //     this.treeIds.forEach(e=>{
            //         if(e.includes(",")){
            //             let id = e.split(",").pop()// 取出勾选的那个值
            //             fn(this.tree,this.treeIds,id)
            //         }
            //     })
            // }else{
            //     let tid = this.treeIds
            //     this.treeIds.forEach(e=>{
            //         if(e.includes(',')){
            //             let id = e.split(",").pop()
            //             this.treeIds.forEach(el=>{
            //                 if(el.includes(id)){
            //                     tid.splice(tid.indexOf(el),1)
            //                 }
            //             })
            //         }
            //     })
            //     console.log(this.treeIds,'ids')
            // }

        },
        async createList(val) {// 唤起清收组弹窗
            // console.log(val,'val')
            this.showRank = true;
            if(val==='new'){// 新增人员
                this.treeIds = []
                this.changeStaffDisabled = false
            }else{
                await this.personnelSelection(val)
                this.changeStaffDisabled = true
                this.chooisYear = val
            }
            this.treeStatus = val
        },
        treeSure(){// 确定
            if (this.treeStatus === 'new') {
                // 新建生成统计表
                if(!this.chooisYear)return this.$message.error('请先选择年份！')
                // let arr = []
                // this.treeIds.forEach((e,index)=>{
                //     if(e.includes(',')){
                //         arr.push(e.split(",").pop())
                //     }
                // })
                if(this.treeIds.length===0) return this.$message.warning('请先选择人员后再生成列表！')
                console.log(this.treeIds,'treeIds')
                this.treeIds.forEach((e)=>{
                    if(e=="全选group"){
                        this.treeIds.splice(this.treeIds.indexOf(e),1)
                        return
                    }
                })
                generateAnnualStatistics({personLiableIds:this.treeIds,year:this.chooisYear,flag:1}).then(res=>{
                    this.showRank = false
                    this.$message.success('操作成功！')
                    this.annualList()
                }).catch(err=>{

                })
            }else{// 编辑
                // let arr = []]
                this.treeIds.forEach((e)=>{
                    if(e=="全选group"){
                        this.treeIds.splice(this.treeIds.indexOf(e),1)
                        return
                    }
                })
                console.log(this.ids,'ids的值',this.treeIds)
                this.ids.forEach(e=>{// 避免重复生成
                    if(this.treeIds.includes(e+"")){
                        this.treeIds.splice(this.treeIds.indexOf(e+""),1)
                    }
                })
                this.treeIds.forEach((e)=>{
                    if(e=="全选group"){
                        this.treeIds.splice(this.treeIds.indexOf(e,1))
                        return
                    }
                })
                generateAnnualStatistics({personLiableIds:this.treeIds,year:this.chooisYear}).then(res=>{
                    this.showRank = false
                    this.$message.success('操作成功！')
                    this.annualList()
                }).catch(err=>{

                })
                
            }
        },
        currentChange(val) {
            // 列表变更
        },
        radioChange(val,groups) {// 排名
            function compare(key){
                return function(value1,value2){
                    let val1=value1[key];
                    let val2=value2[key];
                    return val2-val1;
                }
            }
            if(val==='依据小组排名'){
                console.log(this.liquidWatch,'liquidWatch,小组')
                let groupMap = new Map()// 进行组的总金额排名对象
                let sortGroups = []// 排序组的顺序
                // console.log('开始执行依据小组排名',groups,'groups')
                if(!groups){// 执行列表接口逻辑，从列表走
                    this.annualStatisticsList()
                }
                if(groups){// 传来的后端处理的组排名
                    for (let key in groups) {
                        let group = JSON.parse(JSON.stringify(groups[key]))// 取得每个数组的数据
                        if(group.length===0) return
                        // 只需要把数组进行排序，再把组内进行排序进行展示即可，无需进行人员合并
                        // 进行组的金额叠加
                        let sum = group.reduce((pre,item)=>{
                            return pre + (item.cash||0) + (item.assets||0)
                        },0)
                        console.log(sum,'叠加的组数据')
                        let obj = {
                            sum:sum,
                            id:group[0].groupId
                        }
                        console.log(group,'组group的数据')
                        groupMap.set(group[0].groupId,obj)// 存累加的组的数据，和组的id做为标识
                        console.log(groupMap,'排序的组')
                    }
                    let sortGroup = []// 组排名的数组
                    for (let [key,value] of groupMap) {
                        sortGroup.push(value)
                    }
                    console.log(sortGroup,'取得排序过的数组数据')

                    sortGroup.sort(compare('sum'))// 把组进行排名
                    // 以上的组排名根据多次检测，已无问题


                    // 然后根据排名的组，进行一次排序分离，push进数组中
                    sortGroup.forEach(e=>{
                        sortGroups.push(groups[e.id])// 组排序人员塞进新数组
                    })

                    console.log(sortGroups,'处理好的排序组')
                    let lastData = []// 最后处理出来的数组

                    // 再把组内进行人员合并，且进行排序
                    sortGroups.forEach(e=>{
                        let manMap = new Map()
                        e.forEach(e=>{
                            if(manMap.has(e.jobNumber)){// 合并相同的人员数据
                                let obj = manMap.get(e.jobNumber)
                                obj.enterprise.push({enterprise:e.enterprise,id:e.id})
                                obj.totalAmount += ((+e.cash||0)+(+e.assets))
                                obj.cash.push({cash:e.cash,id:e.id})
                                obj.assets.push({assets:e.assets,id:e.id})
                                obj.collectionTime.push({collectionTime:e.collectionTime,id:e.id})
                                obj.description.push({description:e.description,id:e.id})
                                manMap.set(e.jobNumber,obj)
                            }else{// 处理首次的人员
                                e.enterprise = [{enterprise:e.enterprise||'-',id:e.id}]
                                e.totalAmount = (+e.cash||0)+(+e.assets)
                                e.cash = [{cash:e.cash||'-',id:e.id}]
                                e.assets = [{assets:e.assets||'-',id:e.id}]
                                e.collectionTime = [{collectionTime:e.collectionTime,id:e.id}]
                                e.description = [{description:e.description||'-',id:e.id}]
                                // console.log(e.totalAmount,`首次加入的${e.personLiable}`)
                                manMap.set(e.jobNumber,e)
                            }
                            // 处理完毕，取出处理好的组的数组，解构，取得初步处理完的数据
                        })
                        let handelArr = []
                        for(let [key,val] of manMap){
                            handelArr.push(val)
                        }
                        handelArr.sort(compare('totalAmount'))

                        console.log(handelArr,'handlarr')
                        // 排序完，进行一次赋值操作，把公司排名和组排名搞上去
                        handelArr.forEach((e,i)=>{
                            e.TeamRanks = i+1
                            this.originalData.some(el=>{
                                if(e.jobNumber===el.jobNumber){
                                    e.companyRanks = el.companyRanks
                                    // e.groupName =
                                }
                            })
                            if(e.totalAmount&&e.proportion){
                                e.percent = ((e.totalAmount/e.proportion)*100).toFixed(2)
                            }else{
                                e.percent = '未填写年度指标'
                            }
                        })
                        // 最后处理完成的值
                        lastData.push(...handelArr)
                        // for(let [key,val] of manMap){
                        //     lastData.push(val)
                        // }
                    })
                    lastData.forEach((e,i)=>{
                        e.companyRanks = i+1
                        e.editStr = '编辑'
                        e.edit = false
                    })
                    // console.log(lastData,'处理完的最后的组排名，分人')/
                    this.statisticsData = JSON.parse(JSON.stringify(lastData))
                    console.log(this.statisticsData,'是否有操作的值')

                    


                }                
            }else if(val==='依据公司排名'){
                // this.annualStatisticsList()
                // 取得原始的数组,且进行公司排名
                this.originalData.sort(compare('totalAmount'))
                this.originalData.forEach((e,i)=>{
                    e.companyRanks = i+1
                    e.editStr = '编辑'
                    e.edit = false
                })
                this.statisticsData = JSON.parse(JSON.stringify(this.originalData))
            }

            
        },
        clearOption() {
            // 清空筛选条件
            this.$store.commit('liquidateSearch',{year:this.liquidateSearch.year})
            this.annualStatisticsList()
        },
        search() {
            // 暂时占位
        },
        getRowKeys(row) {
            // 列表的Key
            return row.Id;
        },
        statisticsSelection() {
            // console.log('发',this.searchStr.year)
            // console.log(this.searchStr.year+`年度清收工作完成进度表`)
            let num
            this.radio == "依据公司排名"?num=1:num=0
            core.exportFile(annualStatisticsListExport(this.searchStr.year)+`&flag=${num}`,this.searchStr.year+"年度清收工作完成进度表")
        },
        edit(row, val) {
            // 编辑
            this.liquidate ='2';
            this.$store.commit('liquidateSearch',{
                year:row
            })
            this.$store.commit('liquidate','2')
            // 判断进入查看
            this.$store.commit('liquidWatch',val)
            // console.log(val,this.liquidWatch,'liquidWatch')
            // this.annualStatisticsList()
        },
        yearEdit(row, val){// 编辑功能
            if(row.edit != false){
                row.edit = false
                row.editStr = '编辑'
                // 调接口，存数据，重新请求列表
                let param = []
                row.enterprise.forEach((e,index)=>{
                    let obj = {
                        collectionTime:row.collectionTime[index].collectionTime,
                        id:e.id,
                        description:row.description[index].description,
                        proportion:row.proportion
                    }
                    param.push(obj)
                })
                editAnnualStatistics({collectionStatistics:param}).then(res=>{
                    this.$message.success('编辑成功！')
                    setTimeout(() => {
                        this.annualStatisticsList()
                    }, 1000);
                })
            }else{
                row.editStr = '保存'
                row.edit = true
            }
        },
        personnelSelection(val){// 人员选择
            return personnelSelection({year:val}).then(res=>{
                this.treeIds = res.data.list
                // const disabled = function(arr,ids){
                //     arr.forEach(e=>{
                //         if(ids.includes(e.id)){
                //             e.disabled = true
                //         }
                //     })
                // }
                // disabled(this.tree,this.treeIds)
                console.log(this.treeIds,'ids的值')
                this.tree[0].personnel.forEach(e=>{
                    if(this.treeIds.includes(+e.id)){
                        e.disabled = true
                    }
                })
                this.$forceUpdate();
                // console.log('treeIds',this.treeIds)
                this.ids = res.data.list
            })
        },
        del(row){
            this.$confirm('确定要删除该年度统计数据吗？').then(()=>{
                annualStatisticsDeleted(row).then(res=>{
                    this.annualList()
                    
                })
            })
        },
        // allCheck(val){
        //     console.log(this.tree,'tree')
        //     if(this.tree.length==0) return
        //     let that = this
        //     function recursion(arr){
        //         if(arr&&arr.length>0){
        //             arr.forEach(e=>{
        //                 that.treeIds.push(e.id)
        //                 if(e.personnel&&e.personnel.length>0){
        //                     recursion(e.personnel)
        //                 }
        //             })
        //         }
        //     }
        //     if(val){
        //         recursion(this.tree)
        //         // this.ids = this.treeIds
        //     }else{
        //         this.treeIds = []
        //     }
        //     this.$refs.tree.setCheckedKeys([this.treeIds]);
        //     // console.log(this.treeIds,'ids')
        //     // this.$forceUpdate();
        // },
        allAoumntSymbolChange(val){
            if(!val){
                this.searchStr.allAoumnt = ''
            }
        }
    }
};
</script>
<style lang='scss' scoped>
/deep/ .el-radio-button__inner {
    padding-top: 9px;
    padding-bottom: 9px;
}
.multi-box {
    // border: 1px solid #e6e6e6;
    
    min-height: 50px;
    text-align: center;
    line-height: 50px;
    &:nth-child(2n) {
        background: #e6e6e6;
        border-left: 1px solid #fff;
        border-right: 1px solid #fff;
    }
}
.backTime{
    min-height: 50px;
    line-height: 50px;
    /deep/ .el-input__inner{
        text-align: center;
    }

}
.ratio{
    .top{
        border-bottom: 1px solid;
        height: 52px;
        line-height: 52px;
        margin-bottom: 15px;
    }
}
.dataList{
    min-height: 550px;
    // overflow: auto;
    position: relative;
}
/deep/ .el-table::before{
    background-color: transparent;
}
.more-btn{
    position: absolute;
    bottom: 10px;
    left: 50%;
    transform: translate(-50%,0);
}
/deep/ .el-input.is-disabled .el-input__inner{
    text-align: center;
}
/deep/ .el-table--enable-row-transition .el-table__body td{
    border: 0.0625rem solid #e6e6e6;
    border-top: 0;
}
/deep/ .el-table .cell{
    padding-left: 0;
    padding-right: 0;
}
/deep/ .el-date-editor.el-input{
    width: 100%!important;
    background: transparent;
}
/deep/ .top .el-date-editor.el-input{
    width: 180px!important;
    background: transparent;
}
/deep/ .el-input.is-disabled .el-input__inner{
    color:#606266;
    background: transparent;
}

</style>
