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

import cn.com.countrygarden.bi.main.core.AbstractService;
import cn.com.countrygarden.bi.main.dao.common.CommMapper;
import cn.com.countrygarden.bi.main.dao.marketing.CommOperationHistoryMapper;
import cn.com.countrygarden.bi.main.dao.marketing.MarketingOrganMapper;
import cn.com.countrygarden.bi.main.dao.marketing.ProposalMapper;
import cn.com.countrygarden.bi.main.dao.marketing.QuotaMapper;
import cn.com.countrygarden.bi.main.dao.project.ProjectClassMapper;
import cn.com.countrygarden.bi.main.dao.project.ProjectJointPlanMapper;
import cn.com.countrygarden.bi.main.dao.project.ProjectPlanOneMapper;
import cn.com.countrygarden.bi.main.dao.twerp.hm.TbDeskTopFeesDailyMapper;
import cn.com.countrygarden.bi.main.dao.twerp.hm.TbHsprCommunityMapper;
import cn.com.countrygarden.bi.main.dao.twerp.hm.TbSysOrganMapper;
import cn.com.countrygarden.bi.main.exception.ServiceException;
import cn.com.countrygarden.bi.main.model.PageData;
import cn.com.countrygarden.bi.main.model.common.Comm;
import cn.com.countrygarden.bi.main.model.common.CommConstant;
import cn.com.countrygarden.bi.main.model.common.CommCount;
import cn.com.countrygarden.bi.main.model.common.CommData;
import cn.com.countrygarden.bi.main.model.marketing.MarketingOrgan;
import cn.com.countrygarden.bi.main.model.marketing.Quota;
import cn.com.countrygarden.bi.main.model.project.ProjectClass;
import cn.com.countrygarden.bi.main.model.project.ProjectJointPlan;
import cn.com.countrygarden.bi.main.model.project.ProjectPlanOne;
import cn.com.countrygarden.bi.main.model.twerp.hm.TbDeskTopFeesDaily;
import cn.com.countrygarden.bi.main.model.twerp.hm.TbHsprCommunity;
import cn.com.countrygarden.bi.main.model.twerp.hm.TbSysOrgan;
import cn.com.countrygarden.bi.main.model.twerp.hm.TbSysUser;
import cn.com.countrygarden.bi.main.service.common.CommService;
import cn.com.countrygarden.bi.main.service.marketing.CommOperationHistoryService;
import cn.com.countrygarden.bi.main.service.marketing.model.ContractLastWeekReport;
import cn.com.countrygarden.bi.main.service.marketing.model.ContractYearSummaryReport;
import cn.com.countrygarden.bi.main.service.marketing.model.StatisticsBasic;
import cn.com.countrygarden.bi.main.service.project.impl.vo.IndicatorLight;
import cn.com.countrygarden.bi.main.service.project.impl.vo.OneProject;
import cn.com.countrygarden.bi.main.service.twerp.hm.TbSysUserService;
import cn.com.countrygarden.bi.main.util.DateUtil;
import cn.com.countrygarden.bi.main.util.NumberUtil;
import cn.com.countrygarden.bi.main.util.RedisCacheUtils;

import com.github.pagehelper.PageRowBounds;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by chenweijiang on 2017/9/20.
 */
@Service
@Transactional()
public class CommServiceImpl extends AbstractService<Comm> implements CommService  {
    @Autowired
    private CommMapper commMapper;

    @Autowired
    private MarketingOrganMapper marketingOrganMapper;

    @Autowired
    private TbSysOrganMapper tbSysOrganMapper;

    @Autowired
    private TbDeskTopFeesDailyMapper tbDeskTopFeesDailyMapper;
    @Autowired
    private TbHsprCommunityMapper tbHsprCommunityMapper;

    @Autowired
    private QuotaMapper quotaMapper;
    @Autowired
    private ProjectPlanOneMapper projectPlanOneMapper;
    @Autowired
    private ProjectClassMapper projectClassMapper;
    @Autowired
    private ProposalMapper proposalMapper;
    @Autowired
    private CommOperationHistoryService operationHistoryService;
	  @Autowired
	  private ProjectJointPlanMapper projectJointPlanMapper;
	  @Autowired
	    private TbSysUserService userService;
	  /**
	   * 红黄灯修改
	   */
	  @Override
	  public void savaLight(IndicatorLight li) {
		  List<ProjectClass> list = projectClassMapper.selectAll();
	    	//IndicatorLight il = new IndicatorLight();
	    	for (ProjectClass projectClass : list) {
	    		if(projectClass.getCode().equals(ProjectClass.CODE_CLASSBYA)) {
	    			projectClass.setRed(li.getaRed());
	    			projectClass.setYellow(li.getaYellow());
	    			projectClass.setBlack(li.getaBlack());
	    		}
//	    		if(projectClass.getCode().equals(ProjectClass.CODE_CLASSBYO)) {
//	    			projectClass.setRed(li.getoRed());
//	    			projectClass.setYellow(li.getoYellow());
//	    		}
	    		if(projectClass.getCode().equals(ProjectClass.CODE_CLASSBYB)) {
	    			projectClass.setRed(li.getbRed());
	    			projectClass.setYellow(li.getbYellow());
	    			projectClass.setBlack(li.getbBlack());
	    		}
	    		if(projectClass.getCode().equals(ProjectClass.CODE_CLASSBYC)) {
	    			projectClass.setRed(li.getcRed());
	    			projectClass.setYellow(li.getcYellow());
	    			projectClass.setBlack(li.getcBlack());
	    		}
	    		if(projectClass.getCode().equals(ProjectClass.CODE_CLASSBYD)) {
	    			projectClass.setRed(li.getdRed());
	    			projectClass.setYellow(li.getdYellow());
	    			projectClass.setBlack(li.getdBlack());
	    		}
	    		projectClassMapper.updateByPrimaryKey(projectClass);
			}
	    	warningLight();
	  }
	  /**
	   * 红黄灯设置
	   */
	  @Override
	  public IndicatorLight findLight() {
	    	List<ProjectClass> list = projectClassMapper.selectAll();
	    	IndicatorLight il = new IndicatorLight();
	    	for (ProjectClass projectClass : list) {
	    		if(projectClass.getCode().equals(ProjectClass.CODE_CLASSBYA)) {
	    			il.setaRed(projectClass.getRed());
	    			il.setaYellow(projectClass.getYellow());
	    			il.setaBlack(projectClass.getBlack());
	    		}
//	    		if(projectClass.getCode().equals(ProjectClass.CODE_CLASSBYO)) {
//	    			il.setoRed(projectClass.getRed());
//	    			il.setoYellow(projectClass.getYellow());
//	    		}
	    		if(projectClass.getCode().equals(ProjectClass.CODE_CLASSBYB)) {
	    			il.setbRed(projectClass.getRed());
	    			il.setbYellow(projectClass.getYellow());
	    			il.setbBlack(projectClass.getBlack());
	    		}
	    		if(projectClass.getCode().equals(ProjectClass.CODE_CLASSBYC)) {
	    			il.setcRed(projectClass.getRed());
	    			il.setcYellow(projectClass.getYellow());
	    			il.setcBlack(projectClass.getBlack());
	    		}
	    		if(projectClass.getCode().equals(ProjectClass.CODE_CLASSBYD)) {
	    			il.setdRed(projectClass.getRed());
	    			il.setdYellow(projectClass.getYellow());
	    			il.setdBlack(projectClass.getBlack());
	    		}
			}
	    	return il;
	    }
	  
