package cn.com.countrygarden.bi.main.controller.marketing.backend;

import cn.com.countrygarden.bi.main.controller.project.imports.ProjectImports;
import cn.com.countrygarden.bi.main.core.Response;
import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.dao.common.CommInFoMapper;
import cn.com.countrygarden.bi.main.dao.common.CommMapper;
import cn.com.countrygarden.bi.main.dao.common.CommRecordService;
import cn.com.countrygarden.bi.main.dao.dup.TbHsprContractMapper;
import cn.com.countrygarden.bi.main.dao.marketing.CommReportWeeklyMapper;
import cn.com.countrygarden.bi.main.dao.project.*;
import cn.com.countrygarden.bi.main.dao.sys.RoleMapper;
import cn.com.countrygarden.bi.main.exception.ServiceException;
import cn.com.countrygarden.bi.main.model.AccessToken;
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.marketing.CommReportWeekly;
import cn.com.countrygarden.bi.main.model.project.*;
import cn.com.countrygarden.bi.main.model.sys.Role;
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.AccessTokenService;
import cn.com.countrygarden.bi.main.service.common.CommService;
import cn.com.countrygarden.bi.main.service.dup.DupCommService;
import cn.com.countrygarden.bi.main.service.dup.impl.ExcelHelper;
import cn.com.countrygarden.bi.main.service.marketing.*;
import cn.com.countrygarden.bi.main.service.marketing.model.*;
import cn.com.countrygarden.bi.main.service.project.BiEmergencyService;
import cn.com.countrygarden.bi.main.service.project.impl.vo.IndicatorLight;
import cn.com.countrygarden.bi.main.service.project.impl.vo.OneCommCount;
import cn.com.countrygarden.bi.main.service.project.impl.vo.OneProject;
import cn.com.countrygarden.bi.main.service.twerp.hm.TbSysOrganService;
import cn.com.countrygarden.bi.main.service.twerp.hm.TbSysUserService;
import cn.com.countrygarden.bi.main.util.AxisUtils;
import cn.com.countrygarden.bi.main.util.NumberUtil;
import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import freemarker.core.ParseException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;

@Controller("backendProjectController")
@RequestMapping("/api/biapp/marketing/backend/project")
public class ProjectController {
    @Autowired
    private ProjectPlanOneMapper projectPlanOneMapper;
    @Autowired
    DupCommService dupCommService;
    @Autowired
    private ProjectClassMapper projectClassMapper;
    @Autowired
    private CommMapper commMapper;
    @Autowired
    private CommReportWeeklyMapper commReportWeeklyMapper;

    @Autowired
    private CommService commService;

    @Autowired
    private AccessTokenService accessTokenService;

    @Autowired
    private TbSysUserService userService;


    @Autowired
    private CommOperationHistoryService operationHistoryService;


    @Autowired
    private TbSysOrganService organService;

    @Autowired
    private ChargeService chargeService;

    @Autowired
    private ContractService contractService;

    @Autowired
    private ProposalService proposalService;

    @Autowired
    private QuotaService quotaService;
    @Autowired
    private ProjectJointPlanMapper projectJointPlanMapper;
    @Autowired
    private ProjectImports projectImports;
    @Autowired
    private  RoleMapper roleMapper;

