package com.pusong.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.pusong.business.domain.PsContractInfo;
import com.pusong.business.domain.PsContractPay;
import com.pusong.business.domain.PsTaskAppoint;
import com.pusong.business.domain.PsTaskMain;
import com.pusong.business.domain.vo.home.*;
import com.pusong.business.enums.CommonStatusEnum;
import com.pusong.business.enums.ContractStatusEnum;
import com.pusong.business.enums.PayStatusEnum;
import com.pusong.business.enums.TaskStatusEnum;
import com.pusong.business.mapper.PsContractInfoMapper;
import com.pusong.business.mapper.PsContractPayMapper;
import com.pusong.business.mapper.PsTaskAppointMapper;
import com.pusong.business.mapper.PsTaskMainMapper;
import com.pusong.business.service.HomeService;
import com.pusong.common.core.constant.CacheNames;
import com.pusong.common.core.utils.DateUtils;
import com.pusong.system.domain.bo.SysDictDataBo;
import com.pusong.system.domain.vo.SysDictDataVo;
import com.pusong.system.service.ISysDictDataService;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Service
public class HomeServiceImpl implements HomeService {

    private static final Logger log = LoggerFactory.getLogger(HomeServiceImpl.class);

    private final PsContractInfoMapper psContractInfoMapper;
    private final PsContractPayMapper payMapper;
    private final PsTaskMainMapper taskMainMapper;
    private final PsTaskAppointMapper taskAppointMapper;

    private final ISysDictDataService dictDataService;

