package com.sifang.modules.smallprogram;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.alioss.AliyunOSSClientUtil;
import com.sifang.modules.config.DLock;
import com.sifang.modules.config.SfCacheService;
import com.sifang.modules.customer.Service.*;
import com.sifang.modules.customer.constant.CustomerEntryConstants;
import com.sifang.modules.customer.constant.Nationals;
import com.sifang.modules.customer.constant.PartnerConstants;
import com.sifang.modules.customer.constant.SourceConstants;
import com.sifang.modules.customer.dao.*;
import com.sifang.modules.customer.entity.*;
import com.sifang.modules.customer.form.*;
import com.sifang.modules.customer.utils.EmployeRoleUtils;
import com.sifang.modules.customer.utils.HmacUtil;
import com.sifang.modules.insurance.dao.InsuranceListDao;
import com.sifang.modules.monitor.service.MonitorCollectDataService;
import com.sifang.modules.platform.utils.AddressUtils;
import com.sifang.modules.platform.utils.Base64Url;
import com.sifang.modules.platform.utils.QRCodeUtil;
import com.sifang.modules.setting.service.MemberService;
import com.sifang.modules.sunshine.SystemSetting.dao.ProjectCompanyDao;
import com.sifang.modules.sunshine.SystemSetting.dao.ProjectPcdDao;
import com.sifang.modules.sunshine.SystemSetting.dao.ProjectSettingDao;
import com.sifang.modules.sunshine.SystemSetting.dao.TraderPcdDao;
import com.sifang.modules.sunshine.SystemSetting.entity.*;
import com.sifang.modules.sunshine.SystemSetting.form.FormSetPageVo;
import com.sifang.modules.sunshine.SystemSetting.form.ProjectTypeDetailVo;
import com.sifang.modules.sunshine.SystemSetting.service.*;
import com.sifang.modules.sunshine.SystemSetting.utils.BusinessException;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sunshine.SystemSetting.vo.CrmCustomerEntryComponentVo;
import com.sifang.modules.sunshine.SystemSetting.vo.CrmPlanMaterialEntryVo;
import com.sifang.modules.sunshine.SystemSetting.vo.ProjectSettingVo;
import com.sifang.modules.sunshine.partnerManagement.entity.CrmPartner;
import com.sifang.modules.sunshine.partnerManagement.service.PartnerService;
import com.sifang.modules.supply.stock.utils.MaterialUtils;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.common.utils.DateUtils;
import com.sifang.modules.sys.common.utils.IdGen;
import com.sifang.modules.sys.dao.SysCapitalDictDao;
import com.sifang.modules.sys.dao.UserDao;
import com.sifang.modules.sys.entity.Operator;
import com.sifang.modules.sys.service.WindSnowPressureLevelService;
import com.sifang.modules.sys.util.AuthUtils;
import com.sifang.modules.sys.util.CrmUtils;
import com.sifang.modules.sys.util.GuardUtils;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.sys.web.BaseExceptionController;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * 项目管理小程序端接口
 *
 * @author hongzq
 */
@Controller
@RequestMapping(value = "${adminPath}/main/projectManage")
public class ProjectManageController extends BaseExceptionController {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    CustomerEntryService customerEntryService;
    @Autowired
    OperatingLeaseService operatingLeaseService;
    @Autowired
    CustomerEntryMsgService customerEntryMsgService;
    @Autowired
    ProjectInfoSettingService projectService;
    @Autowired
    TraderService traderService;
    @Autowired
    PlanService planService;
    @Autowired
    MemberService memberService;
    @Autowired
    ProjectInstallService projectInstallService;
    @Autowired
    UserDao userDao;

    @Autowired
    private JedisPool jedisPool;

    @Autowired
    SfCacheService cacheService;

    @Autowired
    CrmAcceptingReportService acceptingReportService;

    @Autowired
    CustomerEntryExtraService customerEntryExtraService;

    @Autowired
    private CrmCustomerIncomingApplicationBasicDao basicDao;

    @Autowired
    private CrmCustomerIncomingApplicationPerInfoDao perInfoDao;

    @Autowired
    private CrmCustomerIncomingApplicationInsuranceDao insuranceDao;


    @Autowired
    private LinkNumberSettingService service;

    @Autowired
    private CrmCustomerIncomingApplicationDao applicationDao;

    @Autowired
    private CrmCustomerIncomingApplicationLeaseItemDao leaseItemDao;

    @Autowired
    private TraderEmployeService traderEmployeService;

    @Autowired
    private CustomerEntryComponentService customerEntryComponentService;
    @Autowired
    private RectificationSettingService rectificationSettingService;

    @Autowired
    private SignContractService signContractService;

    @Autowired
    private CustomerEntrySurveyRecordDao surveyRecordDao;

    @Autowired
    private FormSetService formSetService;

    @Autowired
    InsuranceListDao insuranceListDao;

    @Autowired
    private CustomerEntryOrgFilesService orgFilesService;

    @Autowired
    private PartnerService partnerService;

    @Autowired
    private CustomerEntryTenantService tenantService;

    @Autowired
    private MonitorCollectDataService collectDataService;

    @Autowired
    private TenantYxBankCardDao tenantYxBankCardDao;

    @Autowired
    ProjectPcdDao projectPcdDao;
    @Autowired
    ProjectCompanyDao projectCompanyDao;
    @Autowired
    TraderPcdDao traderPcdDao;
    @Autowired
    ProjectInfoSettingService projectInfoSettingService;

    @Autowired
    ProjectSettingDao projectDao;

    @Autowired
    SysCapitalDictDao sysCapitalDictDao;

    @Autowired
    ContractManagementDao contractManagementDao;

    @Autowired
    private CrmEntryCombinerBoxGroupDao combinerBoxGroupDao;

    @Autowired
    private CustomerContractManagementService contractManagementService;

    @Autowired
    private CrmCustomerEntryProjectDao crmCustomerEntryProjectDao;

    @Autowired
    private CrmCustomerEntryDesignDao crmCustomerEntryDesignDao;
    @Autowired
    private CrmCustomerEntrySurveyRecordDetailService recordDetailService;

    @Autowired
    private CrmAcceptingReportDetailDao crmAcceptingReportDetailDao;

    @Autowired
    private WindSnowPressureLevelService windSnowPressureLevelService;
    /**
     * 项目列表
     */
    @ResponseBody
    @RequestMapping("/projectList")
    public Object projectList(String userId, String type, String management, String filingType,
                              String tenantType,String filType,String projectId){
        if (StrKit.isBlank(userId)) {
            throw new BusinessException("userId不能为空");
        }
        String traderId = null;
        User user = userDao.get(userId);
        if ("6".equals(user.getUserType()) || "7".equals(user.getUserType())) {
            Record rd = CrmUtils.getByUserId(user);
            traderId = StringUtil.isNotBlank(rd.getStr("parent_id"))?rd.getStr("parent_id"):rd.getStr("trader_id");
        }
        List<Record> projectList;
        if ("1".equals(type)) {
            projectList = memberService.getBTProject(traderId, management, tenantType,filType, filingType,projectId);
        } else {
            projectList = memberService.getProjectWithOutBT(user,traderId, management,filType, filingType,projectId);
        }
        return JsonKit.toJson(projectList);
    }

    /**
     * 获取代理商安装地址下的授权产品
     */
    @ResponseBody
    @RequestMapping(value = "getProjectByArea")
    public Object getProjectByArea(HttpServletRequest request) {
        Map<String, String> map = getParams(request);
        User user = userDao.get(map.get("userId"));
        String traderId = null;
        if ("6".equals(user.getUserType()) || "7".equals(user.getUserType())) {
            Record rd = CrmUtils.getByUserId(user);
            traderId = StringUtil.isNotBlank(rd.getStr("parent_id"))?rd.getStr("parent_id"):rd.getStr("trader_id");
        }
        map.put("partner", map.get("projectId"));
        map.put("traderId",traderId);
        map.put("type",map.get("filType"));
        map.put("filingType",map.get("filingType"));
        List<Record> projectByArea = new ArrayList<>();
        if (map.get("area") != null && !Objects.equals(map.get("area"), "")){
            if (StringUtil.isNotBlank(map.get("filingType"))) {
                // 勘测阶段 不可更改备案类型
                projectByArea = memberService.getProjectByTraderLists3(traderId, map.get("filingType"), map.get("projectId"),
                        map.get("province") ,map.get("city"),map.get("area"));
            }
            else {
                // 暂存阶段 可以更改备案类型
                projectByArea = projectService.getProjectByArea(map);
            }
        }
        return Result.success(projectByArea);
    }



    /**
     * 安装方式列表
     */
    @ResponseBody
    @RequestMapping("/installWayList")
    public Object installWayList(HttpServletRequest request){
        String projectId = request.getParameter("projectId");
        List<Record> installWayList = null;
        if(StringUtil.isNotBlank(projectId)){
            installWayList = Lists.newArrayList();
            CrmProjectSetting project = projectService.getById(projectId);
            if(StringUtil.isNotBlank(project.getInstallModeId())){
                String modeId[] = project.getInstallModeId().split(",");
                String modeName[] = project.getInstallModeName().split(",");
                for(int i=0;i<modeId.length;i++){
                    Record rd = new Record();
                    rd.set("id",modeId[i]);
                    rd.set("name",modeName[i]);
                    installWayList.add(rd);
                }
            }
        }

        if(installWayList==null){
            installWayList = projectInstallService.findProjectInstalls();
        }
        return JsonKit.toJson(installWayList);
    }


    /**
     * 获取方案列表
     */
    @ResponseBody
    @RequestMapping("/findAllPlan")
    public Object findAllPlan(){
        List<Record> planList = planService.findAllPlan();
        return JsonKit.toJson(planList);
    }



    /**
     * 根据规格获取支架配置方案
     */
    @ResponseBody
    @RequestMapping(value = "findPlanByAssembly")
    public Object findPlanByAssembly(HttpServletRequest request) {

        Map<String, String> map = getParams(request);

        String projectId = map.get("projectId");
        List<Record> list = planService.findPlanByAssembly(projectId,map.get("name"),map.get("planType"));
        if(StringUtil.isNotBlank(projectId) && StringUtil.isBlank(map.get("planType"))){

            CrmProjectSetting project = customerEntryService.findrojectSettingById(projectId);
            String mode_id = project.getInstallModeId();
            List<Record> rds = Lists.newArrayList();

            for(Record rd :list){
                String plan_type_id = rd.getStr("plan_type_id");
                if(StringUtil.isNotBlank(plan_type_id) && mode_id.contains(plan_type_id)){
                    rds.add(rd);
                }
            }
            return rds;
        }

        return list;
    }


    /**
     * 根据代理商id获取资方
     */
    @ResponseBody
    @RequestMapping("getCapital")
    public Result getCapital(AddEntryReq entry){
        logger.info("getCapital entry={}",new Gson().toJson(entry));
        if (StringUtil.isBlank(entry.getTraderId())) {
            List<Map> re = partnerService.getCapital();
            return Result.success(re);
        }
        CrmTrader trader = traderService.getById(entry.getTraderId());
        if (trader == null) {
            return Result.fail("未查询到代理商信息");
        }
        String traderId = "1".equals(trader.getType()) ? trader.getId() : trader.getParentId();
        List<Map> re = customerEntryService.getCapital(traderId);
        return Result.success(re);
    }



    /**
     * 信息录入
     */
    @ResponseBody
    @RequestMapping("saveOrEditCustomerEntry")
    public Result<Void> saveOrEditCustomerEntry(HttpServletRequest request,@RequestBody AddEntryReq entry){
        Operator operator = getOperatorBy(request);
        logger.info("saveOrEditCustomerEntry entry={}",new Gson().toJson(entry));
        try {
            if(StringUtil.isNotEmpty(entry.getId())){
                //编辑
                String msg;
                if (StringUtil.equalsAny(entry.getType(),CustomerEntryConstants.TYPE_TJ, CustomerEntryConstants.TYPE_ZC)) {
                    //华融
                    if("04".equals(entry.getZfId())){
                        msg = customerEntryService.editHREntryForIXDJ(entry, operator);
                    }else{
                        msg = customerEntryService.editEntryForIXDJ(entry, operator);
                    }
                }
                else {
                    msg = customerEntryService.editCustomerEntry(entry, operator);
                }
                if("206".equals(msg)){
                    return Result.ok("已推送签约短信");
                }
                if (!"200".equals(msg)) {
                    return Result.fail(msg);
                }
            }else{
                String msg;
                if("04".equals(entry.getZfId())){
                    msg = customerEntryService.createHREntryForIXDJ(entry, operator);
                }else {
                    msg = customerEntryService.createEntryForIXDJ(entry, operator);
                }
                if (!"200".equals(msg)) {
                    return Result.fail(msg);
                }
            }
            return Result.ok();
        } catch (IllegalArgumentException | BusinessException i){
            return Result.fail("501", i.getMessage());
        } catch (Exception e) {
            logger.error(">>>>>>>>>>>>>saveCustomerEntry  e:",e);
            e.printStackTrace();
            return Result.fail("501", "操作失败");
        }
    }

