package cn.com.countrygarden.bi.main.service.manager.map.util;

import cn.com.countrygarden.bi.main.dao.manager.map.*;
import cn.com.countrygarden.bi.main.dao.twerp.hm.ManagerMapForErpMapper;
import cn.com.countrygarden.bi.main.dto.*;
import cn.com.countrygarden.bi.main.model.manager.map.ManagerHousekeeperCache;
import cn.com.countrygarden.bi.main.model.manager.map.ManagerHousekeeperCacheTemporary;
import cn.com.countrygarden.bi.main.model.manager.map.ManagerMapCache;
import cn.com.countrygarden.bi.main.model.manager.map.ManagerMapCacheTemporary;
import cn.com.countrygarden.bi.main.service.manager.map.*;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.slf4j.Logger;
import java.math.BigDecimal;
import java.util.*;

/**
 * package: cn.com.countrygarden.bi.main.service.manager.map
 * describe:
 * creat_user: lsl
 * creat_date: 2018/11/28
 * creat_time: 13:25
 **/
@Component
public class ManagerMapUtil {

    @Autowired
    private ManagerMapService managerMapService;
    @Autowired
    private ManagerMapCacheService managerMapCacheService;
    @Autowired
    private ManagerHousekeeperCacheService managerHousekeeperCacheService;
    @Autowired
    private ManagerMapCacheMapper managerMapCacheMapper;
    @Autowired
    private ManagerHousekeeperCacheMapper managerHousekeeperCacheMapper;
    @Autowired
    private ManagerMapCacheTemporaryMapper managerMapCacheTemporaryMapper;
    @Autowired
    private ManagerHousekeeperCacheTemporaryMapper managerHousekeeperCacheTemporaryMapper;
    @Autowired
    private ManagerMapCacheTemporaryService managerMapCacheTemporaryService;
    @Autowired
    private ManagerHousekeeperCacheTemporaryService housekeeperCacheTemporaryService;
    @Autowired
    private ManagerMapMapper managerMapMapper;
    @Autowired
    private ManagerMapForErpMapper managerMapForErpMapper;

    private static  Logger logger = LoggerFactory.getLogger(ManagerMapUtil.class);

    public void cacheManagerMapData() throws InterruptedException {
        managerMapCacheTemporaryService.clearAllCacheData();
        List<ManagerMapDTO> recordList=managerMapService.findPageList1(null);
        List<ManagerMapCacheTemporary> data=new ArrayList<>();
        for (ManagerMapDTO managerMapDTO : recordList) {
            ManagerMapCacheTemporary cache= new ManagerMapCacheTemporary();
            BeanUtils.copyProperties(managerMapDTO,cache);
            cache.setCreatedDate(new Date());
            cache.setCommCount(managerMapDTO.getCommCount());
            if(managerMapDTO.getManageNumAvg()!=null){
                cache.setManagerNumAvg(new BigDecimal(managerMapDTO.getManageNumAvg()));
            }
            if(managerMapDTO.getManageNumCount()!=null){
                cache.setManagerNumCount(new BigDecimal(managerMapDTO.getManageNumCount()));
            }
            cache.setFlag(1);
            data.add(cache);
        }
        if(CollectionUtils.isNotEmpty(data)){
            managerMapCacheTemporaryService.clearAllCacheData();
            Thread.sleep(1000);
            managerMapCacheTemporaryService.saveList(data);

            List<ManagerMapCacheTemporary> maps = managerMapCacheTemporaryMapper.selectAllList();
            //查询正式表中的所有数据
            List<ManagerMapCache> caches = managerMapCacheMapper.selectAll();
            //数据添加或数据编辑
            List<ManagerMapCache> updates = new ArrayList<>();
            List<ManagerMapCache> inserts = new ArrayList<>();
            if(CollectionUtils.isNotEmpty(data)){
                for(ManagerMapCacheTemporary temporary : data){
                    if(null == temporary)continue;
                    boolean flag = false ;
                    if(CollectionUtils.isNotEmpty(caches)){
                        for(ManagerMapCache cache : caches){
                            if(null == cache)continue;
                            //比对数据
                            if(cache.getOrganCode().equals(temporary.getOrganCode())){
                                if(cache.getOrganName().equals(temporary.getOrganName())
                                        &&cache.getCommCount() == temporary.getCommCount()
                                        &&(cache.getManagerNumCount() == null? BigDecimal.ZERO : cache.getManagerNumCount()).compareTo(temporary.getManagerNumCount() == null? BigDecimal.ZERO : temporary.getManagerNumCount()) == 0
                                        &&(cache.getManagerNumAvg() == null? BigDecimal.ZERO : cache.getManagerNumAvg()).compareTo(temporary.getManagerNumAvg() == null? BigDecimal.ZERO : temporary.getManagerNumAvg()) == 0){
                                    flag = true;
                                    break;
                                }else if(!cache.getOrganName().equals(temporary.getOrganName())
                                        ||cache.getCommCount() != temporary.getCommCount()
                                        ||(cache.getManagerNumCount() == null? BigDecimal.ZERO : cache.getManagerNumCount()).compareTo(temporary.getManagerNumCount() == null? BigDecimal.ZERO : temporary.getManagerNumCount()) != 0
                                        ||(cache.getManagerNumAvg() == null? BigDecimal.ZERO : cache.getManagerNumAvg()).compareTo(temporary.getManagerNumAvg() == null? BigDecimal.ZERO : temporary.getManagerNumAvg())  != 0){
                                    ManagerMapCache map = new ManagerMapCache();
                                    BeanUtils.copyProperties(temporary,map);
                                    updates.add(map);
                                    flag = true;
                                    break;
                                }
                            }
                        }
                    }
                    if(flag == false){
                        ManagerMapCache map = new ManagerMapCache();
                        BeanUtils.copyProperties(temporary,map);
                        inserts.add(map);
                    }
                }
            }
            managerMapService.handleManagerMapCache(inserts,updates);
        }
    }