    /**
     * 查询成交总金额
     * @param type
     * @return
     */
    @Cacheable(cacheNames = CacheNames.HOME_A, key = "#type")
    public MakeAmountVo selectMakeAmount(Integer type){
        Map<String, Object> mapParam = this.getDate(type);
        LocalDate startDate = (LocalDate)mapParam.get("startDate");
        LocalDate endDate = (LocalDate)mapParam.get("endDate");
        String date = (String)mapParam.get("date");

        log.info("查询日期：{}到{}",startDate,endDate);
        List<PsContractInfo> list = psContractInfoMapper.selectList(Wrappers.<PsContractInfo>lambdaQuery()
                .select(PsContractInfo::getContractCode, PsContractInfo::getIsDue, PsContractInfo::getContractAmount)
                .ne(PsContractInfo::getIsCancel, CommonStatusEnum.SUCCESS.getCode())
                .ne(PsContractInfo::getContractStatus, ContractStatusEnum.INIT.getCode())
                .ge(startDate != null,PsContractInfo::getApplyDate,startDate)
                .le(endDate != null,PsContractInfo::getApplyDate,endDate));

        Map<String, List<PsContractInfo>> map = list.stream().collect(Collectors.groupingBy(PsContractInfo::getIsDue, Collectors.toList()));
        //续期合同
        List<PsContractInfo> renewList = Optional.ofNullable(map.get(CommonStatusEnum.Y.getCode())).orElse(new ArrayList<>());
        //新签的合同
        List<PsContractInfo> newList = Optional.ofNullable(map.get(CommonStatusEnum.N.getCode())).orElse(new ArrayList<>());

        //装填dto
        MakeAmountVo makeAmountVo = new MakeAmountVo();
        makeAmountVo.setDateStr(date);
        //总金额
        makeAmountVo.setAll(list.stream().map(PsContractInfo::getContractAmount).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add));
        //续期合同
        makeAmountVo.getRenewInfo().setNum(renewList.size()+"单");
        makeAmountVo.getRenewInfo().setMoney(renewList.stream().map(PsContractInfo::getContractAmount).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add));
        fillPay(renewList,makeAmountVo.getRenewInfo());
        //新签合同
        makeAmountVo.getNewInfo().setNum(newList.size()+"单");
        makeAmountVo.getNewInfo().setMoney(newList.stream().map(PsContractInfo::getContractAmount).filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add));
        fillPay(newList,makeAmountVo.getNewInfo());
        //计算比例
        makeAmountVo.cellPer();
        return makeAmountVo;
    }

    private void fillPay(List<PsContractInfo> list, DataAmountVo typeAmountVo){
        //续费/新签的合同编码集合
        List<String> renewCodes = list.stream().map(PsContractInfo::getContractCode).toList();
        //续费/新签的合同已付金额
        if(CollectionUtils.isNotEmpty(renewCodes)){
            List<PsContractPay> payList = payMapper.selectList(Wrappers.<PsContractPay>query().select("business_type", "sum(money) money").lambda()
                    .in(PsContractPay::getContractCode, renewCodes).eq(PsContractPay::getPayStatus, PayStatusEnum.SUCCESS.getCode())
                    .groupBy(PsContractPay::getBusinessType));
            BigDecimal payMoney = BigDecimal.ZERO;
            for (PsContractPay pay : payList) {
                if(pay.getBusinessType().equals("1")){payMoney = payMoney.add(pay.getMoney());}else{ payMoney = payMoney.subtract(pay.getMoney());}
            }
            typeAmountVo.setPayMoney(payMoney);
        }else{
            typeAmountVo.setPayMoney(BigDecimal.ZERO);
        }
        //续费/新签的合同未付金额
        typeAmountVo.setUnPayMoney(typeAmountVo.getMoney().subtract(typeAmountVo.getPayMoney()));
    }

    private Map<String, Object> getDate(Integer type){
        LocalDate startDate = null;
        LocalDate endDate = null;
        String date = "";
        LocalDate now = LocalDate.now();
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM");
        switch (type){
            case 1://本月
                startDate = now.withDayOfMonth(1);
                date =startDate.format(df);
                break;
            case 2: //上月
                startDate = now.minusMonths(1).withDayOfMonth(1);
                endDate = now.withDayOfMonth(1);
                date =startDate.format(df);
                break;
            case 3: //本季度
                int month = (now.getMonthValue()-1) / 3 * 3 + 1;
                startDate = now.withMonth(month).withDayOfMonth(1);
                date =startDate.format(df) + "至今";
                break;
            case 4: //本年
                startDate = now.withMonth(1).withDayOfMonth(1);
                date =startDate.getYear()+"";
                break;
            case 5: //所有
                date = "全部";
                break;
        }
        Map<String,Object> map = new HashMap<>();
        map.put("startDate",startDate);
        map.put("endDate",endDate);
        map.put("date",date);
        return map;
    }

    /**
     * 回款信息统计
     * @param type
     * @return
     */
    @Cacheable(cacheNames = CacheNames.HOME_B, key = "#type")
    public ReturnMoneyInfoVo returnMoney(Integer type){
        Map<String, Object> mapParam = this.getDate(type);
        LocalDate startDate = (LocalDate)mapParam.get("startDate");
        LocalDate endDate = (LocalDate)mapParam.get("endDate");
        String date = (String)mapParam.get("date");

        //当月合同款总数
        BigDecimal sumMoney= new BigDecimal(0);
        //当月已支付合同金额
        BigDecimal payMoney=new BigDecimal(0);
        //当月合同总数
        Integer contractNum=0;

        Map<String,Object> queryParam=new HashMap<>();
        queryParam.put("startDate",startDate);
        queryParam.put("endDate",endDate);
        queryParam.put("payStatus",PayStatusEnum.SUCCESS.getCode());
        queryParam.put("contractStatus",ContractStatusEnum.INIT.getCode());
        queryParam.put("isCancel",CommonStatusEnum.SUCCESS.getCode());

        List<Map<String,Object>> list = psContractInfoMapper.homePageReturnMoneyInfo(queryParam);
        //记录合同编码，防止重复
        Map<String,Integer> repeatNum=new HashMap<>();
        for(Map<String,Object> m : list){
            //计算已回款金额
            BigDecimal money =m.get("money")==null?new BigDecimal(0):(BigDecimal) m.get("money");
            String businessType=m.get("business_type")==null?"":m.get("business_type").toString();
            //判断是回款还是退款
            if(businessType.equals("1")){
                payMoney = payMoney.add(money);
            }else{
                payMoney = payMoney.subtract(money);
            }


            String contractCode=m.get("contract_code").toString();
            if(repeatNum.get(contractCode)==null){
                repeatNum.put(contractCode,1);
                sumMoney=sumMoney.add((BigDecimal) m.get("contract_amount"));
                contractNum++;
            }
        }

        ReturnMoneyInfoVo res = new ReturnMoneyInfoVo();
        res.setDateStr(date);
        res.setContractNum(contractNum);
        res.setSumMoney(sumMoney);
        res.setPayMoney(payMoney);
        res.setUnPayMoney(sumMoney.subtract(payMoney));
        res.setPayMoneyPer(payMoney.multiply(new BigDecimal("100.0")).divide(sumMoney,2, RoundingMode.HALF_UP).toPlainString()+"%");
        res.setUnPayMoneyPer(res.getUnPayMoney().multiply(new BigDecimal("100.0")).divide(sumMoney,2, RoundingMode.HALF_UP).toPlainString()+"%");
        return res;
    }

    private String contractSource="转介绍";
    /**
     * 按人员成交【转介绍】列表，根据部门获取
     * @param type
     * @param deptId
     * @return
     */
    public Object getUserContractSourceAmountsByDeptId(Integer type,Long deptId){
        Map<String, Object> mapParam = this.getDate(type);
        LocalDate startDate = (LocalDate)mapParam.get("startDate");
        LocalDate endDate = (LocalDate)mapParam.get("endDate");
        String date = (String)mapParam.get("date");

        Map<String,Object> queryParam=new HashMap<>();
        queryParam.put("startDate",startDate);
        queryParam.put("endDate",endDate);
        queryParam.put("contractStatus",ContractStatusEnum.INIT.getCode());
        queryParam.put("isCancel",CommonStatusEnum.SUCCESS.getCode());
        queryParam.put("deptId",deptId);

        List<UserContractAmountInfo> list=psContractInfoMapper.getUserContractSourceAmountsByDeptId(queryParam);
        Map<Long,UserContractAmountVo> res=new HashMap<>();
        //记录合同编码，防止重复
        Map<String,String> repeatContractCode=new HashMap<>();
        for(UserContractAmountInfo obj:list){
            UserContractAmountVo vo=res.get(obj.getUserId());
            if(vo==null){
                vo=new UserContractAmountVo();
                vo.setUserId(obj.getUserId());
                vo.setNickName(obj.getNickName());
                vo.setDateStr(date);
                res.put(obj.getUserId(),vo);
            }
            if(repeatContractCode.get(obj.getContractCode())==null){
                repeatContractCode.put(obj.getContractCode(),obj.getContractCode());
                vo.addSumAmount(obj.getContractAmount());
            }
            //判断是否为转介绍合同
            if(contractSource.equals(obj.getCustomSource())){
                vo.addJieShaoAmount(obj.getContractAmount());
                vo.addJieShaoContractNum();
            }else {
                vo.addOtherAmount(obj.getContractAmount());
            }
        }

        //构建表格第一行数据
        UserContractAmountVo title= new UserContractAmountVo();
        title.setNickName("总计");
        title.setDateStr(date);
        title.setOtherAmount(null);
        title.setSoftwareDevAmount(null);
        title.setTuoGuanAmount(null);
        title.setXuFeiAmount(null);

        //按总金额降序处理
        List<UserContractAmountVo> listData=res.values().stream().sorted(
                Comparator.comparing(UserContractAmountVo::getSumAmount,Comparator.reverseOrder())).collect(Collectors.toList());

        for (UserContractAmountVo v:listData) {
            title.addSumAmount(v.getSumAmount());
        }
        //计算转介绍金额占比
        for (UserContractAmountVo v:listData) {
            if(!BigDecimal.ZERO.equals(v.getJieShaoAmount())) {
                v.setJieShaoPer(v.getJieShaoAmount().multiply(new BigDecimal("100.0")).divide(v.getSumAmount(), 2, RoundingMode.HALF_UP).toPlainString() + "%");
            }else {
                v.setJieShaoPer("0.00%");
            }
        }
        listData.add(0,title);
        return listData;
    }
    /**
     * 按人员成交数据列表,根据部门获取
     * @param type 日期过滤规则
     * @param deptId 部门id
     * @return
     */
    public List getUserContractAmountsByDeptId(Integer type,Long deptId) {
        Map<String, Object> mapParam = this.getDate(type);
        LocalDate startDate = (LocalDate)mapParam.get("startDate");
        LocalDate endDate = (LocalDate)mapParam.get("endDate");
        String date = (String)mapParam.get("date");

        Map<String,Object> queryParam=new HashMap<>();
        queryParam.put("startDate",startDate);
        queryParam.put("endDate",endDate);
        queryParam.put("contractStatus",ContractStatusEnum.INIT.getCode());
        queryParam.put("isCancel",CommonStatusEnum.SUCCESS.getCode());
        queryParam.put("deptId",deptId);
        //查询各类合同总金额
        List<UserContractAmountInfo> list=psContractInfoMapper.getUserContractTypeAmountsByDeptId(queryParam);
        Map<Long,UserContractAmountVo> res=new HashMap<>();
        //记录合同编码，防止重复
        Map<String,String> repeatContractCode=new HashMap<>();
        for(UserContractAmountInfo obj:list){
            UserContractAmountVo vo=res.get(obj.getUserId());

            if(vo==null){
                vo=new UserContractAmountVo();
                vo.setUserId(obj.getUserId());
                vo.setNickName(obj.getNickName());
                vo.setDateStr(date);
                res.put(obj.getUserId(),vo);
            }
            if(repeatContractCode.get(obj.getContractCode())==null){
                repeatContractCode.put(obj.getContractCode(),obj.getContractCode());
                vo.addSumAmount(obj.getContractAmount());
            }

            //托管合同金额累计
            if(obj.getBusinessType()!=null&&obj.getBusinessType().equals("4")){
                vo.addTuoGuanAmount(obj.getContractAmount());
            } else
            //软件开发合同金额累计
            if (obj.getBusinessType()!=null&&obj.getBusinessType().equals("9")) {
                vo.addSoftwareDevAmount(obj.getContractAmount());
            } else
            //其他合同金额累计
            if(obj.getIsDue()==null||obj.getIsDue().equals("0")){
                vo.addOtherAmount(obj.getContractAmount());
            }

            //续签合同金额累计
            if(obj.getIsDue()!=null&&obj.getIsDue().equals("1")){
                vo.addXuFeiAmount(obj.getContractAmount());
            }

        }

        //构建表格第一行数据
        UserContractAmountVo title= new UserContractAmountVo();
        title.setNickName("总计");
        title.setDateStr(date);
        title.setOtherAmount(null);
        title.setSoftwareDevAmount(null);
        title.setTuoGuanAmount(null);
        title.setXuFeiAmount(null);

        //按总金额降序处理
        List<UserContractAmountVo> listData=res.values().stream().sorted(
                Comparator.comparing(UserContractAmountVo::getSumAmount,Comparator.reverseOrder())).collect(Collectors.toList());

        for (UserContractAmountVo v:listData) {
            title.addSumAmount(v.getSumAmount());
        }
        //计算金额占比
        for (UserContractAmountVo v:listData) {
            if(!v.getSumAmount().equals(BigDecimal.ZERO)) {
                v.setAmountPer(v.getSumAmount().multiply(new BigDecimal("100.0")).divide(title.getSumAmount(), 2, RoundingMode.HALF_UP).toPlainString() + "%");
            }else {
                v.setAmountPer("0.00%");
            }
        }

        listData.add(0,title);
        return listData;
    }

    /**
     * 按人员成交数据饼图，所有部门人员
     * @param type
     * @return
     */
    public Object getUserContractAndPayInfo(Integer type){
        Map<String, Object> mapParam = this.getDate(type);
        LocalDate startDate = (LocalDate)mapParam.get("startDate");
        LocalDate endDate = (LocalDate)mapParam.get("endDate");
        String date = (String)mapParam.get("date");

        Map<String,Object> queryParam=new HashMap<>();
        queryParam.put("startDate",startDate);
        queryParam.put("endDate",endDate);
        queryParam.put("contractStatus",ContractStatusEnum.INIT.getCode());
        queryParam.put("isCancel",CommonStatusEnum.SUCCESS.getCode());
        queryParam.put("payStatus",PayStatusEnum.SUCCESS.getCode());

        List<UserContractAmountInfo> list=psContractInfoMapper.getUserContractAndPayInfo(queryParam);
        Map<Long,UserAmountInfoVo> resMap=new HashMap<>();
        for (UserContractAmountInfo obj:list) {
            Long userId=obj.getUserId();
            UserAmountInfoVo vo= resMap.get(userId);
            if(vo==null){
                vo=new UserAmountInfoVo();
                vo.setUserId(userId);
                vo.setNickName(obj.getNickName());
                vo.setDateStr(date);
                resMap.put(userId, vo);
            }
            //累计合同数量
            if(obj.getContractCode()!=null&&obj.getContractCode().length()>0){
                vo.addContractNum();
            }
            vo.addSumAmount(obj.getContractAmount());
            vo.addPayedSumAmount(obj.getPayedMoney());
        }
        //计算未付款金额
        resMap.values().forEach(v->{
            v.setUnPaySumAmount(v.getSumAmount().subtract(v.getPayedSumAmount()));
        });
        return resMap.values();
    }


    /**
     * 首页大盘数据：各渠道成交
     * @param type
     * @param dateType 1查全部数据 2查个人权限的数据
     * @return
     */
    @Cacheable(cacheNames = CacheNames.HOME_C, key = "#type+'_'+#dateType")
    public ChannelAmountVo byChannel(Integer type,Integer dateType){
        Map<String, Object> mapParam = dateType == 1?this.getDate(type):this.getDateByUser(type);
        LocalDate startDate = (LocalDate)mapParam.get("startDate");
        LocalDate endDate = (LocalDate)mapParam.get("endDate");
        String date = (String)mapParam.get("date");
        //返回dto
        ChannelAmountVo res = new ChannelAmountVo();
        res.setDateStr(date);
        log.info("查询日期：{}到{}",startDate,endDate);
        QueryWrapper<PsContractInfo> wq = new QueryWrapper<PsContractInfo>()
                .ne("info.is_due", CommonStatusEnum.SUCCESS.getCode()).ne("info.contract_status", ContractStatusEnum.INIT.getCode())
                .eq("pay.pay_status", PayStatusEnum.SUCCESS.getCode())
                .ge(startDate != null, "info.apply_date", startDate).le(endDate != null, "info.apply_date", endDate);
        List<ChannelPayInfo> list;
        if(dateType == 1){//所有的数据权限
            list = psContractInfoMapper.byChannel(wq);
        }else{//用户个人的数据权限
            list = psContractInfoMapper.byChannelUser(wq);
        }

        //查询各个渠道的字典表
        SysDictDataBo dictData = new SysDictDataBo();
        dictData.setInDictType(List.of("custom_source"));
        List<SysDictDataVo> dictList = dictDataService.selectDictDataList(dictData);
        //取字典label（）
        List<String> configList = dictList.stream().map(SysDictDataVo::getDictLabel).toList();
        //把支付信息根据渠道分组（方便下面使用）
        Map<String, List<ChannelPayInfo>> map = list.stream().collect(Collectors.groupingBy(ChannelPayInfo::getChannel, Collectors.toList()));
        //各渠道的支付信息
        List<DataAmountVo> channelList = new ArrayList<>();
        //便利渠道，装填各个渠道信息
        for (String item : configList){
            DataAmountVo data = new DataAmountVo();
            List<ChannelPayInfo> payList = map.get(item) == null ? new ArrayList<>() : map.get(item);
            Set<String> contractCodes = new HashSet<>();
            BigDecimal money = BigDecimal.ZERO;
            BigDecimal paymoney = BigDecimal.ZERO;
            for (ChannelPayInfo pay : payList){
                contractCodes.add(pay.getContractCode());
                money = money.add(pay.getContractAmount());
                paymoney = pay.getBusinessType().equals("1")? paymoney.add(pay.getMoney()) : paymoney.subtract(pay.getMoney());
            }
            BigDecimal unpaymoney = money.subtract(paymoney);
            data.setNum(contractCodes.size()+"单");
            data.setMoney(money);
            data.setPayMoney(paymoney);
            data.setUnPayMoney(unpaymoney);
            data.setType(item);
            channelList.add(data);
        }
        res.setChannelList(channelList);
        //计算总金额和占比
        res.cellPer();
        return res;
    }


    /**
     * 首页大盘数据：任务完成率
     * @param type
     * @return
     */
    @Cacheable(cacheNames = CacheNames.HOME_H, key = "#type")
    public FinishTaskVo getTaskList(Integer type){
        Map<String, Object> mapParam = this.getDate(type);
        LocalDate startDate = (LocalDate)mapParam.get("startDate");
        LocalDate endDate = (LocalDate)mapParam.get("endDate");
        String date = (String)mapParam.get("date");

        LambdaQueryWrapper<PsTaskMain> wq = Wrappers.<PsTaskMain>lambdaQuery().ne(PsTaskMain::getTaskStatus, TaskStatusEnum.CANCEL.getCode())
                .ge(startDate != null,PsTaskMain::getCreateTime,startDate)
                .le(endDate != null,PsTaskMain::getCreateTime,endDate);
        //任务的总数
        Long count = taskMainMapper.selectCount(wq);
        wq.eq(PsTaskMain::getTaskStatus, TaskStatusEnum.FINISH.getCode());
        //完成任务的总数
        Long finishCount = taskMainMapper.selectCount(wq);

        FinishTaskVo finishTaskVo = new FinishTaskVo();
        finishTaskVo.setDateStr(date);
        finishTaskVo.setFinishNum(finishCount);
        finishTaskVo.setCount(count);
        finishTaskVo.setUnfinishNum(count-finishCount);
        finishTaskVo.setFinishPre(new BigDecimal(finishCount).divide(new BigDecimal(count),4,RoundingMode.HALF_UP).multiply(new BigDecimal("100")).toPlainString());
        finishTaskVo.setUnfinishPre(new BigDecimal(finishTaskVo.getUnfinishNum()).divide(new BigDecimal(count),4,RoundingMode.HALF_UP).multiply(new BigDecimal("100")).toPlainString());
        return finishTaskVo;
    }


    /**
     * 首页大盘数据：任务完成时间
     * @param type
     * @return
     */
    @Cacheable(cacheNames = CacheNames.HOME_I, key = "#type")
    public Map<String,Object> getTaskTime(Integer type){
        Map<String, Object> mapParam = this.getDate(type);
        LocalDate startDate = (LocalDate)mapParam.get("startDate");
        LocalDate endDate = (LocalDate)mapParam.get("endDate");
        String date = (String)mapParam.get("date");
        //返回map
        Map<String,Object> map = new HashMap<>();

        //查范围内创建并且范围内完成的数据
        List<Map<String, Object>> allList = taskMainMapper.selectMaps(Wrappers.<PsTaskMain>query().select("round(AVG(TIMESTAMPDIFF(day, create_time, finish_date) )) avg")
                .eq("task_status", TaskStatusEnum.FINISH.getCode())
                .ge(startDate != null, "create_time", startDate).le(endDate != null, "create_time", endDate)
                .ge(startDate != null, "finish_date", startDate).le(endDate != null, "finish_date", endDate));

        List<Map<String, Object>> appointList = taskAppointMapper.selectMaps(Wrappers.<PsTaskAppoint>query().select("appoint_type","round(AVG(TIMESTAMPDIFF(day, create_time, finish_date) )) avg")
                .eq("appoint_status", TaskStatusEnum.AppointStatusEnum.FINISH.getCode())
                .ge(startDate != null, "create_time", startDate).le(endDate != null, "create_time", endDate)
                .ge(startDate != null, "finish_date", startDate).le(endDate != null, "finish_date", endDate)
                .groupBy("appoint_type"));
        map.put("taskAvg",allList.get(0).get("avg"));//任务平均天数
        map.put("inAvg",0);//内勤
        map.put("outAvg",0);//外勤
        map.put("secAvg",0);//特勤
        map.put("dateStr",date);//
        map.put("currentDate", DateUtils.parseDateToStr("yyyy-MM-dd HH:mm",new Date()));//当前时间
        for(Map<String, Object> appointMap : appointList){
            if(StringUtils.equals("1",appointMap.get("appoint_type").toString())){
                appointMap.put("inAvg",appointMap.get("avg"));
            }else if(StringUtils.equals("2",appointMap.get("appoint_type").toString())){
                appointMap.put("outAvg",appointMap.get("avg"));
            }else if(StringUtils.equals("3",appointMap.get("appoint_type").toString())){
                appointMap.put("secAvg",appointMap.get("avg"));
            }
        }
        return map;
    }
    /**
     * 首页大盘数据：销售数据统计
     * @param type
     * @return
     */
    public Map<String,Object> salasData(Integer type){
        Map<String, Object> mapParam = this.getDateByUser(type);
        LocalDate startDate = (LocalDate)mapParam.get("startDate");
        LocalDate endDate = (LocalDate)mapParam.get("endDate");
        String date = (String)mapParam.get("date");




        //返回map
        Map<String,Object> map = new HashMap<>();
        map.put("dateStr",date);//
        map.put("currentDate", DateUtils.parseDateToStr("yyyy-MM-dd HH:mm",new Date()));//当前时间
        return null;
    }

    public static Map<String, Object> getDateByUser(Integer type){
        LocalDate startDate = null;
        LocalDate endDate = null;
        String date = "";
        LocalDate now = LocalDate.now();
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        switch (type){
            case 1://今日
                startDate = now;
                date =startDate.format(df);
                break;
            case 2: //昨日
                startDate = now.plusDays(-1);
                endDate = now;
                date =startDate.format(df);
                break;
            case 3: //本周
                startDate = now.with(TemporalAdjusters.previousOrSame(java.time.DayOfWeek.MONDAY));
                date =startDate.format(df) + " 至今";
                break;
            case 4: //上周
                endDate = now.with(TemporalAdjusters.previousOrSame(java.time.DayOfWeek.MONDAY));
                startDate = endDate.plusDays(-7);
                date =startDate.format(df) +" 至 "+ endDate.format(df);
                break;
            case 5: //本月
                startDate = now.withDayOfMonth(1);
                date =startDate.format(DateTimeFormatter.ofPattern("yyyy-MM"));
                break;
            case 6: //上月
                startDate = now.minusMonths(1).withDayOfMonth(1);
                endDate = now.withDayOfMonth(1);
                date =startDate.format(DateTimeFormatter.ofPattern("yyyy-MM"));
                break;
        }
        Map<String,Object> map = new HashMap<>();
        map.put("startDate",startDate);
        map.put("endDate",endDate);
        map.put("date",date);
        return map;
    }
}