	  @Override
	  public PageData searchByOne(Comm comm,int page, int size ,Boolean isManage) {
		  PageRowBounds pageRowBounds = new PageRowBounds(page,size);
		  String userCode = comm.getContractorCode();
		  if(isManage) {
			  comm.setContractorCode(null);
		  }
		  if(ProjectClass.CODE_CLASSBYSTOP.equals(comm.getProjectClassCode())) {
			  comm.setProjectPlanCode("1");
			  comm.setProjectClassCode(null);
		  }
//		  if(ProjectClass.CODE_CLASSBYWAITING.equals(comm.getProjectClassCode())) {
//			  comm.setProjectPlanCode("2");
//			  comm.setProjectClassCode(null);
//		  }
		  List<OneProject> list = commMapper.selectByOne(comm, pageRowBounds);
		  List<String> region = commMapper.getRegion();
		  Map<String,String> regionMap = new HashMap<>();
		  for (String string : region) {
			  regionMap.put(string, string);
		}
		  comm.setContractorCode(userCode);
		  List<OneProject> newlist = new ArrayList<>();
		  for (OneProject oneProject : list) {		  
			  //如果业务结束  不显示灯
			  if(oneProject.getProjectPlanCode().equals(ProjectPlanOne.CODE_OVER)) {
				  oneProject.setWarningLight(Comm.WARNINGLIGHT_PT.toString());
			  }
			  //是否显示审核按钮
			  
//			if((null == comm.getContractorCode() || oneProject.getRuserCode().equals(comm.getContractorCode())) &&(
//					oneProject.getProjectClassCode().equals(ProjectClass.CODE_CLASSBYO) 
//					|| oneProject.getProjectClassCode().equals(ProjectClass.CODE_CLASSBYD)
//					|| oneProject.getProjectClassCode().equals(ProjectClass.CODE_CLASSBYC)
//					||oneProject.getProjectPlanCode().equals(ProjectPlanOne.CODE_CHECKRESTART)
//					||oneProject.getProjectPlanCode().equals(ProjectPlanOne.CODE_CHECKSTOP))) {
//				oneProject.setIsManage("true");
//				
//			}
			  
			
			  
			  if(oneProject.getRuserCode() == null) {
					oneProject.setRuserCode("1");
				}
			  if(isManage) {
				  if(oneProject.getProjectPlanCode().equals(ProjectPlanOne.CODE_CHECKSTOP)){
					  if(regionMap.containsKey(oneProject.getModifiedBy())||userCode.equals(oneProject.getModifiedBy())) {
							oneProject.setIsManage("true");
						}else {
							oneProject.setIsManage(null);
						}
				  }else if(oneProject.getProjectClassCode().equals(ProjectClass.CODE_CLASSBYD)
							|| oneProject.getProjectClassCode().equals(ProjectClass.CODE_CLASSBYC)							
							||oneProject.getProjectClassCode().equals(ProjectClass.CODE_CLASSBYB) 
							||oneProject.getProjectClassCode().equals(ProjectClass.CODE_CLASSBYA)
							||oneProject.getProjectPlanCode().equals(ProjectPlanOne.CODE_CHECKRESTART))
				  	{
					  //	oneProject.setIsHandover("true");
					  if(!oneProject.getProjectPlanCode().equals(ProjectPlanOne.CODE_OVER)) {
						oneProject.setIsManage("true");			
					  }
					} 
			  }else if(userCode.equals(oneProject.getRuserCode()) &&  
					  !oneProject.getProjectPlanCode().equals(ProjectPlanOne.CODE_OVER)) {
				  if((oneProject.getProjectClassCode().equals(ProjectClass.CODE_CLASSBYO) &&
							!oneProject.getProjectPlanCode().equals(ProjectPlanOne.CODE_PROJECTINFO))
						  && !oneProject.getProjectPlanCode().equals(ProjectPlanOne.CODE_CHECKRESTART)
						  && !oneProject.getProjectPlanCode().equals(ProjectPlanOne.CODE_CHECKSTOP)){
					  oneProject.setIsManage("true");
				  }
				  if(oneProject.getProjectPlanCode().equals(ProjectPlanOne.CODE_CHECKSTOP)) {
					  oneProject.setIsManage("true");
					  if(regionMap.containsKey(oneProject.getModifiedBy())) {
							oneProject.setIsManage(null);
						}else {
							oneProject.setIsManage("true");
						}
					 
				  }							
			}
	
			//区域 是o类 不是结束，结束中，重启中 有终止权限
			if(userCode.equals(oneProject.getContractorCode()) 
					&& oneProject.getProjectClassCode().equals(ProjectClass.CODE_CLASSBYO)
					&& !oneProject.getProjectPlanCode().equals(ProjectPlanOne.CODE_OVER)
					&& !oneProject.getProjectPlanCode().equals(ProjectPlanOne.CODE_CHECKRESTART)
					&& !oneProject.getProjectPlanCode().equals(ProjectPlanOne.CODE_CHECKSTOP)) {
				oneProject.setIsAllowStop("true");
			}
			//大区总 不是 结束，结束中，重启中 有终止权限
			if(userCode.equals(oneProject.getRuserCode())&& !oneProject.getProjectClassCode().equals(ProjectClass.CODE_CLASSBYO)
					&& !oneProject.getProjectPlanCode().equals(ProjectPlanOne.CODE_OVER)
					&& !oneProject.getProjectPlanCode().equals(ProjectPlanOne.CODE_CHECKRESTART)
					&& !oneProject.getProjectPlanCode().equals(ProjectPlanOne.CODE_CHECKSTOP)) {
				oneProject.setIsAllowStop("true");
			}
			//区域/大区总，是终止类型 有重启权限
			if((userCode.equals(oneProject.getContractorCode()) ||userCode.equals(oneProject.getRuserCode()))
					&& oneProject.getProjectPlanCode().equals(ProjectPlanOne.CODE_OVER)) {
				oneProject.setIsAllowReStar("true");
			}		
			newlist.add(oneProject);
		}
		  PageData pageData = new PageData(newlist,pageRowBounds);
		  return pageData;
	  }
	  