    public void cacheHouseKeeperData() {
        housekeeperCacheTemporaryService.clearAllCacheData();
        List<ManagerMapOrganTreeDTO> dto=managerMapMapper.selectAllOrganTree();
        for (ManagerMapOrganTreeDTO tbSysOrgan : dto) {
            if(null == tbSysOrgan)continue;
            HouseKeeperParamVo vo=new HouseKeeperParamVo();
            vo.setOrganCode(tbSysOrgan.getName());
            List<HouseKeeperDTO> recordList = managerMapService.getAllHKData(vo);
            if(CollectionUtils.isNotEmpty(recordList)){
                List<ManagerHousekeeperCacheTemporary> data=new ArrayList<>();
                for (HouseKeeperDTO houseKeeperDTO : recordList) {
                    ManagerHousekeeperCacheTemporary cache=new ManagerHousekeeperCacheTemporary();
                    BeanUtils.copyProperties(houseKeeperDTO,cache);
                    cache.setRegionCode(houseKeeperDTO.getRegionCode());
                    cache.setRegionName(tbSysOrgan.getName());
                    cache.setBirthdate(houseKeeperDTO.getBIRTHDATE());
                    cache.setCommCode(houseKeeperDTO.getCommCode());
                    cache.setCommName(houseKeeperDTO.getCommName());
                    cache.setJoinworkDate(houseKeeperDTO.getJoinworkDate());
                    cache.setHjid(houseKeeperDTO.getPK_PSNDOC());
                    cache.setBid(houseKeeperDTO.getBID());
                    cache.setJobLv(houseKeeperDTO.getJobLv());
                    cache.setOrganName(houseKeeperDTO.getOrganName());
                    cache.setPkOrg(houseKeeperDTO.getPK_ORG());
                    cache.setPkPsndoc(houseKeeperDTO.getPK_PSNDOC());
                    cache.setName(houseKeeperDTO.getNAME());
                    cache.setSex(houseKeeperDTO.getSEX());
                    cache.setVillas(houseKeeperDTO.getVillas());
                    cache.setHouses(houseKeeperDTO.getHouses());
                    cache.setShops(houseKeeperDTO.getShops());
                    cache.setVillas(houseKeeperDTO.getVillas());
                    cache.setHousekeeperPhone(houseKeeperDTO.getMOBILE());
                    cache.setGardenDistrict(houseKeeperDTO.getGardenDistrict());
                    cache.setPhoneIsfixed(houseKeeperDTO.getPhoneIsfixed());
                    cache.setDevelopmentSubject(houseKeeperDTO.getDevelopmentSubject());
                    cache.setServiceCenterHotline(houseKeeperDTO.getServiceCenterHotline());
                    cache.setHotlineConnectionTime(houseKeeperDTO.getHotlineConnectionTime());
                    cache.setIsUpdate(0);
                    cache.setCreatedDate(new Date());
                    cache.setFlag(1);
                    data.add(cache);
                }
                if(CollectionUtils.isNotEmpty(data)){
                    //去重
                    List<ManagerHousekeeperCacheTemporary> list = uniqueInsertList(data);
                    housekeeperCacheTemporaryService.saveList(list);
                }
            }
        }
        List<ManagerHousekeeperCacheTemporary> temporarys = managerHousekeeperCacheTemporaryMapper.selectAllList();
        if(CollectionUtils.isNotEmpty(temporarys)){
            //组装数据
            //查询正式表中的所有数据
            List<ManagerHousekeeperCache> caches = managerHousekeeperCacheMapper.selectAll();
            temporarys = ManagerMapUtil.uniqueInsertList(temporarys);
            //数据添加或数据编辑
            List<ManagerHousekeeperCache> updates = new ArrayList<>();
            List<ManagerHousekeeperCache> inserts = new ArrayList<>();
            if(CollectionUtils.isNotEmpty(temporarys)){
                for(ManagerHousekeeperCacheTemporary temporary : temporarys){
                    if(null == temporary) continue;
                    boolean flag = false ;
                    if(CollectionUtils.isNotEmpty(caches)){
                        for(ManagerHousekeeperCache cache : caches){
                            if(null == cache)continue;
                            //区域、项目、职位相同跳过
                            if(cache.getPkPsndoc().equals(temporary.getPkPsndoc())){
                                if(cache.getRegionName().equals(temporary.getRegionName())
                                        &&cache.getPkOrg().equals(temporary.getPkOrg())
                                        &&cache.getJobLv().equals(temporary.getJobLv())){
                                    flag = true;
                                    break;
                                }else if(!cache.getRegionName().equals(temporary.getRegionName())//区域、项目有一个不同就编辑
                                        || !cache.getPkOrg().equals(temporary.getPkOrg())
                                        ||!cache.getJobLv().equals(temporary.getJobLv())){
                                    ManagerHousekeeperCache houserKeeper = new ManagerHousekeeperCache();
                                    BeanUtils.copyProperties(temporary,houserKeeper);
                                    updates.add(houserKeeper);
                                    flag = true;
                                    break;
                                }
                            }
                        }
                    }
                    if(flag == false){
                        ManagerHousekeeperCache houserKeeper = new ManagerHousekeeperCache();
                        BeanUtils.copyProperties(temporary,houserKeeper);
                        inserts.add(houserKeeper);
                    }
                }
            }
            //操作事务
            managerMapService.handleHouserkeeperCache(inserts,updates,caches);
        }

        //更新管辖户数
        List<ManagerHousekeeperCache> housekeeperCaches = managerHousekeeperCacheMapper.selectAll();
        if(CollectionUtils.isNotEmpty(housekeeperCaches)){
            for(ManagerHousekeeperCache one : housekeeperCaches){
//                List<HouseKeeperDTO> houseErpInfo = managerMapForErpMapper.selectHouseCountPageDataByErp(one.getRegionName(), one.getCommName() ,one.getName());
//                更新户数，已改为页面维护
//                if(houseErpInfo!=null&&houseErpInfo.size()>0) {
//                    if(houseErpInfo.get(0).getHouses()!=null || houseErpInfo.get(0).getVillas()!=null || houseErpInfo.get(0).getShops()!=null) {
//                        one.setHouses(houseErpInfo.get(0).getHouses());
//                        one.setVillas(houseErpInfo.get(0).getVillas());
//                        one.setShops(houseErpInfo.get(0).getShops());
//                    }
//                }
//                更新项目编号
                String commCode = managerMapForErpMapper.selectCommCodeByCommName(one.getCommName(),one.getRegionCode());
                DevelopmentSubjectDTO developmentSubject = managerMapForErpMapper.selectCommByDevelopmentsubjectByOne(one.getCommName());
                one.setCommCode(commCode);
                if(developmentSubject != null)one.setDevelopmentSubject(developmentSubject.getdevelopmentSubject());
                managerHousekeeperCacheMapper.updateByPrimaryKeySelective(one);
            }
        }

        List<ManagerMapCache> allMap = managerMapCacheMapper.selectAll();
        for (ManagerMapCache map : allMap) {
            if(null == map)continue;
            int	count = managerHousekeeperCacheMapper.countHousekeeperByOrgan(map.getOrganName());
            map.setHousekeeperCount(count);
            map.setManagerNumAvg(count!=0&&map.getManagerNumCount() != null?map.getManagerNumCount().divide(new BigDecimal(count),2,BigDecimal.ROUND_HALF_UP):BigDecimal.ZERO);
            managerMapCacheMapper.updateByPrimaryKeySelective(map);
        }
    }

