package cn.com.countrygarden.bi.main.service.dup.impl;

import cn.com.countrygarden.bi.main.core.Response;
import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.dao.dup.ManagerDataMapper;
import cn.com.countrygarden.bi.main.dao.dup.ManagerDataStatusMapper;
import cn.com.countrygarden.bi.main.dao.manager.map.ManagerHousekeeperCacheMapper;
import cn.com.countrygarden.bi.main.dao.personnel.FenghuangCollectionrateMapper;
import cn.com.countrygarden.bi.main.dao.twerp.hm.TbHsprCommunityMapper;
import cn.com.countrygarden.bi.main.dto.FenghuangCollectionrateDTO;
import cn.com.countrygarden.bi.main.dto.HouseKeeperDTO;
import cn.com.countrygarden.bi.main.dto.manager.ManagerKeeperDTO;
import cn.com.countrygarden.bi.main.exception.ServiceException;
import cn.com.countrygarden.bi.main.model.PageData;
import cn.com.countrygarden.bi.main.model.dup.FenghuangCollectionrate;
import cn.com.countrygarden.bi.main.model.dup.ManagerData;
import cn.com.countrygarden.bi.main.model.dup.ManagerDataConstant;
import cn.com.countrygarden.bi.main.model.dup.ManagerDataStatus;
import cn.com.countrygarden.bi.main.model.twerp.ErpCommunity;
import cn.com.countrygarden.bi.main.service.dup.DupCommService;
import cn.com.countrygarden.bi.main.service.dup.ManagerDataService;
import cn.com.countrygarden.bi.main.util.DateUtil;
import cn.com.countrygarden.bi.main.util.NumberUtil;
import cn.com.countrygarden.bi.main.util.erp.StringUtil;
import com.github.pagehelper.ISelect;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageRowBounds;
import com.salesforce.SurveyConfigService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.LogManager;
import java.util.logging.Logger;

/**
 * Created by chenweijiang on 2017/9/11.
 */
@Service
@Transactional
public class ManagerDataServiceImpl implements ManagerDataService {

    @Autowired
    private ManagerDataMapper managerDataMapper;
    @Autowired
    private ManagerDataStatusMapper managerDataStatusMapper;

    @Autowired
    private TbHsprCommunityMapper tbHsprCommunityMapper;

    @Autowired
    private DupCommService dupCommService;

    @Autowired
    private ManagerHousekeeperCacheMapper managerHousekeeperCacheMapper;

    @Autowired
    private SurveyConfigService surveyConfigService;

    @Autowired
    private FenghuangCollectionrateMapper fenghuangCollectionrateMapper;

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    static Logger logger = LogManager.getLogManager().getLogger(ManagerDataServiceImpl.class.getName());