	  @Override
	  public PageData searchByOneList(Comm comm,int page, int size,Boolean isManage) {
		  String userCode = comm.getContractorCode();
		  comm.setContractorCode(null);	 
		  PageRowBounds pageRowBounds = new PageRowBounds(page,size);
		  List<OneProject> list = commMapper.selectByOne(comm, pageRowBounds);
		  List<OneProject> newlist = new ArrayList<>();
		  
		  for (OneProject oneProject : list) {
			  //如果业务结束  不显示灯
			  if(oneProject.getProjectPlanCode().equals(ProjectPlanOne.CODE_OVER)) {
				  oneProject.setWarningLight(Comm.WARNINGLIGHT_PT.toString());
			  }
			  if(isManage==null) {
				  oneProject.setIsHandover("true");
			  }
			  if(oneProject.getRuserCode() == null) {
					oneProject.setRuserCode("1");
				}
			  if(isManage) {
					oneProject.setIsHandover("true");
				  if(oneProject.getProjectPlanCode().equals(ProjectPlanOne.CODE_CHECKSTOP)
						  ||oneProject.getProjectPlanCode().equals(ProjectPlanOne.CODE_CHECKRESTART)
						  ||oneProject.getProjectPlanCode().equals(ProjectPlanOne.CODE_OVER)){
					  
				  }else if(oneProject.getProjectClassCode().equals(ProjectClass.CODE_CLASSBYD)
							|| oneProject.getProjectClassCode().equals(ProjectClass.CODE_CLASSBYC)
							||oneProject.getProjectPlanCode().equals(ProjectPlanOne.CODE_CHECKRESTART)
							||oneProject.getProjectClassCode().equals(ProjectClass.CODE_CLASSBYB) 
							|| oneProject.getProjectClassCode().equals(ProjectClass.CODE_CLASSBYA)
							||oneProject.getProjectPlanCode().equals(ProjectPlanOne.CODE_CHECKSTOP))
				  	{
						oneProject.setIsManage("true");
					} 
			  }else if(userCode.equals(oneProject.getRuserCode()) ) {
				  if((oneProject.getProjectClassCode().equals(ProjectClass.CODE_CLASSBYO) &&
							!oneProject.getProjectPlanCode().equals(ProjectPlanOne.CODE_PROJECTINFO))){
					  oneProject.setIsManage("true");
				  }
				  if(oneProject.getProjectPlanCode().equals(ProjectPlanOne.CODE_CHECKSTOP)
							||oneProject.getProjectPlanCode().equals(ProjectPlanOne.CODE_CHECKRESTART)) {
					  oneProject.setIsManage("true");
				  }							
			}
			newlist.add(oneProject);
		  }
		  PageData pageData = new PageData(newlist,pageRowBounds);
		  return pageData;
	  }
	  /**
	   * 单一项目修改
	   */
	  @Override
	  public void updateByOne(Comm comm) {
		  Comm oldComm = commMapper.selectByPrimaryKey(comm.getId());
//		  if(null == oldComm) {
//			  
//		  }
//		  if(oldComm.getProjectPlanCode().equals(ProjectPlanOne.CODE_PROJECTINFO)) {
//			  if(null != oldComm.getName() && "".equals(oldComm.getName())
//					 && null != oldComm.getCooperationfName() && "".equals(oldComm.getCooperationfName())
//					 && null != oldComm.getBusinessType()
//					 && null != oldComm.getStatus() && "".equals(oldComm.getStatus())
//					 && null != oldComm.getContractArea()
//					 && null != oldComm.getSaturation()
//					 && null != oldComm.getCity() && "".equals(oldComm.getCity()) ) {
//				  comm.setProjectPlanCode(ProjectPlanOne.CODE_PROJECTKEY);
//			  }
//		  }else if(oldComm.getProjectPlanCode() .equals(ProjectPlanOne.CODE_PROJECTKEY)) {
//			  if(null != oldComm.getJoint() && "".equals(oldComm.getJoint())
//					  && null != oldComm.getJointDuty() && "".equals(oldComm.getJointDuty())
//					  && null != oldComm.getJointRight()
//					  ) {
//				  comm.setProjectPlanCode(ProjectPlanOne.CODE_COOPERATION);
//				  }
//		  }else if(oldComm.getProjectPlanCode() .equals(ProjectPlanOne.CODE_COOPERATION)) {
//			  if(null != oldComm.getCorpType()
//					  && null != oldComm.getSignificance()
//					  && null != oldComm.getDemand()
//					 ) {
//				  comm.setProjectPlanCode(ProjectPlanOne.CODE_PRICE);
//				  }
//			  
//			 
//		  }else if(oldComm.getProjectPlanCode() .equals(ProjectPlanOne.CODE_PRICE)) {
//			  if(null != oldComm.getPropertyFee()
//					  && null != oldComm.getMessageFee()) {
//				  comm.setProjectPlanCode(ProjectPlanOne.CODE_OWNER);
//				  }
//		  }else if(oldComm.getProjectPlanCode() .equals(ProjectPlanOne.CODE_OWNER)) {
//			  if(null != oldComm.getIsSubmit()
//					  && null != oldComm.getCompetitor()
//					  && null != oldComm.getOpinion()) {
//				  comm.setProjectPlanCode(ProjectPlanOne.CODE_SIGN);
//				  }
//		  }else if(oldComm.getProjectPlanCode() .equals(ProjectPlanOne.CODE_SIGN)) {
//			  if(null != oldComm.getCallFile()
//					  && null != oldComm.getCallOrganization()
//					  && null != oldComm.getCallEnvironmen()) {
//				  comm.setProjectPlanCode(ProjectPlanOne.CODE_OVER);
//				  }
//		  }
		  commMapper.updateByPrimaryKeySelective(comm);
	  }
	  @Override
	  public void creatOneProject(Comm comm,String userCode) {
	    	Comm c = new Comm();
	    	c.setCreateBy(userCode);
	    	c.setGmtCreate(new Date());
	    	c.setProjectClassCode(ProjectClass.CODE_CLASSBYO);
	    	//c.setProjectPlanCode(ProjectPlanOne.CODE_PROJECTINFO);
	    	c.setGeneralType(Comm.COMM_TYPE_ONE);
	    	c.setContractorCode(userCode);
	    	c.setOrganId(comm.getOrganId());
	    	c.setWarningLight(Comm.WARNINGLIGHT_PT);
	    	
	    	List<Comm> count = mapper.selectAll();
	   
	    	String code = "";
	    	//单一项目为1类型
	    	code+="1";
	    	//大区
	    	code+=commMapper.findOrganRegion(c.getOrganId());
	    	//区域
	    	code+=c.getOrganId();
	    	//年
	    	code+=(DateUtil.getYear()+"").substring(2,4);
	    	//查询项目最大后四位编号+1
	    	//int findMaxCode = commMapper.findMaxCode()+1;
	    	code+=complemented(count.size()+1);
	    	c.setCommCode(code);
	    	c.setErpOrganCode(comm.getErpOrganCode());
	    	c.setErpOrganName(comm.getErpOrganName());
	    	c.setContractorName(comm.getContractorName());
	    	ProjectClass pc = new ProjectClass();
	    	pc.setCode(ProjectPlanOne.CODE_PROJECTKEY);
	    	pc = projectClassMapper.selectOne(pc);
	    	
	    	ProjectPlanOne pp = new ProjectPlanOne();
	    	pp.setCode(ProjectPlanOne.CODE_PROJECTINFO);
	    	pp = projectPlanOneMapper.selectOne(pp);
	    	c.setIsDelete(Byte.valueOf("0"));
	    	c.setScheduleName(pp.getName());
	    	c.setProjectPlanCode(pp.getCode());	  
			c.setName(comm.getName());
			c.setCooperationfName(comm.getCooperationfName());
			c.setBusinessType(comm.getBusinessType());
			c.setStatus(comm.getStatus());
			c.setContractArea(comm.getContractArea());
			c.setSaturation(comm.getSaturation());
			c.setCity(comm.getCity());
			   c.setModifiedBy(userCode);
		         c.setGmtModified(new Date());
	    	TbSysUser sysUser = userService.getCurrentSysUser();
	    	commMapper.insert(c);
	    	operationHistoryService.operation(
	                c.getId(),
	                pp.getName(),
	                sysUser.getUserName() + "创建项目",
	                "",
	                sysUser.getUserCode()
	        );
	    }
	  