    public void show(){
        System.out.println("runing...");
    }


    public static List<ManagerHousekeeperCacheTemporary> uniqueInsertList(List<ManagerHousekeeperCacheTemporary> data) {
        Map<String,ManagerHousekeeperCacheTemporary> map = new HashMap<>();
        for(ManagerHousekeeperCacheTemporary one : data){
            map.put(one.getRegionName()+";"+one.getPkOrg()+";"+one.getPkPsndoc(),one);
        }
        List<ManagerHousekeeperCacheTemporary> list = new ArrayList<>(map.values());
        return list;
    }

    /**
     * 调整缓存管家户数
     */
    public void cacheHouseholdsData() {
        List<ManagerHousekeeperCache> housekeepers = managerHousekeeperCacheMapper.selectAll();
        if(CollectionUtils.isNotEmpty(housekeepers)){
            for(ManagerHousekeeperCache one : housekeepers){
                List<HouseKeeperDTO> houseErpInfo = managerMapForErpMapper.selectHouseCountPageDataByErp(one.getOrganName(), one.getCommName() ,one.getName());
                if(houseErpInfo!=null&&houseErpInfo.size()>0) {
                    if(houseErpInfo.get(0).getHouses()!=null || houseErpInfo.get(0).getVillas()!=null || houseErpInfo.get(0).getShops()!=null) {
                        one.setHouses(houseErpInfo.get(0).getHouses());
                        one.setVillas(houseErpInfo.get(0).getVillas());
                        one.setShops(houseErpInfo.get(0).getShops());
                        managerHousekeeperCacheMapper.updateByPrimaryKeySelective(one);
                    }
                }
            }
        }
    }
}