    /**
     * 勘测提交设计
     */
    @ResponseBody
    @RequestMapping("surveyToDesign")
    public Result<Void> surveyToDesign(HttpServletRequest request,@RequestBody SurveyEntryReq entry){
        Operator operator = getOperatorBy(request);
        logger.info("surveyToDesign entry={}",new Gson().toJson(entry));
        try {
            String msg = customerEntryService.surveyToDesign(entry, operator);
            if (!"200".equals(msg)) {
                return Result.fail(msg);
            }
            return Result.ok();
        } catch (IllegalArgumentException | BusinessException e){
            return Result.fail(e.getMessage());
        } catch (Exception e) {
            logger.error(">>>>>>>>>>>>>saveCustomerEntry  e:",e);
            e.printStackTrace();
            return Result.fail("501", "操作失败");
        }
    }

    /**
     * 设计驳回勘测
     */
    @ResponseBody
    @RequestMapping(value = "backToSurvey")
    public Result backToSurvey(@RequestBody @Validated BackSurveyReq req,HttpServletRequest request) {
        try {
            Operator operator = getOperatorByTwo(req.getUserId());
            String msg = customerEntryService.designBackCustomerEntry(req.getId(), req.getRemark(),operator);
            if (!"200".equals(msg)) {
                return Result.fail(msg);
            }
            return Result.ok();
        } catch (IllegalArgumentException | BusinessException e){
            return Result.fail(e.getMessage());
        } catch (Exception e) {
            logger.error(">>>>>>>>>>>>>backToSurvey  e:",e);
            e.printStackTrace();
            return Result.fail("501", "操作失败");
        }
    }

    /**
     * 设计提交、设计暂存
     */
    @ResponseBody
    @RequestMapping(value = "designCustomerEntry")
    public Result designCustomerEntry(@RequestBody @Validated DesignEntryReq req,HttpServletRequest request) {
        try {
            Operator operator = getOperatorBy(request);
            String msg = customerEntryService.designCustomerEntry(req,operator);
            if (!"200".equals(msg)) {
                return Result.fail(msg);
            }
            return Result.ok();
        } catch (IllegalArgumentException | BusinessException i){
            return Result.fail(i.getMessage());
        } catch (Exception e) {
            logger.error(">>>>>>>>>>>>>designCustomerEntry  e:",e);
            e.printStackTrace();
            return Result.fail("501", "操作失败");
        }
    }