    @Override
    public PageData search(String userCode, String searchKey, String organCode, String takeOverOrgganCode, boolean isCharge, String proposalBefore, String proposalAfter, String contractBefore, String contractAfter, boolean isOwner, String status,Integer generalType,int page, int size) {
        Map<String,Object> query = new HashMap<String,Object>();
        if(isOwner){
            query.put("contractorCode",userCode);
        }
        if(!StringUtils.isEmpty(searchKey)){
            query.put("searchKey",searchKey);
        }
        if(!StringUtils.isEmpty(organCode)){
            query.put("organCode",organCode);
        }
        if(!StringUtils.isEmpty(takeOverOrgganCode)){
            query.put("takeOverOrganCode",takeOverOrgganCode);
        }
        if(isCharge){
            query.put("isCharge","isCharge");
        }
        if(!StringUtils.isEmpty(takeOverOrgganCode)){
            query.put("takeOverOrganCode",takeOverOrgganCode);
        }
        query.put("generalType", generalType);
        
        if(!StringUtils.isEmpty(proposalBefore) && !StringUtils.isEmpty(proposalAfter)){
            Date startDate = DateUtil.parseDate(proposalBefore);
            Date endDate = DateUtil.parseDate(proposalAfter);
            query.put("proposalBefore",startDate);
            query.put("proposalAfter",endDate);
        }
        if(!StringUtils.isEmpty(contractBefore) && !StringUtils.isEmpty(contractAfter)){
            Date startDate = DateUtil.parseDate(contractBefore);
            Date endDate = DateUtil.parseDate(contractAfter);
            query.put("contractBefore",startDate);
            query.put("contractAfter",endDate);
        }
        if(!StringUtils.isEmpty(status)){
            query.put("status",status);
        }
        PageRowBounds pageRowBounds = new PageRowBounds(page,size);
        List<CommData> dataList = commMapper.searchByListCondition(query,pageRowBounds);
        Map<String,Object> organMap = findOrganMapCache();
        for(CommData data :dataList){
            if(!StringUtils.isEmpty(data.getOrganId())){
                String name =(String) organMap.get(data.getOrganId());
                data.setOrganName(name);
            }
            if(!StringUtils.isEmpty(data.getTakeOverOrganId())){
                String name =(String) organMap.get(data.getTakeOverOrganId());
                data.setTakeOverOrganName(name);
            }
            if(!StringUtils.isEmpty(data.getStatus())){
                String statusName = CommConstant.CommStatus.statusName.get(data.getStatus());
                data.setStatus(statusName);
            }
            if(data.getPlanningArea()!=null){
//                BigDecimal num = NumberUtil.toTenOfThousand(data.getPlanningArea());
                BigDecimal num = data.getPlanningArea();
                data.setPlanningArea(num);
            }
            if(data.getChargeArea()!=null){
//                BigDecimal num = NumberUtil.toTenOfThousand(data.getChargeArea());
                BigDecimal num = data.getChargeArea();
                data.setChargeArea(num);
            }
            if(data.getContractArea()!=null){
//                BigDecimal num = NumberUtil.toTenOfThousand(data.getContractArea());
                BigDecimal num = data.getContractArea();
                data.setContractArea(num);
            }
        }
        PageData pageData = new PageData(dataList,pageRowBounds);
        return pageData;
    }