    @Override
    @Transactional("txManager")
    public void addManagers(List<ManagerData> managerDates, String userCode) {
        boolean isDuplicate = checkDuplicate(managerDates);
        if (isDuplicate) {
            throw new ServiceException("同一周期内同一项目，管家名不能重复，请重新输入");
        }

        ManagerData firstData = managerDates.get(0);
        Date beginDate = DateUtils.truncate(firstData.getBeginDate(), Calendar.DATE);
        Date endDate = DateUtils.truncate(firstData.getEndDate(), Calendar.DATE);
        prepareUnFillManagerData(firstData.getOrganCode(), firstData.getCommId(), beginDate, endDate, userCode);

        ManagerData unFilleQuery = new ManagerData();
        unFilleQuery.setStatus(ManagerDataConstant.ManagerDataStatus.unfill);
        unFilleQuery.setOrganCode(managerDates.get(0).getOrganCode());
        unFilleQuery.setCommId(managerDates.get(0).getCommId());
        unFilleQuery.setBeginDate(beginDate);
        unFilleQuery.setEndDate(endDate);
        List<ManagerData> unFillData = managerDataMapper.select(unFilleQuery);
        if (unFillData.size() > 0) {
            managerDataMapper.deleteByPrimaryKey(unFillData.get(0).getId());
        }


        Date currentDate = new Date();
        for (ManagerData managerData : managerDates) {
//            long requestReceived = managerData.getReceivedQuickEvents();
//            requestReceived += managerData.getReceivedRepairEvents();
//            requestReceived += managerData.getReceivedComplaintEvents();
            if (managerData.getCollectionRateTarget() != null && managerData.getCollectionRateTarget() != 0.0 && managerData.getCollectionRateTarget() != 0
                    && managerData.getCollectionRate() != null) {
                double collra = managerData.getCollectionRate() / managerData.getCollectionRateTarget() * 100;
                BigDecimal bgcollra = new BigDecimal(collra).setScale(2, RoundingMode.UP);
                managerData.setCompletionRate(bgcollra.doubleValue());
            }

            if (managerData.getCollectionRate() == null) {
                managerData.setCollectionRate(0.0);
            }

            if (managerData.getCompletionRate() == null) {
                managerData.setCompletionRate(0.0);
            }
            managerData.setRequestReceived(0L);

            Long customers = managerData.getCustomres();
            Long wechatCustomers = managerData.getWechatCustomers();
            Long addedWechat = managerData.getAddedWechat();
            BigDecimal wechatPercentageBD = new BigDecimal(addedWechat);
            BigDecimal wechatCoverPercentageBD = new BigDecimal(wechatCustomers);
            if (customers == 0) {
                wechatPercentageBD = new BigDecimal(0);
                wechatCoverPercentageBD = new BigDecimal(0);
            } else {
                wechatPercentageBD = wechatPercentageBD.divide(new BigDecimal(customers * 2), 4, BigDecimal.ROUND_HALF_UP);
                wechatPercentageBD.setScale(2, BigDecimal.ROUND_HALF_UP);
                wechatPercentageBD = wechatPercentageBD.multiply(new BigDecimal(100));


                wechatCoverPercentageBD = wechatCoverPercentageBD.divide(new BigDecimal(customers), 4, BigDecimal.ROUND_HALF_UP);
                wechatCoverPercentageBD.setScale(2, BigDecimal.ROUND_HALF_UP);
                wechatCoverPercentageBD = wechatCoverPercentageBD.multiply(new BigDecimal(100));
            }
            managerData.setWechatPercentage(wechatPercentageBD.doubleValue());
            managerData.setWechatCoverPercentage(wechatCoverPercentageBD.doubleValue());

//            long requestSolved = managerData.getSolvedQuickEvents();
//            requestSolved += managerData.getSolvedRepairEvents();
//            requestSolved += managerData.getSolvedComplaintEvents();
            managerData.setBeginDate(beginDate);
            managerData.setEndDate(endDate);
            managerData.setRequestSolved(0L);
            managerData.setStatus(ManagerDataConstant.ManagerDataStatus.completed);
            managerData.setCreatedDate(currentDate);
            managerData.setUpdatedDate(currentDate);
            managerData.setCreatedBy(userCode);
            managerData.setUpdatedBy(userCode);
            managerData.setWechatPraise(0L);
            managerData.setWechatSubscription(0L);
            managerData.setReceivedQuickEvents(0L);
            managerData.setReceivedComplaintEvents(0L);
            managerData.setReceivedRepairEvents(0L);
            managerData.setSolvedComplaintEvents(0L);
            managerData.setSolvedQuickEvents(0L);
            managerData.setSolvedRepairEvents(0L);

        }
        managerDataMapper.insertList(managerDates);

    }