    /**
     * 自审驳回
     * 驳回节点：1.待勘测 2.待设计
     */
    @ResponseBody
    @RequestMapping(value = "auditBack")
    private Result auditBack(@RequestBody AuditOperateReq req,HttpServletRequest request) {
        if (StringUtil.isBlank(req.getZsAuditRemarks())){
            return Result.fail("审核备注不能为空");
        }
        try {
            Operator operator = getOperatorBy(request);
            User user = getUserBy(request);
            String userName = operator.getUserName();
            user.setUserName(userName);
            customerEntryService.auditBack(req,user);
            return Result.ok();
        } catch (IllegalArgumentException e) {
            return Result.fail(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 自审通过
     * type 0.暂存 1.提交
     */
    @ResponseBody
    @RequestMapping(value = "updateCustomerEntry")
    public Result updateCustomerEntry(HttpServletRequest request, @RequestBody AddEntryReq req) {
        Operator operator = getOperatorBy(request);
        try {
            String msg = customerEntryService.editCustomerEntryFromPC(req, operator);
            if (!"200".equals(msg)) {
                return Result.fail(msg);
            }
            return Result.ok();
        }catch (BusinessException e){
            logger.error("修改信息错误 updateCustomerEntry Exception ：{}",e);
            e.printStackTrace();
            return Result.fail(e.getMessage());
        }catch (Exception e) {
            logger.error("修改信息错误 updateCustomerEntry  Exception ：{}",e);
            e.printStackTrace();
            throw e;
        }
    }


    //安装自审驳回
    @ResponseBody
    @RequestMapping(value = "acceptZSRefuse")
    public Result acceptZSRefuse(HttpServletRequest request,String id,String remarks){
        try {
            if (StringUtil.isBlank(remarks)){
                return Result.fail("驳回备注不能为空");
            }
            User user = getUserBy(request);
            Operator operator = getOperatorBy(request);
            user.setUserName(operator.getUserName());
            customerEntryService.acceptZSRefuse(id,remarks,user);
            return Result.ok();
        }catch (IllegalArgumentException e){
            logger.error("安装自审驳回错误 acceptZSRefuse Exception ：{}",e);
            return Result.fail(e.getMessage());
        }catch (Exception e) {
            logger.error("安装自审驳回错误 acceptZSRefuse  Exception ：{}",e);
            e.printStackTrace();
            throw e;
        }
    }

    //安装自审通过
    @ResponseBody
    @RequestMapping(value = "acceptZS")
    public Result acceptZS(HttpServletRequest request,String id){
        try {
            User user = getUserBy(request);
            Operator operator = getOperatorBy(request);
            user.setUserName(operator.getUserName());
            customerEntryService.acceptZS(id,user);
            return Result.ok();
        }catch (IllegalArgumentException e){
            logger.error("安装自审通过错误 acceptZS Exception ：{}",e);
            return Result.fail(e.getMessage());
        }catch (Exception e) {
            logger.error("安装自审通过错误 acceptZS  Exception ：{}",e);
            e.printStackTrace();
            throw e;
        }

    }

    @ResponseBody
    @RequestMapping("editCustomerEntryBy")
    public Result<Void> editCustomerEntryBy(HttpServletRequest request,@RequestBody CustomerEntryVo entry){
        Operator operator = getOperatorBy(request);
        logger.info("saveOrEditCustomerEntry entry={}",new Gson().toJson(entry));
        //编辑
        String msg = customerEntryService.editCustomerEntryBy(entry, operator);
        if (!"200".equals(msg)) {
            return Result.fail(msg);
        }
        return Result.ok();
    }


    /**
     * 查询预审状态
     */
    @ResponseBody
    @RequestMapping(value = "/findPreauditStatus")
    public Result findPreauditStatus(HttpServletRequest request){
        String entryId=request.getParameter("entryId");
        Map<String, String> resultMap = customerEntryService.findPreauditStatus(entryId);
        Result result=new Result();
        result.setOk();
        result.data(resultMap);
        return result;

    }


    /**
     * 待审核
     */
    @ResponseBody
    @RequestMapping("/ajaxForAuditEntry")
    public Object ajaxForAuditEntry(HttpServletRequest request){
        LayuiPage<Record> page = new LayuiPage<>(request);
        String userId = request.getParameter("userId");
        if (StrKit.isBlank(userId)) {
            throw new BusinessException("userId不能为空");
        }
        User user = userDao.get(userId);
        Map<String, String> map = getParams(request);
        String port = "XCX";
        customerEntryService.getCustomerList(port, page, map, user);
        return page.renderJson();
    }

    /**
     * 小程序 设计审核  平台员工账号
     */
    @ResponseBody
    @RequestMapping("appletsToExamine")
    public Object appletsToExamine(@RequestBody CustomerEntry entry, HttpServletRequest request) {
        logger.info("appletsToExamine entry={}", JSONObject.toJSONString(entry));
        String id = entry.getId();
        if (StringUtil.isBlank(id)) {
            return Result.fail("201", "参数id为空");
        }
        try {
            Operator operator = getOperatorBy(request);
            if (User.USER_TYPE_WXG.equals(operator.getUserType())) {
                Record r = CrmUtils.getByUserId(operator.getUserType(), operator.getUserId());
                String permission = AuthUtils.getMiniOptPremissVal(1);// 获取设计审核权限
                if (!AuthUtils.checkMiniOptPremissForEmp(r.getStr("id"), permission)) {
                    return Result.fail("201", "暂无权限操作，请让平台管理员授权登录！");
                }
            }
            User user = UserUtils.getUser(operator.getUserId());
            customerEntryService.toExamine(entry.getId(), entry.getExamineRemarks(), operator, user);
        } catch (Exception e) {
            Result result = new Result();
            e.printStackTrace();
            result.setCode("505");
            result.setMsg("Exception" + e);
            throw e;
        }
        return Result.ok();
    }

    /**
     * 上传进件申请附件验收报告至 浙银
     * /main/projectManage/uploadTwoAttachment?type='1'&id=
     */
    @ResponseBody
    @RequestMapping("/uploadTwoAttachment")
    public Result<Void> uploadTwoAttachment(String id,String type){
        GuardUtils.notBlank(id, "id不能为空");
        customerEntryService.uploadTwoAttachmentTh(id,type,"");
        return Result.ok();
    }

    @ResponseBody
    @RequestMapping("/uploadTwoAttachmentNot")
    public Result<Void> uploadTwoAttachmentNot(String powerStationCode,String type){
        GuardUtils.notBlank(powerStationCode, "id不能为空");
        customerEntryService.uploadTwoAttachmentNot(powerStationCode,type,"");
        return Result.ok();
    }



    /**
     * 小程序操作用户信息--删除
     */
    @ResponseBody
    @RequestMapping(value = "deleteCustomerEntry")
    public Object appletsDelete(HttpServletRequest request) {
        String cusId = request.getParameter("id");
        try {
            if (StringUtil.isBlank(cusId)) {
                return Result.fail("201", "参数id为空");
            }
            Operator operator = getOperatorBy(request);
            customerEntryService.deleteCustomerEntry(cusId,operator);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("202", "删除失败! " + e);
        }
        return Result.ok();
    }

    /**
     * 设计审核 驳回
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("appletsFailed")
    public Object appletsFailed(HttpServletRequest request) {
        String id = request.getParameter("id");
        String remarks = request.getParameter("remarks");
        if (StringUtil.isBlank(id)) {
            return Result.fail("202", "参数id为空");
        }
        try {
            Operator operator = getOperatorBy(request);
            if (User.USER_TYPE_WXG.equals(operator.getUserType())) {
                Record r = CrmUtils.getByUserId(operator.getUserType(), operator.getUserId());
                String permission = AuthUtils.getMiniOptPremissVal(1);// 获取设计审核权限
                if (!AuthUtils.checkMiniOptPremissForEmp(r.getStr("id"), permission)) {
                    return Result.fail("202", "暂无权限操作，请让平台管理员授权登录！");
                }
            }
            User user = UserUtils.getUser(operator.getUserId());
            customerEntryService.failedCustomerEntry(id, remarks,operator, user);
        } catch (Exception e) {
            Result result = new Result();
            e.printStackTrace();
            result.setCode("505");
            result.setMsg("Exception" + e);
            throw e;
        }
        return Result.ok();
    }

    /**
     * 小程序 平台员工账号
     * 安装验收接口：type 1.通过 2.驳回
     */
    @ResponseBody
    @RequestMapping(value = "toNetAccept")
    public Object toNetAccept(HttpServletRequest request){
        String id = request.getParameter("id");
        if (StringUtil.isBlank(id)) {
            return Result.fail("201", "参数id为空");
        }
        String type = request.getParameter("type");
        if (!StringUtil.equalsAny(type, "1", "2")) {
            return Result.fail("201", "type值不能为空，只能为1/2");
        }
        // 安装验收意见
        String fixConclusionSh = request.getParameter("fixConclusionSh");
        // 物料安装状态
        String materialFixFlag = request.getParameter("materialFixFlag");
        DLock dLock = null;
        try {
            Operator operator = getOperatorBy(request);
            if (User.USER_TYPE_WXG.equals(operator.getUserType())) {
                Record r = CrmUtils.getByUserId(operator.getUserType(), operator.getUserId());
                String permission = AuthUtils.getMiniOptPremissVal(2);// 获取安装验收权限
                if (!AuthUtils.checkMiniOptPremissForEmp(r.getStr("id"), permission)) {
                    return Result.fail("201", "暂无权限操作，请让平台管理员授权登录！");
                }
            }
            User user= UserUtils.getUser(operator.getUserId());
            if ("2".equals(type)) {
                customerEntryService.fixAcceptRefuse(id, fixConclusionSh, materialFixFlag, operator, user);
                return Result.ok();
            }
            dLock = new DLock("toNetAcceptPass" + id, jedisPool);
            int lockTimeOut = 2*60*1000; // 锁定2分钟
            dLock.lock(lockTimeOut,lockTimeOut);
            customerEntryService.toNetAcceptPass(id, type, fixConclusionSh, materialFixFlag, operator, user);
            try {
                customerEntryService.insertInterFace(id);
            }catch (Exception e) {
                customerEntryService.saveSysRecord(id,"安装验收通过 逆变器新增新的电站接入记录 失败",
                        "", e.getMessage(), "1");
            }
        }
        catch (BusinessException e) {
            if (dLock != null) {
                dLock.unlock();
            }
            logger.error(e.getMessage());
            return Result.fail("201", e.getMessage());
        }
        catch (Exception e) {
            if (dLock != null) {
                dLock.unlock();
            }
            logger.error(e.getMessage(), e);
            Result result = new Result();
            result.setCode("505");
            result.setMsg("Exception" + e);
            return result;
        }
        return Result.ok();
    }

    /**
     * 小程序 平台员工账号
     * 并网验收接口：type 1.通过 2.驳回
     */
    @ResponseBody
    @RequestMapping(value = "twoMergeAcceptRefuse")
    public Object twoMergeAcceptRefuse(HttpServletRequest request){
        String id = request.getParameter("id");
        if (StringUtil.isBlank(id)) {
            return Result.fail("201", "参数id为空");
        }
        String type = request.getParameter("type");
        if (!StringUtil.equalsAny(type, "1", "2")) {
            return Result.fail("201", "type值不能为空，只能为1/2");
        }
        // 安装验收意见
        String fixConclusion = request.getParameter("fixConclusion");
        // 物料并网状态
        String materialMergeFlag = request.getParameter("materialMergeFlag");
        // 近三天发电量
        String powerCapacityUrl = request.getParameter("powerCapacityUrl");

        try {
            Operator operator = getOperatorBy(request);
            if (User.USER_TYPE_WXG.equals(operator.getUserType())) {
                Record r = CrmUtils.getByUserId(operator.getUserType(), operator.getUserId());
                String permission = AuthUtils.getMiniOptPremissVal(3);// 获取并网验收权限
                if (!AuthUtils.checkMiniOptPremissForEmp(r.getStr("id"), permission)) {
                    return Result.fail("201", "暂无权限操作，请让平台管理员授权登录！");
                }
            }
            User user= UserUtils.getUser(operator.getUserId());
            customerEntryService.twoMergeAcceptRefuse(id, type, fixConclusion, materialMergeFlag,
                    powerCapacityUrl, operator, user);
        }
        catch (BusinessException | IllegalArgumentException e) {
            logger.error(e.getMessage());
            return Result.fail("201", e.getMessage());
        }
        catch (Exception e) {
            logger.error(e.getMessage(), e);
            Result result = new Result();
            result.setCode("505");
            result.setMsg("Exception" + e);
            return result;
        }
        return Result.ok();
    }

    /**
     * 列表
     */
    @ResponseBody
    @RequestMapping("/ajaxForWaitOrder")
    public Object ajaxForWaitOrder(HttpServletRequest request){
        LayuiPage<Record> page = new LayuiPage<>(request);
        Map<String, String> map = getParams(request);
//        logger.info("ajaxForWaitOrder, req:{}",map);
        Operator operator = getOperatorBy(request);
        String userId = map.get("userId");
        User user = userDao.getById(userId);
        if (User.USER_TYPE_ADVISOR.equals(user.getUserType())) {
            CrmTraderEmploye employe = traderEmployeService.findByUserId(user.getId());
            map.put("engineerId", employe.getId());
        }
        else if (User.USER_TYPE_WXG.equals(user.getUserType())) {
            Record r = CrmUtils.getByUserId(user);
            if (!AuthUtils.checkMiniOptPremissForEmp(r.getStr("id"), "NULL")) {
                page.setCode("200");
                page.setData(new ArrayList<>());
                page.setCount(0l);
                return page.renderJson();
            }
        }
        customerEntryService.listWaitOrderFromSmallP(page, map, operator);
        page.setCode("200");
        return page.renderJson();
    }


    /**
     * 接入逆变器
     */
    @ResponseBody
    @RequestMapping("/queryInverterList")
    public Object queryInverterList(HttpServletRequest request,String searchParams){
        LayuiPage<Record> page = new LayuiPage<>(request);
        Map<String, String> map = getParams(request);
        // map.put("searchParams","逆变器");//查询参数


        Operator operator = getOperatorBy(request);
        String userId = map.get("userId");
        User user = userDao.getById(userId);
        if (User.USER_TYPE_ADVISOR.equals(user.getUserType())) {
            CrmTraderEmploye employe = traderEmployeService.findByUserId(user.getId());
            map.put("engineerId", employe.getId());
        }
        else if (User.USER_TYPE_WXG.equals(user.getUserType())) {
            Record r = CrmUtils.getByUserId(user);
            if (!AuthUtils.checkMiniOptPremissForEmp(r.getStr("id"), "NULL")) {
                page.setCode("200");
                page.setData(new ArrayList<>());
                page.setCount(0l);
                return page.renderJson();
            }
        }
        customerEntryService.queryInverterList(page, map, operator);
        page.setCode("200");

        return page.renderJson();
    }

    @ResponseBody
    @RequestMapping("/findRetrialPage")
    public Object findRetrialPage(HttpServletRequest request){
        LayuiPage<Record> page = new LayuiPage<>(request);
        Map<String, String> map = getParams(request);
        logger.info("findRetrialPage, req:{}",map);
        Operator operator = getOperatorBy(request);
        String userId = map.get("userId");
        User user = userDao.getById(userId);
        if (User.USER_TYPE_ADVISOR.equals(user.getUserType())) {
            CrmTraderEmploye employe = traderEmployeService.findByUserId(user.getId());
            map.put("engineerId", employe.getId());
        }
        else if (User.USER_TYPE_WXG.equals(user.getUserType())) {
            Record r = CrmUtils.getByUserId(user);
            if (!AuthUtils.checkMiniOptPremissForEmp(r.getStr("id"), "NULL")) {
                page.setCode("200");
                page.setData(new ArrayList<>());
                page.setCount(0l);
                return page.renderJson();
            }
        }
        map.put("apply","1");
        customerEntryService.findRetrialPage(page, map, operator,"2");
        page.setCode("200");
        return page.renderJson();
    }

    /**
     * 逆变器接入详情
     */
    @ResponseBody
    @RequestMapping("/nbqInsertDetail")
    public Object nbqInsertDetail(String entryId,HttpServletRequest request) {
        if (StringUtil.isBlank(entryId)) {
            throw new IllegalArgumentException("请先选择接入项目");
        }
        return JsonKit.toJson(customerEntryService.nbqInsertDetail(entryId));
    }

    /**
     * 锦浪云新增电站信息接口
     */
    @ResponseBody
    @RequestMapping("/insertInterFace")
    public Result insertInterFace(HttpServletRequest request) {
        String entryId=request.getParameter("entryId");
        if (StringUtil.isBlank(entryId)) {
            throw new IllegalArgumentException("请先选择接入项目");
        }
        Result result= customerEntryService.insertInterFace(entryId);
        return result;
    }

    /**
     * 电站详情
     */
    @ResponseBody
    @RequestMapping("/entryDetail")
    public Object entryDetail(String entryId,HttpServletRequest request) {
        GuardUtils.notBlank(entryId, "entryId不能为空");
        String userId=request.getParameter("userId");

        Record ret = customerEntryService.getRecordById(entryId);
        ret.set("entry_id", entryId);
        String traderId="";
        List<Record> optList =new ArrayList<>();   //过程信息
        String partnerId = null;
        if(ret != null){
            partnerId = ret.getStr("partner_id");
            CrmCustomerContractManagement contract = contractManagementDao.getContractByEntryId(entryId);
            if(!Objects.isNull(contract)) {
                ret.set("contractUrl", contract.getContractUrl());
                ret.set("contractNumber", contract.getContractNumber());
                if(!Objects.isNull(contract.getTenantSignTime())) {
                    ret.set("tenantSignTime",  DateUtils.formatDate(contract.getTenantSignTime(), "yyyy-MM-dd"));
                }
            }
            if(StringUtil.isNotBlank(userId)){
                User user = userDao.get(userId);
                if (User.USER_TYPE_KJ.equals(user.getUserType())) {
                    traderId = CrmUtils.getTraderIdByUserId(userId);
                }else if(User.USER_TYPE_ADVISOR.equals(user.getUserType())){
                    traderId = CrmUtils.getUserRelId(user);
                }
            }
            optList = customerEntryMsgService.listOptRecordByEntryId(entryId,traderId);
            CrmProjectSetting project = null;
            if (StringUtil.isNotBlank(ret.getStr("project_id"))) {
                project = projectService.getById(ret.getStr("project_id"));
            }
            CrmTrader trader = traderService.getById(ret.getStr("distributor_id"));
            if (CustomerEntryConstants.ENTRY_STATUS_ZRDJ.equals(ret.getStr("status"))) {
                ret.set("project_id", "");
                ret.set("project_name", "");
                ret.set("project_code", "");
                ret.set("projectCode", "");
                ret.set("projectName", "");
            } else {
                ret.set("projectCode", (project == null ? "" : project.getCode()));
                ret.set("projectName", (project == null ? "" : project.getName()));
                ret.set("assemblySpecs", (project == null ? "0" : String.valueOf(project.getAssemblySpecs())));
                ret.set("modeId", "");
                // 获取规格列表
                List<Record> list = planService.getElectricSet("3");
                for (Record r : list) {
                    if (Objects.equals(r.getStr("model"), ret.getStr("assemblySpecs"))) {
                        ret.set("modeId", r.getStr("id"));
                    }
                }
            }
            ret.set("management", partnerId);
            // 获取资方
            CrmPartner partner = partnerService.getById(partnerId);
            ret.set("overageFlag", partner.getOverageFlag());
            String reportId = ret.getStr("receiving_report_id");
            if (StringUtil.isNotBlank(reportId)) {
                CrmAcceptingReport report = customerEntryService.getReportById(reportId);
                ret.set("report", report);
            }
            ret.set("traderName", trader.getName());
            ret.set("traderTel", trader.getTelephone());

            if (ret.get("lease_date") != null) {
                ret.set("lease_date",ret.getStr("leaseDate"));
            }
            if(PartnerConstants.PARTNER_ID_YX.equals(ret.getStr("partner_id"))){  //越秀
                //获取历史设置的汇流方式

                Record recordBox=combinerBoxGroupDao.getEntryCombinerBoxSet(entryId);
                ret.set("recordBoxHistory",recordBox);
                //获取一户多站的信息
                Record oneToAnyBoxSet=combinerBoxGroupDao.getOneToAnyBoxSet(ret.getStr("id_code"),ret.getStr("regno"),ret.getStr("create_trader_id"),ret.getStr("tenant_type"));
                ret.set("oneToAnyBoxSet",oneToAnyBoxSet);
            }
            List<Record> projectList = projectInfoSettingService.getEntryProjectByEntryId(entryId);
            ret.set("projectList",projectList);
        }else{
            ret = new Record();
            ret.set("projectCode", "");
            ret.set("projectName", "");
            ret.set("traderName", "");
            ret.set("traderTel", "");
        }
        Integer designCapacity = ret.getInt("design_capacity");
        BigDecimal actualCapacity = ret.getBigDecimal("actual_capacity");
        String powerName = ret.getStr("province") + ret.getStr("area") +
                (StringUtil.isBlank(ret.getStr("street")) ? "" : ret.getStr("street")) +
                ret.getStr("tenant_name");
        if (designCapacity != null) {
            powerName = powerName + (BigDecimal.ZERO.compareTo(actualCapacity) == 0 ?
                    (BigDecimal.valueOf(designCapacity).divide(new BigDecimal(1000), 2, RoundingMode.HALF_UP)) :
                    (actualCapacity.divide(new BigDecimal(1000), 2, RoundingMode.HALF_UP)));
            powerName = powerName + "KW光伏电站";
            ret.set("powerName", powerName);
        }
        else if (actualCapacity != null) {
            powerName = powerName + actualCapacity.divide(new BigDecimal(1000), 2, RoundingMode.HALF_UP);
            powerName = powerName + "KW光伏电站";
            ret.set("powerName", powerName);
        }
        else {
            ret.set("powerName", "");
        }

        String reportId = ret.getStr("receiving_report_id");
        CrmAcceptingReport report = null;
        if(StrKit.notBlank(reportId)){
            report = customerEntryService.getReportById(reportId);
            String completeRemark = report.getCompleteRemark();
            if (StringUtil.isBlank(completeRemark)) {
                report.setCompleteRemark("");
            }
            ret.set("report", report);
        }
        // 显示驳回原因
        String design_audit_flag = ret.getStr("design_audit_flag");
        String zs_result = ret.getStr("zs_result");
        String install_flag = ret.getStr("install_flag");
        String check_accept_flag = ret.getStr("check_accept_flag");
        String on_grid_flag = ret.getStr("on_grid_flag");
        ret.set("auditType", "0");
        // 自审驳回
        if (StringUtil.equalsAny(zs_result, "2", "3")) {
            ret.set("auditType", "2");
            ret.set("auditRemark", ret.getStr("audit_remarks"));
        }
        //设计审核驳回
        else if("4".equals(zs_result)) {
            ret.set("auditType", "2");
            ret.set("auditRemark", ret.getStr("examine_remarks"));
        }
        else if(report != null && StringUtil.isNotBlank(report.getFixConclusion()) &&
                (CustomerEntryConstants.INSTALL_FLAG_ZSBH.equals(install_flag) ||
                        CustomerEntryConstants.CHECK_ACCEPT_FLAG_YSBH.equals(check_accept_flag))) {
            ret.set("auditType", "3");
            ret.set("auditRemark", report.getFixConclusion());
        }
        else if(report != null && StringUtil.isNotBlank(report.getMergeConclusion()) &&
                CustomerEntryConstants.ON_GRID_FLAG_BWYSBH.equals(on_grid_flag)) {
            ret.set("auditType", "4");
            ret.set("auditRemark", report.getMergeConclusion());
        }

        String proCode = ret.getStr("province_code");
        if (StringUtil.isNotBlank(proCode)) {
            ret.set("province_code_name", AddressUtils.findProCodeNameByCode(proCode));
        }
        else {
            ret.set("province_code_name", "");
        }

        List<Record> zhijialist = Lists.newArrayList();
        Map<String,Object> map = Maps.newHashMap();
        String brand = "";//组件品牌
        String nbqSpecOne = "";//逆变器一
        String nbqSpecTwo = "";//逆变器二
        String bwxBrand = "";//并网箱
        String zjBrand ="";
        //获取使用的物料
        int bwxCOunt=0;
        int zujCOunt=0;
        List<Record> list = customerEntryService.findMaterialListByEntryId(ret.getStr("id"));
        for (Record re:list){
            if(StringUtil.equalsAny(re.getStr("type"),"组件")){
                if(StringUtil.isBlank(brand)){
                    brand = re.getStr("material_brand");
                    map.put("zujBrand",brand);
                    map.put("zujSpec",re.getStr("spec"));
                    map.put("zujUnit", re.getStr("unit"));
                }
                zujCOunt++;
            }
            if(StringUtil.equalsAny(re.getStr("type"),"逆变器")){
                if(StringUtil.isBlank(nbqSpecOne)){
                    nbqSpecOne=re.getStr("material_brand");
                    map.put("nbqBrandOne",nbqSpecOne);
                    map.put("nbqSpecOne",re.getStr("spec"));
                    map.put("nbqUnitOne", re.getStr("unit"));
                }else{
                    nbqSpecTwo=re.getStr("material_brand");
                    map.put("nbqBrandTwo",nbqSpecTwo);
                    map.put("nbqSpecTwo",re.getStr("spec"));
                    map.put("nbqUnitTwo", re.getStr("unit"));
                }
            }
            if(StringUtil.equalsAny(re.getStr("type"),"支架")){
                if(StringUtil.isBlank(zjBrand)){
                    zjBrand=re.getStr("material_brand");
                    map.put("zjBrand",zjBrand);
                }
                zhijialist.add(re);
            }
            if(StringUtil.equalsAny(re.getStr("type"),"并网箱")){
                bwxCOunt++;
                if(StringUtil.isBlank(bwxBrand)) {
                    bwxBrand = re.getStr("material_brand");
                    map.put("bwxBrand", bwxBrand);
                    map.put("bwxSpec", re.getStr("spec"));
                }
            }

        }
        map.put("zhijialist", zhijialist);
        map.put("bwxCOunt", bwxCOunt);
        map.put("zujCOunt", zujCOunt);
        map.put("zjCount", zhijialist.size());
        map.put("filingType", ret.getStr("filing_type"));

        String sn = ret.getStr("sn"); // sn码序列号
        if(StringUtil.isNotBlank(sn) && sn.indexOf(",")>0){
            String[] sns = sn.split(",");
            if(sns.length>1){
                map.put("snOne", sns[0]);
                map.put("snTwo", sns[1]);
            }else{
                map.put("snOne", sn);
            }
        }else{
            map.put("snOne", sn);
        }
        String nbqSn = ret.getStr("nbq_sn"); // 逆变器SN码
        if(StringUtil.isNotBlank(nbqSn) && nbqSn.indexOf(",")>0){
            String[] sns = nbqSn.split(",");
            if(sns.length>1){
                map.put("nbqSnOne", sns[0]);
                map.put("nbqSnTwo", sns[1]);
            }else{
                map.put("nbqSnOne", nbqSn);
            }
        }else{
            map.put("nbqSnOne", nbqSn);
        }
        ret.set("map", map);

        if(CustomerEntryConstants.SCHEME_TYPE_TWO.equals(ret.getStr("scheme_type"))){
            List<ComposePlan> rdss = customerEntryService.findByEntryId(entryId);
            ret.set("composePlanList", rdss);
        }
        ret.set("optList", optList);
        // 获取电站电器材料
        List<Record> componentList = customerEntryComponentService.findByEntryIdForSmallPrograms(entryId);
        if(!PartnerConstants.PARTNER_ID_HR.equals(partnerId))
        ret.set("componentList", componentList);
        CrmCustomerIncomingApplicationInsurance insurance = insuranceDao.getByEntryId(entryId);
        ret.set("insurance", insurance);

        ret.set("insuranceName", null);
        if (insurance != null) {//有保险
            ret.set("insuranceName", insurance.getInsuranceName());
        }
        CrmTenantYxBankCard card=null;
        if (StringUtil.isNotBlank(partnerId)) {
            card = tenantYxBankCardDao.getByIdCard(ret.getStr("id_code"),
                    ret.getStr("management_type"), partnerId);
        }
        String querySql=" select id,name from crm_partner where id=(select partner_id from crm_customer_entry where id=?)";
        List<Record> records = Db.find(querySql, entryId);
        String zfId="";
        String zfName="";
        for(Record rd:records){
            zfId=rd.get("id");
            zfName=rd.get("name");
        }
        ret.set("zfId",zfId);
        ret.set("zfName",zfName);
        // bankFlag 开卡标记：1.可开卡 2.不可开卡
        ret.set("bankFlag","1");
        if(card!=null){
            ret.set("secCardName",card.getName());  //二类卡账户名
            ret.set("secCardNo",card.getAccountCode());  //二类卡账号
            switch (partnerId) {
                case PartnerConstants.PARTNER_ID_HR:
                    ret.set("secBankNumber","102331002044");  //华融二类卡联行号
                    break;
                case PartnerConstants.PARTNER_ID_YX:
                    ret.set("secBankNumber","102581000353");  //越秀二类卡联行号
                    break;
            }
            if (StringUtil.equalsAny(card.getStatus(), "1","2","4","7","8","9")) {
                ret.set("bankFlag","2");
            } else if (!PartnerConstants.PARTNER_ID_YX.equals(partnerId)) {
                ret.set("bankFlag","2");
            }
        }else {
            ret.set("cardName","");
            ret.set("secCardNo","");
            ret.set("secBankNumber","");
        }
        String[] columnNames = ret.getColumnNames();
        for (String columnName : columnNames) {
            if (ret.get(columnName) == null){
                ret.set(columnName,"");
            }
        }
        //华融多产品-勘测返回
        List<Record>  surveyDetail =  recordDetailService.getEntryDetail(entryId);
        for(Record record:surveyDetail){
            List<CrmCustomerEntryDesign> designDetail = crmCustomerEntryDesignDao.findByEntryIdAndProjectId(entryId,record.getStr("projectId"));
            record.set("addEntryReqDesignDetails",designDetail);
            List<Record> components = customerEntryComponentService.findByEntryIdByProjectIdForSmallPrograms(entryId,record.getStr("projectId"));
            record.set("componentList",components);
            CrmAcceptingReportDetail acceptingReport = crmAcceptingReportDetailDao.findByEntryIdAndProjectId(entryId,record.getStr("projectId"));
            if(acceptingReport != null){
                record.set("acceptingReport",acceptingReport);
            }else{
                CrmAcceptingReportDetail reportDetail = new CrmAcceptingReportDetail();
                reportDetail.setBkImg1("");
                record.set("acceptingReport",reportDetail);
            }
        }
        ret.set("projectDetailList",surveyDetail);
        return JsonKit.toJson(ret);
    }

    /**
     * 获取逆变器 并网箱 组件 支架
     */
    @ResponseBody
    @RequestMapping(value = "getElectricPlanAll")
    public Object getElectricPlanAll(String partnerId){
        Map<String,Object> map = Maps.newHashMap();//1逆变器 2并网箱 3组件
        Record info2 = formSetService.getListByCondition("02", partnerId);
        FormSetPageVo vo = info2.get("component1_model");
        boolean flag = false;
        if (vo != null && "1".equals(vo.getStatus())){
            flag = true;//需要型号
        }
        map.put("boxs",planService.getElectricSet("2"));
        if (StringUtil.isNotBlank(partnerId) && "03".equals(partnerId)){
            if (flag){
                map.put("inverters",planService.findAllInverterGF2());
            }else {
                map.put("inverters",planService.findAllInverterGF());
            }
            map.put("zjs",planService.getElectricSetGF("3"));
        }else {
            if (flag){
                map.put("inverters",planService.findAllInverter2());
            }else {
                map.put("inverters",planService.findAllInverter());
            }
            map.put("zjs",planService.getElectricSet("3"));
        }
        map.put("zhij",planService.getElectricSet("4"));
        return map;
    }

    /**
     * 根据组件规格和组件块数查找电气配置
     */
    @ResponseBody
    @RequestMapping(value = "findElectricPlan")
    public Object findElectricPlan(String assembly,String assemblyNum){
        if(StringUtil.isNotBlank(assembly) && StringUtil.isNotBlank(assemblyNum)){
            Record es= planService.findElectricPlan(assembly,assemblyNum);
            return es.getColumns();
        }

        return Result.fail("2004","参数为空");
    }


    /**
     * 查看已匹配的方案
     */
    @ResponseBody
    @RequestMapping(value = "viewMatchedPlan")
    public Object viewMatchedPlan(String entryId, HttpServletRequest request) {
        GuardUtils.notBlank(entryId, "entryId不能为空");
        CustomerEntry entry = customerEntryService.getById(entryId);
        Record ret = new Record();
        ret.set("schemeType", entry.getSchemeType());
        ret.set("designDrawings", entry.getDesignDrawings());
        ret.set("designDrawingsName", entry.getDesignDrawingsName());
        ret.set("designCapacity", entry.getDesignCapacity());
        // 组合方案
        if (CustomerEntryConstants.SCHEME_TYPE_TWO.equals(entry.getSchemeType())) {
            List<ComposePlan> rdss = customerEntryService.findByEntryId(entryId);
            ret.set("composePlanList", rdss);
        } else {
            ret.set("planId", entry.getSchemeId());
            ret.set("planName", entry.getSchemeName());
            ret.set("planTypeId", entry.getSchemeTypeId());
            ret.set("planTypeName", entry.getSchemeTypeName());
        }
        List<Record> materials = planService.listMatchedMaterialByPlanId(entryId);
        ret.set("materials", materials);
        ret.set("matchTime", entry.getExamineTime());
        return JsonKit.toJson(ret);
    }

    /**
     * 查看验收报告
     */
    @ResponseBody
    @RequestMapping("/toMergeAccept")
    public String toMergeAccept(String entryId, HttpServletRequest request){
        GuardUtils.notBlank(entryId, "entryId不能为空");
        Record ret = new Record();
        CustomerEntry entry = customerEntryService.getById(entryId);
        CustomerEntrySurveyRecord surveyRecord = surveyRecordDao.findOneByEntryId(entryId);
        String reportId = entry.getReceivingReportId();
        if(StrKit.notBlank(reportId)){
            CrmAcceptingReport report = customerEntryService.getReportById(reportId);
            ret.set("report", report);
        }
        CrmProjectSetting project = projectService.getById(entry.getProjectId());
        CrmTrader trader = traderService.getById(entry.getDistributorId());
        ret.set("projectCode", project.getCode());
        ret.set("projectName", project.getName());
        ret.set("traderName", trader.getName());
        ret.set("traderTel", trader.getTelephone());
        ret.set("tenantName", entry.getTenantName());
        ret.set("idCode", entry.getIdCode());
        ret.set("location", entry.getProvince() + entry.getCity() + entry.getArea());
        ret.set("address", entry.getAddress());
        ret.set("mobile", entry.getMobile());
        ret.set("schemeName", entry.getSchemeName());
        ret.set("powerStationCode", entry.getPowerStationCode());
        ret.set("componentSpec", entry.getComponentSpec());
        ret.set("actualCapacity", entry.getActualCapacity());
        ret.set("roofType", surveyRecord.getRoofType());
        ret.set("angle", surveyRecord.getAngle());
        ret.set("azimuth", surveyRecord.getAzimuth());
        return JsonKit.toJson(ret);
    }

    /**
     * 确认下单
     */
    @ResponseBody
    @RequestMapping("/batchOrder")
    public Result<Void> batchOrder(String ids, HttpServletRequest request) {

        GuardUtils.notBlank(ids, "ids不能为空");
        Operator currentUser = getOperatorBy(request);
        List<String> orderIds = Arrays.asList(ids.split(","));
        customerEntryService.batchOrder(orderIds, currentUser, null, null);
        return Result.ok();
    }

    /**
     * 确认收货
     */
    @ResponseBody
    @RequestMapping("/batchReceive")
    public Result<Void> batchReceive(String ids, HttpServletRequest request) {
        GuardUtils.notBlank(ids, "ids不能为空");
        Operator currentUser = getOperatorBy(request);
        List<String> orderIds = Arrays.asList(ids.split(","));
        customerEntryService.batchReceive(orderIds, currentUser);
        return Result.ok();
    }


    /**
     * 提交验收报告
     */
    @ResponseBody
    @RequestMapping("/tempSaveReport")
    public Result<Void> tempSaveReport(AddReportReq req, HttpServletRequest request) {
        GuardUtils.notBlank(req.getEntryId(), "entryId不能为空");
        Operator operator = getOperatorBy(request);
        //customerEntryService.tempSaveReport(req, operator);
        return Result.ok();
    }

    @ResponseBody
    @RequestMapping(value = "/getMateriallist")
    public Result getMateriallist(String entryId, String type, String warehouseId) {
        Result result = new Result<>();
        List<Record> list = customerEntryService.getMateriallist(entryId,type,warehouseId);
        result.setOk();
        result.setData(list);
        return result;
    }

    /**
     * 小程序操作派工
     * @param req
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "dispatch")
    public Result dispatch(@RequestBody DispatchReq req){
        if (StringUtil.isBlank(req.getUserId())) {
            return Result.fail("操作人不能为空");
        }
        Operator currentUser = getOperatorByTwo(req.getUserId());
        try {
            customerEntryService.dispatch(req, currentUser);
            return Result.ok();
        } catch (IllegalArgumentException e) {
            return Result.fail(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.fail("操作失败");
    }

    /**
     * 安装完成
     */
    @ResponseBody
    @RequestMapping("/install")
    public Result<Void> install(@RequestBody @Validated AddReportReq req, HttpServletRequest request) {
        GuardUtils.notBlank(req.getEntryId(), "entryId不能为空");
        Operator currentUser = getOperatorBy(request);
        try {
            customerEntryService.batchInstall(req, currentUser);
            return Result.ok();
        } catch (Exception e) {
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 派工-员工数据
     */
    @ResponseBody
    @RequestMapping(value = "selectDispatchEngineer")
    public Object ajaxForDispatchEngineer(HttpServletRequest request) {
        LayuiPage<Record> page = new LayuiPage<>(request);
        Map<String, String> params = getParams(request);
        String userId = request.getParameter("userId");
        if(StringUtil.isBlank(userId)){
            return null;
        }
        String traderId = null;
        User user = userDao.get(userId);
        if (User.USER_TYPE_KJ.equals(user.getUserType())) {
            traderId = CrmUtils.getTraderIdByUserId(userId);
        } else if (User.USER_TYPE_ADVISOR.equals(user.getUserType())) {
            traderId = CrmUtils.getUserRelId(user);
        }
        page.setData(traderEmployeService.getTraderEmployeDataList(params, traderId));
        page.setCode("200");
        return page.renderJson();
    }

    /**
     * 安装暂存
     */
    @ResponseBody
    @RequestMapping("/installZc")
    public Result<Void> installZc(@RequestBody @Validated AddReportZcReq req, HttpServletRequest request) {
        GuardUtils.notBlank(req.getEntryId(), "entryId不能为空");
        CustomerEntry entry = customerEntryService.getById(req.getEntryId());
        Operator currentUser = getOperatorBy(request);
        try {
            if("04".equals(entry.getPartnerId())){
                customerEntryService.batchInstallZcHr(req, currentUser);
            }else{
                customerEntryService.batchInstallZc(req, currentUser);
            }
            return Result.ok();
        } catch (Exception e) {
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 并网暂存(提交国网授权)
     */
    @ResponseBody
    @RequestMapping(value = "/mergeTmp")
    public Result<Void> mergeTmp(@RequestBody @Validated AddReportSecondReq req, HttpServletRequest request){
        Operator currentUser = getOperatorBy(request);
        customerEntryService.merge(req, currentUser,true);
        return Result.ok();
    }

    /**
     * 并网(并网提交)
     */
    @ResponseBody
    @RequestMapping("/accept")
    public Result<Void> accept(@RequestBody @Validated AddReportSecondReq req, HttpServletRequest request){
        Operator currentUser = getOperatorBy(request);
        /* customerEntryService.accept(req, currentUser);*/
        customerEntryService.merge(req, currentUser, false);
        return Result.ok();
    }

    /**
     * 确认归档
     */
    @ResponseBody
    @RequestMapping("/sureInDoc")
    public Result<Void> sureInDoc(String id, HttpServletRequest request){
        GuardUtils.notBlank(id, "id不能为空");
        Operator operator = getOperatorBy(request);
        customerEntryService.sureInDoc(id, operator);
        return Result.ok();
    }

    /**
     * 归档退回
     */
    @ResponseBody
    @RequestMapping("/refuseInDoc")
    public Result<Void> refuseInDoc(String id, String reason, HttpServletRequest request){
        GuardUtils.notBlank(id, "id不能为空");
        GuardUtils.notBlank(reason, "reason不能为空");
        Operator operator = getOperatorBy(request);
        customerEntryService.refuseInDoc(id, reason, operator);
        return Result.ok();
    }

    /**
     * 代理商查看统计数据
     * 待审核、待验收、待交付、已交付
     * 旧的接口  现小程序已不使用
     */
    @ResponseBody
    @RequestMapping("/statistic")
    public Object statistic(HttpServletRequest request){

        Operator operator = getOperatorBy(request);
        Record record;
        String factime =  cacheService.hget("userIdoOperatorTime",operator.getUserId());
        String time = DateUtils.getDate("yyyy-MM-dd HH:mm:ss");
        long diff = DateUtils.getTwoTime(factime,time);
        logger.info("代理商查看统计数据 : statistic  userId:{}  factime:{} , diff:{}",operator.getUserId(),factime,diff);
        if(diff<30&&diff>0){
            String faccount =  cacheService.hget("operatorUserId",operator.getUserId());
            if (StringUtil.isNotBlank(faccount)) {
                Record rd = new Gson().fromJson(faccount, new TypeToken<Record>() {
                }.getType());
                logger.info("代理商查看统计数据缓存取数据 : statistic  record {}",rd);
                return JsonKit.toJson(rd);
            }
        }
        cacheService.hdel("userIdoOperatorTime",operator.getUserId());
        cacheService.hdel("operatorUserId",operator.getUserId());
        cacheService.hdel("userIdoOperatorTime",operator.getUserId());
        if(User.USER_TYPE_WXG.equals(operator.getUserType())){
            //平台人员
            Map<String,String> map  = Maps.newHashMap();
            EmployeRoleUtils.getRoleDataAuthority(operator.getUserId(),  map);
            record = customerEntryService.statisticForPlaft(map);
        }else if(User.USER_TYPE_ADVISOR.equals(operator.getUserType())){
            //代理商人员
            String traderId = CrmUtils.getTraderId(operator.getUserId());
            record = customerEntryService.statisticForTrader(traderId,operator.getUserId());
        }else{
            //代理商自己
            CrmTrader trader = traderService.getTraderBuserId(operator.getUserId());
            record = customerEntryService.statisticForTrader(trader.getId(),"");
        }
        logger.info("statistic_record : {} ",record);
        cacheService.hset("operatorUserId",operator.getUserId(),new Gson().toJson(record));
        cacheService.hset("userIdoOperatorTime",operator.getUserId(),time);
        return JsonKit.toJson(record);
    }

    /**
     * 第三方呢系统调用 开放接口
     */
    @ResponseBody
    @RequestMapping(value = "getCustomerEntryByIdCode",method = RequestMethod.POST)
    public Object getCustomerEntryByIdCode(HttpServletRequest request) throws Exception {

        String syscode = request.getParameter("syscode");
        String generator_no =request.getParameter("generatorNo");
        String powerStationCode = request.getParameter("powerStationCode");
        String timeStamp =request.getParameter("timeStamp");
        if(StringUtil.isBlank(syscode)){
            return Result.fail("2001","参数syscode 为空");
        }
        if(StringUtil.isBlank(generator_no) && StringUtil.isBlank(powerStationCode)){
            return Result.fail("2001","参数generatorNo或者 powerStationCode为空");
        }
        if(StringUtil.isBlank(timeStamp)){
            return Result.fail("2001","参数timeStamp为空");
        }
        //判断是否失效（失效时间为1分钟）
        if(HmacUtil.isEffectiveDate(Long.valueOf(timeStamp))){
            return Result.fail("2001","参数已失效，请重新获取");
        }

        //加密--sfid_code_901
        String encrypt = HmacUtil.HMACSHA256(timeStamp,"");
        if(!encrypt.equals(syscode)){
            return Result.fail("2003","系统编码错误");
        }
        logger.info("根据发电户号获取数据：发电户号为 {}",generator_no);
        Record rds = customerEntryService.findCustomerEntryGeneratorNo(generator_no,powerStationCode);
        Result result = new Result();
        if(rds == null){
            return Result.fail("2004","查无数据");
        }
     /*   if(rds.getInt("component_count") ==null ||rds.getInt("component_count")<1){
            CrmAcceptingReport report = customerEntryService.getReportById(rds.getStr("receiving_report_id"));
            rds.set("component_count",report.getComponentNum());
        }*/
        Map<String,Object> map = Maps.newHashMap();
        map.putAll(rds.getColumns());
        logger.info("根据发电户号获取数据：发电户号为 {},获取到数据 map：{} ",generator_no,map);
        result.setCode("200");
        result.setMsg("请求成功");
        result.setData(map);
        return result;
    }


    /**
     * 批量获取项目及验收报告信息
     */
    @ResponseBody
    @RequestMapping(value = "findCustomerEntryAllByCode",method = RequestMethod.POST)
    public Object findCustomerEntryAllByCode(HttpServletRequest request){
        LayuiPage<Record> page = new LayuiPage<>(request);
        String syscode = request.getParameter("syscode");
        String timeStamp =request.getParameter("timeStamp");
        String generator_no =request.getParameter("generatorNo");
        String powerStationCode = request.getParameter("powerStationCode");
        String id = request.getParameter("id");
        String checkAcceptTimeMin = request.getParameter("checkAcceptTimeMin");
        String checkAcceptTimeMax = request.getParameter("checkAcceptTimeMax");

        if(StringUtil.isBlank(syscode)){
            return Result.fail("2001","参数syscode 为空");
        }

        if(StringUtil.isBlank(timeStamp)){
            return Result.fail("2001","参数timeStamp为空");
        }
        //判断是否失效（失效时间为1分钟）
        if(HmacUtil.isEffectiveDate(Long.valueOf(timeStamp))){
            return Result.fail("2001","参数已失效，请重新获取");
        }
        String encrypt="";
        //加密--sfid_code_901
        try {
            encrypt = HmacUtil.HMACSHA256(timeStamp,"");
        }catch (Exception e){
            return Result.fail("2003","系统编码格式错误");
        }
        if(!encrypt.equals(syscode)){
            return Result.fail("2003","系统编码错误");
        }
        Map<String,String> map = Maps.newHashMap();
        map.put("generatorNo",generator_no);
        map.put("powerStationCode",powerStationCode);
        map.put("id",id);
        map.put("checkAcceptTimeMin",checkAcceptTimeMin);
        map.put("checkAcceptTimeMax",checkAcceptTimeMax);
        List<Record> list = customerEntryService.findCustomerEntryList(page,map);
        Result result = new Result();
        if(list.size()<1){
            return Result.fail("2004","查无数据");
        }
        List<Map<String,Object>> mapslist = Lists.newArrayList();
        for(Record rds:list){
            Map<String,Object> maps = Maps.newHashMap();
            maps.putAll(rds.getColumns());
            mapslist.add(maps);
        }
        result.setCode("200");
        result.setMsg("请求成功");
        result.setData(mapslist);
        return result;
    }


    /**
     * 获取项目方案详情
     */
    @ResponseBody
    @RequestMapping(value = "findCustomerEntryMatchedPlan")
    public Result findCustomerEntryMatchedPlan(HttpServletRequest request) {

        String entryId = request.getParameter("entryId");
        String syscode = request.getParameter("syscode");
        String timeStamp =request.getParameter("timeStamp");
        if(StringUtil.isBlank(syscode)){
            return Result.fail("2001","参数syscode 为空");
        }

        if(StringUtil.isBlank(timeStamp)){
            return Result.fail("2001","参数timeStamp为空");
        }
        //判断是否失效（失效时间为1分钟）
        if(HmacUtil.isEffectiveDate(Long.valueOf(timeStamp))){
            return Result.fail("2001","参数已失效，请重新获取");
        }
        String encrypt="";
        //加密--sfid_code_901
        try {
            encrypt = HmacUtil.HMACSHA256(timeStamp,"");
        }catch (Exception e){
            return Result.fail("2003","系统编码格式错误");
        }
        if(!encrypt.equals(syscode)){
            return Result.fail("2003","系统编码错误");
        }
        Map<String,Object> maps= Maps.newHashMap();
        String matchedPlan = cacheService.hget("MatchedPlan",entryId);
        if(StringUtil.isNotBlank(matchedPlan)){
            maps = new Gson().fromJson(matchedPlan, new TypeToken<Map<String,Object>>() {
            }.getType());
        }else{
            CustomerEntry entry = customerEntryService.getById(entryId);
            //获取所有物料明细
            List<Record> materials = planService.listMatchedMaterialByPlanId(entryId);
            maps.put("materials",materials);
            List<Record> lists;
            if(CustomerEntryConstants.SCHEME_TYPE_TWO.equals(entry.getSchemeType())){
                //匹配方案
                //获取方案
                lists = planService.findComposePlanByEntryId(entryId);
            }else{
                lists = Lists.newArrayList();
                Record plan = planService.getPlanById(entry.getSchemeId());
                plan.set("name", entry.getSchemeName());
                lists.add(plan);
            }
            if(lists.size()>0){
                for(Record rd :lists){
                    rd.set("attach", Base64Url.ImageToBase64ByOnline(rd.getStr("attach")));
                    rd.set("attach2",Base64Url.ImageToBase64ByOnline(rd.getStr("attach2")));
                }
            }
            maps.put("planList",lists);
            cacheService.hset("MatchedPlan",entryId,new Gson().toJson(maps));
        }
        Result result = new Result();
        result.setCode("200");
        result.setMsg("请求成功");
        result.setData(maps);
        return result;
    }


    /**
     * 根据验收报告id 获取报告信息
     */
    @RequestMapping("findAccRepostById")
    @ResponseBody
    public Result findAccRepostById(HttpServletRequest request){
        logger.info("任务开始......");
        long begin = System.currentTimeMillis();
        String reportId = request.getParameter("reportId");
        String syscode = request.getParameter("syscode");
        String timeStamp =request.getParameter("timeStamp");
        if(StringUtil.isBlank(syscode)){
            return Result.fail("2001","参数syscode 为空");
        }

        if(StringUtil.isBlank(timeStamp)){
            return Result.fail("2001","参数timeStamp为空");
        }
        //判断是否失效（失效时间为1分钟）
        if(HmacUtil.isEffectiveDate(Long.valueOf(timeStamp))){
            return Result.fail("2001","参数已失效，请重新获取");
        }
        String encrypt="";
        //加密--sfid_code_901
        try {
            encrypt = HmacUtil.HMACSHA256(timeStamp,"");
        }catch (Exception e){
            return Result.fail("2003","系统编码格式错误");
        }
        if(!encrypt.equals(syscode)){
            return Result.fail("2003","系统编码错误");
        }
        Result result = new Result();
        if(StringUtil.isBlank(reportId)){
            result.setMsg("请求参数为空");
            result.setCode("2011");
            return result;
        }

        Map<String,String> maps = acceptingReportService.dealWithQueue(reportId);
        if(maps.size()<1){
            result.setMsg("暂无数据");
            result.setCode("2004");
            return result;
        }
        result.setData(maps);
        result.setMsg("请求成功");
        result.setCode("200");
        long end = System.currentTimeMillis();
        logger.info("定时任务结束，共耗时：[" + (end-begin) / 1000 + "]秒");
        return result;

    }




    /**
     */
    @ResponseBody
    @RequestMapping("/synchroGeneratorNo")
    public Result<Void> synchroGeneratorNo(HttpServletRequest request){
        //   customerEntryService.synchroGeneratorNo();
        return Result.ok();
    }

    /**
     */
    @ResponseBody
    @RequestMapping("/updateCustomerPlanEntry")
    public Result<Void> updateCustomerPlanEntry(HttpServletRequest request){
        String id = request.getParameter("id");
        String code = request.getParameter("code");
        if(StringUtil.isBlank(id)&& StringUtil.isBlank(code)){
            return Result.fail("2003","参数为空");
        }
        customerEntryService.updateCustomerPlanEntry(id,code);
        return Result.ok();
    }

    /**
     * 修改全部的无方案明细的数据
     */
    @ResponseBody
    @RequestMapping("/updateCustomerPlanDetil")
    public Result updateCustomerPlanDetil(HttpServletRequest request){
        List<Record> list = Db.find("SELECT b.id FROM crm_customer_entry b LEFT JOIN crm_plan_material_entry a  ON b.id=a.entry_id WHERE a.id IS NULL AND b.status IN('3','4','5','6','7','8','9','10','11','a')");
        if(list.size()>0){
            for(Record rd:list){
                customerEntryService.updateCustomerPlanEntry(rd.getStr("id"),"");
            }
            return Result.ok();
        }
        return Result.fail("查无数据");
    }

    /**
     * 第一次进件申请
     */
    @ResponseBody
    @RequestMapping(value = "/saveIncomingApplication")
    public Result saveIncomingApplication(@RequestBody AddIncomingApplication addIncomingApplication,HttpServletRequest request){
        String userId=addIncomingApplication.getUserId();
        logger.info(">>>>>>>>>>userId:{}",userId);
        try {
            Operator operator = getOperatorByTwo(userId);
            customerEntryExtraService.addIncomingApplication(addIncomingApplication,operator);
        }catch (IllegalArgumentException i){
            return Result.fail(i.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            logger.error(">>>>>>>>>>>>>>>>>>>saveIncomingApplication  e:{}",e);
            return Result.fail("内部错误!");
        }
        return Result.ok();
    }

    /**
     * 第二次进件申请
     */
    @ResponseBody
    @RequestMapping(value = "/nextIncomingApplication")
    public Result nextIncomingApplication(@RequestBody AddIncomingApplication addIncomingApplication,HttpServletRequest request){

        String userId=addIncomingApplication.getUserId();
        try {
            Operator operator = getOperatorByTwo(userId);
            customerEntryExtraService.supplyIncomingApplication(addIncomingApplication,operator);
        }catch (IllegalArgumentException i){
            return Result.fail(i.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            logger.error(">>>>>>>>>>>>>>>>>>>nextIncomingApplication  e:{}",e);
            return Result.fail("内部错误!");
        }
        return Result.ok();
    }

    /**
     * 征信查询
     */
    @ResponseBody
    @RequestMapping(value = "/lookCreditResult")
    public Result lookCreditResult(HttpServletRequest request){
        String entryId=request.getParameter("entryId");
        CustomerEntry entry = customerEntryService.getById(entryId);
        operatingLeaseService.investigation(entry);
        Result result=new Result();
        result.setOk();
        result.data(entry);
        return result;

    }

    /**
     * 进件状态 查询
     */
    @ResponseBody
    @RequestMapping(value = "/lookApplyResult")
    public Result lookApplyResult(HttpServletRequest request){
        String entryId=request.getParameter("entryId");
//        CrmCustomerIncomingApplication application=operatingLeaseService.incomingParts(entryId);
        /*CrmCustomerIncomingApplication application=applicationDao.getByEntryId(entryId);*/
        Result result=new Result();
        result.setOk();
//        result.data(application);
        return result;
    }

    /**
     * 获取民族
     */
    @ResponseBody
    @RequestMapping(value = "getNationals")
    public Result getNationals(){
        List<SelectVo> list= Nationals.getNationalList();
        Result result= new Result();
        result.setOk();
        result.data(list);
        return result;
    }

    //进件申请的详情
    @ResponseBody
    @RequestMapping(value = "/getOnceIncomingApplication")
    public Result getOnceIncomingApplication(HttpServletRequest request){
        String entryId=request.getParameter("entryId");
        CustomerEntry entry = customerEntryService.getById(entryId);
        CrmCustomerIncomingApplication application=applicationDao.getByEntryId(entryId);
        AddIncomingApplication vo=new AddIncomingApplication();
        if(application!=null){
            CrmCustomerIncomingApplicationBasic basic=basicDao.getByApplicationId(application.getId());
            CrmCustomerIncomingApplicationPerInfo perInfo=perInfoDao.getByApplicationId(application.getId());
            if(perInfo!=null && StringUtil.isNotBlank(perInfo.getMailingAddr())){
                String[] arr=perInfo.getMailingAddr().split(",");
                perInfo.setProvince(arr[0]);
                perInfo.setCity(arr[1]);
                perInfo.setArea(arr[2]);
            }
            CrmCustomerIncomingApplicationLeaseItem leaseItem=leaseItemDao.getByEntryId(entryId);
            vo.setApplicationBasic(basic);
            vo.setPerInfo(perInfo);
            vo.setLeaseItem(leaseItem);
        }
        vo.setEntryId(entryId);
        Result result=new Result();
        result.setOk();
        result.data(vo);
        return result;
    }

    //审核进件申请
    @ResponseBody
    @RequestMapping(value = "examineIncomingApplication")
    public Result examineIncomingApplication(String entryId,String result,String failReason,String userId){
        logger.info(">>>>>>>>>>>>small examineIncomingApplication entryId:{},result:{}",entryId,result);
        Operator operator = getOperatorByTwo(userId);
        if(SourceConstants.TWO.equals(result) && StringUtil.isBlank(failReason)){
            return Result.fail("请输入审核不通过原因!");
        }
        try{
            customerEntryExtraService.examineIncomingApplication(entryId,operator,result,failReason,"","","","","");
        }catch (Exception e){
            e.printStackTrace();
            logger.info(">>>>>>>>>>>>examineIncomingApplication  e:{} ",e);
            return Result.fail("内部错误!");
        }
        return Result.ok();
    }


    @ResponseBody
    @RequestMapping(value = "/getProvince")
    public Result getProvince(){
        //地址信息
        List<Record> pros = AddressUtils.getProvincesList();
        Result result=new Result();
        result.setOk();
        result.data(pros);
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/getCityByPros")
    public Result getCityByPros(HttpServletRequest request){
        String provinceId=request.getParameter("provinceId");
        //地址信息
        List<Record> citys = AddressUtils.getCitysByProId(provinceId);
        Result result=new Result();
        result.setOk();
        result.data(citys);
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/getAreaByCity")
    public Result getAreaByCity(HttpServletRequest request){
        String cityId=request.getParameter("cityId");
        //地址信息
        List<Record> areas = AddressUtils.getAreaByCityId(cityId);
        Result result=new Result();
        result.setOk();
        result.data(areas);
        return result;
    }

    /**
     * 小程序首页统计，包括代理商/平台账号
     */
    @ResponseBody
    @RequestMapping(value = "getHomeStatistics")
    public Result getHomeStatistics(HttpServletRequest request) {
        Map<String, String> map = getParams(request);
        Operator operator = getOperatorBy(request);
        String userId = map.get("userId");
        User user = userDao.getById(userId);
        boolean isShow = true;
        if (User.USER_TYPE_ADVISOR.equals(user.getUserType())) {
            CrmTraderEmploye employe = traderEmployeService.findByUserId(user.getId());
            map.put("engineerId", employe.getId());
        }
        else if (User.USER_TYPE_WXG.equals(user.getUserType())) {
            Record r = CrmUtils.getByUserId(user);
            if (!AuthUtils.checkMiniOptPremissForEmp(r.getStr("id"), "NULL")) {
                isShow = false;
            }
        }
        Result result = new Result<>();
        result.setOk();
        Record record = customerEntryService.homeStatistics(map, user, isShow,operator);
        result.setData(new Gson().toJson(record));

        return result;
    }

    @ResponseBody
    @RequestMapping(value = "getUsedMaterialInfo")
    public Result getUsedMaterialInfo(String entryId) {

        Result result = new Result<>();
        List<Record> records;
        Map<String,Object> map = new HashMap<>();
        List<CrmPlanMaterialEntry> usedByEntryId;
        List<ProjectSettingVo> projectSettingList = new ArrayList<>();
        CustomerEntry entry = customerEntryService.getById(entryId);
        if (StringUtil.isNotBlank(entry.getPartnerId()) && "04".equals(entry.getPartnerId())){
            String projectIds[] = entry.getProjectId().split(",");
            List<Record> projectList = projectInfoSettingService.getEntryProjectByEntryId(entryId);
            for(Record record : projectList){
                records = customerEntryComponentService.findModelByEntryProjectId(entryId,record.get("projectId"));
                List<CrmCustomerEntryComponentVo> nbqMap = new ArrayList<>();
                CrmCustomerEntryComponentVo zjMap = new CrmCustomerEntryComponentVo();
                for(Record re : records){
                    //逆变器
                    if ("1".equals(re.getStr("item_type"))){
                        CrmCustomerEntryComponentVo customerEntryComponentVo = new CrmCustomerEntryComponentVo();
                        customerEntryComponentVo.setModel(re.getStr("model"));
                        customerEntryComponentVo.setMaterialModel(re.getStr("material_model") == null ? "" : re.getStr("material_model"));
                        customerEntryComponentVo.setNum(re.getInt("num"));
                        nbqMap.add(customerEntryComponentVo);
                    }
                    //组件
                    if ("3".equals(re.getStr("item_type"))){
                        zjMap.setModel(re.getStr("model"));
                        zjMap.setMaterialModel(re.getStr("material_model") == null ? "" : re.getStr("material_model"));
                        zjMap.setNum(re.getInt("num"));
                    }
                }
                ProjectSettingVo settingVo = new ProjectSettingVo();
                settingVo.setProjectId(record.get("projectId"));
                settingVo.setProjectCode(record.get("projectCode"));
                settingVo.setProjectName(record.get("projectName"));
                settingVo.setFilingType(record.get("filingType"));
                settingVo.setRoofType(record.get("roofType"));
                settingVo.setPayCycle(record.get("payCycle"));
                settingVo.setNbqMap(nbqMap);
                settingVo.setZjMap(zjMap);
                projectSettingList.add(settingVo);
            }
            usedByEntryId = customerEntryService.findByEntryProjectId(entryId,projectIds);
        }else {
            usedByEntryId = customerEntryService.findUsedByEntryId(entryId);
        }
        Record info2 = formSetService.getListByCondition("02", entry.getPartnerId());
        FormSetPageVo vo = info2.get("component1_model");
        boolean flag = true;//不需要型号
        if (vo != null && "1".equals(vo.getStatus())){
            flag = false;//需要型号
        }
        List<CrmPlanMaterialEntryVo> lists=new ArrayList<>();
        for(CrmPlanMaterialEntry obj:usedByEntryId){
            CrmPlanMaterialEntryVo a=new CrmPlanMaterialEntryVo();
            BeanUtil.copyProperties(obj,a);
            a.setMaterialBrand(customerEntryService.findVoByEntryId(a.getCode()));
            if (flag){
                a.setModel("");
            }
            lists.add(a);
        }
        String warehouseId = customerEntryService.getWarehouseId(entryId);
        if(!"04".equals(entry.getPartnerId())){
            records = customerEntryComponentService.findModelByEntryId(entryId);
            List<Map<String,String>> nbqList = new ArrayList<>();
            Map<String,String> zjMap = new HashMap<>();
            for (Record record : records) {
                //逆变器
                if ("1".equals(record.getStr("item_type"))){
                    Map<String,String> nbqMap = new HashMap<>();
                    nbqMap.put("model",record.getStr("model"));
                    nbqMap.put("materialModel",record.getStr("material_model") == null ? "" : record.getStr("material_model"));
                    nbqMap.put("num",String.valueOf(record.getInt("num")));
                    nbqList.add(nbqMap);
                }
                //组件
                if ("3".equals(record.getStr("item_type"))){
                    zjMap.put("model",record.getStr("model"));
                    zjMap.put("materialModel",record.getStr("material_model") == null ? "" : record.getStr("material_model"));
                    zjMap.put("num",String.valueOf(record.getInt("num")));
                }
            }
            map.put("nbqMap",new Gson().toJson(nbqList));
            map.put("zjMap",new Gson().toJson(zjMap));
        }
        map.put("warehouseId",warehouseId);
        map.put("materialEntryList",new Gson().toJson(lists));
        map.put("projectSettingList",new Gson().toJson(projectSettingList));
        result.setOk();
        result.setData(map);
        return result;

    }

    /**
     * 使用物料
     */
    @ResponseBody
    @RequestMapping(value = "usedMaterial")
    public Result usedMaterial(UsedMaterialReq req) {
        Result ret = Result.ok();
        StringBuilder sb = new StringBuilder();
        String[] barcodes = req.getBarcode().split(",");
        for (int i = 0; i < barcodes.length; i++) {
            req.setBarcode(barcodes[i]);
            Result result = customerEntryService.usedMaterial(req);
            if (!"200".equals(result.getCode())) {
                sb.append(String.format("物料:%s添加失败:%s ", barcodes[i], result.getMsg()));
            }
        }
        if(StringUtil.isNotBlank(sb.toString())){
            ret = Result.fail(sb.toString());
        }
        return ret;
    }

    /**
     * 使用前 校验物料条码是否有效
     */
    @ResponseBody
    @RequestMapping(value = "checkMaterialCode")
    public Result checkMaterialCode(UsedMaterialReq req) {
        return customerEntryService.checkMaterialCode(req);
    }

    //使用逆变器
    @ResponseBody
    @RequestMapping(value = "saveMaterialSN")
    public Result saveMaterialSN(@RequestBody @Validated InstallReq req) {
        try {
            Operator currentUser = getOperatorByTwo(req.getUserId());
            return customerEntryService.saveMaterialSN(req.getSnList(), currentUser);
        } catch (BusinessException e) {
            return Result.fail(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.ok();
    }

    //使用并网箱、支架
    @ResponseBody
    @RequestMapping(value = "usedMaterialOther")
    public Result usedMaterial2(@RequestBody UsedMaterialReq req) {
        return customerEntryService.usedMaterial2(req);
    }

    @ResponseBody
    @RequestMapping(value = "saveWarehouse")
    public Result saveWarehouse(String entryId, String warehouseId) {
        if (StringUtil.isBlank(entryId)) {
            Result.ok();
        }
        return customerEntryService.saveWarehouse(entryId,warehouseId);
    }

    /**
     * 删除使用物料
     */
    @ResponseBody
    @RequestMapping(value = "deleteUsedRecord")
    public Result deleteUsedRecord(String ids) {
        return customerEntryService.deleteUsedRecord(ids);
    }

    /**
     * 查询安装组件信息：使用最多的规格，数量 ，实际安装容量
     */
    @ResponseBody
    @RequestMapping(value = "getActualCapacity")
    public Result getActualCapacity(String entryId) {
        return customerEntryService.findActualCapacity(entryId);
    }

    @ResponseBody
    @RequestMapping("/getRectificationList")
    public Result getRectificationList() {
        Result result = new Result<>();
        List<Record> list = rectificationSettingService.getList(null);
        result.setOk();
        result.setData(list);
        return result;
    }

    /**
     * 整改审核
     */
    @ResponseBody
    @RequestMapping("/rectificationAudit")
    public Result rectificationAudit(HttpServletRequest request) {
        String id = request.getParameter("id");
        if (StringUtil.isBlank(id)) {
            return Result.fail("2001", "项目信息为空");
        }
        String type = request.getParameter("type");
        String userId = request.getParameter("userId");
        String auditComments = request.getParameter("auditComments");
        Operator operator = getOperatorByTwo(userId);
        try {
            if ("1".equals(type)) {
                // 变更类型
                String rectificationId = request.getParameter("rectificationId");
                return customerEntryService.approved(id, operator, rectificationId, auditComments);
            } else {
                return customerEntryService.auditFailed(id, operator, auditComments);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("变更审核失败:{}", e);
            return Result.fail("操作失败");
        }
    }

    /**
     * 邀请签约
     * entryId  电站id
     */
    @ResponseBody
    @RequestMapping(value = "askToContract")
    public Result askToContract(HttpServletRequest request){
        // 电站id
        String entryId = request.getParameter("entryId");
        String userId = request.getParameter("userId");
        logger.info(">>>>>>>>>>>>>>>>>>>>askToContract  entryId:{},userId:{}",entryId,userId);
        Operator operator = getOperatorByTwo(userId);
        try{
            signContractService.inviteSign(entryId,operator);
            return Result.ok();
        }catch (BusinessException b){
            logger.error(">>>>>>>>>>>>inviteSignQr  b:{}",b);
            return Result.fail("邀请签约失败：" + b.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            logger.error(">>>>>>>>>>>>inviteSignQr  e:{}",e);
            return Result.fail("邀请签约失败：" + e.getMessage());
        }
    }

    /**
     * 获取所属仓库列表（安装时）
     */
    @ResponseBody
    @RequestMapping("/getWarehouseList")
    public Result getWarehouseList(String userId){
        Result result = new Result();
        String traderId;
        User user = userDao.get(userId);
        if ("6".equals(user.getUserType())) {
            traderId = CrmUtils.getTraderIdByUserId(userId);
        } else {
            traderId = CrmUtils.getUserRelId(user);
        }
        CrmTrader trader = traderService.getById(traderId);
        List<Record> list;
        if (trader != null && Objects.equals("2", trader.getType())) {
            list = MaterialUtils.findWarehouseBySecondTrader(traderId);
        } else {
            list = MaterialUtils.findMaterialWarehouseByAscriptionId(traderId);
        }
        result.setOk();
        result.setData(list);
        return result;
    }

    /**
     * 获取施工人员数量(施工人员这个角色维护的人员在8（不含）个以内时，代理商不可录信息)
     */
    @ResponseBody
    @RequestMapping(value = "getEmpCountByRole")
    public Result  getEmpCountByRole(String traderId){
       /* if(StringUtil.isBlank(traderId)){
            return Result.fail("必传项不能为空!");
        }
        String traderIdss= "";
        Operator operator = getOperatorByTwo(traderId);
        if ("6".equals(operator.getUserType())) {
            traderIdss = CrmUtils.getTraderIdByUserId(traderId);
        } else {
            traderIdss = CrmUtils.getTraderId(traderId);
        }
        Long count=traderService.getEmpCountByRole(TraderEmpConstants.TRADER_ROLE_ID, traderIdss);*/
        return Result.success(10);
    }


    /**
     * 获取联行号
     */
    @ResponseBody
    @RequestMapping(value = "findLinkNumberList")
    public Object findLinkNumberList(HttpServletRequest request){
        Map<String, String> params = getParams(request);
        LayuiPage<Record> page = null;
        if (StringUtil.isNotBlank(request.getParameter("page"))) {
            page = new LayuiPage<>(request);
        }
        List<Record> list = service.getList(params,page);
        if (page != null) {
            page.setCode("200");
            return page.renderJson();
        }
        return list;
    }

    /**
     * 预审查询
     */
    @ResponseBody
    @RequestMapping(value = "findResult")
    public Object findResult(HttpServletRequest request) {
        String entryId = request.getParameter("id");
        return customerEntryService.findPreauditStatus(entryId);
    }

    /**
     * 获取地图导航二维码
     */
    @ResponseBody
    @RequestMapping(value = "createQrcode")
    public Object createQrcode(HttpServletRequest request) {
        String content = request.getParameter("content");
        /** 1.创建临时文件夹  */
        String rootPath = request.getSession().getServletContext().getRealPath("/");
        String name = rootPath + "qrcode";
        File temDir = new File(name);
        if (!temDir.exists()) {
            temDir.mkdirs();
        }
        String fileName = IdGen.uuid() + ".jpg";
        String realPath = name + File.separator + fileName;
        System.out.println(realPath);
        File downloadFile = null;
        try {
            String url = "https://www.nhhyy.com/createQrcode?lonLat=" + content;
            QRCodeUtil.encode(url, "", realPath, true);
            //文件的目录
            downloadFile = new File(realPath);
            //上传到阿里云服务器
            MultipartFile multipartFile = new MockMultipartFile("file",downloadFile.getName(),null,new FileInputStream(downloadFile));
            String filename= multipartFile.getOriginalFilename();
            String extName = filename.substring(filename.lastIndexOf(".")).toLowerCase();
            String fileInfo = null;
            String path="";
            try {
                fileInfo = AliyunOSSClientUtil.uploadImage(multipartFile.getBytes(), extName,filename.replace(extName,""));
                if(StringUtils.isNotBlank(fileInfo)){
                    path= com.sifang.modules.sys.common.utils.StringUtil.convertBackSlant(fileInfo);
                }
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            return path;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (!downloadFile.exists()) {
                return null;
            }
            QRCodeUtil.deleteFile(downloadFile);
        }
        return null;
    }

    /**
     * 校验代理商员工授权
     */
    @ResponseBody
    @RequestMapping(value = "checkTraderEmpAuth")
    public Object checkTraderEmpAuth(HttpServletRequest request) {
        String userId = request.getParameter("userId");
        String permission = request.getParameter("permission");
        Result<Object> result = new Result<>();
        result.setOk();
        result.setData(AuthUtils.checkMiniTraderPremissForEmp(userId, permission));
        return result;
    }

    /**
     * 客户管理 里面的统计
     */
    @ResponseBody
    @RequestMapping(value = "customerManagementStatic")
    public Result customerManagementStatic(HttpServletRequest request){
        Map<String, String> map = getParams(request);
        Operator operator = getOperatorBy(request);
       /* String userId = map.get("userId");
        User user = userDao.getById(userId);
        if (User.USER_TYPE_ADVISOR.equals(user.getUserType())) {
            CrmTraderEmploye employe = traderEmployeService.findByUserId(user.getId());
            map.put("engineerId", employe.getId());
        }*/
        Record record=customerEntryService.customerManagementStatic(map,operator);
        return Result.success(record);
    }

    //查看授权合同--返回合同地址
    @ResponseBody
    @RequestMapping(value = "lookAuthBook")
    public Result lookAuthBook(HttpServletRequest request){
        String idCode=request.getParameter("idCode");
        String partnerId=request.getParameter("partnerId");
        String pathUrl=customerEntryService.lookAuthBook(idCode,partnerId);
        Map<String,Object> resultMap=new HashMap<>();
        resultMap.put("pathUrl",pathUrl);
        return Result.success(resultMap);
    }

    /**
     * 获取的表单设置
     */
    @ResponseBody
    @RequestMapping(value = "getFormSet")
    public Result getFormSet(HttpServletRequest request) {
        String stage = request.getParameter("stage");
        String partner = request.getParameter("partner");
        String groupType = request.getParameter("groupType");
        return Result.success(formSetService.getListByCondition(stage, partner, groupType));
    }


    /**
     * 获取全部表单设置
     */
    @ResponseBody
    @RequestMapping(value = "getAllConditionList")
    public Result getAllConditionList(HttpServletRequest request) {
        String partner = request.getParameter("partner");
        return Result.success(formSetService.getAllConditionList(partner));
    }


    /**
     * 提交档案
     */
    @ResponseBody
    @RequestMapping(value = "saveArchives")
    public Result saveArchives(@RequestBody @Validated SubmitArchivesReq req,HttpServletRequest request) {
        try {
            Operator operator = getOperatorBy(request);
            return orgFilesService.submitArchives(req,operator);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 档案审核
     */
    @ResponseBody
    @RequestMapping(value = "auditArchives")
    public Result auditArchives(@RequestBody @Validated AuditArchivesReq req) {
        try {
            return orgFilesService.auditArchives(req, getOperatorByTwo(req.getUserId()));
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(e.getMessage());
        }
    }

    @ResponseBody
    @RequestMapping(value = "/findTypeReferenceList")
    public Result findTypeReferenceList(String typeId) {
        List<CrmProjectTypeReference> reflist=projectInstallService.getProjectReference(typeId);
        if(reflist.size()==0){
            reflist = Lists.newArrayList();
        }
        return Result.success(reflist);
    }

    @ResponseBody
    @RequestMapping(value = "/findTypeReferenceListNew")
    public Result findTypeReferenceListNew(String typeId) {
        List<ProjectTypeDetailVo> reflist=projectInstallService.getProjectReference2(typeId);
        if(reflist.size()==0){
            reflist = Lists.newArrayList();
        }
        return Result.success(reflist);
    }

    /**
     * 获取客户列表
     */
    @ResponseBody
    @RequestMapping(value = "getTenantList")
    public Result getTenantList(HttpServletRequest request) {
        Operator operator = getOperatorBy(request);
        String tenantType = request.getParameter("tenantType");
        return tenantService.getListByUserAuth(operator, tenantType);
    }

    /**
     * 获取客户详情
     */
    @ResponseBody
    @RequestMapping(value = "getTenantDetail")
    public Result getTenantDetail(String id) {
        return tenantService.getDetailById(id);
    }

    /**
     * 近三天发电量
     */
    @ResponseBody
    @RequestMapping(value = "getDataInThreeDays")
    public Result getDataInThreeDays(String id) {
        return Result.success(collectDataService.getDataInThreeDays(id));
    }



    @ResponseBody
    @RequestMapping(value = "/getCompany")
    public Result getCompany(HttpServletRequest request) {
        String province = request.getParameter("province");
        String city = request.getParameter("city");
        String area = request.getParameter("area");
        String partner = request.getParameter("partner");
        String filingType = request.getParameter("filingType");
        List<Record> projectVo = new ArrayList<>();
        if(StringUtil.isNotBlank(province) && StringUtil.isNotBlank(city) &&
                StringUtil.isNotBlank(area) && StringUtil.isNotBlank(partner)){
            Map<String,String> map = new HashMap<>();
            map.put("province",province);
            map.put("city",city);
            map.put("area",area);
            map.put("partner",partner);
            map.put("filingType",filingType);
            projectVo = projectCompanyDao.getCompanyByArea(map);
        }
        return Result.success(projectVo);
    }

    @ResponseBody
    @RequestMapping("getTraderList")
    public Result getTraderList(HttpServletRequest request){
        String userId = request.getParameter("userId");
        String keyword = request.getParameter("keyword");
        String partner = request.getParameter("partner");
        User user = userDao.get(userId);
        Map<String,String> map = new HashMap<>();
        if (StringUtil.isNotBlank(keyword)) {
            map.put("name", keyword.trim());
        }
        if (StringUtil.isNotBlank(partner)) {
            map.put("partner", partner);
        }
        List<Record> traderList = new ArrayList<>();
        if(User.USER_TYPE_WXG.equals(user.getUserType())){  //平台员工
            EmployeRoleUtils.getUserDataAuthority(user.getId(),map);
            traderList  = traderService.getTraderList(map);
        }
        return Result.success(traderList);
    }


    @ResponseBody
    @RequestMapping("isByIdCode")
    public Result isByIdCode(HttpServletRequest request){
        String idCode = request.getParameter("idCode");
        String userId = request.getParameter("userId");
        String tenantType = request.getParameter("tenantType");
        String traderId = CrmUtils.getCurrentTraderId(userId);
        Map<String,String> map = new HashMap<>();//平台员工
        List<Record> customerEntry = customerEntryService.getCustomerEntryInfoByIdCode(idCode,tenantType);
        if (customerEntry.size() > 0){
            for (Record entry : customerEntry) {
                if(CustomerEntryConstants.TENANT_TYPE_COMPANY.equals(entry.getStr("tenant_type"))){
                    map.put("status","1");
                    continue;
                }
                map.put("mobile",entry.getStr("mobile"));
                String distributorId = entry.getStr("trader_id");
                if (distributorId.equals(traderId)){
                    map.put("status","1");    //用户已存在并且业务员是当前代理商
                }else {
                    map.put("status","2");      //用户已存在但是业务员不是当前代理商
                }
            }
        }else {
            map.put("mobile","");
            map.put("status","0");  //用户不存在
        }
        return Result.success(map);
    }
    /**
     * 小程序审批记录
     */
    @ResponseBody
    @RequestMapping("/getOptList")
    public Result getOptList(String entryId) {
        Result result = new Result();
        if (StringUtils.isBlank(entryId)){
            return Result.fail("entryId为空");
        }
        List<CustomerEntryMsg> customerEntryMsgList = new ArrayList<>();
        List<String> typeList = new ArrayList<>();
        Collections.addAll(typeList,"85","87","88","89","90","11","6","63","62","65","661","662","91","92","93","94","511","512","513","514","51","52","502","519","506","507","515","516");
        //新增电站变更 508 505 509 510
        Collections.addAll(typeList,"508","505","509","510");
        List<Record> records = customerEntryMsgService.listOptRecordByEntryId2(entryId);
        for (Record record : records) {
            CustomerEntryMsg customerEntryMsg = new CustomerEntryMsg();
            String type = record.getInt("type").toString();
            if (typeList.contains(type)){
                customerEntryMsg.setId(record.getStr("id"));
                customerEntryMsg.setCustomerEntryId(record.getStr("customer_entry_id"));
                customerEntryMsg.setType(record.getInt("type").toString());
                customerEntryMsg.setOperator(record.getStr("operator"));
                customerEntryMsg.setOperatorId(record.getStr("operator_id"));
                customerEntryMsg.setContent(record.getStr("content"));
                customerEntryMsg.setOperateTime(record.get("operate_time"));
                customerEntryMsgList.add(customerEntryMsg);
            }
        }
        result.setCode("200");
        result.setData(JsonKit.toJson(customerEntryMsgList));
        return result;
    }

    /**
     * 小程序获取字典集
     * @param code 字典码
     * @param capitalId 资方id
     * @return
     */
    @ResponseBody
    @RequestMapping("/getDictionaryList")
    public Result getDictionaryList(String code ,String capitalId){
        List<Record> records = sysCapitalDictDao.getDictionaryList(code, capitalId);
        return Result.success(records);
    }
    /**
     * 小程序获取字典下拉选择
     */
    @ResponseBody
    @RequestMapping(value = "getAllDictionarySelect")
    public Result getAllDictionarySelect(String capitalId){
        List<Record> angle_azimuth= sysCapitalDictDao.getDictionaryList("angle_azimuth",capitalId);
        List<Record> bp_relation= sysCapitalDictDao.getDictionaryList("bp_relation",capitalId);
        List<Record> roof_type  = sysCapitalDictDao.getDictionaryList("roof_type", capitalId);
        //并网电压等级
        List<Record> voltage_classes = sysCapitalDictDao.getDictionaryList("voltage_classes",capitalId);
        Map<String,Object> resultMap=new HashMap<>();
        resultMap.put("angle_azimuth",angle_azimuth);
        resultMap.put("bp_relation",bp_relation);
        resultMap.put("roof_type",roof_type);
        resultMap.put("voltage_classes",voltage_classes);
        //结构类型
        List<Record> structure_type = sysCapitalDictDao.getDictionaryList("structure_type",capitalId);
        //地面类型
        List<Record> ground_type = sysCapitalDictDao.getDictionaryList("ground_type",capitalId);
        resultMap.put("structure_type",structure_type);
        resultMap.put("ground_type",ground_type);
        return Result.success(resultMap);
    }
    //合同列表数据
    @ResponseBody
    @RequestMapping(value = "contractListDate")
    public Object getContractListDate(HttpServletRequest request) {
        LayuiPage<Record> page = new LayuiPage<>(request);
        Map<String, String> map = getParams(request);
        Operator operator = getOperatorBy(request);
        User user = userDao.getById(operator.getUserId());
        if (User.USER_TYPE_WXG.equals(user.getUserType())) {
            Record r = CrmUtils.getByUserId(user);
            if (!AuthUtils.checkMiniOptPremissForEmp(r.getStr("id"), "NULL")) {
                page.setCode("200");
                page.setData(new ArrayList<>());
                page.setCount(0l);
                return page.renderJson();
            }
        }
        contractManagementService.listDate(page, map,operator);
        return page.renderJson();
    }
    //提交预审
    @ResponseBody
    @RequestMapping("batchAdmit")
    public Result batchAdmit(HttpServletRequest request){
        String userId = request.getParameter("userId");
        String entryId = request.getParameter("entryId");
        List<String> ids = Arrays.asList(entryId.split(","));
        User user = userDao.get(userId);
        Operator operator = Operator.of(user);
        BatchOperateReq req = new BatchOperateReq();
        req.setIds(ids);
        Result result = null;
        try {
            result =  customerEntryService.batchAdmit(req,operator);
        }catch (Exception e){
            logger.error(e.getMessage(), e);
            return Result.fail(e.getMessage());
        }
        return result;
    }

    /**
     * 小程序获取风雪压等级
     * @param province
     * @param city
     * @param area
     * @return
     */
    @ResponseBody
    @RequestMapping("getPressureLevel")
    public Result getPressureLevel(String province,String city ,String area){
        Record record = windSnowPressureLevelService.findPressureLevel(province, city, area);
        if (record == null){
            record = new Record();
            record.set("wind_pressure", "");
            record.set("snow_pressure", "");
            record.set("pressure_level", "");
        }
        return Result.success(record);
    }
}