    @Override
    public CommCount count(String userCode,Integer generalType){
        CommCount result = new CommCount();
        Comm query = new Comm();
        query.setContractorCode(userCode);
        query.setIsDelete((byte)0);
        query.setGeneralType(generalType);
        int count = commMapper.selectCount(query);
        result.setTotal(count);

        query = new Comm();
        query.setContractorCode(userCode);
        query.setIsDelete((byte)0);
        query.setStatus(CommConstant.CommStatus.prophase);
        query.setGeneralType(generalType);
        count = commMapper.selectCount(query);
        result.setProphase(count);

        query = new Comm();
        query.setContractorCode(userCode);
        query.setIsDelete((byte)0);
        query.setStatus(CommConstant.CommStatus.candidate);
        query.setGeneralType(generalType);
        count = commMapper.selectCount(query);
        result.setCandidate(count);

        query = new Comm();
        query.setContractorCode(userCode);
        query.setIsDelete((byte)0);
        query.setStatus(CommConstant.CommStatus.passed);
        query.setGeneralType(generalType);
        count = commMapper.selectCount(query);
        result.setPassed(count);

        query = new Comm();
        query.setContractorCode(userCode);
        query.setIsDelete((byte)0);
        query.setStatus(CommConstant.CommStatus.suspend);
        query.setGeneralType(generalType);
        count = commMapper.selectCount(query);
        result.setSuspend(count);

        query = new Comm();
        query.setContractorCode(userCode);
        query.setIsDelete((byte)0);
        query.setStatus(CommConstant.CommStatus.contract);
        query.setGeneralType(generalType);
        count = commMapper.selectCount(query);
        result.setContract(count);

        query = new Comm();
        query.setContractorCode(userCode);
        query.setIsDelete((byte)0);
        query.setStatus(CommConstant.CommStatus.release);
        query.setGeneralType(generalType);
        count = commMapper.selectCount(query);
        result.setRelease(count);
        return result;
    }


    public Map<String,Object> findOrganMapCache(){

        return RedisCacheUtils.rememberMap(CommConstant.ORGANCACHEKEY,
                CommConstant.ORGANCACHTIME,
                new HashMap<String,String>(),
                p-> {
                    HashMap<String,Object> result = new HashMap<String,Object>();
                    MarketingOrgan query = new MarketingOrgan();
                    query.setIsDelete((byte)0);
                    List<MarketingOrgan> marketingOrgans = marketingOrganMapper.select(query);
                    for(MarketingOrgan marketingOrgan: marketingOrgans){
                        result.put(marketingOrgan.getId(),marketingOrgan.getName());
                    }
                    List<TbSysOrgan> list = tbSysOrganMapper.findAllActive();

                    for(TbSysOrgan organ:list){
                        result.put(organ.getOrganCode(),organ.getOrganName());
                    }
                    return result;
                });
    }

    @Override
    public Map<String,Object> findOrganNameMapCache(){
        return RedisCacheUtils.rememberMap(CommConstant.ORGANNameCACHEKEY,
                CommConstant.ORGANCACHTIME,
                new HashMap<String,String>(),
                p-> {
                    HashMap<String,Object> result = new HashMap<String,Object>();
                    MarketingOrgan query = new MarketingOrgan();
                    query.setIsDelete((byte)0);
                    List<MarketingOrgan> marketingOrgans = marketingOrganMapper.select(query);
                    for(MarketingOrgan marketingOrgan: marketingOrgans){
                        result.put(marketingOrgan.getName(),marketingOrgan.getId());
                    }

                    List<TbSysOrgan> list = tbSysOrganMapper.findAllActive();

                    for(TbSysOrgan organ:list){

                        result.put(organ.getOrganName(),organ.getOrganCode());
                    }
                    return result;
                });
    }