    private boolean checkDuplicate(List<ManagerData> managerDateList) {
        Map<String, String> dataMap = new HashMap<String, String>();

        for (ManagerData data : managerDateList) {
            String dataKey = data.getManagerName();
            if (dataMap.get(dataKey) == null) {
                dataMap.put(data.getManagerName(), data.getManagerName());
            } else {
                return true;
            }
        }
        if (managerDateList.size() > 0) {
            ManagerData data = managerDateList.get(0);
            ManagerData query = new ManagerData();
            query.setBeginDate(data.getBeginDate());
            query.setEndDate(data.getEndDate());
            query.setOrganCode(data.getOrganCode());
            query.setCommId(data.getCommId());
            query.setStatus("completed");
            List<ManagerData> dbDataList = managerDataMapper.select(query);
            if (data.getId() != null) {

                for (ManagerData dbData : dbDataList) {
                    if (data.getId().intValue() != dbData.getId().intValue() && dataMap.get(dbData.getManagerName()) != null) {
                        return true;
                    }
                }
            } else {
                for (ManagerData dbData : dbDataList) {
                    if (dataMap.get(dbData.getManagerName()) != null) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    @Override
    @Transactional("txManager")
    public void updateManagerData(ManagerData managerData, String userCode) {
        List<ManagerData> managerDates = new ArrayList<ManagerData>();
        managerDates.add(managerData);
        boolean isDuplicate = checkDuplicate(managerDates);
        if (isDuplicate) {
            throw new ServiceException("同一周期内同一项目，管家名不能重复，请重新输入");
        }

        Long customers = managerData.getCustomres();
        Long wechatCustomers = managerData.getWechatCustomers();
        Long addedWechat = managerData.getAddedWechat();
        BigDecimal wechatPercentageBD = new BigDecimal(addedWechat);
        BigDecimal wechatCoverPercentageBD = new BigDecimal(wechatCustomers);
        if (customers == 0) {
            wechatPercentageBD = new BigDecimal(0);
            wechatCoverPercentageBD = new BigDecimal(0);
        } else {
            wechatPercentageBD = wechatPercentageBD.divide(new BigDecimal(customers * 2), 4, BigDecimal.ROUND_HALF_UP);
            wechatPercentageBD.setScale(2, BigDecimal.ROUND_HALF_UP);
            wechatPercentageBD = wechatPercentageBD.multiply(new BigDecimal(100));


            wechatCoverPercentageBD = wechatCoverPercentageBD.divide(new BigDecimal(customers), 4, BigDecimal.ROUND_HALF_UP);
            wechatCoverPercentageBD.setScale(2, BigDecimal.ROUND_HALF_UP);
            wechatCoverPercentageBD = wechatCoverPercentageBD.multiply(new BigDecimal(100));
        }
        managerData.setWechatPercentage(wechatPercentageBD.doubleValue());
        managerData.setWechatCoverPercentage(wechatCoverPercentageBD.doubleValue());

        if (managerData.getCollectionRateTarget() != 0 && managerData.getCollectionRateTarget() != null && managerData.getCollectionRateTarget() != 0.0 && managerData.getCollectionRate() != null) {
            double collra = managerData.getCollectionRate() / managerData.getCollectionRateTarget() * 100;
            BigDecimal bgcollra = new BigDecimal(collra).setScale(2, RoundingMode.UP);
            managerData.setCompletionRate(bgcollra.doubleValue());
        }


        Date currentDate = new Date();
//        long requestReceived = managerData.getReceivedQuickEvents();
//        requestReceived += managerData.getReceivedRepairEvents();
//        requestReceived += managerData.getReceivedComplaintEvents();
//        managerData.setRequestReceived(requestReceived);

//        long requestSolved = managerData.getSolvedQuickEvents();
//        requestSolved += managerData.getSolvedRepairEvents();
//        requestSolved += managerData.getSolvedComplaintEvents();
//        managerData.setRequestSolved(requestSolved);
        managerData.setUpdatedDate(currentDate);
        managerData.setUpdatedBy(userCode);
        managerData.setStatus(null);
        managerDataMapper.updateByPrimaryKeySelective(managerData);
    }

    @Override
    @Transactional("txManager")
    public void deleteManagerData(Integer managerDataId, String userCode) {
        ManagerData managerData = managerDataMapper.selectByPrimaryKey(managerDataId);

        ManagerData countQuery = new ManagerData();
        countQuery.setStatus(ManagerDataConstant.ManagerDataStatus.completed);
        countQuery.setCommId(managerData.getCommId());
        countQuery.setOrganCode(managerData.getOrganCode());
        countQuery.setBeginDate(managerData.getBeginDate());
        countQuery.setEndDate(managerData.getEndDate());
        int count = managerDataMapper.selectCount(countQuery);
        if (count == 0) {
            return;
        }
        if (count == 1) {
            resetManagerData(managerData);
            managerData.setUpdatedBy(userCode);
            managerData.setUpdatedDate(new Date());
            managerData.setStatus(ManagerDataConstant.ManagerDataStatus.unfill);
            managerData.setManagerName(null);
            managerDataMapper.updateByPrimaryKey(managerData);
        } else {
            managerDataMapper.deleteByPrimaryKey(managerDataId);
        }
    }

    @Override
    @Transactional("txManager")
    public List<ManagerData> findLastManagers(String organCode, String commId, String startDateStr, String endDateStr, String startDateInquire, String endDateInquire) {
        Date startDateInqu = null;
        Date endDateInqu = null;
        if (startDateInquire != null && !startDateInquire.equals("") && endDateInquire != null && !endDateInquire.equals("")) {
            startDateInqu = DateUtil.parseDate(startDateInquire);
            endDateInqu = DateUtil.parseDate(endDateInquire);
        }
        Calendar rightNow = Calendar.getInstance();
        rightNow.setTime(new Date());
        rightNow.add(Calendar.MONTH, -2);
        Date dt1 = rightNow.getTime();
        String reStr = dateFormat.format(dt1);

        String minMonth = getMinMonthDate(reStr);
        String maxMonth = getMaxMonthDate(reStr);

        List<ManagerData> managers = new ArrayList<ManagerData>();
        Condition condition = new Condition(ManagerData.class);
        Example.Criteria criteria = condition.createCriteria();
        criteria.andEqualTo("organCode", organCode);
        criteria.andEqualTo("commId", commId);
        criteria.andEqualTo("status", ManagerDataConstant.ManagerDataStatus.completed);
        if (startDateInqu != null && endDateInqu != null) {
            criteria.andBetween("beginDate", startDateInqu, endDateInqu);
        }
        condition.setOrderByClause("begin_date desc");
        Page<ManagerData> page = PageHelper.startPage(1, 1).doSelectPage(new ISelect() {
            @Override
            public void doSelect() {
                managerDataMapper.selectByCondition(condition);
            }
        });
//        if (page.size() <= 0) {
//            return managers;
//        }

//      获取管家列表
        List<ManagerKeeperDTO> housekeeperCaches = managerHousekeeperCacheMapper.selectByKeeper(organCode,
                commId);

        List<ManagerData> lastDataListDTO = new ArrayList<>();
//      如果没有管家的情况下
        if (CollectionUtils.isEmpty(housekeeperCaches)) {
            housekeeperCaches=new ArrayList<>();
        }
//      获取上月的管家全部数据
        List<ManagerData> lastDataListMapp = managerDataMapper.lastDataListDTO(null, organCode, commId,
                ManagerDataConstant.ManagerDataStatus.completed, minMonth, maxMonth);
        if (CollectionUtils.isEmpty(lastDataListMapp)) {
            lastDataListMapp=new ArrayList<>();
        }
//      返回合集
        return mergeManagerData(lastDataListMapp,housekeeperCaches);
    }

    /**
     * 获取数据合集
     * @param lastDataListDTO
     * @param houseKeeperDTOS
     * @return
     */
    private List<ManagerData> mergeManagerData(List<ManagerData> lastDataListDTO, List<ManagerKeeperDTO> houseKeeperDTOS) {
        Map<String,ManagerData> managerDataMap=new HashMap<>(lastDataListDTO.size());
//      放置管家地图管家
        for (ManagerKeeperDTO dto : houseKeeperDTOS) {
            managerDataMap.put(dto.getName(),buildTmpManagerData(dto));
        }
//      放置上月数据包含的管家
        if(CollectionUtils.isNotEmpty(lastDataListDTO)){
            for (ManagerData managerData : lastDataListDTO) {
                ManagerData data = managerDataMap.get(managerData.getManagerName());
                managerData.setSource(0);
                if(data!=null){
                    managerData.setCollectionRate(data.getCollectionRate());
                    managerData.setSource(data.getSource());
                    managerData.setUserId(data.getUserId());
                }
                if(managerData.getCollectionRate()==null||managerData.getCollectionRate()==0){
                    buildCollectionRate(managerData);
                }
                managerDataMap.put(managerData.getManagerName(),managerData);
            }
        }
        List<ManagerData> result=new ArrayList<>(managerDataMap.size());
        Iterator<String> iterator = managerDataMap.keySet().iterator();
        while (iterator.hasNext()){
            result.add(managerDataMap.get(iterator.next()));
        }
        return result;
    }


    private void buildCollectionRate(ManagerData managerData) {
        Double rate=fenghuangCollectionrateMapper.selectNewCollectionRate(managerData.getUserId());
        if(rate!=null)managerData.setCollectionRate(rate);
    }

    private ManagerData buildTmpManagerData(ManagerKeeperDTO dto) {
        ManagerData data=new ManagerData();
        data.setOrganCode(dto.getOrganCode());
        data.setOrganName(dto.getOrganName());
        data.setCommId(dto.getCommCode());
        data.setCommName(dto.getCommName());
        data.setManagerName(dto.getName());
        data.setCollectionRate(dto.getCollectionRate());
        data.setUserId(dto.getUserId());
        data.setSource(1);
        data.setFiles("[]");
        return data;
    }

    public String getMinMonthDate(String date) {
        Calendar calendar = Calendar.getInstance();
        try {
            calendar.setTime(dateFormat.parse(date));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
        return dateFormat.format(calendar.getTime());
    }

    public String getMaxMonthDate(String date) {
        Calendar calendar = Calendar.getInstance();
        try {
            calendar.setTime(dateFormat.parse(date));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        return dateFormat.format(calendar.getTime());
    }


    @Override
    @Transactional("txManager")
    public Result findManagerData(Boolean isUnFinished, String organCode, String commId, String startDateStr, String endDateStr, String userCode, int size, int page) {
        Date startDate = DateUtil.parseDate(startDateStr);
        Date endDate = DateUtil.parseDate(endDateStr);
        prepareUnFillManagerData(organCode, commId, startDate, endDate, userCode);
        Map<String, Object> queryMap = new HashMap<String, Object>();
        queryMap.put("beginDate", startDate);
        queryMap.put("endDate", endDate);
        //当区域没有选择时查询可查的项目

        List<String> CommIdfenghuang = tbHsprCommunityMapper.findCommsByUserCodeAndOrganCodefenghuang(userCode, organCode);

        if (StringUtils.isEmpty(commId)) {
            List<ErpCommunity> organBase = tbHsprCommunityMapper.findOrganBaseByUserCode(userCode, organCode);
            List<ErpCommunity> commBase = tbHsprCommunityMapper.findCommBaseByUserCode(userCode, organCode);

            List<String> organCodes = new ArrayList<String>();
            List<String> commIds = new ArrayList<String>();
            for (ErpCommunity community : organBase) {
                organCodes.add(community.getOrganCode());
            }
            for (ErpCommunity community : commBase) {
                commIds.add(community.getCommId());
            }
            if (organCodes.size() > 0) {
                queryMap.put("organCodes", organCodes);
            }
            if (commIds.size() > 0) {
                queryMap.put("commIds", commIds);
            }
            if (organCodes.size() == 0 && commIds.size() == 0) {
                List<ManagerData> emptyList = new ArrayList<ManagerData>();
                PageRowBounds pageRowBounds = new PageRowBounds(page, size);
                pageRowBounds.setTotal(0l);
                PageData pageData = new PageData(emptyList, pageRowBounds);
                return Response.response(pageData);
            }
        } else {
            queryMap.put("organCode", organCode);
            queryMap.put("commId", commId);
        }
        if (isUnFinished) {
            queryMap.put("status", ManagerDataConstant.ManagerDataStatus.unfill);
        }
        if (CommIdfenghuang.size() != 0) {
            queryMap.put("CommIdfenghuang", CommIdfenghuang);
        }
        PageRowBounds pageRowBounds = new PageRowBounds(page, size);
        pageRowBounds.setCount(true);
        List<ManagerData> result =buildManagerPageData(queryMap,pageRowBounds);
        String dateRang = DateUtil.monthFormat(startDate, endDate);
        for (ManagerData data : result) {
            data.setDateRang(dateRang);
        }
        if (!isUnFinished) {
            List<ManagerData> sum = managerDataMapper.sumByDate(queryMap);
            ManagerData summary = null;
            if (sum.size() > 0) {
                summary = sum.get(0);
            } else {
                summary = generateEmptyDate(startDate, endDate);
                summary.setOrganName("0");
                summary.setCommName("0");
                summary.setManagerName("0");
            }
            //计算百分比
//            String organ = paramMap.get("organCode") == null ? null : String.valueOf(paramMap.get("organCode"));
            int total = StringUtil.isBlank(summary.getManagerName()) ? 0 : Integer.parseInt(summary.getManagerName());
            double avgPhonePercentage = summary.getPhonePercentage() != null ? NumberUtil.avgPercentage(summary.getPhonePercentage(), total) : 0;
            summary.setPhonePercentage(avgPhonePercentage);
            double avgWechatPercentage = summary.getWechatPercentage() != null ? NumberUtil.avgPercentage(summary.getWechatPercentage(), total) : 0;
            summary.setWechatPercentage(avgWechatPercentage);
            double avgWechatCoverPercentage = summary.getWechatCoverPercentage() != null ? NumberUtil.avgPercentage(summary.getWechatCoverPercentage(), total) : 0;
            summary.setWechatCoverPercentage(avgWechatCoverPercentage);
            double avgRecognitionPercentage = summary.getRecognitionPercentage() != null ? NumberUtil.avgPercentage(summary.getRecognitionPercentage(), total) : 0;
            summary.setRecognitionPercentage(avgRecognitionPercentage);
            double avgSatisfaction = summary.getSatisfaction() != null ? NumberUtil.avgPercentage(summary.getSatisfaction(), total) : 0;
            summary.setSatisfaction(avgSatisfaction);

            double avgcompletionRate = summary.getCompletionRate() != null ? NumberUtil.avgPercentage(summary.getCompletionRate(), total) : 0;
            BigDecimal bg = new BigDecimal(avgcompletionRate).setScale(2, RoundingMode.UP);
            summary.setCompletionRate(bg.doubleValue());

            double avgcollectionRate = summary.getCollectionRate() != null ? NumberUtil.avgPercentage(summary.getCollectionRate(), total) : 0;
            summary.setCollectionRate(avgcollectionRate);

            double avgcollectionRateTarget = summary.getCollectionRateTarget() != null ? NumberUtil.avgPercentage(summary.getCollectionRateTarget(), total) : 0;
            summary.setCollectionRateTarget(avgcollectionRateTarget);

            summary.setStatus(ManagerDataConstant.ManagerDataStatus.sum);
            result.add(0, summary);

        }

        for (int i = 0; i < result.size(); i++) {
            int countManagerData = managerDataStatusMapper.countManagerData(result.get(i).getOrganCode(), result.get(i).getCommId());
            if (countManagerData <= 0) {
                result.get(i).setOrganName("-");
                result.get(i).setCommName("-");
            }
        }

        PageData pageData = new PageData(result, pageRowBounds);
        return Response.response(pageData);
    }

    /**
     * 构建管家数据
     * @param queryMap
     * @param pageRowBounds
     * @return
     */
    private List<ManagerData> buildManagerPageData(Map<String, Object> queryMap, PageRowBounds pageRowBounds) {
        Date beginDate = (Date) queryMap.get("beginDate");
        if(DateUtil.isLastMonth(beginDate)){
//          上月取合集展示
            return managerDataMapper.fincByLastMonth(queryMap, pageRowBounds);
        }
//      过往只展示管家数据
        return managerDataMapper.fincByDate(queryMap, pageRowBounds);
    }

    private void prepareUnFillManagerData(String organCode, String commId, Date startDate, Date endDate, String userCode) {
        ManagerDataStatus query = new ManagerDataStatus();
        query.setBeginDate(startDate);
        query.setEndDate(endDate);
        List<ManagerDataStatus> statusList = managerDataStatusMapper.select(query);

        if (statusList.size() == 0) {
            generateUnfillData(startDate, endDate, userCode);
            ManagerDataStatus status = new ManagerDataStatus();
            status.setBeginDate(startDate);
            status.setEndDate(endDate);
            status.setCreatedBy(userCode);
            status.setCreatedDate(new Date());
            status.setStatus(ManagerDataConstant.ManagerDataStatus.completed);
            managerDataStatusMapper.insert(status);
        }
    }

    private List<ManagerData> generateUnfillData(Date startDate, Date endDate, String userCode) {
        List<ErpCommunity> communitis = tbHsprCommunityMapper.findAllBaseComm();
        List<ManagerData> dataList = new ArrayList<ManagerData>();
        for (ErpCommunity community : communitis) {
            ManagerData data = generateEmptyDate(startDate, endDate);
            data.setOrganCode(community.getOrganCode());
            data.setOrganName(community.getOrganName());
            data.setCommId(community.getCommId());
            data.setCommName(community.getCommName());
            data.setStatus(ManagerDataConstant.ManagerDataStatus.unfill);
            data.setCreatedBy(userCode);
            data.setUpdatedBy(userCode);
            data.setCreatedDate(new Date());
            data.setUpdatedDate(data.getCreatedDate());
            dataList.add(data);
        }
        if (dataList.size() > 0) {
            managerDataMapper.insertList(dataList);
        }

        return dataList;
    }

    private ManagerData resetManagerData(ManagerData data) {
        data.setPhonePercentage(0d);
        data.setWechatPercentage(0d);
        data.setWechatCoverPercentage(0d);
        data.setRecognitionPercentage(0d);
        data.setSatisfaction(0d);
        data.setReceivedQuickEvents(0l);
        data.setReceivedRepairEvents(0l);
        data.setReceivedComplaintEvents(0l);
        data.setSolvedQuickEvents(0l);
        data.setSolvedRepairEvents(0l);
        data.setSolvedComplaintEvents(0l);
        data.setRequestReceived(0l);
        data.setRequestSolved(0l);
        data.setWechatPraise(0l);
        data.setLetterPraise(0l);
        data.setBannerNum(0l);
        data.setOtherPraise(0l);
        data.setWechatSubscription(0l);
        data.setCustomres(0l);
        data.setAddedWechat(0l);
        data.setWechatCustomers(0l);
        return data;
    }

    private ManagerData generateEmptyDate(Date startDate, Date endDate) {
        ManagerData data = new ManagerData();
        data.setBeginDate(startDate);
        data.setEndDate(endDate);
        data.setCreatedDate(new Date());
        data.setUpdatedDate(data.getCreatedDate());
        data.setCustomres(0l);
        data.setWechatCustomers(0l);
        data.setAddedWechat(0l);
        data.setPhonePercentage(0d);
        data.setWechatPercentage(0d);
        data.setWechatCoverPercentage(0d);
        data.setRecognitionPercentage(0d);
        data.setSatisfaction(0d);
        data.setReceivedQuickEvents(0l);
        data.setReceivedRepairEvents(0l);
        data.setReceivedComplaintEvents(0l);
        data.setSolvedQuickEvents(0l);
        data.setSolvedRepairEvents(0l);
        data.setSolvedComplaintEvents(0l);
        data.setRequestReceived(0l);
        data.setRequestSolved(0l);
        data.setWechatPraise(0l);
        data.setLetterPraise(0l);
        data.setBannerNum(0l);
        data.setOtherPraise(0l);
        data.setWechatSubscription(0l);
        return data;
    }

    @Override
    public Result collectionRate(String employeeNumber) {

        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateCacheData(List<FenghuangCollectionrate> fDtosSavelist, List<FenghuangCollectionrate> fDtosUpdatelist, List<FenghuangCollectionrateDTO> fDtoUpdateList, String time) {
        if(CollectionUtils.isEmpty(fDtosSavelist)){
            return;
        }
        List<String> userIds=new ArrayList<>();
        for (FenghuangCollectionrate rate : fDtosSavelist) {
            userIds.add(rate.getUserId());
        }
//      因加入增量方式，添加新数据需先忽略旧数据
        fenghuangCollectionrateMapper.deleteColl(time,userIds);

        if (CollectionUtils.isNotEmpty(fDtosSavelist)) fenghuangCollectionrateMapper.insertList(fDtosSavelist);
        for (FenghuangCollectionrate collectionrate : fDtosUpdatelist) {
            fenghuangCollectionrateMapper.updatecoll(collectionrate);
        }
        for (FenghuangCollectionrateDTO collectionrate : fDtoUpdateList) {
            fenghuangCollectionrateMapper.updateFenghuangCollectionrate(collectionrate);
        }

    }


}