    @Autowired
    TbHsprContractMapper tbHsprContractMapper;
    @Autowired
	CommInFoMapper commInFoMapper;
    @Autowired
    CommRecordService commRecordService;
	@Autowired
	private BiEmergencyService biEmergencyService;
	//http://bip.countrygarden.com.cn/sys/webservice/kmReviewThirdWebserviceService?wsdl		
	//http://ekptestv12.countrygarden.com.cn:8080/sys/webservice/kmReviewThirdWebserviceService?wsdl
	String  url = "http://bip.countrygarden.com.cn/sys/webservice/kmReviewThirdWebserviceService?wsdl";
	String metod = "getEmergencyReview";
	 @Autowired
	BiEmergencyMapper biEmergencyMapper;
	 @Autowired
	 BiApplnoteMapper biApplnoteMapper;
    @ResponseBody
    @RequestMapping(value = "saveLight", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    public Object saveLight(IndicatorLight li) {
        commService.savaLight(li);
        return  Response.response(1);

    }
    @ResponseBody
    @RequestMapping(value = "findLight", produces = "application/json;charset=utf-8", method = RequestMethod.GET)
    public Object findLight() {
        return  Response.response(commService.findLight());

    }

    /**
     *
     * @param comm
     * @param requestsaveLight
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/search/pageByOne", produces = "application/json;charset=utf-8", method = RequestMethod.GET)
    public Object pageByOne(Comm comm,HttpServletRequest request, HttpServletResponse response) {
        Integer page = Integer.parseInt(request.getParameter("pageIndex"));
        Integer size = Integer.parseInt(request.getParameter("pageSize"));
        String accessToken = request.getParameter("AccessToken");
        AccessToken token = accessTokenService.findByToken(accessToken);
        String userCode = token.getUserCode();
        List<Role> rList=  roleMapper.findByUserCode(userCode);
        Boolean isManage = false;
        for (Role role : rList) {
            if(role.getCode().equals("marketing_manager")) {
                isManage = true;
            }
        }
        comm.setContractorCode(userCode);
        if(comm.getProjectClassCode().equals("classByAll")) {
            comm.setProjectClassCode(null);
        }
        List<Map<String, String>> findOrganByUserCode = tbHsprContractMapper.findOrganByUserCode(userCode);
        String organCode = null;
        if(findOrganByUserCode.size()>0) {
        	comm.setOrganCode(findOrganByUserCode.get(0).get("OrganCode"));
   		 }
        return  Response.response(commService.searchByOne(comm, page, size,isManage));
    }
    /**
     *
     * @param comm
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/search/pageByOneList", produces = "application/json;charset=utf-8", method = RequestMethod.GET)
    public Object pageByOneList(Comm comm,HttpServletRequest request, HttpServletResponse response) {
        Integer page = Integer.parseInt(request.getParameter("pageIndex"));
        Integer size = Integer.parseInt(request.getParameter("pageSize"));
        String accessToken = request.getParameter("AccessToken");
        AccessToken token = accessTokenService.findByToken(accessToken);
        String userCode = token.getUserCode();
        comm.setContractorCode(userCode);
        List<Role> rList=  roleMapper.findByUserCode(userCode);
        Boolean isManage = false;
        for (Role role : rList) {
            if(role.getCode().equals("marketing_manager")) {
                isManage = true;
            }
        }
        comm.setContractorCode(userCode);
        if(comm.getProjectClassCode().equals("classByAll")) {
            comm.setProjectClassCode(null);
        }
        List<Map<String, String>> findOrganByUserCode = tbHsprContractMapper.findOrganByUserCode(userCode);
        if(findOrganByUserCode.size()>0) {
        	comm.setOrganCode(findOrganByUserCode.get(0).get("OrganCode"));
   		 }
        return  Response.response(commService.searchByOneList(comm, page, size,isManage));
    }
    @ResponseBody
    @RequestMapping(value = "/updateByOne", produces = "application/json;charset=utf-8", method = RequestMethod.GET)
    public Object updateByOne(Comm comm,HttpServletRequest request, HttpServletResponse response) {
        String accessToken = request.getParameter("AccessToken");
        AccessToken token = accessTokenService.findByToken(accessToken);
        String userCode = token.getUserCode();
        comm.setModifiedBy(userCode);
        comm.setGmtModified(new Date());


        commService.updateByOne(comm);
        return 1;
    }
    /**
     * 获取项目基础信息
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/detail/basic", produces = "application/json;charset=utf-8", method = RequestMethod.GET)
    public Result basicDetail(@RequestParam(value = "serialNumber", required = true, defaultValue = "") String serialNumber) {
        String commId = serialNumber;
        Comm comm = new Comm();
        comm.setCommCode(commId);
        comm = commMapper.selectOne(comm);
        if (comm == null) {
            throw new ServiceException("项目不存在");
        }


        Map<String, Object> organs = commService.findOrganMapCache();
        String organCode = comm.getProposalOrganId();
        String organName = organs.getOrDefault(organCode, "").toString();
        String takeOverOrganCode = comm.getOrganId();
        String takeOverOrganName = organs.getOrDefault(takeOverOrganCode, "").toString();

        ProjectJointPlan p = new ProjectJointPlan();
        List<ProjectJointPlan> type = new ArrayList<ProjectJointPlan>();
        String cooperationTypeName = "";
        String projectTypeName="";
        String projectNatureName="";
        if(comm.getGeneralType() == 1) {
            p.setId(comm.getCorpType());
            p.setMenuId(4);
            type = projectJointPlanMapper.select(p);
            if(type.size() > 0) {
                cooperationTypeName = type.get(0).getName();
            }

            p.setId(comm.getProjectType());
            p.setMenuId(3);
            type = projectJointPlanMapper.select(p);
            if(type.size() > 0) {
                projectTypeName = type.get(0).getName();
            }


            p.setId(comm.getProjectNature());
            p.setMenuId(2);
            type = projectJointPlanMapper.select(p);
            if(type.size() > 0) {
                projectNatureName = type.get(0).getName();
            }
        }else if(comm.getGeneralType() == 2 || comm.getGeneralType() == 3) {
            p.setId(comm.getCorpType());
            p.setMenuId(5);
            type = projectJointPlanMapper.select(p);
            if(type.size() > 0) {
                cooperationTypeName = type.get(0).getName();
            }
        }
        //String cooperationTypeName;
        //  CooperationType cooperationType = cooperationTypeService.findBy("code", comm.getCorpType());
//        if (cooperationType != null) {
//            cooperationTypeName = cooperationType.getName();
//        } else {
//            cooperationTypeName = "";
//        }

//        String projectTypeName;
//        ProjectType projectType = typeService.findBy("code", comm.getProjectType());
//        if (projectType != null) {
//            projectTypeName = projectType.getName();
//        } else {
//            projectTypeName = "";
//        }
//
//        String projectNatureName;
//        ProjectNature projectNature = natureService.findBy("code", comm.getProjectNature());
//        if (projectNature != null) {
//            projectNatureName = projectNature.getName();
//        } else {
//            projectNatureName = "";
//        }

        BigDecimal planningArea = comm.getArea();
        BigDecimal contractArea = comm.getContractArea();
        BigDecimal chargeArea = comm.getChargeArea();

        // 构建返回数据
        Map<String, Object> response = new HashMap<String, Object>() ;
        response.put("id", comm.getId());
        response.put("serialNumber", serialNumber);
        response.put("projectName", comm.getName());
        response.put("organCode", organCode);
        response.put("organName", organName);
        response.put("takeOverOrganCode", takeOverOrganCode);
        response.put("takeOverOrganName", takeOverOrganName);
        response.put("projectType", projectTypeName);
        response.put("projectNature", projectNatureName);
        response.put("cooperationTypes", cooperationTypeName);
        response.put("state", CommConstant.CommStatus.statusName.get(comm.getStatus()));
        response.put("prophaseMemo", comm.getProphase());
//            put("planningArea", planningArea != null ? NumberUtil.toTenOfThousand(planningArea) : 0f);
//            put("contractArea", contractArea != null ? NumberUtil.toTenOfThousand(contractArea) : 0f);
//            put("chargeArea", chargeArea != null ? NumberUtil.toTenOfThousand(chargeArea) : 0f);

        response.put("planningArea", planningArea != null ? planningArea : 0f);
        response.put("contractArea", contractArea != null ? contractArea : 0f);
        response.put("chargeArea", chargeArea != null ? chargeArea : 0f);
        response.put("contact", comm.getContractorName()); // TODO 跟进人是提报人？还是联系人
        response.put("memo", comm.getComment());
        response.put("generalType",comm.getGeneralType());
        response.put("cooperationfName",comm.getCooperationfName());
        response.put("saturation", comm.getSaturation());
        response.put("cooperationfContact", comm.getCooperationfContact());
        response.put("cooperationfNumber", comm.getCooperationfNumber());
        response.put("proportion", comm.getProphase());
        response.put("projectNumber", comm.getProjectNumber());
        response.put("targetArea", comm.getTargetArea());
        response.put("targetIncome", comm.getTargetIncome());
        response.put("schedule", comm.getSchedule());
        response.put("city", comm.getCity());
        response.put("remark", comm.getRemark());
        response.put("region", comm.getRegion());
        response.put("scheduleName", comm.getScheduleName());

        return Response.response(response);
    }


    @ResponseBody
    @RequestMapping(value = "search", produces = "application/json;charset=utf-8", method = RequestMethod.GET)
    public Result search(@RequestParam(value = "search", required = false, defaultValue = "") String searchKey,
                         @RequestParam(value = "organCode", required = false, defaultValue = "") String organCode,
                         @RequestParam(value = "takeOverOrganCode", required = false, defaultValue = "") String takeOverOrgganCode,
                         @RequestParam(value = "isCharge", required = false, defaultValue = "false") boolean isCharge,
                         @RequestParam(value = "proposalBefore", required = false, defaultValue = "") String proposalBefore,
                         @RequestParam(value = "proposalAfter", required = false, defaultValue = "") String proposalAfter,
                         @RequestParam(value = "contractBefore", required = false, defaultValue = "") String contractBefore,
                         @RequestParam(value = "contractAfter", required = false, defaultValue = "") String contractAfter,
                         @RequestParam(value = "isOwner", required = false, defaultValue = "false") boolean isOwner,
                         @RequestParam(value = "status", required = false, defaultValue = "") String status,
                         @RequestParam(value = "generalType", required = false, defaultValue = "1") Integer generalType,
                         @RequestParam(value = "pageIndex", required = false, defaultValue = "0") int page,
                         @RequestParam(value = "pageSize", required = false, defaultValue = "0") int size,
                         @RequestParam(value = "statusCode", required = false, defaultValue = "") String statusCode,
                         HttpServletRequest request, HttpServletResponse response) {
        String accessToken = request.getParameter("AccessToken");
        AccessToken token = accessTokenService.findByToken(accessToken);
        if (searchKey != null) {
            try {
                searchKey = URLDecoder.decode(searchKey, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        PageData pageData = commService.search(token.getUserCode(), searchKey, organCode, takeOverOrgganCode,
                isCharge, proposalBefore, proposalAfter
                , contractBefore, contractAfter, isOwner, status,generalType, page, size);

        return Response.response(pageData);
    }


    @RequestMapping(value = "/export", produces = "multipart/form-data", method = RequestMethod.GET)
    public Result export(@RequestParam(value = "search", required = false, defaultValue = "") String searchKey,
                         @RequestParam(value = "organCode", required = false, defaultValue = "") String organCode,
                         @RequestParam(value = "takeOverOrganCode", required = false, defaultValue = "") String takeOverOrgganCode,
                         @RequestParam(value = "isCharge", required = false, defaultValue = "false") boolean isCharge,
                         @RequestParam(value = "proposalBefore", required = false, defaultValue = "") String proposalBefore,
                         @RequestParam(value = "proposalAfter", required = false, defaultValue = "") String proposalAfter,
                         @RequestParam(value = "contractBefore", required = false, defaultValue = "") String contractBefore,
                         @RequestParam(value = "contractAfter", required = false, defaultValue = "") String contractAfter,
                         @RequestParam(value = "isOwner", required = false, defaultValue = "false") boolean isOwner,
                         @RequestParam(value = "status", required = false, defaultValue = "") String status,
                         HttpServletRequest request, HttpServletResponse response) {
        String accessToken = request.getParameter("AccessToken");
        AccessToken token = accessTokenService.findByToken(accessToken);
        PageData pageData = commService.search(token.getUserCode(), searchKey, organCode, takeOverOrgganCode,
                isCharge, proposalBefore, proposalAfter
                , contractBefore, contractAfter, isOwner, status, null,1, 0);
        Result result = Response.response(pageData);
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet();
        ExcelHelper helper = new ExcelHelper();
        helper.createProjectListHeader(workbook, sheet);
        helper.createProjectListBody((PageData) result.getData(), workbook, sheet);
        response.setContentType("multipart/form-data");
        String fileName = "export.xlsx";
        try {
            fileName = URLEncoder.encode("项目列表.xlsx", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
        OutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
        } catch (Exception ex) {

        } finally {
            try {
                workbook.close();
            } catch (Exception ex) {

            }
        }
        return null;
    }

    @ResponseBody
    @RequestMapping(value = "state", produces = "application/json;charset=utf-8", method = RequestMethod.GET)
    public Result state(@RequestParam(value = "isOwner", required = false, defaultValue = "false") boolean isOwner,
                        HttpServletRequest request, HttpServletResponse response) {
        String accessToken = request.getParameter("AccessToken");
        Integer generalType = Integer.parseInt(request.getParameter("generalType"));
        AccessToken token = accessTokenService.findByToken(accessToken);
        String userCode = null;
        if (isOwner) {
            userCode = token.getUserCode();
        }
        CommCount commCount = commService.count(userCode,generalType);

        return Response.response(commCount);
    }
    @ResponseBody
    @RequestMapping(value = "stateByOne", produces = "application/json;charset=utf-8", method = RequestMethod.GET)
    public Result stateByOne(@RequestParam(value = "isOwner", required = false, defaultValue = "false") boolean isOwner,
                             HttpServletRequest request, HttpServletResponse response) {
        String accessToken = request.getParameter("AccessToken");
        AccessToken token = accessTokenService.findByToken(accessToken);
        String userCode = token.getUserCode();
//        if (isOwner) {
//            userCode = token.getUserCode();
//        }
        // CommCount commCount = commService.count(userCode);
        Comm c = new Comm();
        OneCommCount commCount = new OneCommCount();
        commCount.setClassByA(0) ;
        commCount.setClassByB(0) ;
        commCount.setClassByC(0) ;
        commCount.setClassByD(0) ;
        commCount.setClassByO(0) ;
        commCount.setClassByY(0) ;
        commCount.setClassByStop(0) ;
        commCount.setClassByWaiting(0) ;
        List<Map<String, String>> findOrganByUserCode = tbHsprContractMapper.findOrganByUserCode(userCode);
        List<Role> rList=  roleMapper.findByUserCode(userCode);
        for (Role role : rList) {
            if(role.getCode().equals("marketing_manager")) {
                userCode = null;
                break;
            }
        }
        Map<String, String> map = new HashMap<>();
        map.put("contractorCode", userCode);
        if(findOrganByUserCode.size()>0) {
   		 map.put("areaCode", findOrganByUserCode.get(0).get("OrganCode"));
   		 }
        List<Map<String, Object>> commByCount = commMapper.getCommByCount(map);
        int count=0;
        for (Map<String, Object> map2 : commByCount) {
        	int intValue = ((Long)map2.get("count")).intValue();
        	count += intValue;
        	String string = map2.get("CODE")+"";
			switch (string) {
			case ProjectClass.CODE_CLASSBYA:
		        commCount.setClassByA(intValue) ;
				break;
			case ProjectClass.CODE_CLASSBYB:
		        commCount.setClassByB(intValue) ;
				break;
			case ProjectClass.CODE_CLASSBYC:
		        commCount.setClassByC(intValue) ;
				break;
			case ProjectClass.CODE_CLASSBYD:
		        commCount.setClassByD(intValue) ;
				break;
			case ProjectClass.CODE_CLASSBYO:
		        commCount.setClassByO(intValue) ;
				break;
			case ProjectClass.CODE_CLASSBYY:
		        commCount.setClassByY(intValue) ;
				break;
			case ProjectPlanOne.CODE_OVER:
		        commCount.setClassByStop(intValue) ;
				break;
			case ProjectPlanOne.CODE_CHECKRESTART:
		        commCount.setClassByWaiting(intValue) ;
				break;
			case ProjectPlanOne.CODE_CHECKSTOP:
		        commCount.setClassByA(intValue) ;
			}
		}
        commCount.setClassByAll(count);
//        c.setContractorCode(userCode);
//        c.setGeneralType(Comm.COMM_TYPE_ONE);
//        
//        c.setProjectClassCode(ProjectClass.CODE_CLASSBYB);
//        commCount.setClassByB(commMapper.selectByOneCount(c));
//        c.setProjectClassCode(ProjectClass.CODE_CLASSBYC);
//        commCount.setClassByC(commMapper.selectByOneCount(c));
//        c.setProjectClassCode(ProjectClass.CODE_CLASSBYD);
//        commCount.setClassByD(commMapper.selectByOneCount(c));
//        c.setProjectClassCode(ProjectClass.CODE_CLASSBYO);
//        commCount.setClassByO(commMapper.selectByOneCount(c));
//        c.setProjectClassCode(null);
//        commCount.setClassByAll(commMapper.selectByOneCount(c));
//        c.setProjectClassCode(ProjectClass.CODE_CLASSBYSTOP);
//        commCount.setClassByStop(commMapper.selectByOneCount(c));
//        c.setProjectClassCode(ProjectClass.CODE_CLASSBYWAITING);
//        commCount.setClassByWaiting(commMapper.selectByOneCount(c));
//        c.setProjectClassCode(ProjectClass.CODE_CLASSBYY);
//        commCount.setClassByY(commMapper.selectByOneCount(c));
        return Response.response(commCount);
    }
    @ResponseBody
    @RequestMapping(value = "findType/{id}", produces = "application/json;charset=utf-8", method = RequestMethod.GET)
    public Result findType(@PathVariable Integer id) {
        ProjectJointPlan p = new ProjectJointPlan();
        p.setMenuId(id);
        return  Response.response(projectJointPlanMapper.select(p));
    }
    @ResponseBody
    @RequestMapping(value = "/createByOne", produces = "application/json; charset=utf-8", method = RequestMethod.POST)
    public Object createByOne(Comm comm,HttpServletRequest request, HttpServletResponse response) {
    	 String accessToken = request.getParameter("AccessToken");
    	AccessToken token = accessTokenService.findByToken(accessToken);
    	TbSysUser sysUser = userService.findByUserCode(token.getUserCode());
    	comm.setContractorName(sysUser.getUserName());
    	List<Map<String, String>> findOrganByUserCode = tbHsprContractMapper.findOrganByUserCode(token.getUserCode());
    	if(findOrganByUserCode.size()>0) {
    	comm.setErpOrganCode(findOrganByUserCode.get(0).get("OrganCode"));
    	comm.setErpOrganName(findOrganByUserCode.get(0).get("organName"));
    	}else {
    		
    	}
        if(!commService.repetition(comm)) {
       	 throw new ServiceException("名称重复");
        }
        
    	commService.creatOneProject (comm,token.getUserCode());
    	return Response.response(1);
    }
    /**
     * 创建项目
     *
     * @param organCode
     * @param projectName
     * @param planningArea
     * @param projectTypeCode
     * @param cooperationTypeCode
     * @param projectNatureCode
     * @param memo
     * @param prophaseMemo
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "", produces = "application/json; charset=utf-8", method = RequestMethod.POST)
    public Result create(@RequestParam(value = "organId", required = true, defaultValue = "") String organCode,
                         @RequestParam(value = "name", required = true, defaultValue = "") String projectName,
                         @RequestParam(value = "planningArea", required = true, defaultValue = "0") float planningArea,
                         @RequestParam(value = "contacts", required = false) String contacts,

                         @RequestParam(value = "projectType", required = true, defaultValue = "") Integer projectTypeCode,
                         @RequestParam(value = "corpType", required = true, defaultValue = "") Integer cooperationTypeCode,
                         @RequestParam(value = "projectNature", required = false, defaultValue = "") Integer projectNatureCode,
                         @RequestParam(value = "memo", required = false, defaultValue = "") String memo,
                         @RequestParam(value = "prophaseMemo", required = false, defaultValue = "") String prophaseMemo,
                         @RequestParam(value = "generalType", required = false, defaultValue = "") Integer generalType,
                         @RequestParam(value = "cooperationfName", required = false, defaultValue = "") String cooperationfName,
                         @RequestParam(value = "saturation", required = false, defaultValue = "") Float saturation,
                         @RequestParam(value = "cooperationfContact", required = false, defaultValue = "") String cooperationfContact,
                         @RequestParam(value = "cooperationfNumber", required = false, defaultValue = "") String cooperationfNumber,
                         @RequestParam(value = "proportion", required = false, defaultValue = "") Float proportion,
                         @RequestParam(value = "projectNumber", required = false, defaultValue = "") Integer projectNumber,
                         @RequestParam(value = "targetArea", required = false, defaultValue = "") Float targetArea,
                         @RequestParam(value = "targetIncome", required = false, defaultValue = "") Float targetIncome,
                         @RequestParam(value = "schedule", required = false, defaultValue = "") String schedule,
                         @RequestParam(value = "city", required = false, defaultValue = "") String city,
                         @RequestParam(value = "remark", required = false, defaultValue = "") String remark,
                         @RequestParam(value = "region", required = false, defaultValue = "") String region


    ) {

        // TODO check if organ exists
        Map<String, Object> organs = commService.findOrganMapCache();

        Object organName = organs.getOrDefault(organCode, null);

        if (organName == null) {
            throw new ServiceException("接管区域不存在");
        }
        TbSysOrgan takeOverOrgan = organService.findByOrganCode(organCode);
        if (takeOverOrgan == null) {
            throw new ServiceException("所属区域不存在");
        }
        if(null == generalType) {
            throw new ServiceException("大类必须填写");
        }
        if(generalType == 1) {

        }
        ProjectJointPlan p = new ProjectJointPlan();
        List<ProjectJointPlan> type = new ArrayList<>();
        String cooperationTypeName = "";
        String projectTypeName = "";
        String projectNatureName = "";
        if(1==generalType) {

            p.setId(cooperationTypeCode);
            p.setMenuId(4);
            type = projectJointPlanMapper.select(p);
            if (type == null || type.size() < 1) {
                throw new ServiceException("合作模式不存在");
            }
            cooperationTypeName = type.get(0).getName();

            p.setId(projectTypeCode);
            p.setMenuId(3);
            type = projectJointPlanMapper.select(p);
            if (type == null || type.size() < 1) {
                throw new ServiceException("项目类型不存在");
            }
            projectTypeName = type.get(0).getName();

            p.setId(projectNatureCode);
            p.setMenuId(2);
            type = projectJointPlanMapper.select(p);
            if (type == null || type.size() < 1) {
                throw new ServiceException("项目性质不存在");
            }
            projectNatureName = type.get(0).getName();

        }else if(2 == generalType || 3==generalType) {
            p.setId(cooperationTypeCode);
            p.setMenuId(5);
            type = projectJointPlanMapper.select(p);
            if (type == null || type.size() < 1) {
                throw new ServiceException("合作模式不存在");
            }
            cooperationTypeName = type.get(0).getName();

        }else {
            throw new ServiceException("该大类不存在");
        }




        TbSysUser sysUser = userService.getCurrentSysUser();
        TbSysOrgan sysOrgan = userService.getSysOrgan();
        String proposalOrganCode = "";
        if (sysOrgan != null) {
            proposalOrganCode = sysOrgan.getOrganCode();
        }
        Comm comm = new Comm();
        comm.setCreateBy(sysUser.getUserCode());
        comm.setGmtCreate(new Date());
        comm.setName(projectName);
        comm.setOrganId(organCode);
        comm.setProposalOrganId(proposalOrganCode); // TODO 提报区域ID
        comm.setProjectType(projectTypeCode);
        comm.setProjectNature(projectNatureCode);
        comm.setCity(city);
        comm.setCorpType(cooperationTypeCode);
//        BigDecimal area = NumberUtil.fromTenOfThousand(BigDecimal.valueOf(planningArea));
        BigDecimal area = BigDecimal.valueOf(planningArea);
        comm.setArea(area);
        comm.setContractorCode(sysUser.getUserCode());
        comm.setContractorName(sysUser.getUserName());
        comm.setContacts(contacts); // TODO set mobile / phone or contracts
        comm.setComment(memo);
        comm.setProphase(prophaseMemo);
        comm.setRegion(region);
        comm.setStatus(CommConstant.CommStatus.prophase);
        comm.setGeneralType(generalType);
        comm.setCooperationfName(cooperationfName);
        if(null != saturation) {
            comm.setSaturation(new BigDecimal(saturation));
        }else {
            comm.setSaturation(null);
        }

        comm.setCooperationfContact(cooperationfContact);


        comm.setCooperationfNumber(cooperationfNumber);

        comm.setProportion(proportion+"");
        comm.setProjectNumber(projectNumber);
        if(null != targetArea) {
            comm.setTargetArea(new BigDecimal(targetArea));
        }else {
            comm.setTargetArea(null);
        }
        if(null != targetIncome) {
            comm.setTargetIncome(new BigDecimal(targetIncome));
        }else {
            comm.setTargetIncome(null);
        }
        List<Comm> count = commMapper.selectAll();

        String code = "";

        code+=generalType;
        code+="01";
        code+=comm.getOrganId();
        code+="18";
        code+=complemented(count.size());
        //comm.setSchedule(schedule);
        comm.setIsDelete(new Byte("0"));
        comm.setCommCode(code);
        comm.setCommNum(code);



        commService.save(comm);
        // 设置6位自增编号
        String commNum = "WT" + String.format("%06d", comm.getId());

        commService.update(comm);

        String stateText = CommConstant.CommStatus.statusName.get(CommConstant.CommStatus.prophase);
        // 构建返回数据
        Map<String, Object> response = new HashMap<String, Object>();
        response.put("id", comm.getId());
        response.put("organCode", organCode);
        response.put("contract", sysUser.getUserName());
        response.put("projectName", projectName);
        response.put("planningArea", NumberUtil.decimalFormat(planningArea));
        response.put("projectType", projectTypeName);
        response.put("corporationType", cooperationTypeName);
        response.put("projectNature", projectNatureName);
        response.put("memo", memo);
        response.put("prophaseMemo", prophaseMemo);
        response.put("serialNumber", comm.getCommNum());
        response.put("organName", organName);
        response.put("commNum", commNum);
        response.put("stateText", stateText);


        // TODO 添加修改节点
        operationHistoryService.operation(
                comm.getId(),
                CommConstant.OperationName.prophase,
                sysUser.getUserName() + "创建项目",
                JSON.toJSONString(response),
                sysUser.getUserCode()
        );

        return Response.response(response);
    }

    /**
     * 编辑项目
     *
     * @param serialNumber
     * @param projectName
     * @param planningArea
     * @param projectTypeCode
     * @param cooperationTypeCode
     * @param introduction
     * @param projectNatureCode
     * @param prophaseMemo
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "", produces = "application/json; charset=utf-8", method = RequestMethod.PUT)
    public Result update(

            @RequestParam(value = "serialNumber", required = true, defaultValue = "") String serialNumber,
            @RequestParam(value = "projectName", required = true, defaultValue = "") String projectName,


            @RequestParam(value = "introduction", required = true, defaultValue = "") String introduction,

            @RequestParam(value = "city", required = false, defaultValue = "") String city,
            @RequestParam(value = "remark", required = false, defaultValue = "") String remark,
            @RequestParam(value = "prophaseMemo", required = false, defaultValue = "") String prophaseMemo,
            @RequestParam(value = "cooperationfContact", required = false, defaultValue = "") String cooperationfContact,
            @RequestParam(value = "cooperationfNumber", required = false, defaultValue = "") String cooperationfNumber,

            HttpServletRequest request
    ) {
        Integer id = null;

        if(!request.getParameter("id").equals("null")&&!request.getParameter("id").equals("")) {
            id = Integer.parseInt(request.getParameter("id"));
        }
        Integer cooperationTypeCode = null;
        if(!request.getParameter("cooperationTypeCode").equals("null")&&!request.getParameter("cooperationTypeCode").equals("")) {
            cooperationTypeCode = Integer.parseInt(request.getParameter("cooperationTypeCode"));
        }
        float planningArea = 0f;
        if(!request.getParameter("planningArea").equals("null")&&!request.getParameter("planningArea").equals("")) {
            planningArea = Float.parseFloat(request.getParameter("planningArea"));
        }
        Integer projectTypeCode = null;
        if(!request.getParameter("projectTypeCode").equals("null") && !request.getParameter("projectTypeCode").equals("")) {
            projectTypeCode = Integer.parseInt(request.getParameter("projectTypeCode"));
        }
        Integer projectNatureCode = null;
        if(!request.getParameter("projectNatureCode").equals("null")&&!request.getParameter("projectNatureCode").equals("")) {
            projectNatureCode = Integer.parseInt(request.getParameter("projectNatureCode"));
        }
        Float proportion = null;
        if(!request.getParameter("proportion").equals("null")&&!request.getParameter("proportion").equals("")) {
            proportion = Float.parseFloat(request.getParameter("proportion"));
        }
        Integer projectNumber = null;
        if(!request.getParameter("projectNumber").equals("null")&&!request.getParameter("projectNumber").equals("")) {
            projectNumber = Integer.parseInt(request.getParameter("projectNumber"));
        }
        Float targetArea = 0f ;
        if(!request.getParameter("targetArea").equals("null")&&!request.getParameter("targetArea").equals("")) {
            targetArea = Float.parseFloat(request.getParameter("targetArea"));
        }
        Float targetIncome = 0f;
        if(!request.getParameter("targetIncome").equals("null")&&!request.getParameter("targetIncome").equals("")) {
            targetIncome = Float.parseFloat(request.getParameter("targetIncome"));
        }
        // int commId = Integer.parseInt(serialNumber.substring(2));

        Comm comm = commService.findById(id);
        if (comm == null) {
            throw new ServiceException("项目不存在");
        }



        String projectNatureName;


        TbSysUser sysUser = userService.getCurrentSysUser();
        comm.setModifiedBy(sysUser.getUserCode());
        comm.setGmtModified(new Date());
        comm.setName(projectName);
        comm.setProjectType(projectTypeCode);
        comm.setCorpType(cooperationTypeCode);
        comm.setProjectNature(projectNatureCode);
        comm.setCity(city);
        comm.setRemark(remark);
        comm.setCooperationfContact(cooperationfContact);
        comm.setCooperationfNumber(cooperationfNumber);
        comm.setProportion(proportion+"");
        comm.setProjectNumber(projectNumber);
        comm.setTargetArea(new BigDecimal(targetArea));
        comm.setTargetIncome(new BigDecimal(targetIncome));

        comm.setArea(new BigDecimal(planningArea) );


        BigDecimal area = BigDecimal.valueOf(planningArea);
//        area = NumberUtil.fromTenOfThousand(area);
        comm.setArea(area);
        comm.setComment(introduction);

        if (!prophaseMemo.equals("")) {
            comm.setProphase(prophaseMemo);
        }

        commService.update(comm);

        String stateText = CommConstant.CommStatus.statusName.getOrDefault(comm.getStatus(), "");
        // 构建返回数据
        Map<String, Object> response = new HashMap<String, Object>();
        response.put("id", comm.getId());
        response.put("projectName", projectName);
        response.put("planningArea", NumberUtil.decimalFormat(planningArea));
        //put("projectType", projectType.getName());
        //put("corporationType", cooperationType.getName());
        // put("projectNature", projectNatureName);
        response.put("memo", introduction);
        response.put("prophaseMemo", prophaseMemo);
        response.put("planningArea", planningArea);
        response.put("serialNumber", serialNumber);
        response.put("stateText", stateText);


        return Response.response(response);
    }

    /**
     * 停止项目
     *
     * @param serialNumber
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/toggle", produces = "application/json; charset=utf-8", method = RequestMethod.PUT)
    public Result toggle(@RequestParam(value = "serialNumber", required = true, defaultValue = "") String serialNumber) {

        int commId = Integer.parseInt(serialNumber.substring(2));
        Comm comm = commService.findById(commId);
        if (comm == null) {
            throw new ServiceException("项目不存在");
        }

        TbSysUser sysUser = userService.getCurrentSysUser();
        comm.setModifiedBy(sysUser.getUserCode());
        comm.setGmtModified(new Date());
        comm.setStatus(CommConstant.CommStatus.suspend);
        commService.update(comm);

        // 构建返回数据
        Map<String, Object> response = new HashMap<String, Object>() {{
            put("id", comm.getId());
            put("serialNumber", serialNumber);
            put("stateText", CommConstant.CommStatus.statusName.get(CommConstant.CommStatus.suspend));
        }};

        // TODO 添加修改节点
        operationHistoryService.operation(
                commId,
                CommConstant.OperationName.suspend,
                sysUser.getUserName() + "手动停止项目",
                JSON.toJSONString(response),
                sysUser.getUserCode()
        );

        return Response.response(response);
    }


    @ResponseBody
    @RequestMapping(value = "/upload", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    public Result upload(@RequestParam(value = "type", defaultValue = "1", required = true) String type,
                         @RequestParam(value = "uploadfile", defaultValue = "", required = true) MultipartFile multipartFile,
                         HttpServletRequest request, HttpServletResponse response) throws ServiceException {
        String accessToken = request.getParameter("AccessToken");
        AccessToken token = accessTokenService.findByToken(accessToken);
        Map<String, Object> data = new HashMap<>();

        if (multipartFile == null) {
            throw new ServiceException("请选择需要上传的文件");
        }

        switch (type) {
            case CommConstant.CommUploadFileType.FILE_TYPE_PROPOSAL:
            case CommConstant.CommUploadFileType.FILE_TYPE_CONTRACT:
            case CommConstant.CommUploadFileType.FILE_TYPE_MONTH_CHARGE:
            case CommConstant.CommUploadFileType.FILE_TYPE_QUATER_CHARGE:
            case CommConstant.CommUploadFileType.FILE_TYPE_MISSION_QUOTA:
                break;
            default:
                throw new ServiceException("不支持的数据类型");
        }

        CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile) multipartFile;
        if (commonsMultipartFile.isEmpty()) {
            return Response.responseFail("上传文件为空文件");
        }
        String fileName = commonsMultipartFile.getOriginalFilename();
        if (fileName.indexOf(".xlsx") <= 0 || fileName.indexOf(".xls") <= 0) {
            return Response.responseFail("上传文件应为excel文件格式为：xlsx 或 xls");
        }
        InputStream inputStream = null;
        try {
            inputStream = commonsMultipartFile.getInputStream();
            Workbook workbook = null;
            if (fileName.indexOf(".xlsx") > 0) {
                workbook = new XSSFWorkbook(inputStream);
            } else {
                workbook = new HSSFWorkbook(inputStream);
            }
            processUpdateFile(workbook, type, token.getUserCode());
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new ServiceException(ex.getMessage());
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Response.response("");
    }

    private void processUpdateFile(Workbook workbook, String type, String userCode) {
        ExcelDataParser parser = new ExcelDataParser();
        switch (type) {
            case CommConstant.CommUploadFileType.FILE_TYPE_PROPOSAL:
                List<ProposalData> proposalDataList = parser.parseProposal(workbook);
                proposalService.parseUploadFile(proposalDataList, userCode);
                break;
            case CommConstant.CommUploadFileType.FILE_TYPE_CONTRACT:
                List<ContractData> contractDataList = parser.parseContract(workbook);
                contractService.parseUploadFile(contractDataList, userCode);
                break;
            case CommConstant.CommUploadFileType.FILE_TYPE_MONTH_CHARGE:
                List<ChargeData> monthChargeList = parser.parseCharge(workbook, false);
                chargeService.parseUploadFile(monthChargeList, userCode, false);
                break;
            case CommConstant.CommUploadFileType.FILE_TYPE_QUATER_CHARGE:
                List<ChargeData> quaterChargeList = parser.parseCharge(workbook, true);
                chargeService.parseUploadFile(quaterChargeList, userCode, true);
                break;
            case CommConstant.CommUploadFileType.FILE_TYPE_MISSION_QUOTA:
                quotaService.processingExcelValue(workbook, userCode);
                break;
            default:
                throw new ServiceException("不支持的数据类型");
        }
    }

    /**
     * 数据看板
     *
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/statistics/basic", produces = "application/json;charset=utf-8", method = RequestMethod.GET)
    public Result statisticsBasic(HttpServletRequest request, HttpServletResponse response) {
        StatisticsBasic statisticsBasic = commService.countStatisticsBasic();
        return Response.response(statisticsBasic);
    }

    /**
     * 数据看板
     *
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/statistics/proposal", produces = "application/json;charset=utf-8", method = RequestMethod.GET)
    public Result statisticsPropotal(HttpServletRequest request, HttpServletResponse response) {
        List<StatisticsProposal> dataList = proposalService.statisticsProposal();
        return Response.response(dataList);
    }
    /**
     * 跟进动态
     * @param id
     * @param schedule
     * @param remark
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/followUp", produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    public Object followUp( @RequestParam(value = "id", required = false) Integer id,
                            @RequestParam(value = "schedule", required = false) Integer schedule,
                            @RequestParam(value = "remark", required = false) String remark, HttpServletRequest request, HttpServletResponse response) {
        String accessToken = request.getParameter("AccessToken");
        AccessToken token = accessTokenService.findByToken(accessToken);

        Comm c = commMapper.selectByPrimaryKey(id);


        ProjectJointPlan p = new ProjectJointPlan();
        if(c.getGeneralType() .equals(Comm.COMM_TYPE_JOINT)) {
            p.setMenuId(7);
            p.setId(schedule);
        }else if(c.getGeneralType().equals(Comm.COMM_TYPE_STOCK)) {
            p.setMenuId(8);
            p.setId(schedule);
        }


        p = projectJointPlanMapper.selectOne(p);
        if(null == p) {
            throw new ServiceException("节点不存在");
        }
        c.setSchedule(p.getId());
        c.setScheduleName(p.getName());
        String dynamicName = "";
        if(null != p) {
            dynamicName = p.getName();
        }
        operationHistoryService.operation(
                id,
                dynamicName,
                remark,
                "",
                token.getUserCode()
        );

        commService.update(c);

        return 1;

    }
//   /**
//    * 基本资料填写
//    * @param comm
//    * @return
//    */
//   @ResponseBody
//   @RequestMapping(value = "/next/basics", produces = "application/json;charset=utf-8",method = RequestMethod.POST)
//   public Object basics( Comm comm,HttpServletRequest request, HttpServletResponse response) {
//
//	   if(comm.getId()  == null) {
//		   throw new ServiceException("请选择项目");
//	   }
//	   Comm c = commMapper.selectByPrimaryKey(comm.getId());
//	   if(null == c) {
//		   throw new ServiceException("没有找到该项目");
//	   }
//	   String accessToken = request.getParameter("AccessToken");
//	   TbSysUser sysUser = userService.getCurrentSysUser();
//	   ProjectClass pc = new ProjectClass();
//   	pc.setCode(ProjectClass.CODE_CLASSBYO);
//   	pc = projectClassMapper.selectOne(pc);
//
//   	ProjectPlanOne pp = new ProjectPlanOne();
//   	pp.setCode(ProjectPlanOne.CODE_PROJECTKEY);
//   	pp = projectPlanOneMapper.selectOne(pp);
//	   operationHistoryService.operation(
//               c.getId(),
//               pp.getName(),
//               sysUser.getUserName() + "变更业务进度",
//               "",
//               sysUser.getUserCode()
//       );
//	   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());
//	   commMapper.updateByPrimaryKey(c);
//	   return 1;
//   }

   /**
    * 关键人接触
    * @param comm
    * @return
    */
   @ResponseBody
   @RequestMapping(value = "/next/keyPerson",produces = "application/json;charset=utf-8", method = RequestMethod.POST)
   public Object keyPerson( Comm comm) {
	   if(comm.getId()  == null) {
		   throw new ServiceException("请选择项目");
	   }
	   Comm c = commMapper.selectByPrimaryKey(comm.getId());
	   if(null == c) {
		   throw new ServiceException("没有找到该项目");
	   }
	   
	   TbSysUser sysUser = userService.getCurrentSysUser();
	   ProjectClass pc = new ProjectClass();
   	pc.setCode(ProjectClass.CODE_CLASSBYO);
   	pc = projectClassMapper.selectOne(pc);
   	
   	ProjectPlanOne pp = new ProjectPlanOne();
   	pp.setCode(ProjectPlanOne.CODE_PROJECTKEY);
   	pp = projectPlanOneMapper.selectOne(pp);
	   operationHistoryService.operation(
               c.getId(),
               pp.getName(),
               sysUser.getUserName() + "变更业务进度",
               "",
               sysUser.getUserCode()
       );
	   c.setUpperProjectPlanCode(c.getProjectPlanCode());
	   c.setProjectPlanCode(pp.getCode());
	   c.setJoint(comm.getJoint());
	   c.setJointDuty(comm.getJointDuty());
	   c.setJointRight(comm.getJointRight());
	   c.setGmtModified(new Date());
	 
       c.setGmtModified(new Date());
	   commService.boostJudge(c);
	   commMapper.updateByPrimaryKey(c);
	   return 1;
   }
   
   /**
    * 合作意向确认
    * @param comm
    * @return
    */
   @ResponseBody
   @RequestMapping(value = "/next/symbiosisVerify",produces = "application/json;charset=utf-8", method = RequestMethod.POST)
   public Object symbiosisVerify( Comm comm) {
	   if(comm.getId()  == null) {
		   throw new ServiceException("请选择项目");
	   }
	   Comm c = commMapper.selectByPrimaryKey(comm.getId());
	   if(null == c) {
		   throw new ServiceException("没有找到该项目");
	   }
	 
	   TbSysUser sysUser = userService.getCurrentSysUser();
	   ProjectClass pc = new ProjectClass();
   	pc.setCode(ProjectClass.CODE_CLASSBYO);
   	pc = projectClassMapper.selectOne(pc);
   	
   	ProjectPlanOne pp = new ProjectPlanOne();
   	pp.setCode(ProjectPlanOne.CODE_COOPERATION);
   	pp = projectPlanOneMapper.selectOne(pp);
	   operationHistoryService.operation(
               c.getId(),
               pp.getName(),
               sysUser.getUserName() + "变更业务进度",
               "",
               sysUser.getUserCode()
       );
	   c.setUpperProjectPlanCode(c.getProjectPlanCode());
	   c.setProjectPlanCode(pp.getCode());
	   c.setCorpType(comm.getCorpType());
	   c.setSignificance(comm.getSignificance());
	   c.setDemand(comm.getDemand());
	   c.setGmtModified(new Date());
	   commService.boostJudge(c);
	   commMapper.updateByPrimaryKey(c);
	   return 1;
   }
   
   /**
    * 价格详细
    * @param comm
    * @return
    */
   @ResponseBody
   @RequestMapping(value = "/next/priceDetail",produces = "application/json;charset=utf-8", method = RequestMethod.POST)
   public Object priceDetail(Comm comm) {
	   if(comm.getId()  == null) {
		   throw new ServiceException("请选择项目");
	   }
	   Comm c = commMapper.selectByPrimaryKey(comm.getId());
	   if(null == c) {
		   throw new ServiceException("没有找到该项目");
	   }
	  
	   TbSysUser sysUser = userService.getCurrentSysUser();
	   ProjectClass pc = new ProjectClass();
   	pc.setCode(ProjectClass.CODE_CLASSBYO);
   	pc = projectClassMapper.selectOne(pc);
   	
   	ProjectPlanOne pp = new ProjectPlanOne();
   	pp.setCode(ProjectPlanOne.CODE_PRICE);
   	pp = projectPlanOneMapper.selectOne(pp);
	   operationHistoryService.operation(
               c.getId(),
               pp.getName(),
               sysUser.getUserName() + "变更业务进度",
               "",
               sysUser.getUserCode()
       );
	   c.setUpperProjectPlanCode(c.getProjectPlanCode());
	   c.setProjectPlanCode(pp.getCode());
	   c.setMessageFee(comm.getMessageFee());
	   c.setPropertyFee(comm.getPropertyFee());
	   c.setGmtModified(new Date());
	   commService.boostJudge(c);
	   commMapper.updateByPrimaryKey(c);
	   return 1;
   }
   /**
    * 决策层合作意见
    * @param comm
    * @return
    */
   @ResponseBody
   @RequestMapping(value = "/next/decision",produces = "application/json;charset=utf-8", method = RequestMethod.POST)
   public Object decision(Comm comm) {
	   if(comm.getId()  == null) {
		   throw new ServiceException("请选择项目");
	   }
	   Comm c = commMapper.selectByPrimaryKey(comm.getId());
	   if(null == c) {
		   throw new ServiceException("没有找到该项目");
	   }
//	   if(!c.getProjectClassCode().equals(ProjectClass.CODE_CLASSBYO)
//			   || !c.getProjectClassCode().equals(ProjectClass.CODE_CLASSBYC)) {
//		   throw new ServiceException("当前节点不能继续推进");
//	   }
	   TbSysUser sysUser = userService.getCurrentSysUser();
	   ProjectClass pc = new ProjectClass();
   	pc.setCode(ProjectClass.CODE_CLASSBYO);
   	pc = projectClassMapper.selectOne(pc);
   	
   	ProjectPlanOne pp = new ProjectPlanOne();
   	pp.setCode(ProjectPlanOne.CODE_OWNER);
   	pp = projectPlanOneMapper.selectOne(pp);
	   operationHistoryService.operation(
               c.getId(),
               pp.getName(),
               sysUser.getUserName() + "变更业务进度",
               "",
               sysUser.getUserCode()
       );
	   c.setUpperProjectPlanCode(c.getProjectPlanCode());
	   c.setProjectPlanCode(pp.getCode());
	   c.setIsSubmit(comm.getIsSubmit());
	   c.setCompetitor(comm.getCompetitor());
	   c.setOpinion(comm.getOpinion());
	   c.setGmtModified(new Date());
	   commService.boostJudge(c);
	   commMapper.updateByPrimaryKey(c);
	   return 1;
   }
   /**
    * 合规性操盘
    * @param comm
    * @return
    */
   @ResponseBody
   @RequestMapping(value = "/next/trader",produces = "application/json;charset=utf-8", method = RequestMethod.POST)
   public Object trader(Comm comm) {
	   if(comm.getId()  == null) {
		   throw new ServiceException("请选择项目");
	   }
	   Comm c = commMapper.selectByPrimaryKey(comm.getId());
	   if(null == c) {
		   throw new ServiceException("没有找到该项目");
	   }
//	   if( !c.getProjectClassCode().equals(ProjectClass.CODE_CLASSBYA)) {
//		   throw new ServiceException("当前节点不能继续推进");
//	   }
//	 
	   TbSysUser sysUser = userService.getCurrentSysUser();
	   ProjectClass pc = new ProjectClass();
   	pc.setCode(ProjectClass.CODE_CLASSBYO);
   	pc = projectClassMapper.selectOne(pc);
   	
   	ProjectPlanOne pp = new ProjectPlanOne();
   	pp.setCode(ProjectPlanOne.CODE_SIGN);
   	pp = projectPlanOneMapper.selectOne(pp);
	   operationHistoryService.operation(
               c.getId(),
               pp.getName(),
               sysUser.getUserName() + "变更业务进度",
               "",
               sysUser.getUserCode()
       );
	   c.setUpperProjectPlanCode(c.getProjectPlanCode());
	   c.setProjectPlanCode(pp.getCode());
	   c.setCallFile(comm.getCallFile());
	   c.setCallEnvironmen(comm.getCallEnvironmen());
	   c.setCallOrganization(comm.getCallOrganization());
	   c.setGmtModified(new Date());
	   commService.boostJudge(c);
	   commMapper.updateByPrimaryKey(c);
	   return 1;
   }
   /**
    * 获取单个
    * @param comm
    * @return
    */
   @ResponseBody
   @RequestMapping(value = "/selectOneById/{id}",produces = "application/json;charset=utf-8", method = RequestMethod.GET)
   public Object selectOneById(@PathVariable Integer id) {
	   Comm c = commMapper.selectByPrimaryKey(id);
	   
	   
	   if(c == null) {
		   throw new ServiceException("项目不存在");
	   }
	   Integer stage = -1;
	   String projectPlanCode = c.getProjectPlanCode();
	   switch (projectPlanCode) {
       case ProjectPlanOne.CODE_PROJECTINFO:
    	   stage = 0;
           break;
       case ProjectPlanOne.CODE_PROJECTKEY:
    	   stage = 1;
           break;
       case ProjectPlanOne.CODE_COOPERATION:
    	   stage = 2;
           break;
       case ProjectPlanOne.CODE_PRICE:
    	   stage = 3;
           break;
       case ProjectPlanOne.CODE_OWNER:
    	   stage = 4;
           break;
       case ProjectPlanOne.CODE_SIGN:
    	   stage = 5;
           break;
       default:
    	   stage = 0;
           break;
       }
   
	   c.setStage(stage); 
	   return Response.response(c);
   }
   /**
    * 周报提醒
    * @param request
    * @param response
    * @return
    */
   @ResponseBody
   @RequestMapping(value = "/remind",produces = "application/json;charset=utf-8", method = RequestMethod.GET)
   public Object remind(HttpServletRequest request, HttpServletResponse response) {
	   String accessToken = request.getParameter("AccessToken");
       AccessToken token = accessTokenService.findByToken(accessToken);
       String userCode = token.getUserCode();
       Comm c = new Comm();
       c.setContractorCode(userCode);
       c.setGeneralType(Comm.COMM_TYPE_ONE);
       List<Comm> commList = commMapper.select(c);
       Date now = new Date();
       Calendar calendar = Calendar.getInstance(); 
       calendar.setTime(now); 
       List<Map<String,String>> msgList = new ArrayList<>();
       for (Comm comm : commList) {
    	   if(!comm.getProjectPlanCode().equals(ProjectPlanOne.CODE_OVER) 
    			   && !comm.getProjectClassCode().equals(ProjectClass.CODE_CLASSBYY)) {
    		   CommReportWeekly crw = new CommReportWeekly();
    		   crw.setYear(2018);
    		   crw.setWoy(calendar.get(Calendar.WEEK_OF_YEAR));
    		   crw.setCommId(comm.getId());
    		   crw = commReportWeeklyMapper.selectOne(crw);
    		   if(null == crw) {
    			   Map<String,String> map = new HashMap<String,String>();
    			   map.put("msg", "友情提示：您本周有项目"+comm.getName()+"项目周报未填写");
    			   msgList.add(map);
    		   }
    	   }
       }
       return Response.response(msgList);
		 
   }
   /**
    * 内部进度审核
    * @param id
    * @param request
    * @param response
    * @return
    */
   @ResponseBody
   @RequestMapping(value = "/nextClass/{id}",produces = "application/json;charset=utf-8", method = RequestMethod.POST)
   public Object nextClass(@PathVariable Integer id,HttpServletRequest request, HttpServletResponse response) {
	   String accessToken = request.getParameter("AccessToken");
	   String remark =  request.getParameter("remark");
       AccessToken token = accessTokenService.findByToken(accessToken);
       String userCode = token.getUserCode();
       Comm c = commMapper.selectByPrimaryKey(id);
       if(null == c) {
    	   throw new ServiceException("项目不存在");
       }
      String uup = c.getUpperProjectPlanCode();
       //查询项目时间配置 组装时间配置 优先级 项目==》公共==》默认
       CommInfoVO ci = new CommInfoVO();
       ci.setCommId(c.getId().toString());
       List<CommInfoVO> select = commInFoMapper.select(ci);
       IndicatorLight findLight = commService.findLight();
       //组装项目过期时间
       Map<String, CommInfoVO> colourDay = CommUtil.colourDay(select,findLight);
	   //当前节点时间
	   Date endDateStr = c.getThisStage();
	   //下一节点时间
	   Date beginDateStr = new Date();
	   CommRecord cr = null; 
	   //计算 下一节点时间 - 下一节点时间 天数
	   long daySub2 = CommUtil.getDaySub(beginDateStr, endDateStr);
	   Date thisStage = c.getThisStage();
	   //如果是 关键人接触 第二阶段 O》D 如果是D跳过 
        if(c.getProjectPlanCode().equals(ProjectPlanOne.CODE_PROJECTKEY)) {
    	   if(!c.getProjectClassCode().equals(ProjectClass.CODE_CLASSBYD)) {
    		   c.setThisStage(new Date());
    		   //组装 存储灯 O跳D不存储灯
    		 //  cr = CommUtil.assembleCommRecord(ProjectClass.CODE_CLASSBYD,c,colourDay,daySub2);
    		   c.setWarningLight(Comm.WARNINGLIGHT_PT);
    	   }
    	   c.setProjectClassCode(ProjectClass.CODE_CLASSBYD);
    	  
    	//如果是 合作意向确认 第三阶段 O》C D》C 如果是C跳过 
       }else if(c.getProjectPlanCode().equals(ProjectPlanOne.CODE_COOPERATION)) {
    	   if(!c.getProjectClassCode().equals(ProjectClass.CODE_CLASSBYC)) {
    		   //组织存储灯 O跳C D绿，D跳C D需要计算时间判断灯类型 
    		  
    		   cr = CommUtil.assembleCommRecord(ProjectClass.CODE_CLASSBYC,c,colourDay,daySub2,thisStage);
    		   c.setThisStage(new Date());
    		   c.setWarningLight(Comm.WARNINGLIGHT_PT);
    	   }
    	   c.setProjectClassCode(ProjectClass.CODE_CLASSBYC);
    	   
    	 //如果是 合作意向确认 第四阶段 O》D  O》C  O》B C》B 如果是B跳过    
       }else if(c.getProjectPlanCode().equals(ProjectPlanOne.CODE_PRICE)) {
    	   //如果不是C类 剩下o，b  O C B 如果是c类就跳b
    	   if(!c.getProjectClassCode().equals(ProjectClass.CODE_CLASSBYC)) {
    		   
    		   c.setThisStage(new Date());
    		   c.setWarningLight(Comm.WARNINGLIGHT_PT);
    		   if(c.getProjectClassCode().equals(ProjectClass.CODE_CLASSBYB)) {
    			  // cr = CommUtil.assembleCommRecord(ProjectClass.CODE_CLASSBYB,c,colourDay,daySub2);
    			   c.setProjectClassCode(ProjectClass.CODE_CLASSBYB);
    		   }else {
    			   cr = CommUtil.assembleCommRecord(ProjectClass.CODE_CLASSBYC,c,colourDay,daySub2,thisStage);
    			   c.setProjectClassCode(ProjectClass.CODE_CLASSBYC);
    		   }
    		  
    	   }else {
    		   c.setThisStage(new Date());
    		   c.setWarningLight(Comm.WARNINGLIGHT_PT);
    		   cr = CommUtil.assembleCommRecord(ProjectClass.CODE_CLASSBYB,c,colourDay,daySub2,thisStage);
    		   c.setProjectClassCode(ProjectClass.CODE_CLASSBYB);
    	   }
    	   
    	  
    	 //如果是 决策层合作确认 第五阶段 O》D  O》C  O》B C》B 如果是B跳过    
       }else if(c.getProjectPlanCode().equals(ProjectPlanOne.CODE_OWNER)) {
    	   if(c.getProjectClassCode().equals(ProjectClass.CODE_CLASSBYA)){
    		   cr = CommUtil.assembleCommRecord(ProjectClass.CODE_CLASSBYY,c,colourDay,daySub2,thisStage);    		   
    		   c.setThisStage(new Date());
    		   c.setWarningLight(Comm.WARNINGLIGHT_PT);
    		   c.setProjectClassCode(ProjectClass.CODE_CLASSBYY);
    	   }else
    	   if(c.getProjectClassCode().equals(ProjectClass.CODE_CLASSBYO)) {
    		   cr = CommUtil.assembleCommRecord(ProjectClass.CODE_CLASSBYB,c,colourDay,daySub2,thisStage);
    		   c.setThisStage(new Date());
    		   c.setWarningLight(Comm.WARNINGLIGHT_PT);
    		   c.setProjectClassCode(ProjectClass.CODE_CLASSBYB);
    	   }else if(c.getProjectClassCode().equals(ProjectClass.CODE_CLASSBYB)||c.getProjectClassCode().equals(ProjectClass.CODE_CLASSBYA)){
    		   cr = CommUtil.assembleCommRecord(ProjectClass.CODE_CLASSBYA,c,colourDay,daySub2,thisStage);
    		   c.setThisStage(new Date());
    		   c.setWarningLight(Comm.WARNINGLIGHT_PT);
    		   c.setProjectClassCode(ProjectClass.CODE_CLASSBYA);
    	   }else if(c.getProjectClassCode().equals(ProjectClass.CODE_CLASSBYC)){
    		   cr = CommUtil.assembleCommRecord(ProjectClass.CODE_CLASSBYB,c,colourDay,daySub2,thisStage);
    		   c.setThisStage(new Date());
    		   c.setWarningLight(Comm.WARNINGLIGHT_PT);
    		   c.setProjectClassCode(ProjectClass.CODE_CLASSBYB);

    	   }else {
    		   cr = CommUtil.assembleCommRecord(ProjectClass.CODE_CLASSBYB,c,colourDay,daySub2,thisStage);
    		   c.setThisStage(new Date());
    		   c.setWarningLight(Comm.WARNINGLIGHT_PT);
    		   c.setProjectClassCode(ProjectClass.CODE_CLASSBYB);
    	   }  
    	   //如果是 等待中止
       }else if(c.getProjectPlanCode().equals(ProjectPlanOne.CODE_CHECKSTOP)) {
    	//   c.setProjectClassCode(ProjectClass.CODE_CLASSBYY);
    	  // c.setUpperProjectPlanCode(uup);
    	   c.setProjectPlanCode(ProjectPlanOne.CODE_OVER);
    	   c.setWarningLight(Comm.WARNINGLIGHT_PT);
       }else if(c.getProjectPlanCode().equals(ProjectPlanOne.CODE_CHECKRESTART)) {
    	   c.setProjectPlanCode(uup==null ? ProjectPlanOne.CODE_PROJECTINFO:uup);
    	   c.setThisStage(new Date());
    	   //c.setUpperProjectPlanCode(null);
    	   CommRecord crc = new CommRecord();
           crc.setCommId(c.getId().toString());
           CommRecord select2 = commRecordService.selectOne(crc);
    	   cr = select2;
    	  // c.setProjectPlanCode(ProjectPlanOne.CODE_PROJECTKEY);
    	   c.setWarningLight(Comm.WARNINGLIGHT_PT);
       }else if(c.getProjectPlanCode().equals(ProjectPlanOne.CODE_SIGN)) {
    	   c.setThisStage(new Date());
    	   cr = CommUtil.assembleCommRecord(ProjectClass.CODE_CLASSBYY,c,colourDay,daySub2,thisStage);
    	   //c.setUpperProjectPlanCode(uup);
    	  // c.setProjectPlanCode(ProjectPlanOne.CODE_OVER);
    	   c.setProjectClassCode(ProjectClass.CODE_CLASSBYY);
    	   c.setWarningLight(Comm.WARNINGLIGHT_PT);
       }
       else {
    	   throw new ServiceException("业务节点有误");
       }
       c.setWarningLight(Comm.WARNINGLIGHT_PT);
       c.setGmtModified(new Date());
       commMapper.updateByPrimaryKey(c);
       CommRecord crc = new CommRecord();
       crc.setCommId(c.getId().toString());
       CommRecord select2 = commRecordService.selectOne(crc);
      
       if(select2==null&&cr!=null) {
    	   cr.setCommId(c.getId().toString());
    	   commRecordService.insert(cr);
       }else if(cr!=null) {
    	   if(select2.getClassA()!=null) {
    		   cr.setClassA(select2.getClassA());
    		   cr.setaDate(select2.getaDate());
    	   }
    	   if(select2.getClassB()!=null) {
    		   cr.setClassB(select2.getClassB());
    		   cr.setbDate(select2.getbDate());
    	   }
    	   if(select2.getClassC()!=null) {
    		   cr.setClassC(select2.getClassC());
    		   cr.setcDate(select2.getcDate());
    	   }
    	   if(select2.getClassD()!=null) {
    		   cr.setdDate(select2.getdDate());
    		   cr.setClassD(select2.getClassD());
    	   }
    	   
    	   cr.setId(select2.getId());
    	   cr.setCommId(c.getId().toString());
    	   commRecordService.updateByPrimaryKey(cr);
       }
       return Response.response(1);
   }
   
   @ResponseBody
   @RequestMapping(value = "/nextClassByHQ/{id}",produces = "application/json;charset=utf-8", method = RequestMethod.POST)
   public Object nextClassByHQ(@PathVariable Integer id,HttpServletRequest request, HttpServletResponse response) {
	   String accessToken = request.getParameter("AccessToken");
       AccessToken token = accessTokenService.findByToken(accessToken);
       String remark =  request.getParameter("remark");
       String userCode = token.getUserCode();
       Comm c = commMapper.selectByPrimaryKey(id);
       if(null == c) {
    	   throw new ServiceException("项目不存在");
       }
       if(c.getProjectPlanCode().equals(ProjectPlanOne.CODE_PROJECTKEY)) {
    	   if(!c.getProjectClassCode().equals(ProjectClass.CODE_CLASSBYD)) {
    		   c.setThisStage(new Date());
    		   c.setWarningLight(Comm.WARNINGLIGHT_PT);
    	   }
    	   c.setProjectClassCode(ProjectClass.CODE_CLASSBYD);
    	  
    	
       }else if(c.getProjectPlanCode().equals(ProjectPlanOne.CODE_COOPERATION)) {
    	   if(!c.getProjectClassCode().equals(ProjectClass.CODE_CLASSBYC)) {
    		   c.setThisStage(new Date());
    		   c.setWarningLight(Comm.WARNINGLIGHT_PT);
    	   }
    	   c.setProjectClassCode(ProjectClass.CODE_CLASSBYC);
    	   
    	   
       }else if(c.getProjectPlanCode().equals(ProjectPlanOne.CODE_PRICE)) {
    	   if(!c.getProjectClassCode().equals(ProjectClass.CODE_CLASSBYC)) {
    		   c.setThisStage(new Date());
    		   c.setWarningLight(Comm.WARNINGLIGHT_PT);
    		   if(c.getProjectClassCode().equals(ProjectClass.CODE_CLASSBYB)) {
    			   c.setProjectClassCode(ProjectClass.CODE_CLASSBYB);
    		   }else {
    			   c.setProjectClassCode(ProjectClass.CODE_CLASSBYC);
    		   }
    		  
    	   }else {
    		   c.setProjectClassCode(ProjectClass.CODE_CLASSBYB);
    	   }
    	   
    	  
    	 
       }else if(c.getProjectPlanCode().equals(ProjectPlanOne.CODE_OWNER)) {
    	   if(c.getProjectClassCode().equals(ProjectClass.CODE_CLASSBYA)){
    		   c.setThisStage(new Date());
    		   c.setWarningLight(Comm.WARNINGLIGHT_PT);
    		   c.setProjectClassCode(ProjectClass.CODE_CLASSBYY);
    	   }else
    	   if(c.getProjectClassCode().equals(ProjectClass.CODE_CLASSBYO)) {
    		   c.setThisStage(new Date());
    		   c.setWarningLight(Comm.WARNINGLIGHT_PT);
    		   c.setProjectClassCode(ProjectClass.CODE_CLASSBYB);
    	   }else if(c.getProjectClassCode().equals(ProjectClass.CODE_CLASSBYB)||c.getProjectClassCode().equals(ProjectClass.CODE_CLASSBYA)){
    		   c.setThisStage(new Date());
    		   c.setWarningLight(Comm.WARNINGLIGHT_PT);
    		   c.setProjectClassCode(ProjectClass.CODE_CLASSBYA);
    	   }else if(c.getProjectClassCode().equals(ProjectClass.CODE_CLASSBYC)){
    		   c.setThisStage(new Date());
    		   c.setWarningLight(Comm.WARNINGLIGHT_PT);
    		   c.setProjectClassCode(ProjectClass.CODE_CLASSBYB);

    	   }else{
    		   c.setThisStage(new Date());
    		   c.setWarningLight(Comm.WARNINGLIGHT_PT);
    		   c.setProjectClassCode(ProjectClass.CODE_CLASSBYB);
    	   }
    	  
    	   
       }else if(c.getProjectPlanCode().equals(ProjectPlanOne.CODE_CHECKSTOP)) {
    	//   c.setProjectClassCode(ProjectClass.CODE_CLASSBYY);
    	   c.setProjectPlanCode(ProjectPlanOne.CODE_OVER);
    	   c.setWarningLight(Comm.WARNINGLIGHT_PT);
       }else if(c.getProjectPlanCode().equals(ProjectPlanOne.CODE_CHECKRESTART)) {
    	   c.setProjectClassCode(ProjectClass.CODE_CLASSBYD);
    	   c.setProjectPlanCode(ProjectPlanOne.CODE_PROJECTKEY);
    	   c.setWarningLight(Comm.WARNINGLIGHT_PT);
       }else if(c.getProjectPlanCode().equals(ProjectPlanOne.CODE_SIGN)) {
    	   if(!c.getProjectClassCode().equals(ProjectClass.CODE_CLASSBYY)) {
    		   c.setThisStage(null);
    	   }
    	   c.setProjectPlanCode(ProjectPlanOne.CODE_OVER);
    	   c.setProjectClassCode(ProjectClass.CODE_CLASSBYY);
    	   c.setWarningLight(Comm.WARNINGLIGHT_PT);
       }
       c.setWarningLight(Comm.WARNINGLIGHT_PT);
       c.setGmtModified(new Date());
       commMapper.updateByPrimaryKey(c);
       return Response.response(1);
   }   
   /**
    * 判断调准节点
    * @param request
    * @param response
    * @return
    */
   @ResponseBody
   @RequestMapping(value = "/judgeJump/{id}",produces = "application/json;charset=utf-8", method = RequestMethod.GET)
   public Object judgeJump(@PathVariable Integer id,HttpServletRequest request, HttpServletResponse response) {
	   Comm c = commMapper.selectByPrimaryKey(id);
	   
	   Map<String,String> map = new HashMap<>();
	   ProjectClass pc = new ProjectClass();
	   pc.setCode(c.getProjectClassCode());
	   pc = projectClassMapper.selectOne(pc);
	   map.put("str", pc.getName());
	   
	   String code = "";
	   if(null == c) {
    	   throw new ServiceException("项目不存在");
       }
	   if(c.getProjectPlanCode().equals(ProjectPlanOne.CODE_CHECKRESTART)) {
           code = c.getProjectClassCode();
           map.put("msg",  c.getReReason());
       }else if(c.getProjectPlanCode().equals(ProjectPlanOne.CODE_CHECKSTOP)) {
           code = "cq";
           map.put("msg",  c.getStopReason());
       }else if(c.getProjectPlanCode().equals(ProjectPlanOne.CODE_PROJECTKEY)) {
            code = ProjectClass.CODE_CLASSBYD;


        }else if(c.getProjectPlanCode().equals(ProjectPlanOne.CODE_COOPERATION)) {
            code = ProjectClass.CODE_CLASSBYC;


        }else if(c.getProjectPlanCode().equals(ProjectPlanOne.CODE_PRICE)) {
            if(pc.getCode().equals(ProjectClass.CODE_CLASSBYC)){
                code = ProjectClass.CODE_CLASSBYB;
            }else {
                if(c.getProjectClassCode().equals(ProjectClass.CODE_CLASSBYB)) {
                    code = ProjectClass.CODE_CLASSBYB;
                }else {
                    code = ProjectClass.CODE_CLASSBYC;
                }


            }
            // code = ProjectClass.CODE_CLASSBYC;

        }else if(c.getProjectPlanCode().equals(ProjectPlanOne.CODE_OWNER)) {
            if(pc.getCode().equals(ProjectClass.CODE_CLASSBYO)) {
                code = ProjectClass.CODE_CLASSBYB;
            }else if(pc.getCode().equals(ProjectClass.CODE_CLASSBYB) ){
                code = ProjectClass.CODE_CLASSBYA;
            }else if(pc.getCode().equals(ProjectClass.CODE_CLASSBYA)){
                code = ProjectClass.CODE_CLASSBYY;
            }else if(c.getProjectClassCode().equals(ProjectClass.CODE_CLASSBYC)){
                code = ProjectClass.CODE_CLASSBYB;
            }else{
                code = pc.getCode();
            }



        }else if(c.getProjectPlanCode().equals(ProjectPlanOne.CODE_SIGN)) {

            code = ProjectClass.CODE_CLASSBYY;


        }
        else {
            throw new ServiceException("业务节点有误");
        }
        if(code.equals("cq")) {
            map.put("end",  "中止");
        }else {
            ProjectClass pce = new ProjectClass();
            pce.setCode(code);
            pce = projectClassMapper.selectOne(pce);
            map.put("end",  pce.getName());
        }
        if(map.get("str").equals(map.get("end"))) {
            map.put("isTrue", "false");
        }else {
            map.put("isTrue", "true");
        }
        if(c.getProjectPlanCode().equals(ProjectPlanOne.CODE_CHECKRESTART)) {
        	map.put("isTrue", "true");
        }
        return Response.response(map);
    }
    /**
     * 判断调准节点
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/judgeJumpByHQ/{id}",produces = "application/json;charset=utf-8", method = RequestMethod.GET)
    public Object judgeJumpByHQ(@PathVariable Integer id,HttpServletRequest request, HttpServletResponse response) {
        Comm c = commMapper.selectByPrimaryKey(id);

        Map<String,String> map = new HashMap<>();
        ProjectClass pc = new ProjectClass();
        pc.setCode(c.getProjectClassCode());
        pc = projectClassMapper.selectOne(pc);
        map.put("str", pc.getName());

        String code = "";
        if(null == c) {
            throw new ServiceException("项目不存在");
        }
        if(c.getProjectPlanCode().equals(ProjectPlanOne.CODE_PROJECTKEY)) {
            code = ProjectClass.CODE_CLASSBYD;


        }else if(c.getProjectPlanCode().equals(ProjectPlanOne.CODE_COOPERATION)) {
            code = ProjectClass.CODE_CLASSBYC;


        }else if(c.getProjectPlanCode().equals(ProjectPlanOne.CODE_PRICE)) {

            if(pc.getCode().equals(ProjectClass.CODE_CLASSBYC)){
                code = ProjectClass.CODE_CLASSBYB;
            }else {
                if(c.getProjectClassCode().equals(ProjectClass.CODE_CLASSBYB)) {
                    code = ProjectClass.CODE_CLASSBYB;
                }else {
                    code = ProjectClass.CODE_CLASSBYC;
                }


            }

        }else if(c.getProjectPlanCode().equals(ProjectPlanOne.CODE_OWNER)) {
            if(pc.getCode().equals(ProjectClass.CODE_CLASSBYO)) {
                code = ProjectClass.CODE_CLASSBYB;
            }else if(pc.getCode().equals(ProjectClass.CODE_CLASSBYB) ){
                code = ProjectClass.CODE_CLASSBYA;
            }else if(pc.getCode().equals(ProjectClass.CODE_CLASSBYA)){
                code = ProjectClass.CODE_CLASSBYY;
            }else if(c.getProjectClassCode().equals(ProjectClass.CODE_CLASSBYC)){
                code = ProjectClass.CODE_CLASSBYB;
            }else{
                code = pc.getCode();
            }



        }else if(c.getProjectPlanCode().equals(ProjectPlanOne.CODE_SIGN)) {

            code = ProjectClass.CODE_CLASSBYY;


        }else if(c.getProjectPlanCode().equals(ProjectPlanOne.CODE_CHECKRESTART)) {
            code = ProjectClass.CODE_CLASSBYD;
            map.put("msg",  c.getReReason());
        }else if(c.getProjectPlanCode().equals(ProjectPlanOne.CODE_CHECKSTOP)) {
            code = "cq";
            map.put("msg",  c.getStopReason());
        }
        else {
            throw new ServiceException("业务节点有误");
        }
        if(code.equals("cq")) {
            map.put("end",  "中止");
        }else {
            ProjectClass pce = new ProjectClass();
            pce.setCode(code);
            pce = projectClassMapper.selectOne(pce);
            map.put("end",  pce.getName());
        }

        if(map.get("str").equals(map.get("end"))) {
            map.put("isTrue", "false");
        }else {
            map.put("isTrue", "true");
        }
        return Response.response(map);
    }
    @ResponseBody
    @RequestMapping(value = "/stop",produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    public Object stopProject(Comm comm,HttpServletRequest request) {
    	String accessToken = request.getParameter("AccessToken");
    	 AccessToken token = accessTokenService.findByToken(accessToken);
         String userCode = token.getUserCode();
        Comm c = commMapper.selectByPrimaryKey(comm.getId());
        if(null == c) {
            throw new ServiceException("找不到该项目");
        }
        c.setModifiedBy(userCode);
        c.setUpperProjectPlanCode(c.getProjectPlanCode());
        c.setProjectPlanCode(ProjectPlanOne.CODE_CHECKSTOP);
        c.setStopReason(comm.getStopReason());
        commMapper.updateByPrimaryKey(c);
        return Response.response(1);
    }
    @ResponseBody
    @RequestMapping(value = "/reStar",produces = "application/json;charset=utf-8", method = RequestMethod.POST)
    public Object reStarProject(Comm comm) {
        Comm c = commMapper.selectByPrimaryKey(comm.getId());
        if(null == c) {
            throw new ServiceException("找不到该项目");
        }
        if(!c.getProjectPlanCode().equals(ProjectPlanOne.CODE_OVER)) {
            throw new ServiceException("该项目尚未结束");
        }
        c.setProjectPlanCode(ProjectPlanOne.CODE_CHECKRESTART);
        c.setReReason(comm.getReReason());
        commMapper.updateByPrimaryKey(c);

        return Response.response(1);
    }

    /**
     * 导出
     * @throws ParseException
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/exportByOne", produces = "multipart/form-data",  method = RequestMethod.GET)
    public void exportByOne(Comm comm, HttpServletRequest request, HttpServletResponse response) throws ParseException {
//		 if(!StringUtil.isEmpty(siteResources.getAddDates())) {
//			 siteResources.setAddDate(StringChangeDate(siteResources.getAddDates()));
//			 }
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet();

        String accessToken = request.getParameter("AccessToken");
        AccessToken token = accessTokenService.findByToken(accessToken);
        String userCode = token.getUserCode();
        List<Role> rList=  roleMapper.findByUserCode(userCode);
        for (Role role : rList) {
            if(role.getCode().equals("marketing_manager")) {
                userCode = null;
                break;
            }
        }
        comm.setContractorCode(userCode);
        if(comm.getProjectClassCode().equals("classByAll")) {
            comm.setProjectClassCode(null);
        }
        List<OneProject> pList = commMapper.selectByOne(comm);

        projectImports.createHeader(workbook,sheet);//创建表头
        projectImports.createBody(pList,workbook,sheet);
        response.setContentType("multipart/form-data");
        String fileName = "export.xlsx";
        try {
            fileName = URLEncoder.encode("单一项目.xlsx","UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setHeader("Content-Disposition", "attachment;fileName="+fileName);

        OutputStream outputStream =null;
        try{
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
        } catch (Exception ex){

        } finally {
            try{
                workbook.close();
            } catch (Exception ex){

            }
        }
    }
    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;
    }

    @ResponseBody
    @RequestMapping(value = "/delete/{id}", produces = "application/json;charset=utf-8", method = RequestMethod.GET)
    public Object delete(@PathVariable Integer id) {
        commMapper.deleteByPrimaryKey(id);
        return Response.response(1);
    }
    
	 @ResponseBody
	 @GetMapping("findlist")
	 public Object findlist(@RequestParam(value = "name", required = true) String name) {
		 List<String> getlist = commMapper.getlist(name);
		 return Response.response(getlist);
	 }
	 @ResponseBody
	 @GetMapping("sql")
	 public Object sql(String sdate,String edate) {
		 try {
				
				
				//	TbDupContractTimedEmergency time = biEmergencyService.findDateStart();
					Object[] args = new Object[2];
				//	args[0] = sdate;
				//	args[1] = edate;
					//args[0] = time.getStartDate();
					//args[1] = time.getEndDate();
					String a = AxisUtils.callService(url, metod, args);
					System.out.println(a);
					Gson g = new Gson();
					cn.com.countrygarden.bi.main.service.project.impl.vo.outburst.Result r = g.fromJson(a, cn.com.countrygarden.bi.main.service.project.impl.vo.outburst.Result.class);
					
				//	biEmergencyMapper.delete(null);
				//	biApplnoteMapper.delete(null);
					biEmergencyService.json2Date(r.data);
				 //dupCommService.synchronizationOrg();
				 } catch (Exception e) {
					 e.printStackTrace();
				}
		 return "成功";
	 }
	 
	 @ResponseBody
	 @GetMapping("updateCommUser")
	 public Object updateCommUser(@RequestParam(value = "name", required = true) String name,
			 @RequestParam(value = "code", required = true) String code,
			 @RequestParam(value = "id", required = true) String id){
		 List<Map<String, String>> findOrganByUserCode = tbHsprContractMapper.findOrganByUserCode(code);
		 Map<String,String> map = new HashMap<>();
		 map.put("id", id);
		 if(findOrganByUserCode.size()>0) {
		 map.put("organCode", findOrganByUserCode.get(0).get("OrganCode"));
		 map.put("organName", findOrganByUserCode.get(0).get("organName"));
		 }
		 map.put("userName", name);
		 map.put("userCode", code);
		 int updateCommUser = commMapper.updateCommUser(map);
		 return Response.response(updateCommUser);
	 }
	 
	 @ResponseBody
	 @GetMapping("getCommUser")
	 public Object getCommUser() {
		 List<String> userCode = commMapper.getUserCode();
		 List<Map<String, String>> commUser = tbHsprContractMapper.getCommUser(userCode);
		 return Response.response(commUser);		 
	 }
	 
}