    public StatisticsBasic countStatisticsBasic(){
        DecimalFormat numberFormat = new DecimalFormat("0.##");
        DecimalFormat countFormat = new DecimalFormat("0");
        StatisticsBasic result = new StatisticsBasic();
        BigDecimal currentContactArea = commMapper.sumCurrentContactArea();
        currentContactArea = NumberUtil.toTenOfThousand(currentContactArea);
        BigDecimal contractRegional = commMapper.sumContractRegional();
        BigDecimal contractProject = commMapper.sumContractProject();
        BigDecimal currentChargeArea = commMapper.sumCurrentChargeArea();
        currentChargeArea = NumberUtil.toTenOfThousand(currentChargeArea);
        BigDecimal chargeRegional = commMapper.sumChargeRegional();
        BigDecimal chargeProject = commMapper.sumChargeProject();
        BigDecimal regularFormatCharge = commMapper.sumRegularFormatCharge();
        regularFormatCharge = NumberUtil.toTenOfThousand(regularFormatCharge);
        BigDecimal specialFormatCharge = commMapper.sumSpecialFormatCharge();
        specialFormatCharge= NumberUtil.toTenOfThousand(specialFormatCharge);

        //读取ERP的总收费面积
        TbDeskTopFeesDaily tbDeskTopFeesDaily = tbDeskTopFeesDailyMapper.totalChargeArea();
        String totalChargeArea;
        if(null == tbDeskTopFeesDaily) {
        	totalChargeArea = "";
        }else {
        	totalChargeArea = tbDeskTopFeesDaily.getChargeArea();
        }
         

        //读取ERP的收费区域数和项目数
        TbHsprCommunity tbHsprCommunity = tbHsprCommunityMapper.countMarketingExpansionCharge();
        Integer comms;
        Integer organs;
        if(null == tbHsprCommunity) {
        	 comms = 0;
             organs =0;
        }else {
        	  comms = tbHsprCommunity.getComms();
              organs = tbHsprCommunity.getOrgans();
        }
       



        //本月签约面积
        Calendar cal = Calendar.getInstance();
        cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONDAY), cal.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.DAY_OF_MONTH));
        Calendar para = Calendar.getInstance(java.util.Locale.CHINA);
        para.setTime(new Date());
        para.set(Calendar.DATE, para.getActualMaximum(Calendar.DAY_OF_MONTH));
        para.set(Calendar.HOUR_OF_DAY, 23);
        para.set(Calendar.MINUTE, 59);
        para.set(Calendar.SECOND, 59);
        SimpleDateFormat thismonthsdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        String thismonthstr1 = thismonthsdf.format(cal.getTime());
        String thismonthstr2 = thismonthsdf.format(para.getTime());
        Date thismonth1 = new Date(thismonthstr1);
        Date thismonth2 = new Date(thismonthstr2);
        BigDecimal thisMonthContractAreaNum = commMapper.sumContractAreaByTime(thismonth1, thismonth2);

        //上月签约面积
        Calendar lastMonthCal1=Calendar.getInstance(java.util.Locale.CHINA);
        lastMonthCal1.add(Calendar.MONTH, -1);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/01 00:00:00");
        String gtimelast = sdf.format(lastMonthCal1.getTime()); //上月
        lastMonthCal1.set(lastMonthCal1.get(Calendar.YEAR), lastMonthCal1.get(Calendar.MONTH), 1, 0, 0, 0);
        Date last = lastMonthCal1.getTime();
        String lastmonthstr1 = thismonthsdf.format(lastMonthCal1.getTime());
        int lastMonthMaxDay=lastMonthCal1.getActualMaximum(Calendar.DAY_OF_MONTH);
        lastMonthCal1.set(lastMonthCal1.get(Calendar.YEAR), lastMonthCal1.get(Calendar.MONTH), lastMonthMaxDay, 23, 59, 59);


        String lastmonthstr2 = thismonthsdf.format(lastMonthCal1.getTime());
        Date lastmonth1 = new Date(lastmonthstr1);
        Date lastmonth2 = new Date(lastmonthstr2);

        BigDecimal lastMonthContractAreaNum = commMapper.sumContractAreaByTime(lastmonth1, lastmonth2);

        result.setCurrentContactArea(numberFormat.format(currentContactArea));
        result.setContractRegional(countFormat.format(contractRegional));
        result.setContractProject(countFormat.format(contractProject));
        //这是原有的总收费面积逻辑
//        result.setCurrentChargeArea(numberFormat.format(currentChargeArea));
        //new DecimalFormat("#.00").format(Double.parseDouble(totalChargeArea)/10000)
        result.setCurrentChargeArea(totalChargeArea);
        //这是原有的收费区域逻辑，果断干掉
//        result.setChargeRegional(countFormat.format(chargeRegional));
        result.setChargeRegional(countFormat.format(organs));
        //这是原有的收费项目逻辑，果断干掉
//        result.setChargeProject(countFormat.format(chargeProject));
        result.setChargeProject(countFormat.format(comms));
        //这两个常规业态收费和特殊业态收费，还不知道咋算
        result.setRegularFormatCharge(numberFormat.format(regularFormatCharge));
        result.setSpecialFormatCharge(numberFormat.format(specialFormatCharge));

        result.setThisMonthContractArea(numberFormat.format(thisMonthContractAreaNum));
        result.setLastMonthContractArea(numberFormat.format(lastMonthContractAreaNum));
        return result;
    }

    public static void main(String[] args){
        Date ddd = new Date("2017/11/01 00:00:00");
        System.out.println("ddd:"+ddd);

        Calendar para = Calendar.getInstance(java.util.Locale.CHINA);
        para.setTime(new Date());
        para.set(Calendar.DATE, para.getActualMaximum(Calendar.DAY_OF_MONTH));
        para.set(Calendar.HOUR_OF_DAY, 23);
        para.set(Calendar.MINUTE, 59);
        para.set(Calendar.SECOND, 59);


        Calendar lastMonthCal1=Calendar.getInstance(java.util.Locale.CHINA);
        lastMonthCal1.add(Calendar.MONTH, -1);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-01 00:00:00");
        String gtimelast = sdf.format(lastMonthCal1.getTime()); //上月
        lastMonthCal1.set(lastMonthCal1.get(Calendar.YEAR), lastMonthCal1.get(Calendar.MONTH), 1, 0, 0, 0);
        System.out.println("上月第一天："+lastMonthCal1.getTime());
        int lastMonthMaxDay=lastMonthCal1.getActualMaximum(Calendar.DAY_OF_MONTH);
        System.out.println("上月最大一天："+lastMonthMaxDay);
        lastMonthCal1.set(lastMonthCal1.get(Calendar.YEAR), lastMonthCal1.get(Calendar.MONTH), lastMonthMaxDay, 23, 59, 59);
        System.out.println(lastMonthCal1.getTime());
        System.out.print(para.getTime());
    }

    @Override
    public ContractYearSummaryReport contractYearSummaryReport(){
        SimpleDateFormat firstFormat = new SimpleDateFormat("yyyy-01-01");
        SimpleDateFormat lastFormat = new SimpleDateFormat("yyyy-12-31");
        ContractYearSummaryReport report = new ContractYearSummaryReport();
        Date firstDateOfYear = DateUtil.parseDate(firstFormat.format(new Date()));
        Date lastDateOfYear = DateUtil.parseDate(lastFormat.format(new Date()));
        BigDecimal area = commMapper.sumContractAreaByTime(firstDateOfYear,lastDateOfYear);
        area = NumberUtil.toTenOfThousand(area);
        report.setArea(area);
        Calendar calendar = Calendar.getInstance();
        Short year =Short.parseShort(calendar.get(Calendar.YEAR)+"");
        Map<String,Object> summaryMap = new HashMap<String,Object>();
        summaryMap.put("year",year);
        Quota summaryQuota = quotaMapper.sum(summaryMap);
        if(summaryQuota!=null){
            BigDecimal quota = new BigDecimal(0);
            if(summaryQuota.getContractArea1st()!=null){
                quota= quota.add(summaryQuota.getContractArea1st());
            }
            if(summaryQuota.getContractArea2nd()!=null){
                quota= quota.add(summaryQuota.getContractArea2nd());
            }
            if(summaryQuota.getContractArea3rd()!=null){
                quota=quota.add(summaryQuota.getContractArea3rd());

            }
            if(summaryQuota.getContractArea4th()!=null){
                quota=quota.add(summaryQuota.getContractArea4th());
            }
            quota = NumberUtil.toTenOfThousand(quota);
            report.setQuota(quota);
        } else {
            report.setQuota(new BigDecimal(0));
        }

        calendar = DateUtil.removeTime(calendar);
        calendar = DateUtil.goToLastWeek(calendar);
        calendar = DateUtil.goToLastDateOfWeek(calendar,false);
        Date lastWeekEndDate = calendar.getTime();
        calendar = DateUtil.goToFirstDateOfWeek(calendar,false);
        Date lastWeekStartDate = calendar.getTime();
        BigDecimal lastWeekContractArea = commMapper.sumContractAreaByTime(lastWeekStartDate,lastWeekEndDate);
        calendar = DateUtil.goToLastDateOfWeek(calendar,false);
        Date  lastTwoWeekEndDate = calendar.getTime();
        calendar = DateUtil.goToFirstDateOfWeek(calendar,false);
        Date lastTwoWeekStartDate = calendar.getTime();
        BigDecimal lastTwoWeekContractArea = commMapper.sumContractAreaByTime(lastTwoWeekStartDate,lastTwoWeekEndDate);
        lastWeekContractArea = NumberUtil.toTenOfThousand(lastWeekContractArea);
        lastTwoWeekContractArea = NumberUtil.toTenOfThousand(lastTwoWeekContractArea);

        ContractLastWeekReport weekReport = new ContractLastWeekReport();
        weekReport.setArea(lastWeekContractArea);
        weekReport.setAreaIncrease(lastWeekContractArea.subtract(lastTwoWeekContractArea));


        Integer lastWeekContractProject = commMapper.sumContractProjectByTime(lastWeekStartDate,lastWeekEndDate);
        Integer lastTwoWeekContractProject = commMapper.sumContractProjectByTime(lastTwoWeekStartDate,lastTwoWeekEndDate);

        weekReport.setContractComm(lastWeekContractProject);
        weekReport.setContractCommIncrease(lastWeekContractProject-lastTwoWeekContractProject);

        Integer lastWeekProposalComm =  proposalMapper.countCommByTime(lastWeekStartDate,lastWeekEndDate);
        Integer lastTwoWeekProposalComm =  proposalMapper.countCommByTime(lastTwoWeekStartDate,lastTwoWeekEndDate);

        weekReport.setProposalComm(lastWeekProposalComm);
        weekReport.setProposalCommIncrease(lastWeekProposalComm-lastTwoWeekProposalComm);
        report.setLastWeek(weekReport);
        return  report;
    }
    /**
     * 更改红黄灯状态
     * @throws ParseException 
     */
    @Override
    public void warningLight() {
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    	Comm c = new Comm();
    	c.setGeneralType(Comm.COMM_TYPE_ONE);
    	List<Comm> cList = commMapper.selectAll();
    	Date now = new Date();
    	Date creTime;
		try {
			creTime = sdf.parse(sdf.format(new Date()));
		
	    	ProjectClass pc = new ProjectClass();
	    	for (Comm comm : cList) {
				if(!comm.getProjectClassCode().equals(ProjectClass.CODE_CLASSBYO)
						&& !comm.getProjectClassCode().equals(ProjectClass.CODE_CLASSBYSTOP)
						&& !comm.getProjectClassCode().equals(ProjectClass.CODE_CLASSBYWAITING)
						&& !comm.getProjectClassCode().equals(ProjectClass.CODE_CLASSBYY)
						&& null != comm.getProjectClassCode()
						&& null != comm.getThisStage()
						&& comm.getGeneralType() == Comm.COMM_TYPE_ONE) {
					pc.setCode(comm.getProjectClassCode());
					ProjectClass pcs = projectClassMapper.selectOne(pc);
					creTime = comm.getThisStage();
					creTime = sdf.parse(sdf.format(creTime));
					if(pcs.getYellow()==0) {
						comm.setWarningLight(Comm.WARNINGLIGHT_PT);
					}else {
					if((now.getTime() - creTime.getTime())/(1000 * 3600 * 24) >= pcs.getYellow()) {
						comm.setWarningLight(Comm.WARNINGLIGHT_JG);
					}
					if((now.getTime() - creTime.getTime())/(1000 * 3600 * 24) >= pcs.getRed()) {
						comm.setWarningLight(Comm.WARNINGLIGHT_YZ);
					}
					if((now.getTime() - creTime.getTime())/(1000 * 3600 * 24) < pcs.getRed()
							&& (now.getTime() - creTime.getTime())/(1000 * 3600 * 24) < pcs.getYellow()) {
						comm.setWarningLight(Comm.WARNINGLIGHT_PT);
					}
				}
				}
				commMapper.updateByPrimaryKeySelective(comm);
			}
		} catch (ParseException e) {
			
			e.printStackTrace();
			throw new ServiceException("事件处理有误");
		}
    }
    
    @Override
	public Integer followUp( Integer id,Integer dynamicId,String remark,String userCode) {
		Comm c = mapper.selectByPrimaryKey(id);
		
		
		ProjectJointPlan p = new ProjectJointPlan();
		if(c.getGeneralType() .equals(Comm.COMM_TYPE_JOINT)) {
			p.setMenuId(7);
			p.setId(dynamicId);
		}else if(c.getGeneralType().equals(Comm.COMM_TYPE_STOCK)) {
			p.setMenuId(8);
			p.setId(dynamicId);
		}
		p = projectJointPlanMapper.findOneProjectJointPlan(id);
		c.setSchedule(p.getId());
		c.setScheduleName(p.getName());
		p = projectJointPlanMapper.selectOne(p);
		String dynamicName = "";
		if(null != p) {
			dynamicName = p.getName();
		}
		 operationHistoryService.operation(
				 	id,
				 	dynamicName,
	                "进度更改为"+dynamicName,
	                "",
	                userCode
	        );
		return mapper.updateByPrimaryKey(c);
		 
	} 
    @Override
    public void boostJudge(Comm comm) {
    	if(comm.getProjectClassCode().equals(ProjectClass.CODE_CLASSBYO)) {
    		if(comm.getProjectPlanCode().equals(ProjectPlanOne.CODE_SIGN)) {
    			throw new ServiceException("当前节点不再继续推进，请联系大区总确认");
    		}
    	}else
    	if(comm.getProjectClassCode().equals(ProjectClass.CODE_CLASSBYD)) {
    		if(comm.getProjectPlanCode().equals(ProjectPlanOne.CODE_PRICE)) {
    			throw new ServiceException("当前节点不再继续推进，请联系大区总确认");
    		}
    	}else
    	if(comm.getProjectClassCode().equals(ProjectClass.CODE_CLASSBYC)) {
        	if(comm.getProjectPlanCode().equals(ProjectPlanOne.CODE_SIGN)) {
        		throw new ServiceException("当前节点不再继续推进，请联系大区总确认");
        	}
        }
    	else
        	if(comm.getProjectClassCode().equals(ProjectClass.CODE_CLASSBYB)) {
            	if(comm.getProjectPlanCode().equals(ProjectPlanOne.CODE_SIGN)) {
            		throw new ServiceException("当前节点不再继续推进，请联系总部确认");
            	}
            }
    }
  public Date addDate(Date time,Integer day) {
	  Calendar c = Calendar.getInstance();
	  c.setTime(time);
	  c.add(Calendar.DATE, day);
	  c.set(Calendar.HOUR_OF_DAY, 0);
      c.set(Calendar.MINUTE, 0);
      c.set(Calendar.SECOND, 0);
      return c.getTime();

  }
  public String complemented(int code) {
	  String str = code+"";
	  if(str.length() == 1) {
		  str = "000" + str;
	  }
	  if(str.length() == 2) {
		  str = "00" + str;
	  }
	  if(str.length() == 1) {
		  str = "0" + str;
	  }
	  return str;
  }
  /**
   * 判断重名
   * @param c
   * @return
   */
  @Override
  public Boolean repetition(Comm c) {
	  Comm map = new Comm();
	  map.setCity(c.getCity());
	  //map.setOrganId(c.getOrganId());
	  map.setName(c.getName());
	  List<Comm> list = commMapper.select(map);
	  if (list.size() > 0) {
			return false;
	}
	  return true;
  }


}
