package com.sifang.modules.customer.controller;

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.StrKit;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.completionrectification.dao.CompletionDao;
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.PartnerConstants;
import com.sifang.modules.customer.constant.SourceConstants;
import com.sifang.modules.customer.constant.TraderConstants;
import com.sifang.modules.customer.dao.*;
import com.sifang.modules.customer.entity.*;
import com.sifang.modules.customer.excel.MaterialExcel;
import com.sifang.modules.customer.form.*;
import com.sifang.modules.customer.pdf.PdfReport;
import com.sifang.modules.customer.utils.CustomerEntryUtil;
import com.sifang.modules.customer.utils.EmployeRoleUtils;
import com.sifang.modules.customer.vo.CustomerEntryMsgVo;
import com.sifang.modules.esign.service.RedSunAskAuthContractService;
import com.sifang.modules.insurance.dao.InsuranceListDao;
import com.sifang.modules.insurance.entity.CrmInsuranceList;
import com.sifang.modules.platform.service.AddressService;
import com.sifang.modules.platform.utils.AddressUtils;
import com.sifang.modules.setting.constant.EmpRoleConstants;
import com.sifang.modules.setting.service.MemberService;
import com.sifang.modules.site.siteInfo.service.SiteEmployeeService;
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.RoofSetFormVo;
import com.sifang.modules.sunshine.partnerManagement.entity.CrmPartner;
import com.sifang.modules.sunshine.partnerManagement.service.PartnerService;
import com.sifang.modules.sunshine.partnerManagement.service.PartnerStaffService;
import com.sifang.modules.supply.setting.dao.CrmSupplyWarehouseDao;
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.dao.SysCapitalDictDao;
import com.sifang.modules.sys.entity.Ascription;
import com.sifang.modules.sys.entity.Operator;
import com.sifang.modules.sys.service.WindSnowPressureLevelService;
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.util.excel.ExportExcel;
import com.sifang.modules.sys.web.BaseExceptionController;
import com.sifang.modules.utils.util.IsInteger;
import com.sifang.modules.youkua.service.NhPowerStationService;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.tools.ant.taskdefs.condition.Http;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

@Controller
@RequestMapping(value = "${adminPath}/customerEntry")
public class CustomerEntryController extends BaseExceptionController {


    @Autowired
    CustomerEntryService customerService;

    @Autowired
    CustomerEntryMsgService customerEntryMsgService;

    @Autowired
    TraderService traderService;

    @Autowired
    ProjectInstallService projectInstallService;

    @Autowired
    MemberService memberService;

    @Autowired
    PlanService planService;

    @Autowired
    ProjectInfoSettingService projectService;

    @Autowired
    SiteEmployeeService siteEmployeeService;

    @Autowired
    private OrderMarkSettingService markSettingService;

    @Autowired
    TraderEmployeService traderEmployeService;

    @Autowired
    private CrmReasonForApplicationService applicationService;

    @Autowired
    AddressService addressService;

    @Autowired
    SfCacheService cacheService;

    @Autowired
    private CrmCustomerIncomingApplicationBasicDao basicDao;

    @Autowired
    private CrmCustomerIncomingApplicationPerInfoDao perInfoDao;

    @Autowired
    private CrmCustomerIncomingApplicationRetailPayInfoDao retailPayInfoDao;

    @Autowired
    private CrmCustomerIncomingApplicationDao applicationDao;

    @Autowired
    private CrmCustomerIncomingApplicationLeaseItemDao equipInfoNormalDao;

    @Autowired
    private PartnerService partnerService;

    @Autowired
    private PartnerStaffService staffService;

    @Autowired
    private RectificationSettingService rectificationSettingService;

    @Autowired
    private CustomerEntryComponentService customerEntryComponentService;

    @Autowired
    private CrmSupplyWarehouseDao supplyWarehouseDao;

    @Autowired
    private CustomerEntryToExamineService examineService;

    @Autowired
    private CrmYxIncomingProcessDao crmYxIncomingProcessDao;

    @Autowired
    private TenantYxBankCardDao tenantYxBankCardDao;

    @Autowired
    private YueXiuContractService yueXueContractService;

    @Autowired
    private CustomerEntryExtraService customerEntryExtraService;

    @Autowired
    private LinkNumberSettingService linkNumberSettingService;

    @Autowired
    private RedSunAskAuthContractService askAuthContractService;

    @Autowired
    private ProjectInfoSettingService projectInfoSettingService;

    @Autowired
    private FormSetService formSetService;

    @Autowired
    private CustomerEntrySurveyRecordDao surveyRecordDao;

    @Autowired
    private CustomerEntryOrgFilesDao orgFilesDao;

    @Autowired
    private CrmYxIncomingLogDao yxIncomingLogDao;

    @Autowired
    private CustomerEntryTenantDao tenantDao;

    @Autowired
    ProjectSettingDao projectDao;

    @Autowired
    ProjectPcdDao projectPcdDao;

    @Autowired
    ProjectCompanyDao projectCompanyDao;

    @Autowired
    TraderPcdDao traderPcdDao;

    @Autowired
    CompletionDao completionDao;

    @Autowired
    private ContractManagementDao contractManagementDao;

    @Autowired
    private NhPowerStationService nhPowerStationService;

    @Autowired
    private CrmEntryCombinerBoxGroupDao combinerBoxGroupDao;

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

    @Autowired
    private JedisPool jedisPool;

    private static final String FILE_PATH_TEMPLATE = System.getProperty("java.io.tmpdir") + "/tempdf/%s";

    @Value("${img.domain}")
    private  String OSS_URL;

    @Autowired
    private CrmCustomerIncomingApplicationInsuranceDao insuranceDao;

    @Autowired
    InsuranceListDao insuranceListDao;

    @Autowired
    private ProductLineSetService productLineSetService;

    @Autowired
    private SysCapitalDictDao sysCapitalDictDao;
    @Autowired
    private CrmCustomerEntryProjectDao crmCustomerEntryProjectDao;
    @Autowired
    private CrmCustomerEntryDesignDao crmCustomerEntryDesignDao;

    @Autowired
    private CrmCustomerEntrySurveyRecordDetailDao crmCustomerEntrySurveyRecordDetailDao;

    @Autowired
    private CrmCustomerEntrySurveyRecordDetailService recordDetailService;

    @Autowired
    private CrmAcceptingReportDetailDao crmAcceptingReportDetailDao;
    @Autowired
    private GuangFaManagemnetService guangFaManagemnetService;
    @Autowired
    private WindSnowPressureLevelService windSnowPressureLevelService;


    /**
     * 信息登记列表
     */
    @RequestMapping(value = "temporaryStorageList/{partner}")
    public String temporaryStorageList(Model model,@PathVariable("partner") String partner) {
        User user = UserUtils.getUser();
        model.addAttribute("user", user);
        String traderId=user.getTraderId();
        model.addAttribute("ifTop",user.getTraderType());
        List<Record> twoTrader=traderService.getTwoTrader(traderId);
        model.addAttribute("twoTrader",twoTrader);
        //施工人员 在8（不含）个以内时，代理商不可录信息
       /* Long count=traderService.getEmpCountByRole(TraderEmpConstants.TRADER_ROLE_ID,traderId);
        model.addAttribute("empCount",count);*/
        List<Record> list;
        if(StringUtil.isBlank(traderId)){
            list=memberService.getProjectLists();
        }else{
            list=memberService.getProjectByTraderLists(traderId);
        }
        //代理商列表
        List<Record> traderList = traderService.getTopTrader();
        model.addAttribute("traderList", traderList);
        List<Record> pros = addressService.getProvinces();
        model.addAttribute("province", pros);
        model.addAttribute("projectList",list);
        model.addAttribute("partner",partner);
        model.addAttribute("editBthPermission","XMGL_DZDACX_EDIT_B_"+partner);
        return "modules/yangguang/customer/entry/temporaryStorageList";
    }
    @RequestMapping(value = "infoAuthorizationList/{partner}")
    public String infoAuthorizationList(Model model,@PathVariable("partner") String partner) {
        model.addAttribute("partner",partner);
        return "modules/yangguang/customer/entry/infoAuthorizationList";
    }
    @ResponseBody
    @RequestMapping(value = "ajaxForInfoAuthorizationData")
    public Object ajaxForInfoAuthorizationData(HttpServletRequest request) {
        LayuiPage<Record> page = new LayuiPage<>(request);
        Map<String, String> params = getParams(request);
        User user = UserUtils.getUser();
        Operator operator = Operator.of(user.getId(), CrmUtils.getUserXM(user),user.getUserType());
        customerService.ajaxForInfoAuthorizationData(page, params, operator);
        return page.renderJson();
    }

    /**
     * 重新授权
     */
    @ResponseBody
    @RequestMapping(value = "reAuthorization")
    public Result reAuthorization(String idCode ,String mobile,String patnerId,String id){
        customerService.reAuthorization(idCode,mobile,patnerId,id);
        return Result.ok();
    }
    @RequestMapping(value = "uploadAuthorizationPage")
    public String uploadAuthorizationPage(Model model,String entryId){
        model.addAttribute("entryId",entryId);
        return "modules/yangguang/customer/entry/uploadAuthorizationPage";
    }
    //广发上传信息授权书
    @ResponseBody
    @RequestMapping(value = "uploadAuthorization")
    public Result uploadAuthorization(String entryId,String authorization){
        try {
            customerService.uploadAuthorization(entryId,authorization);
        }catch (IllegalArgumentException e ){
            return Result.fail(e.getMessage());
        }catch (RuntimeException e ){
            return Result.fail(e.getMessage());
        }catch (Exception e){
            return Result.fail("操作失败，"+e.getMessage());
        }
        return Result.ok();
    }

    /**
     * 信息登记列表数据
     * 查询'暂存','审核不通过'的电站数据
     */
    @ResponseBody
    @RequestMapping(value = "ajaxForTemporaryStorageData")
    public Object ajaxForTemporaryStorageData(HttpServletRequest request) {
        LayuiPage<Record> page = new LayuiPage<>(request);
        Map<String, String> params = getParams(request);
        if(!params.containsKey("credit") || StringUtil.isBlank(params.get("credit")) || ",".equals(params.get("credit"))){
            params.put("credit","0,1,2,3,5");
        }
        params.put("status", "0");
        User user = UserUtils.getUser();
        Operator operator = Operator.of(user.getId(), CrmUtils.getUserXM(user),user.getUserType());
        customerService.listWaitOrder(page, params, operator);
        return page.renderJson();
    }

    /**
     * 批量删除
     */
    @ResponseBody
    @RequestMapping(value = "batchDelete")
    public Result<Void> batchDelete(@RequestBody BatchOperateReq req) {
        logger.info("into batchDelete, req={}", req);
        customerService.batchDelete(req);
        return Result.ok();
    }

    /**
     * 批量申请准入
     */
    @ResponseBody
    @RequestMapping(value = "batchAdmit")
    public Result batchAdmit(@RequestBody BatchOperateReq req) {
        logger.info("into batchAdmit, req={}", req);
        User user = UserUtils.getUser();
        Operator operator = Operator.of(user);
        Result result = null;
        try {
            result =  customerService.batchAdmit(req,operator);
        }catch (Exception e){
            logger.error(e.getMessage(), e);
            return Result.fail(e.getMessage());
        }
        return result;
    }

    /**
     * 批量提交审核
     */
    @ResponseBody
    @RequestMapping(value = "batchAudit")
    public Result<Void> batchAudit(@RequestBody BatchOperateReq req) {
        logger.info("into batchAudit, req={}", req);
        return customerService.batchAudit(req);
    }


    @RequestMapping(value = "customerList/{partner}")
    public String CustomerList(@PathVariable("partner")String partner,Model model) {
        setCommonData(model);
        User user = UserUtils.getUser();
        if(StringUtil.isBlank(user.getId())){
            model.addAttribute("types", "1");
            //  return "redirect:" + Global.getAdminPath() + "/login";
        }
        model.addAttribute("user", user);
        //系统工程师列表
        List<Record> empList = siteEmployeeService.findProjectEmpList("1,b,c");
        model.addAttribute("empList", empList);
        model.addAttribute("typeList", markSettingService.getAllMarkType("2"));
        List<Record> pros = addressService.getProvinces();
        model.addAttribute("province", pros);
        model.addAttribute("partner",partner);
        //屋顶类型
        List<Record> roofTypeList = sysCapitalDictDao.getDictionaryList("roof_type", partner);
        model.addAttribute("roofTypeList",roofTypeList);
        //按钮权限
        model.addAttribute("toExaminePermission","XMGL_KCDA_SJSH_B_"+partner);
        model.addAttribute("zsExaminePermission","XMGL_KCDA_SJZS_B_"+partner);
        model.addAttribute("fileReviewPermission","XMGL_KCDA_DASH_B_"+partner);
        model.addAttribute("kcBthPermission","XMGL_KCDA_KC_B_"+partner);
        model.addAttribute("daBthPermission","XMGL_KCDA_DA_B_"+partner);
        model.addAttribute("sjBthPermission","XMGL_KCDA_SJ_B_"+partner);
        return "modules/yangguang/customer/entry/customerentryList";
    }
    /**
     * 选择产品
     */
//    @RequestMapping(value = "platform/chooseProduct")
//    public String toChooseProduct(HttpServletRequest request, Model model) {
//        // 获取代理商
//        User user = UserUtils.getUser();
//        CrmTrader trader;
//        if (User.USER_TYPE_ADVISOR.equals(user.getUserType())) {
//            String traderId = CrmUtils.getUserRelId(user);
//            trader = traderService.getById(traderId);
//        } else {
//            trader = traderService.getTraderBuserId(user.getId());
//        }
//        String traderId = trader.getId();
//        if ("2".equals(trader.getType())) {
//            traderId = trader.getParentId();
//        }
//        // 获取代理商项目信息
//        model.addAttribute("project", memberService.getProjectByTraderLists(traderId));
//        return "modules/yangguang/customer/entry/customer/chooseProduct";
//    }


    /**
     * 选择代理商对应资方
     */
    @RequestMapping(value = "platform/chooseProduct")
    public String toChooseProduct(HttpServletRequest request, Model model) {
        // 获取代理商
        User user = UserUtils.getUser();
        CrmTrader trader;
        if (User.USER_TYPE_ADVISOR.equals(user.getUserType())) {
            String traderId = CrmUtils.getUserRelId(user);
            trader = traderService.getById(traderId);
        } else {
            trader = traderService.getTraderBuserId(user.getId());
        }
        String traderId = trader.getId();
        if ("2".equals(trader.getType())) {
            traderId = trader.getParentId();
        }
        // 获取代理商对应资方
        model.addAttribute("capital", customerService.getCapital(traderId));
        return "modules/yangguang/customer/entry/customer/chooseProduct";
    }


    /**
     * 平台下跳转新建客户信息
     */
//    @RequestMapping(value = "platform/addNewCustomerEntry")
//    public String toAddOrderForm(HttpServletRequest request, Model model) {
//
//        User user = UserUtils.getUser();
//        CrmTrader trader;
//        if (User.USER_TYPE_ADVISOR.equals(user.getUserType())) {
//            String traderId = CrmUtils.getUserRelId(user);
//            trader = traderService.getById(traderId);
//        } else {
//            trader = traderService.getTraderBuserId(user.getId());
//        }
//
//        model.addAttribute("trader", trader);
//        // 获取产品信息
//        String projectId = request.getParameter("projectId");
//        Record project = projectInfoSettingService.getProjectForTranscription(projectId);
//        model.addAttribute("projectId", projectId);
//        model.addAttribute("project", project);
//        //校验项目对应的项目公式与代理商区域进行匹配
//        //获取产品（项目）授权区域  （暂时用不上）
//        List<ProjectPcd> projects = projectPcdDao.findListByProjectId(projectId);
//        CrmProjectSetting crmProjectSetting = projectDao.get(projectId);
//        //获取代理商授权区域
//        List<TraderPcd> traders = traderPcdDao.findListByTraderId(trader.getId());
//        //获取项目公司的id
//        String[] split = crmProjectSetting.getProjectCompanyId().split(",");
//        //授权区域集合
//        List<String> idList = new ArrayList<>();
//        for (String s : split) {
//            //获取项目公司授权地址的id
//            for (TraderPcd traderPcd : traders) {
//                boolean b = projectCompanyDao.checkAuth2(s, traderPcd.getProvince(), traderPcd.getCity(), traderPcd.getArea());
//                if (b) {
//                    idList.add(s);
//                }
//            }
//        }
//        List<Record> projectInfo = projectInfoSettingService.getProjectInfo(projectId);
//        //对比id时候存在项目公司授权的idList中
//        List<Record> projectVo = new ArrayList<>();
//        for (Record record : projectInfo) {
//            String id = record.getStr("id");
//            if (idList.contains(id)){
//                projectVo.add(record);
//            }
//        }
//        model.addAttribute("projectCompany",projectVo);
//        // 产品线信息
//        model.addAttribute("productLineAttribute", productLineSetService.getProductLineAttribute(project.getStr("productLineId")));
//        //地址信息
//        List<Record> pros = AddressUtils.findProvinceListByTraderId(CrmUtils.getCurrentTraderId(user.getId()), null);
//        model.addAttribute("pros", pros);
//        // 获取表单设置 信息登记阶段
//        model.addAttribute("info", formSetService.getListByCondition("01", project.getStr("management")));
//        // 获取资方信息
//        model.addAttribute("partner", partnerService.getById(project.getStr("management")));
//        return "modules/yangguang/customer/entry/customer/addForm";
//    }


    /**
     * 代理商下跳转新建客户信息 根据资方
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = "platform/addNewCustomerEntry")
    public String toAddOrderForm(HttpServletRequest request, Model model) {

        User user = UserUtils.getUser();
        CrmTrader trader;
        String traderId =  CrmUtils.getUserRelId(user);
        if (User.USER_TYPE_ADVISOR.equals(user.getUserType())) {
            trader = traderService.getById(traderId);
        } else {
            trader = traderService.getTraderBuserId(user.getId());
        }
        model.addAttribute("traderId",traderId);
        model.addAttribute("trader", trader);
        // 获取资方信息
        String capitalId = request.getParameter("capitalId");
        List<Map> capital = new ArrayList<>();
        if (user.getTraderType().equals("2")){
            capital = customerService.getCapital(user.getTopTraderId());
        }else {
            capital = customerService.getCapital(traderId);
        }
        for (Map map : capital) {
            if (map.get("id").equals(capitalId)) {
                model.addAttribute("capital",map);
            }
        }
        List<Record> projectList = new ArrayList<>();
        if (!Objects.equals(traderId, "")){
            //  projectList = memberService.getProjectByTraderLists(traderId);
            //获取产品信息 默认个人  农户产品，项目公司产品
            if (user.getTraderType().equals("2")){
                projectList =   memberService.getProjectByTraderLists(user.getTopTraderId());
            }else {
                projectList =   memberService.getProjectByTraderLists(traderId);
            }

        }
        //获取产品信息 默认农户备案产品
          model.addAttribute("projectList",projectList);
//        Record project = projectInfoSettingService.getProjectForTranscription(projectId);
//        model.addAttribute("projectId", projectId);
//        model.addAttribute("project", project);

//        // 产品线信息
//        model.addAttribute("productLineAttribute", productLineSetService.getProductLineAttribute("00000000000000000000000000000e"));
        //地址信息
        List<Record> pros = AddressUtils.findProvinceListByTraderId(CrmUtils.getCurrentTraderId(user.getId()), null);
        model.addAttribute("pros", pros);
        // 获取表单设置 信息登记阶段
        Record record = formSetService.getListByCondition("01", capitalId);
        model.addAttribute("info", record);
        // 获取资方信息
        model.addAttribute("partner", partnerService.getById(capitalId));
        //获取共签人关系字典
        List<Record> bpRelationList = sysCapitalDictDao.getDictionaryList("bp_relation", capitalId);
        model.addAttribute("bpRelationList",bpRelationList);
        if("04".equals(capitalId)){
            //屋顶类型
            List<Record> roofTypeList = sysCapitalDictDao.getDictionaryList("roof_type", capitalId);
            model.addAttribute("roofTypeList",roofTypeList);
            return "modules/yangguang/customer/entry/customer/addHrForm";
        }else {
            return "modules/yangguang/customer/entry/customer/addForm";
        }

    }

    /**
     * 编辑
     */
    @RequestMapping(value = "editCustomerEntryForm")
    public String editCustomerEntryForm(HttpServletRequest request, Model model){

        String entryId = request.getParameter("entryId");
        CustomerEntry entry = customerService.getById(entryId);
        model.addAttribute("entry", entry);
        CrmProjectSetting pro;
        if(StringUtil.isNotBlank(entry.getProjectId())){
            pro = projectService.getById(entry.getProjectId());
        }
        else {
            pro = new CrmProjectSetting();
        }

        //校验项目对应的项目公式与代理商区域进行匹配
        User user = UserUtils.getUser();
        String traderIds = CrmUtils.getUserRelId(user);
        String projectId = entry.getProjectId();
        Object projectSet = null;
//        if (StringUtil.isNotBlank(projectId)){
//            projectSet = customerService.getProjectInfo(projectId);
//        }
//        model.addAttribute("projectCompany",projectSet);
        model.addAttribute("pro", pro);
        //地址信息
        String province = entry.getProvince();
        List<Record> pros = AddressUtils.findProvinceListByTraderId(entry.getCreateTraderId(), null);
        model.addAttribute("pros", pros);
        String city = entry.getCity();
        String area = entry.getArea();
        String partner = entry.getPartnerId();
        //根据安装地址获取项目公司
        if(StringUtil.isNotBlank(province) && StringUtil.isNotBlank(city) && StringUtil.isNotBlank(area)){
            Map<String,String> map = new HashMap<>();
            map.put("province",province);
            map.put("city",city);
            map.put("area",area);
            map.put("partner",partner);
            projectSet = projectCompanyDao.getCompanyByArea(map);
        }
        model.addAttribute("projectCompany",projectSet);
        //根据省查询下面的
        List<Record> citys = AddressUtils.findCityListByTraderId(entry.getCreateTraderId(), null, province, null);
        List<Record> areas = AddressUtils.findAreaListByTraderId(entry.getCreateTraderId(), province,null, city, null);
        model.addAttribute("faccitys", citys);
        model.addAttribute("areas", areas);
        CrmTrader trader = traderService.getById(entry.getDistributorId());

        model.addAttribute("trader", trader);
        String traderId = trader.getId();
        if (TraderConstants.TYPE_TWO.equals(trader.getType())) {
            traderId = trader.getParentId();
        }
        model.addAttribute("traderId",traderId);
        // 获取单位资料信息
//        if (Objects.equals("2", entry.getTenantType())) {
            model.addAttribute("orgFiles", orgFilesDao.findOneByEntryId(entry.getId()));
//        }
        List<Record> projectList = new ArrayList<>();
        //根据省市区获取代理商项目信息
        if(StringUtil.isNotBlank(province) && StringUtil.isNotBlank(city) && StringUtil.isNotBlank(area)){
            if (entry.getFilingType() != null){
                projectList = memberService.getProjectByTraderLists3(traderId, entry.getFilingType(), partner, province, city, area);
            }else {
                Map<String, String> map = getParams(request);
                map.put("traderId", traderId);
                map.put("partner", partner);
                map.put("province",province);
                map.put("city",city);
                map.put("area",area);
                map.put("type",entry.getTenantType());
                if (map.get("area") != null && !Objects.equals(map.get("area"), "")){
                    projectList = projectService.getProjectByArea(map);
                }
            }
        }
//        if (entry.getFilingType() != null &&entry.getFilingType().equals("2")){
//            projectList =   memberService.getProjectByTraderListAndFilingType(user.getTopTraderId(),entry.getFilingType());
//        }else {
//            projectList = memberService.getProjectByTraderLists(user.getTopTraderId());
//        }
        model.addAttribute("project", projectList);
        if("04".equals(partner)){
            List<Record> epRecord = projectInfoSettingService.getEntryProjectByEntryId(entryId);
            model.addAttribute("epRecord",epRecord);
        }else{
            if(StringUtil.isNotBlank(entry.getProjectId())){
                // 产品线信息
                CrmProjectSetting projectSetting = projectInfoSettingService.getById(entry.getProjectId());
                model.addAttribute("productLineAttribute", productLineSetService.getProductLineAttribute(projectSetting.getProductLineId()));
            }
        }
        // 获取表单设置 信息登记阶段
        model.addAttribute("info", formSetService.getListByCondition("01", entry.getPartnerId()));
        // 获取资方信息
        model.addAttribute("partner", partnerService.getById(entry.getPartnerId()));
        CustomerEntrySurveyRecord surveyRecord = surveyRecordDao.findOneByEntryId(entryId);
        if (surveyRecord != null){
            model.addAttribute("surveyRecord", surveyRecord);
        }
        //获取共签人关系字典
        List<Record> bpRelationList = sysCapitalDictDao.getDictionaryList("bp_relation", entry.getPartnerId());
        model.addAttribute("bpRelationList",bpRelationList);
        if("04".equals(partner)){
            //屋顶类型
            List<Record> roofTypeList = sysCapitalDictDao.getDictionaryList("roof_type", partner);
            model.addAttribute("roofTypeList",roofTypeList);
            List<Record> projectLists = memberService.getProjectByTraderLists2(traderId, entry.getFilingType(), partner);
            model.addAttribute("project", projectLists);
            return "modules/yangguang/customer/entry/customer/editHrForm";
        }else{
            return "modules/yangguang/customer/entry/customer/editForm";
        }

    }



    /**
     * 保存信息  信息录入 新增/修改接口
     */
    @ResponseBody
    @RequestMapping(value = "/saveCustomerEntry")
    public Object saveCustomerEntry(@Validated @RequestBody AddEntryReq entry, HttpServletRequest request,
                                    HttpServletResponse response) {
        User user = UserUtils.getUser();
        Result result = new Result();
        if(!SourceConstants.STATUS_ZERO.equals(user.getStatus())){
            result.setCode("2001");
            result.setMsg("当前账号已禁用或已删除，不可操作！");
            return result;
        }
        if("04".equals(entry.getZfId())) {
            if(entry.getProjectId() == null || "".equals(entry.getProjectId())){
                result.setErrMsg("请选择产品");
                result.setCode("501");
                return result;
            }
            if (entry.getProjectList().size() > 0) {
                int i = 0;
                String projectId = "";
                for (ProjectInfoVo vo : entry.getProjectList()) {
                    if (i == 0) {
                        projectId = vo.getProjectId();
                    } else {
                        if (projectId.equals(vo.getProjectId())) {
                            result.setErrMsg("不可选择重复产品");
                            result.setCode("501");
                            return result;
                        }
                    }
                    i++;
                }
            }
        }
        Record pro = null;
        if (StringUtil.equals(entry.getType(),CustomerEntryConstants.TYPE_TJ)) {
            if (StringUtil.isBlank(entry.getProjectId())) {
                result.setErrMsg("请先选择产品");
                result.setCode("501");
                return result;
            }
            //华融
            if("04".equals(entry.getZfId())){
                if(entry.getProjectList() != null) {
                    for (ProjectInfoVo vo : entry.getProjectList()) {
                        if (StringUtil.isNotBlank(vo.getProjectId())) {
                            pro = projectDao.getProject(vo.getProjectId());
                        }
                        if (pro == null) {
                            result.setErrMsg("当前产品不存在");
                            result.setCode("501");
                            return result;
                        }
                        entry.setZfId(pro.getStr("management"));
                    }
                }
            }else{
                if (StringUtil.isNotBlank(entry.getProjectId())) {
                    pro = projectDao.getProject(entry.getProjectId());
                }
                if (pro == null) {
                    result.setErrMsg("当前产品不存在");
                    result.setCode("501");
                    return result;
                }
                entry.setZfId(pro.getStr("management"));
            }
            if (StringUtil.isBlank(entry.getCompany())) {
                result.setErrMsg("请先选择项目公司");
                result.setCode("501");
                return result;
            }

        }

        try {
            Operator operator = Operator.of(user.getId(), CrmUtils.getUserXM(user), user.getUserType());
            String code="";
            if(StringUtil.isNotBlank(entry.getId())){

                if (StringUtil.equalsAny(entry.getType(),CustomerEntryConstants.TYPE_TJ, CustomerEntryConstants.TYPE_ZC)) {
                    //华融
                    if("04".equals(entry.getZfId())){
                        code = customerService.editHREntryForIXDJ(entry, operator);
                    }else{
                        code = customerService.editEntryForIXDJ(entry, operator);
                    }
                }
                else {
                    code = customerService.editCustomerEntry(entry, operator);
                }
            }else {
                if("04".equals(entry.getZfId())){
                    //华融
                    code = customerService.createHREntryForIXDJ(entry, operator);
                }else{
                    code = customerService.createEntryForIXDJ(entry, operator);
                }
            }
            if (Objects.equals("200", code)) {
                result.setCode(code);
            } else {
                result.setCode("201");
                result.setErrMsg(code);
            }
        } catch (IllegalArgumentException i){
            result.setErrMsg(i.getMessage());
            result.setCode("501");
        }catch (BusinessException b){
            result.setErrMsg(b.getMessage());
            result.setCode(b.getErrorCode());
        }catch (Exception e) {
            logger.error(">>>>>>>>>>>>>saveCustomerEntry  e:{} ",e);
            e.printStackTrace();
            result.setCode("505");
            result.setErrMsg("内部错误!");
            throw e;
        }
        cacheService.hdel("operatorUserId",user.getId());
        cacheService.hdel("userIdoOperatorTime",user.getId());
        return result;
    }

    /**
     * 保存信息  信息录入 新增/修改接口
     */
    @ResponseBody
    @RequestMapping(value = "/saveHRCustomerEntry")
    public Object saveHRCustomerEntry(@Validated @RequestBody AddEntryReq entry, HttpServletRequest request,
                                    HttpServletResponse response) {
        User user = UserUtils.getUser();
        Result result = new Result();
        if(!SourceConstants.STATUS_ZERO.equals(user.getStatus())){
            result.setCode("2001");
            result.setMsg("当前账号已禁用或已删除，不可操作！");
            return result;
        }
        Record pro = null;
        if (StringUtil.equals(entry.getType(),CustomerEntryConstants.TYPE_TJ)) {
            for(ProjectInfoVo vo :entry.getProjectList()){
                if (StringUtil.isBlank(vo.getProjectId())) {
                    result.setErrMsg("请先选择产品");
                    result.setCode("501");
                    return result;
                }
                if (StringUtil.isNotBlank(entry.getProjectId())) {
                    pro = projectDao.getProject(entry.getProjectId());
                }
                if (pro == null) {
                    result.setErrMsg("当前产品不存在");
                    result.setCode("501");
                    return result;
                }
            }
            if (StringUtil.isBlank(entry.getCompany())) {
                result.setErrMsg("请先选择项目公司");
                result.setCode("501");
                return result;
            }
            entry.setZfId(pro.getStr("management"));
        }

        try {
            Operator operator = Operator.of(user.getId(), CrmUtils.getUserXM(user), user.getUserType());
            String code="";
            if(StringUtil.isNotBlank(entry.getId())){
                if (StringUtil.equalsAny(entry.getType(),CustomerEntryConstants.TYPE_TJ,
                        CustomerEntryConstants.TYPE_ZC)) {
                    code = customerService.editEntryForIXDJ(entry, operator);
                }
                else {
                    code = customerService.editCustomerEntry(entry, operator);
                }
            }else {
                code = customerService.createEntryForIXDJ(entry, operator);
            }
            if (Objects.equals("200", code)) {
                result.setCode(code);
            } else {
                result.setCode("201");
                result.setErrMsg(code);
            }
        } catch (IllegalArgumentException i){
            result.setErrMsg(i.getMessage());
            result.setCode("501");
        }catch (BusinessException b){
            result.setErrMsg(b.getMessage());
            result.setCode(b.getErrorCode());
        }catch (Exception e) {
            logger.error(">>>>>>>>>>>>>saveCustomerEntry  e:{} ",e);
            e.printStackTrace();
            result.setCode("505");
            result.setErrMsg("内部错误!");
            throw e;
        }
        cacheService.hdel("operatorUserId",user.getId());
        cacheService.hdel("userIdoOperatorTime",user.getId());
        return result;
    }

    /**
     * 操作用户信息--删除
     */
    @ResponseBody
    @RequestMapping(value = "deleteCustomerEntry")
    public Object deleteCustomerEntry(HttpServletRequest request) {
        String cusId = request.getParameter("cusId");
        try {
            User user = UserUtils.getUser();
            Operator operator = Operator.of(user.getId(), CrmUtils.getUserXM(user),user.getUserType());
            customerService.deleteCustomerEntry(cusId,operator);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("202", "删除失败! " + e);
        }
        return Result.ok();
    }


    /**
     * 根据客户类型 获取项目信息
     */
    @ResponseBody
    @RequestMapping(value = "getProjectInfoByType")
    public Object getProjectInfoByType(HttpServletRequest request) {
        String type = request.getParameter("type");
        User user = UserUtils.getUser();
        String traderId = request.getParameter("traderId");
        List<Record> projectList = new ArrayList<>();
        if (type.equals("2")){
            projectList =   memberService.getProjectByTraderListAndFilingType(user.getTopTraderId(),"2");
        }else {
            projectList = memberService.getProjectByTraderLists(user.getTopTraderId());
        }
        return Result.success(projectList);
    }



    /**
     * 项目查询中批量删除
     */
    @ResponseBody
    @RequestMapping("/batchDeleteOrder")
    public Result<Void> batchDeleteOrder(@RequestBody List<String> ids) {
        User user = UserUtils.getUser();
        Operator operator = Operator.of(user.getId(), CrmUtils.getUserXM(user),user.getUserType());
        for(String id:ids){
            customerService.deleteCustomerEntry(id,operator);
        }
        return Result.ok();
    }


    /**
     * 待国电投审核
     */
    @RequestMapping(value = "gwshCustomerList")
    public String gdtCustomerList(HttpServletRequest request, Model model) {
        setCommonData(model);
        User user = UserUtils.getUser();
        if(StringUtil.isBlank(user.getId())){
            model.addAttribute("types", "1");
            //  return "redirect:" + Global.getAdminPath() + "/login";
        }
        model.addAttribute("user", user);
        //系统工程师列表
        List<Record> empList = siteEmployeeService.findProjectEmpList("1,b,c");
        model.addAttribute("empList", empList);
        model.addAttribute("typeList", markSettingService.getAllMarkType("2"));
        return "modules/yangguang/customer/entry/gdt/gdtcustomerentryList";
    }

    @ResponseBody
    @RequestMapping(value = "getgdtCustomerList")
    public Object getgdtCustomerList(HttpServletRequest request) {
        Map<String, String> map = getParams(request);
        LayuiPage page = new LayuiPage(request);
        User user = UserUtils.getUser();
        //如果是平台人员--则需要按数据权限
        if(StringUtil.isBlank(user.getId())){
            throw new RuntimeException("user " + user + "is null  ");
        }
        if (StringUtil.isNotBlank(user.getId()) && "4".equals(user.getUserType())) {
            EmployeRoleUtils.getRoleDataAuthority(user.getId(),  map);
        }
        map.put("status","g");
        customerService.getGdtCustomerList(page, map, user);
        return page.renderJson();
    }

    /**
     * 待国电投安装审核
     */
    @RequestMapping(value = "gdtazshCustomerList")
    public String gdtazshCustomerList(HttpServletRequest request, Model model) {
        setCommonData(model);
        User user = UserUtils.getUser();
        if(StringUtil.isBlank(user.getId())){
            model.addAttribute("types", "1");
            //  return "redirect:" + Global.getAdminPath() + "/login";
        }
        //系统工程师列表
        List<Record> empList = siteEmployeeService.findProjectEmpList("1,b,c");
        model.addAttribute("empList", empList);
        List<Record> traderList = traderService.listTraderRecords(null, new HashMap<String, String>());
        return "modules/yangguang/customer/entry/gdt/gdtazcustomerentryList";
    }

    @ResponseBody
    @RequestMapping(value = "getgdtazCustomerList")
    public Object getgdtazCustomerList(HttpServletRequest request) {
        Map<String, String> map = getParams(request);
        LayuiPage page = new LayuiPage(request);
        User user = UserUtils.getUser();
        //如果是平台人员--则需要按数据权限
        if(StringUtil.isBlank(user.getId())){
            throw new RuntimeException("user " + user + "is null  ");
        }
        if (StringUtil.isNotBlank(user.getId()) && "4".equals(user.getUserType())) {
            EmployeRoleUtils.getRoleDataAuthority(user.getId(),  map);
        }
        map.put("status","AN");
        customerService.getGdtCustomerList(page, map, user);
        return page.renderJson();
    }



    /**
     * 待国电投安装审核
     */
    @RequestMapping(value = "gdtBwshCustomerList")
    public String gdtBwshCustomerList(HttpServletRequest request, Model model) {
        setCommonData(model);
        User user = UserUtils.getUser();
        if(StringUtil.isBlank(user.getId())){
            model.addAttribute("types", "1");
            //  return "redirect:" + Global.getAdminPath() + "/login";
        }
        //系统工程师列表
        List<Record> empList = siteEmployeeService.findProjectEmpList("1,b,c");
        model.addAttribute("empList", empList);
        return "modules/yangguang/customer/entry/gdt/gdtBwcustomerentryList";
    }

    @ResponseBody
    @RequestMapping(value = "getgdtBwCustomerList")
    public Object getgdtBwCustomerList(HttpServletRequest request) {
        Map<String, String> map = getParams(request);
        LayuiPage page = new LayuiPage(request);
        User user = UserUtils.getUser();
        //如果是平台人员--则需要按数据权限
        if(StringUtil.isBlank(user.getId())){
            throw new RuntimeException("user " + user + "is null  ");
        }
        if (StringUtil.isNotBlank(user.getId()) && "4".equals(user.getUserType())) {
            EmployeRoleUtils.getRoleDataAuthority(user.getId(),  map);
        }
        map.put("status","BW");
        customerService.getGdtCustomerList(page, map, user);
        return page.renderJson();
    }

    @ResponseBody
    @RequestMapping(value = "getCustomerList")
    public Object getCustomerList(HttpServletRequest request)  {
        Map<String, String> map = getParams(request);
        LayuiPage page = new LayuiPage(request);
        User user = UserUtils.getUser();
        //如果是平台人员--则需要按数据权限
        if(StringUtil.isBlank(user.getId())){
            throw new RuntimeException("user " + user + "is null  ");
        }
//        if (StringUtil.isNotBlank(user.getId()) && "4".equals(user.getUserType())) {
//            EmployeRoleUtils.getRoleDataAuthority(user.getId(),  map);
//        }
        String port = "PC";// PC端能查看设计自审、设计审核的数据
        customerService.getCustomerList(port, page, map, user);
        return page.renderJson();
    }

    @RequestMapping(value = "customerListJjsh")
    public String customerListJjsh(HttpServletRequest request, Model model) {
        setCommonData(model);
        User user = UserUtils.getUser();
        if(StringUtil.isBlank(user.getId())){
            model.addAttribute("types", "1");
            //  return "redirect:" + Global.getAdminPath() + "/login";
        }
        //系统工程师列表
        List<Record> empList = siteEmployeeService.findProjectEmpList("1,b,c");
        model.addAttribute("empList", empList);
        return "modules/yangguang/customer/entry/JjshCustomerentryList";
    }

    //广发审核查询
    @RequestMapping(value = "customerListGFJjsh")
    public String customerListGFJjsh(HttpServletRequest request, Model model) {
        setCommonData(model);
        User user = UserUtils.getUser();
        if(StringUtil.isBlank(user.getId())){
            model.addAttribute("types", "1");
            //  return "redirect:" + Global.getAdminPath() + "/login";
        }
        //系统工程师列表
        List<Record> empList = siteEmployeeService.findProjectEmpList("1,b,c");
        model.addAttribute("empList", empList);
        return "modules/yangguang/customer/entry/GFJjshCustomerentryList";
    }

    //华融审核查询
    @RequestMapping(value = "customerListHRJjsh")
    public String customerListHRJjsh(HttpServletRequest request, Model model) {
        setCommonData(model);
        User user = UserUtils.getUser();
        if(StringUtil.isBlank(user.getId())){
            model.addAttribute("types", "1");
        }
        //系统工程师列表
        List<Record> empList = siteEmployeeService.findProjectEmpList("1,b,c");
        model.addAttribute("empList", empList);
        return "modules/yangguang/customer/entry/HRJjshCustomerentryList";
    }
    @ResponseBody
    @RequestMapping(value = "queryDocumentStatus")
    public Result queryDocumentStatus(String entryId,String powerStationCode){
        QueryDocumentRes res=yueXueContractService.queryDocumentStatus(entryId);
        CustomerEntry entry = customerService.findCustomerEntryById(powerStationCode);
        if(entry==null){
            return Result.fail("未找到电站信息!");
        }
        //修改合同状态
        yueXueContractService.editContractStatusAfterLook(res,res.getBusinessKey(),entry);
        //更新进件状态
        CrmCustomerIncomingApplication application=applicationDao.getByEntryId(entry.getId());
        customerEntryExtraService.updateIncomingApplicationStatus(res,powerStationCode,entry,application);
        return Result.ok();
    }

    /**
     * 广发状态同步
     */
    @ResponseBody
    @RequestMapping(value = "queryGuangFaStatus")
    public Result queryGuangFaStatus(String entryId){
        CustomerEntry entry = customerService.getById(entryId);
        Result result = Result.ok();
        if(!"1".equals(entry.getIsHistory())){
            customerService.dealGfQueryData(entry);
        }else {
            //广发存量电站状态同步
            result = nhPowerStationService.tbStatus2(entryId);
        }
        return result;
    }

    /**
     * 华融状态同步
     * queryHuaRongStatus
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "queryHuaRongStatus")
    public Result queryHuaRongStatus(@RequestBody List<String> ids){
        for (String entryId : ids) {
            try {
                customerService.dealHRQueryData(entryId,"3");
            }catch (Exception e){
                logger.info("queryHuaRongStatus error entryId:{}",entryId);
            }
        }
        return Result.ok();
    }
    /**
     * 华融取消进件页面
     */
    @RequestMapping("/toCancelHRApplyPage")
    public String toCancelHRApplyPage(HttpServletRequest request,Model model) {
        String id = request.getParameter("entryId");
        model.addAttribute("id",id);
        return "modules/yangguang/customer/entry/cancelHRApplyPage";
    }

    //华融取消进件
    @ResponseBody
    @RequestMapping(value = "terminateHuaRongProject")
    public Result terminateHuaRongProject(String entryId,String reason){
        User user = UserUtils.getUser();
        CustomerEntry entry = customerService.getById(entryId);
        customerService.terminateHuaRongProject(user,entry,reason);
        return Result.ok();
    }


    @RequestMapping("/toUploadHRFilePage")
    public String toUploadFilePage(HttpServletRequest request,Model model) {
        String id = request.getParameter("entryId");
        String step = request.getParameter("step");
        model.addAttribute("id",id);
        model.addAttribute("step",step);
        //获取华融建档进件的附件编码
        model.addAttribute("fileCode", PartnerConstants.getHrFileCodeList(step));
        return "modules/yangguang/customer/entry/uploadHRFilePage";
    }

    /**
     *补充资料 step 1.补充建档资料 3.补充并网资料
     */
    @ResponseBody
    @RequestMapping(value = "updateHRFiles")
    public Result updateHRFiles(String entryId, String step ,String fileCode){
        CustomerEntry entry = customerService.getById(entryId);
        CrmCustomerIncomingApplication application = applicationDao.getByEntryId(entryId);
        User user = UserUtils.getUser();
        Operator operator = Operator.of(user);
        if ("1".equals(step)){
            if (!"FS".equals(entry.getFirstApplyStatus())){
                return Result.fail("当前进件状态不可操作补充建档资料");
            }
            return customerService.updateHRFiles(entry,application,operator, fileCode);
        }else {
            if (!"DS".equals(entry.getNextApplyStatus())){
                return Result.fail("当前进件状态不可操作补充并网资料");
            }
            return customerService.updateHRBWFiles(entry,application,operator, fileCode);
        }
    }
    @ResponseBody
    @RequestMapping(value = "uploadHRAllFile")
    public Result uploadHRAllFile(String entryId){
        CustomerEntry entry = customerService.getById(entryId);
        CrmCustomerIncomingApplication application = applicationDao.getByEntryId(entryId);
        return customerService.uploadHRAllFile(entry,application);
    }


    @ResponseBody
    @RequestMapping(value = "getJjshCustomerList")
    public Object getJjshCustomerList(HttpServletRequest request) {
        Map<String, String> map = getParams(request);
        LayuiPage page = new LayuiPage(request);
        User user = UserUtils.getUser();
        //如果是平台人员--则需要按数据权限
        if(StringUtil.isBlank(user.getId())){
            throw new RuntimeException("user " + user + "is null  ");
        }
//        if (StringUtil.isNotBlank(user.getId()) && "4".equals(user.getUserType())) {
//            EmployeRoleUtils.getRoleDataAuthority(user.getId(),  map);
//        }
        customerService.getJjshCustomerList(page, map, user);
        return page.renderJson();
    }

    /**
     * 浙银项目 待确认
     */
    @RequestMapping(value = "getDqrCustomerEntryForm")
    public String getDqrCustomerEntryForm(HttpServletRequest request, Model model) {
        String entryId = request.getParameter("entryId");

        CustomerEntry entry = customerService.getById(entryId);
        model.addAttribute("entry", entry);

        CrmProjectSetting pro = projectService.getById(entry.getProjectId());
        model.addAttribute("pro", pro);
        //地址信息
        List<Record> pros = addressService.getProvinces();

        model.addAttribute("pros", pros);
        String province = entry.getProvince();
        String city = entry.getCity();
        //根据省查询下面的
        List<Record> citys = AddressUtils.getCityByProName(province);
        List<Record> areas = AddressUtils.getAreaByCityName(city);
        model.addAttribute("faccitys", citys);
        model.addAttribute("areas", areas);
        CrmTrader trader = traderService.getById(entry.getDistributorId());

        model.addAttribute("trader", trader);
        //获取所有项目信息
        model.addAttribute("project", memberService.getProjectLists());
        //获取方案类型
        model.addAttribute("insta", projectInstallService.findProjectInstalls());
        //获取方案
        model.addAttribute("plan", planService.findAllPlan());
        if(CustomerEntryConstants.SCHEME_TYPE_TWO.equals(entry.getSchemeType())){
            model.addAttribute("compose", customerService.findByEntryId(entryId));
            model.addAttribute("comPlan",planService.findPlanByAssembly(entry.getProjectId(), "",""));
        }

        String managementType= projectService.getManageType(entry.getManagementType());

        model.addAttribute("managementType", managementType);
        return "modules/yangguang/customer/entry/dqrCustomerEntryForm";
    }


    /**
     * 自审
     */
    @RequestMapping(value = "getUpdateCustomerEntryForm")
    public String getUpdateCustomerEntryForm(HttpServletRequest request, Model model) {
        String entryId = request.getParameter("entryId");

        CustomerEntry entry = customerService.getById(entryId);
        CrmPartner crmPartner = partnerService.getById(entry.getPartnerId());
        model.addAttribute("partner", crmPartner);
        model.addAttribute("entry", entry);
        CustomerEntrySurveyRecord surveyRecord = surveyRecordDao.findOneByEntryId(entryId);
        model.addAttribute("surveyRecord", surveyRecord);

        String projectId = entry.getProjectId();
        if(PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())){
            List<Record> projects = crmCustomerEntryProjectDao.getProjectsByEntryId(entry.getId());
            projectId = projects.get(0).getStr("id");
        }
        CrmProjectSetting pro = projectService.getById(projectId);
        model.addAttribute("pro", pro);
        //地址信息
        String province = entry.getProvince();
        List<Record> pros = AddressUtils.findProvinceListByTraderId(entry.getDistributorId(), null);
        model.addAttribute("pros", pros);
        String city = entry.getCity();
        String area = entry.getArea();
        String partner = entry.getPartnerId();
        //根据省查询下面的
        List<Record> citys = AddressUtils.findCityListByTraderId(entry.getDistributorId(), null, province, null);
        List<Record> areas = AddressUtils.findAreaListByTraderId(entry.getDistributorId(), province,null, city, null);
        model.addAttribute("faccitys", citys);
        model.addAttribute("areas", areas);
        CrmTrader trader = traderService.getById(entry.getDistributorId());

        model.addAttribute("trader", trader);
        String traderId = trader.getId();
        if(TraderConstants.TYPE_TWO.equals(trader.getType())){
            traderId =trader.getParentId();
        }
        model.addAttribute("traderId",traderId);
        //获取所有项目信息
        if (StringUtil.isBlank(area)){
            List<Record> projectLists = memberService.getProjectByTraderLists2(traderId, pro.getFilingType(), pro.getManagement());
            model.addAttribute("project", projectLists);
        }else {
            List<Record> projectLists = memberService.getProjectByTraderLists3(traderId, pro.getFilingType(), pro.getManagement(), province, city, area);
            model.addAttribute("project",projectLists);
        }
        // 校验项目对应的项目公式与代理商区域进行匹配
        User user = UserUtils.getUser();
        String traderIds = CrmUtils.getUserRelId(user);
        CrmTrader traderInfo = traderService.getById(traderIds);
        // 获取产品（项目）授权区域  （暂时用不上）
        Object projectSet = null;
//        if (StringUtil.isNotBlank(projectId)){
//            projectSet = customerService.getProjectInfo(projectId);
//        }
        //根据安装地址获取项目公司
        if(StringUtil.isNotBlank(province) && StringUtil.isNotBlank(city) && StringUtil.isNotBlank(area)){
            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",entry.getFilingType());
            projectSet = projectCompanyDao.getCompanyByArea(map);
        }
        model.addAttribute("companyList",projectSet);
        //获取方案类型
        model.addAttribute("insta", projectInstallService.findProjectInstalls());
        //获取方案
        model.addAttribute("plan", planService.findAllPlan());
        if(!PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())) {
            if (CustomerEntryConstants.SCHEME_TYPE_TWO.equals(entry.getSchemeType())) {
                model.addAttribute("compose", customerService.findPlanInfoEntryId(entryId));
            } else {//标准方案
                model.addAttribute("composeOne", customerService.findByEntrySchemeId(entry.getSchemeId()));
            }
        }
        // 获取电站电器材料
        List<Record> componentList = customerEntryComponentService.findByEntryId(entryId);
        List<Record> assemblyList = componentList.stream().filter(r -> r.getStr("item_type").equals("3") ).collect(Collectors.toList());
        List<Record> inverterList = componentList.stream().filter(r -> r.getStr("item_type").equals("1")).collect(Collectors.toList());
        List<Record> gridConnectionList = componentList.stream().filter(r -> r.getStr("item_type").equals("2")).collect(Collectors.toList());
        List<Record> gridSupportList = componentList.stream().filter(r -> r.getStr("item_type").equals("4")).collect(Collectors.toList());
        // 获取系统设置的电器材料
        List<Record> allElectric = planService.findAllElectric();
        //
//        List<Record> sysAssemblyList = allElectric.stream().filter(r -> r.getStr("type").equals("3") && Integer.valueOf(r.get("model"))>=pro.getAssemblySpecs()).collect(Collectors.toList());
        List<Record> records = planService.getElectricSet("3");
        List<Record> sysAssemblyList = new ArrayList<>();
        for (Record record : records) {
            if (Integer.valueOf(record.get("model")) >= pro.getAssemblySpecs()){
                sysAssemblyList.add(record);
            }
        }
        model.addAttribute("partnerId",entry.getPartnerId());
        List<Record> sysInverterList = new ArrayList<>();
        Record info2 = formSetService.getListByCondition("02", pro.getManagement());
        FormSetPageVo vo = info2.get("component1_model");
        if (vo != null && "1".equals(vo.getStatus())){
            sysInverterList = planService.findAllInverter2();
        }else {
            sysInverterList = planService.findAllInverter();
        }
        List<Record> sysGridConnectionList = allElectric.stream().filter(r -> r.getStr("type").equals("2")).collect(Collectors.toList());
        List<Record> sysGridSupportList = allElectric.stream().filter(r -> r.getStr("type").equals("4")).collect(Collectors.toList());
        model.addAttribute("assemblyList", assemblyList);
        model.addAttribute("inverterList", inverterList);
        model.addAttribute("gridConnectionList", gridConnectionList);
        model.addAttribute("gridSupportList", gridSupportList);
        model.addAttribute("sysAssemblyList", sysAssemblyList);
        model.addAttribute("sysInverterList", sysInverterList);
        model.addAttribute("sysGridConnectionList", sysGridConnectionList);
        model.addAttribute("sysGridSupportList", sysGridSupportList);
        //二类卡号
        model.addAttribute("accountCode", customerService.findYxBankConditionCode(entry.getIdCode(),entry.getMobile(),entry.getPartnerId()));
        model.addAttribute("quaimgsCount",0);
        if(StringUtil.isNotBlank(surveyRecord.getHouseOwnership())){
            String[] arr=surveyRecord.getHouseOwnership().split(",");
            model.addAttribute("quaimgs",arr);
            model.addAttribute("quaimgsCount", arr.length);
        }
        int surveyFilesCount = 0;
        if(StringUtil.isNotBlank(surveyRecord.getSurveyFiles())){
            String[] arr=surveyRecord.getSurveyFiles().split(",");
            surveyFilesCount = arr.length;
        }
        model.addAttribute("surveyFilesCount", surveyFilesCount);
        int vrRoofOneCount = 0;
        if(StringUtil.isNotBlank(surveyRecord.getVrRoofOne())){
            String[] arr=surveyRecord.getVrRoofOne().split(",");
            vrRoofOneCount = arr.length;
        }
        model.addAttribute("vrRoofOneCount", vrRoofOneCount);
        int vrRoofTwoCount = 0;
        if(StringUtil.isNotBlank(surveyRecord.getVrRoofTwo())){
            String[] arr=surveyRecord.getVrRoofTwo().split(",");
            vrRoofTwoCount = arr.length;
        }
        model.addAttribute("vrRoofTwoCount", vrRoofTwoCount);
        int vrRoofThreeCount = 0;
        if(StringUtil.isNotBlank(surveyRecord.getVrRoofThree())){
            String[] arr=surveyRecord.getVrRoofThree().split(",");
            vrRoofThreeCount = arr.length;
        }
        model.addAttribute("vrRoofThreeCount", vrRoofThreeCount);
        int vrRoofFourCount = 0;
        if(StringUtil.isNotBlank(surveyRecord.getVrRoofFour())){
            String[] arr=surveyRecord.getVrRoofFour().split(",");
            vrRoofFourCount = arr.length;
        }
        model.addAttribute("vrRoofFourCount", vrRoofFourCount);
        int attachFilesCount = 0;
        if(StringUtil.isNotBlank(entry.getDesignDrawings())){
            String[] arr=entry.getDesignDrawings().split(",");
            attachFilesCount = arr.length;
        }
        model.addAttribute("attachFilesCount", attachFilesCount);
        int zjpbImgCount = 0;
        if(StringUtil.isNotBlank(entry.getZjpbImg())){
            String[] arr=entry.getZjpbImg().split(",");
            zjpbImgCount = arr.length;
        }
        model.addAttribute("zjpbImgCount", zjpbImgCount);
        int zjzxImgCount = 0;
        if(StringUtil.isNotBlank(entry.getZjzxImg())){
            String[] arr=entry.getZjzxImg().split(",");
            zjzxImgCount = arr.length;
        }
        model.addAttribute("zjzxImgCount", zjzxImgCount);
        int zjcsImgCount = 0;
        if(StringUtil.isNotBlank(entry.getZjcsImg())){
            String[] arr=entry.getZjcsImg().split(",");
            zjcsImgCount = arr.length;
        }
        model.addAttribute("zjcsImgCount", zjcsImgCount);
        int zjhsImgCount = 0;
        if(StringUtil.isNotBlank(entry.getZjhsImg())){
            String[] arr=entry.getZjhsImg().split(",");
            zjhsImgCount = arr.length;
        }
        model.addAttribute("zjhsImgCount", zjhsImgCount);
        CustomerEntryTenant tenant = tenantDao.getByTenantId(entry.getTenantId());
        model.addAttribute("tenant",tenant);
        //屋顶类型
        List<Record> roofTypeList = sysCapitalDictDao.getDictionaryList("roof_type", pro.getManagement());
        model.addAttribute("roofTypeList",roofTypeList);
        //房屋偏向
        List<Record> angleAzimuthList = sysCapitalDictDao.getDictionaryList("angle_azimuth", pro.getManagement());
        model.addAttribute("angleAzimuthList",angleAzimuthList);
        //并网电压等级
        List<Record> voltageClassesList = sysCapitalDictDao.getDictionaryList("voltage_classes", pro.getManagement());
        model.addAttribute("voltageClassesList",voltageClassesList);
        // 获取表单设置 信息登记阶段
        model.addAttribute("info", formSetService.getListByCondition("01", pro.getManagement()));
        //获取表单设置  勘测设计
        model.addAttribute("info2", formSetService.getListByCondition("02", pro.getManagement()));
        CrmTenantYxBankCard card=tenantYxBankCardDao.getByIdCard(entry.getIdCode(),entry.getManagementType(),entry.getPartnerId());
        model.addAttribute("card",card);
        model.addAttribute("orgFiles", orgFilesDao.findOneByEntryId(entry.getId()));

        if(PartnerConstants.PARTNER_ID_YX.equals(entry.getPartnerId())){
            //获取历史设置的汇流方式
            Record recordBox=combinerBoxGroupDao.getEntryCombinerBoxSet(entryId);
            model.addAttribute("recordBox",recordBox);
            //获取一户多站的信息
            Record oneToAnyBoxSet=combinerBoxGroupDao.getOneToAnyBoxSet(entry.getIdCode(),entry.getRegno(),entry.getCreateTraderId(),entry.getTenantType());
            model.addAttribute("oneToAnyBoxSet",oneToAnyBoxSet);
        }
        //多产品参数获取
        if(PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())){
            List<Record> entryProject = crmCustomerEntryProjectDao.getProjectsByEntryId(entry.getId());
            List<CrmCustomerEntryDesign> entryDesigns = crmCustomerEntryDesignDao.findByEntryId(entry.getId());
            List<CrmCustomerEntrySurveyRecordDetail> entrySurveys = crmCustomerEntrySurveyRecordDetailDao.findByEntryId(entry.getId());
            int entryProjectNum = entryProject.size();
            if(entryProjectNum<5){
                for(int i=0;i<5-entryProjectNum;i++){
                    entryProject.add(new Record());
                }
            }
            int entryDesignsNum = entryDesigns.size();
            if(entryDesignsNum<5){
                for(int i=0;i<5-entryDesignsNum;i++){
                    entryDesigns.add(new CrmCustomerEntryDesign());
                }
            }
            int entrySurveysNum = entrySurveys.size();
            if(entrySurveysNum<5){
                for(int i=0;i<5-entrySurveysNum;i++){
                    entrySurveys.add(new CrmCustomerEntrySurveyRecordDetail());
                }
            }
            if (CustomerEntryConstants.SCHEME_TYPE_TWO.equals(entry.getSchemeType())) {
                model.addAttribute("compose", customerService.findPlanInfoEntryId(entryId));
            } else {//标准方案
                List<Record> composeOnes = new ArrayList<>();
                for(CrmCustomerEntryDesign entryDesign:entryDesigns){
                    Record composeOne = customerService.findByEntrySchemeId(entryDesign.getSchemeId());
                    if(composeOne!=null){
                        composeOne.set("projectId",entryDesign.getProjectId());
                    }
                    composeOnes.add(composeOne);
                }
                model.addAttribute("composeOneHr", composeOnes);
            }
            model.addAttribute("entryProject",entryProject);
            model.addAttribute("entryProjectNum",entrySurveysNum);
            model.addAttribute("entryDesigns",entryDesigns);
            model.addAttribute("entrySurveys",entrySurveys);
            return "modules/yangguang/customer/entry/editCustomerEntryFormHR";
        }
        if(PartnerConstants.PARTNER_ID_GF.equals(entry.getPartnerId())){
            List<RoofSetFormVo> GfRoofTypeFormSet=FormSetService.getGfFormSetByRoofType();
            model.addAttribute("GfRoofTypeFormSet",new Gson().toJson(GfRoofTypeFormSet));
        }
        return "modules/yangguang/customer/entry/editCustomerEntryForm";
    }

    /**
     * 跳转勘测/设计页面  type 1.勘测  2.设计
     */
    @RequestMapping(value = "getUpdateCustomerEntryForm2")
    public String getUpdateCustomerEntryForm2(HttpServletRequest request, Model model) {
        String entryId = request.getParameter("entryId");

        CustomerEntry entry = customerService.getById(entryId);
        CrmPartner crmPartner = partnerService.getById(entry.getPartnerId());
        model.addAttribute("partner", crmPartner);
        model.addAttribute("entry", entry);
        CustomerEntrySurveyRecord surveyRecord = surveyRecordDao.findOneByEntryId(entryId);
        if (surveyRecord != null){
            model.addAttribute("surveyRecord", surveyRecord);
        }
        String projectId = entry.getProjectId();
        if(PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())){
            List<Record> projects = crmCustomerEntryProjectDao.getProjectsByEntryId(entry.getId());
            projectId = projects.get(0).getStr("id");
        }
        CrmProjectSetting pro = projectService.getById(projectId);
        model.addAttribute("pro", pro);
        //地址信息
        String province = entry.getProvince();
        List<Record> pros = AddressUtils.findProvinceListByTraderId(entry.getDistributorId(), null);
        model.addAttribute("pros", pros);
        String city = entry.getCity();
        String area = entry.getArea();
        String partner = entry.getPartnerId();
        //根据省查询下面的
        List<Record> citys = AddressUtils.findCityListByTraderId(entry.getDistributorId(), null, province, null);
        List<Record> areas = AddressUtils.findAreaListByTraderId(entry.getDistributorId(), province,null, city, null);
        model.addAttribute("faccitys", citys);
        model.addAttribute("areas", areas);
        CrmTrader trader = traderService.getById(entry.getDistributorId());

        model.addAttribute("trader", trader);
        String traderId = trader.getId();
        if(TraderConstants.TYPE_TWO.equals(trader.getType())){
            traderId =trader.getParentId();
        }
        model.addAttribute("traderId",traderId);
        //获取所有项目信息
        if (StringUtil.isBlank(area)){
            List<Record> projectLists = memberService.getProjectByTraderLists2(traderId, pro.getFilingType(), pro.getManagement());
            model.addAttribute("project", projectLists);
        }else {
            List<Record> projectLists = memberService.getProjectByTraderLists3(traderId, pro.getFilingType(), pro.getManagement(), province, city, area);
            model.addAttribute("project",projectLists);
        }
        // 校验项目对应的项目公式与代理商区域进行匹配
        User user = UserUtils.getUser();
        String traderIds = CrmUtils.getUserRelId(user);
        CrmTrader traderInfo = traderService.getById(traderIds);
        // 获取产品（项目）授权区域  （暂时用不上）
        Object projectSet = null;
//        if (StringUtil.isNotBlank(projectId)){
//            projectSet = customerService.getProjectInfo(projectId);
//        }
        //根据安装地址获取项目公司
        if(StringUtil.isNotBlank(province) && StringUtil.isNotBlank(city) && StringUtil.isNotBlank(area)){
            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",entry.getFilingType());
            projectSet = projectCompanyDao.getCompanyByArea(map);
        }
        model.addAttribute("companyList",projectSet);
        //获取方案类型
        model.addAttribute("insta", projectInstallService.findProjectInstalls());
        //获取方案
        model.addAttribute("plan", planService.findAllPlan());
        if(!PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())) {
            if (CustomerEntryConstants.SCHEME_TYPE_TWO.equals(entry.getSchemeType())) {
                model.addAttribute("compose", customerService.findPlanInfoEntryId(entryId));
            } else {//标准方案
                model.addAttribute("composeOne", customerService.findByEntrySchemeId(entry.getSchemeId()));
            }
        }
        // 获取电站电器材料
        List<Record> componentList = customerEntryComponentService.findByEntryId(entryId);
        List<Record> assemblyList = componentList.stream().filter(r -> r.getStr("item_type").equals("3") ).collect(Collectors.toList());
        List<Record> inverterList = componentList.stream().filter(r -> r.getStr("item_type").equals("1")).collect(Collectors.toList());
        List<Record> gridConnectionList = componentList.stream().filter(r -> r.getStr("item_type").equals("2")).collect(Collectors.toList());
        List<Record> gridSupportList = componentList.stream().filter(r -> r.getStr("item_type").equals("4")).collect(Collectors.toList());
        // 获取系统设置的电器材料
        List<Record> allElectric = planService.findAllElectric();
        //
//        List<Record> sysAssemblyList = allElectric.stream().filter(r -> r.getStr("type").equals("3") && Integer.valueOf(r.get("model"))>=pro.getAssemblySpecs()).collect(Collectors.toList());
        List<Record> records = planService.getElectricSet("3");
        List<Record> sysAssemblyList = new ArrayList<>();
        if(!PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())){
            for (Record record : records) {
                if (Integer.valueOf(record.get("model")) >= pro.getAssemblySpecs()){
                    sysAssemblyList.add(record);
                }
            }
            model.addAttribute("sysAssemblyList", sysAssemblyList);
        }
        model.addAttribute("partnerId",entry.getPartnerId());
        List<Record> sysInverterList = new ArrayList<>();
        Record info2 = formSetService.getListByCondition("02", pro.getManagement());
        FormSetPageVo vo = info2.get("component1_model");
        if (vo != null &&  "1".equals(vo.getStatus())){
            sysInverterList = planService.findAllInverter2();
        }else {
            sysInverterList = planService.findAllInverter();
        }
        List<Record> sysGridConnectionList = allElectric.stream().filter(r -> r.getStr("type").equals("2")).collect(Collectors.toList());
        List<Record> sysGridSupportList = allElectric.stream().filter(r -> r.getStr("type").equals("4")).collect(Collectors.toList());
        model.addAttribute("assemblyList", assemblyList);
        model.addAttribute("inverterList", inverterList);
        model.addAttribute("gridConnectionList", gridConnectionList);
        model.addAttribute("gridSupportList", gridSupportList);

        model.addAttribute("sysInverterList", sysInverterList);
        model.addAttribute("sysGridConnectionList", sysGridConnectionList);
        model.addAttribute("sysGridSupportList", sysGridSupportList);
        //二类卡号
        model.addAttribute("accountCode", customerService.findYxBankConditionCode(entry.getIdCode(),entry.getMobile(),entry.getPartnerId()));
        model.addAttribute("quaimgsCount",0);
        if(surveyRecord != null){
            if(StringUtil.isNotBlank(surveyRecord.getHouseOwnership())){
                String[] arr=surveyRecord.getHouseOwnership().split(",");
                model.addAttribute("quaimgs",arr);
                model.addAttribute("quaimgsCount", arr.length);
            }
            int surveyFilesCount = 0;
            if(StringUtil.isNotBlank(surveyRecord.getSurveyFiles())){
                String[] arr=surveyRecord.getSurveyFiles().split(",");
                surveyFilesCount = arr.length;
            }
            model.addAttribute("surveyFilesCount", surveyFilesCount);
            int vrRoofOneCount = 0;
            if(StringUtil.isNotBlank(surveyRecord.getVrRoofOne())){
                String[] arr=surveyRecord.getVrRoofOne().split(",");
                vrRoofOneCount = arr.length;
            }
            model.addAttribute("vrRoofOneCount", vrRoofOneCount);
            int vrRoofTwoCount = 0;
            if(StringUtil.isNotBlank(surveyRecord.getVrRoofTwo())){
                String[] arr=surveyRecord.getVrRoofTwo().split(",");
                vrRoofTwoCount = arr.length;
            }
            model.addAttribute("vrRoofTwoCount", vrRoofTwoCount);

            int vrRoofThreeCount = 0;
            if(StringUtil.isNotBlank(surveyRecord.getVrRoofThree())){
                String[] arr=surveyRecord.getVrRoofThree().split(",");
                vrRoofThreeCount = arr.length;
            }
            model.addAttribute("vrRoofThreeCount", vrRoofThreeCount);
            int vrRoofFourCount = 0;
            if(StringUtil.isNotBlank(surveyRecord.getVrRoofFour())){
                String[] arr=surveyRecord.getVrRoofFour().split(",");
                vrRoofFourCount = arr.length;
            }
            model.addAttribute("vrRoofFourCount", vrRoofFourCount);
        }
        int attachFilesCount = 0;
        if(StringUtil.isNotBlank(entry.getDesignDrawings())){
            String[] arr=entry.getDesignDrawings().split(",");
            attachFilesCount = arr.length;
        }
        model.addAttribute("attachFilesCount", attachFilesCount);
        int zjpbImgCount = 0;
        if(StringUtil.isNotBlank(entry.getZjpbImg())){
            String[] arr=entry.getZjpbImg().split(",");
            zjpbImgCount = arr.length;
        }
        model.addAttribute("zjpbImgCount", zjpbImgCount);
        int zjzxImgCount = 0;
        if(StringUtil.isNotBlank(entry.getZjzxImg())){
            String[] arr=entry.getZjzxImg().split(",");
            zjzxImgCount = arr.length;
        }
        model.addAttribute("zjzxImgCount", zjzxImgCount);
        int zjcsImgCount = 0;
        if(StringUtil.isNotBlank(entry.getZjcsImg())){
            String[] arr=entry.getZjcsImg().split(",");
            zjcsImgCount = arr.length;
        }
        model.addAttribute("zjcsImgCount", zjcsImgCount);
        int zjhsImgCount = 0;
        if(StringUtil.isNotBlank(entry.getZjhsImg())){
            String[] arr=entry.getZjhsImg().split(",");
            zjhsImgCount = arr.length;
        }
        model.addAttribute("zjhsImgCount", zjhsImgCount);
        CustomerEntryTenant tenant = tenantDao.getByTenantId(entry.getTenantId());
        model.addAttribute("tenant",tenant);
        // 获取表单设置 信息登记阶段
        model.addAttribute("info", formSetService.getListByCondition("01", pro.getManagement()));
        //获取表单设置  勘测设计
        model.addAttribute("info2", formSetService.getListByCondition("02", pro.getManagement()));
        CrmTenantYxBankCard card=tenantYxBankCardDao.getByIdCard(entry.getIdCode(),entry.getManagementType(),entry.getPartnerId());
        model.addAttribute("card",card);
        //屋顶类型
        List<Record> roofTypeList = sysCapitalDictDao.getDictionaryList("roof_type", pro.getManagement());
        model.addAttribute("roofTypeList",roofTypeList);
        //房屋偏向
        List<Record> angleAzimuthList = sysCapitalDictDao.getDictionaryList("angle_azimuth", pro.getManagement());
        model.addAttribute("angleAzimuthList",angleAzimuthList);
        //并网电压等级
        List<Record> voltageClassesList = sysCapitalDictDao.getDictionaryList("voltage_classes", pro.getManagement());
        model.addAttribute("voltageClassesList",voltageClassesList);
        //获取示例图
        List<ProjectTypeDetailVo> reflist=projectInstallService.getProjectReference2("02");
        if(reflist.size()==0){
            reflist = Lists.newArrayList();
        }
        model.addAttribute("reflist",reflist);
        String leaseDate=DateUtils.dateChangeDays(new Date(),60,"yyyy-MM-dd");
        model.addAttribute("leaseDate",leaseDate);
        model.addAttribute("orgFiles", orgFilesDao.findOneByEntryId(entry.getId()));
        String type = request.getParameter("type");
        if(PartnerConstants.PARTNER_ID_YX.equals(entry.getPartnerId())){
            //获取历史设置的汇流方式
            Record recordBox=combinerBoxGroupDao.getEntryCombinerBoxSet(entryId);
            model.addAttribute("recordBox",recordBox);
            //获取一户多站的信息
            Record oneToAnyBoxSet=combinerBoxGroupDao.getOneToAnyBoxSet(entry.getIdCode(),entry.getRegno(),entry.getCreateTraderId(),entry.getTenantType());
            model.addAttribute("oneToAnyBoxSet",oneToAnyBoxSet);
        }
        //多产品参数获取
        if(PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())){
                List<Record> entryProject = crmCustomerEntryProjectDao.getProjectsByEntryId(entry.getId());
                List<CrmCustomerEntryDesign> entryDesigns = crmCustomerEntryDesignDao.findByEntryId(entry.getId());
                List<CrmCustomerEntrySurveyRecordDetail> entrySurveys = crmCustomerEntrySurveyRecordDetailDao.findByEntryId(entry.getId());
                int entryProjectNum = entryProject.size();
               /* if(entryProjectNum<5){
                    for(int i=0;i<5-entryProjectNum;i++){
                        entryProject.add(new Record());
                    }
                }*/
                int entryDesignsNum = entryDesigns.size();
                if(entryDesignsNum<5){
                    for(int i=0;i<5-entryDesignsNum;i++){
                        entryDesigns.add(new CrmCustomerEntryDesign());
                    }
                }
               /* int entrySurveysNum = entrySurveys.size();
                if(entrySurveysNum<5){
                    for(int i=0;i<5-entrySurveysNum;i++){
                        entrySurveys.add(new CrmCustomerEntrySurveyRecordDetail());
                    }
                }*/
                if (CustomerEntryConstants.SCHEME_TYPE_TWO.equals(entry.getSchemeType())) {
                    model.addAttribute("compose", customerService.findPlanInfoEntryId(entryId));
                } else {//标准方案
                    List<Record> composeOnes = new ArrayList<>();
                    for(CrmCustomerEntryDesign entryDesign:entryDesigns){
                        Record composeOne = customerService.findByEntrySchemeId(entryDesign.getSchemeId());
                        if(composeOne!=null){
                            composeOne.set("projectId",entryDesign.getProjectId());
                        }
                        composeOnes.add(composeOne);
                    }
                    model.addAttribute("composeOneHr", composeOnes);
                }
                for(Record project:entryProject){
                    if(project!=null&&StringUtil.isNotBlank(project.getStr("id"))){
                        for (Record record : records) {
                            if (Integer.valueOf(record.get("model")) >= project.getInt("assembly_specs")){
                                    Record record1 = new Record().setColumns(record);
                                    record1.set("projectId",project.getStr("id"));
                                    sysAssemblyList.add(record1);
                            }
                        }
                    }
                }
                model.addAttribute("sysAssemblyList", sysAssemblyList);
                model.addAttribute("entryProject",entryProject);
                model.addAttribute("entryProjectNum",entryProjectNum);
                model.addAttribute("entryDesigns",entryDesigns);
                model.addAttribute("entrySurveys",entrySurveys);
                if ("1".equals(type)){
                    return "modules/yangguang/customer/entry/editCustomerEntryForm2HR";
                } else if ("2".equals(type)) {
                    return "modules/yangguang/customer/entry/designCustomerEntryHR";
                }
        }
        if(PartnerConstants.PARTNER_ID_GF.equals(entry.getPartnerId())){
            List<RoofSetFormVo> GfRoofTypeFormSet=FormSetService.getGfFormSetByRoofType();
            model.addAttribute("GfRoofTypeFormSet",new Gson().toJson(GfRoofTypeFormSet));
        }
        if ("1".equals(type)){
            return "modules/yangguang/customer/entry/editCustomerEntryForm2";
        } else if ("2".equals(type)) {
            return "modules/yangguang/customer/entry/designCustomerEntry";
        }
        return null;
    }

    @ResponseBody
    @RequestMapping(value = "/getCompany/{projectId}", method = RequestMethod.GET)
    public Result getCompany(@PathVariable String projectId) {
        // 校验项目对应的项目公式与代理商区域进行匹配
        User user = UserUtils.getUser();
        String traderIds = CrmUtils.getUserRelId(user);
        CrmTrader traderInfo = traderService.getById(traderIds);
        // 获取产品（项目）授权区域  （暂时用不上）
        List<ProjectPcd> projects = projectPcdDao.findListByProjectId(projectId);
        CrmProjectSetting crmProjectSetting = projectDao.get(projectId);
        // 获取代理商授权区域
        List<TraderPcd> traders = traderPcdDao.findListByTraderId(traderInfo.getId());
        // 获取项目公司的id
        String[] split = crmProjectSetting.getProjectCompanyId().split(",");
        // 授权区域集合
        List<String> idList = new ArrayList<>();
        for (String s : split) {
            // 获取项目公司授权地址的id
            for (TraderPcd traderPcd : traders) {
                boolean b = projectCompanyDao.checkAuth2(s, traderPcd.getProvince(), traderPcd.getCity(), traderPcd.getArea());
                if (b) {
                    idList.add(s);
                }
            }
        }
        List<Record> projectInfo = projectInfoSettingService.getProjectInfo(projectId);
        // 对比id时候存在项目公司授权的idList中
        List<Record> projectVo = new ArrayList<>();
        for (Record record : projectInfo) {
            //判断产品授权公司是否为空
            if (record != null){
                String id = record.getStr("id");
                if (record.getStr("name").equals("广州越创皓光伏科技有限公司")){
                    projectVo.add(record);
                    continue;
                }
                if (idList.contains(id)) {
                    projectVo.add(record);
                }
            }
        }
        return Result.success(projectVo);
    }


    /**
     * 勘测提交设计
     */
    @ResponseBody
    @RequestMapping(value = "surveyToDesign")
    public Object surveyToDesign(@RequestBody SurveyEntryReq req) {
        User user = UserUtils.getUser();
        if(!SourceConstants.STATUS_ZERO.equals(user.getStatus())){
            return Result.fail("当前账号已禁用或已删除，不可操作！");
        }
        try {
            Operator operator = Operator.of(user.getId(), CrmUtils.getUserXM(user),user.getUserType());
            String msg = customerService.surveyToDesign(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 = "backToSurvey")
    public Result backToSurvey(String id,String remark) {
        if (StringUtils.isBlank(id)){
            return Result.fail("电站id为空");
        }
        try {
            User user = UserUtils.getUser();
            Operator operator = Operator.of(user.getId(), CrmUtils.getUserXM(user),user.getUserType());
            String msg = customerService.designBackCustomerEntry(id, remark,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) {
        try {
            User user = UserUtils.getUser();
            Operator operator = Operator.of(user.getId(), CrmUtils.getUserXM(user),user.getUserType());
            String msg = customerService.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", "操作失败");
        }
    }


    @ResponseBody
    @RequestMapping(value = "updateCustomerEntry")
    public Object updateCustomerEntry(HttpServletRequest request, @RequestBody AddEntryReq req) {
        User user = UserUtils.getUser();
        if(!SourceConstants.STATUS_ZERO.equals(user.getStatus())){
            return Result.fail("当前账号已禁用或已删除，不可操作！");
        }
        try {
            Operator operator = Operator.of(user.getId(), CrmUtils.getUserXM(user),user.getUserType());
            String msg = customerService.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 = "updateCustomerEntry2")
    public Object updateCustomerEntry2(HttpServletRequest request, @RequestBody AddEntryReq req) {
        User user = UserUtils.getUser();
        if(!SourceConstants.STATUS_ZERO.equals(user.getStatus())){
            return Result.fail("当前账号已禁用或已删除，不可操作！");
        }
        try {
            Operator operator = Operator.of(user.getId(), CrmUtils.getUserXM(user),user.getUserType());
            String msg = customerService.editCustomerEntry(req, operator);
            if (!"200".equals(msg)) {
                return Result.fail(msg);
            }
            return Result.ok();
        }catch (BusinessException e){
            logger.error(e.getMessage(),e);
            e.printStackTrace();
            return Result.fail(e.getMessage());
        }catch (Exception e) {
            logger.error(e.getMessage(),e);
            e.printStackTrace();
            throw e;
        }
    }


    /**
     * 跳转审核页面
     */
    @RequestMapping(value = "toExamineForm")
    public String toExamineForm(HttpServletRequest request, Model model) {
        String entryId = request.getParameter("entryId");

        String type = request.getParameter("type");
        model.addAttribute("type", type);
        CustomerEntry entry = customerService.getById(entryId);
        model.addAttribute("entry", entry);

        CustomerEntrySurveyRecord surveyRecord = surveyRecordDao.findOneByEntryId(entryId);
        model.addAttribute("surveyRecord", surveyRecord);
        String projectId = entry.getProjectId();
        if(PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())){
            List<Record> projects = crmCustomerEntryProjectDao.getProjectsByEntryId(entry.getId());
            projectId = projects.get(0).getStr("id");
        }
        CrmProjectSetting pro = projectService.getById(projectId);
        model.addAttribute("pro", pro);
        //地址信息
        List<Record> pros = addressService.getProvinces();
        model.addAttribute("pros", pros);
        String province = entry.getProvince();
        String city = entry.getCity();
        //根据省查询下面的
        List<Record> citys = AddressUtils.getCityByProName(province);
        List<Record> areas = AddressUtils.getAreaByCityName(city);
        model.addAttribute("faccitys", citys);
        model.addAttribute("areas", areas);
        CrmTrader trader = traderService.getById(entry.getDistributorId());

        model.addAttribute("trader", trader);
        //获取所有项目信息
        model.addAttribute("project", memberService.getProjectByTraderLists(trader.getId()));
        //获取安装方式
        model.addAttribute("insta", projectInstallService.findProjectInstalls());

        //获取方案
        model.addAttribute("plan", planService.findAllPlan());
        if(CustomerEntryConstants.SCHEME_TYPE_TWO.equals(entry.getSchemeType())){
            model.addAttribute("compose", customerService.findPlanInfoEntryId(entryId));
            model.addAttribute("comPlan",planService.findPlanByAssembly("","",""));
            if(entry.getDesignCapacity() == null){
                entry.setDesignCapacity(0);
            }
            //根据组件规格和组件块数查找电气配置
            if(StringUtil.isNotBlank(entry.getComponentSpec())&& entry.getDesignCapacity()!= null&& entry.getDesignCapacity()>0){
                model.addAttribute("elect",planService.findElectricPlan(entry.getComponentSpec(),entry.getDesignCapacity().toString()));
            }
            // planService.findPlanByAssembly(entry.getComponentSpec(),"",entry);

        }else{
            model.addAttribute("composeOne",customerService.findByEntrySchemeId(entry.getSchemeId()));
        }
        // 获取电站电器材料
        List<Record> componentList = customerEntryComponentService.findByEntryId(entryId);
        List<Record> assemblyList = componentList.stream().filter(r -> r.getStr("item_type").equals("3")).collect(Collectors.toList());
        List<Record> inverterList = componentList.stream().filter(r -> r.getStr("item_type").equals("1")).collect(Collectors.toList());
        List<Record> gridConnectionList = componentList.stream().filter(r -> r.getStr("item_type").equals("2")).collect(Collectors.toList());
        List<Record> gridSupportList = componentList.stream().filter(r -> r.getStr("item_type").equals("4")).collect(Collectors.toList());
        // 获取系统设置的电器材料
        List<Record> allElectric = planService.findAllElectric();
        List<Record> sysAssemblyList = new ArrayList<>();
        if(!PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())){
            sysAssemblyList = allElectric.stream().filter(r -> r.getStr("type").equals("3") && Integer.valueOf(r.get("model"))>=pro.getAssemblySpecs() ).collect(Collectors.toList());
        }

        List<Record> sysInverterList = allElectric.stream().filter(r -> r.getStr("type").equals("1")).collect(Collectors.toList());
        List<Record> sysGridConnectionList = allElectric.stream().filter(r -> r.getStr("type").equals("2")).collect(Collectors.toList());
        List<Record> sysGridSupportList = allElectric.stream().filter(r -> r.getStr("type").equals("4")).collect(Collectors.toList());
        model.addAttribute("assemblyList", assemblyList);
        model.addAttribute("inverterList", inverterList);
        model.addAttribute("gridConnectionList", gridConnectionList);
        model.addAttribute("sysAssemblyList", sysAssemblyList);
        model.addAttribute("sysInverterList", sysInverterList);
        model.addAttribute("sysGridConnectionList", sysGridConnectionList);
        model.addAttribute("sysGridSupportList", sysGridSupportList);
        model.addAttribute("gridSupportList", gridSupportList);
        //获取所欲逆变器和并网箱
        model.addAttribute("inverters",planService.getElectricSet("1"));
        model.addAttribute("boxs",planService.getElectricSet("2"));
        model.addAttribute("quaimgsCount",0);
        if(StringUtil.isNotBlank(surveyRecord.getHouseOwnership())){
            String[] arr=surveyRecord.getHouseOwnership().split(",");
            model.addAttribute("quaimgs",arr);
            model.addAttribute("quaimgsCount", arr.length);
        }
        // 获取表单设置 信息登记阶段
        model.addAttribute("info", formSetService.getListByCondition("01", pro.getManagement()));
        //获取表单设置  勘测设计
        model.addAttribute("info2", formSetService.getListByCondition("02", pro.getManagement()));
        CrmTenantYxBankCard card=tenantYxBankCardDao.getByIdCard(entry.getIdCode(),entry.getManagementType(),entry.getPartnerId());
        model.addAttribute("card",card);
        CustomerEntryTenant tenant = tenantDao.getByTenantId(entry.getTenantId());
        model.addAttribute("tenant",tenant);

        IsInteger str = new IsInteger();
        if(str.isInteger(entry.getStatus())&& (entry.getStatus().equals("0")|| entry.getStatus().equals("1") || entry.getStatus().equals("2") || entry.getStatus().equals("3") || entry.getStatus().equals("4")) ){
            String stationName=entry.getProvince()+entry.getArea()+entry.getTenantName()+(new BigDecimal(entry.getDesignCapacity()).divide(new BigDecimal(1000),3, RoundingMode.DOWN).stripTrailingZeros().toPlainString())+"KW光伏电站";
            model.addAttribute("stationName", stationName);
        }else{
            String stationName=entry.getProvince()+entry.getArea()+entry.getTenantName()+(entry.getActualCapacity().divide(new BigDecimal(1000),3, RoundingMode.DOWN).stripTrailingZeros().toPlainString())+"KW光伏电站";
            model.addAttribute("stationName", stationName);
        }
        //房屋偏向
        List<Record> angleAzimuthList = sysCapitalDictDao.getDictionaryList("angle_azimuth", pro.getManagement());
        model.addAttribute("angleAzimuthList",angleAzimuthList);

        if ("1".equals(entry.getTenantType())) {
            model.addAttribute("authorizationUrl", customerService.getContractPath(entry));
        }
        if(PartnerConstants.PARTNER_ID_YX.equals(entry.getPartnerId())){
            //获取历史设置的汇流方式
            Record recordBox=combinerBoxGroupDao.getEntryCombinerBoxSet(entryId);
            model.addAttribute("recordBox",recordBox);
            //获取一户多站的信息
            Record oneToAnyBoxSet=combinerBoxGroupDao.getOneToAnyBoxSet(entry.getIdCode(),entry.getRegno(),entry.getCreateTraderId(),entry.getTenantType());
            model.addAttribute("oneToAnyBoxSet",oneToAnyBoxSet);
        }
        //多产品参数获取
        if(PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())){
            List<Record> entryProject = crmCustomerEntryProjectDao.getProjectsByEntryId(entry.getId());
            List<CrmCustomerEntryDesign> entryDesigns = crmCustomerEntryDesignDao.findByEntryId(entry.getId());
            List<CrmCustomerEntrySurveyRecordDetail> entrySurveys = crmCustomerEntrySurveyRecordDetailDao.findByEntryId(entry.getId());
            int entryProjectNum = entryProject.size();
            if(entryProjectNum<5){
                for(int i=0;i<5-entryProjectNum;i++){
                    entryProject.add(new Record());
                }
            }
            int entryDesignsNum = entryDesigns.size();
            if(entryDesignsNum<5){
                for(int i=0;i<5-entryDesignsNum;i++){
                    entryDesigns.add(new CrmCustomerEntryDesign());
                }
            }
            int entrySurveysNum = entrySurveys.size();
            if(entrySurveysNum<5){
                for(int i=0;i<5-entrySurveysNum;i++){
                    entrySurveys.add(new CrmCustomerEntrySurveyRecordDetail());
                }
            }
            if (CustomerEntryConstants.SCHEME_TYPE_TWO.equals(entry.getSchemeType())) {
                model.addAttribute("compose", customerService.findPlanInfoEntryId(entryId));
            } else {//标准方案
                List<Record> composeOnes = new ArrayList<>();
                for(CrmCustomerEntryDesign entryDesign:entryDesigns){
                    Record composeOne = customerService.findByEntrySchemeId(entryDesign.getSchemeId());
                    if(composeOne!=null){
                        composeOne.set("projectId",entryDesign.getProjectId());
                    }
                    composeOnes.add(composeOne);
                }
                model.addAttribute("composeOneHr", composeOnes);
            }
            List<Record> records = planService.getElectricSet("3");
            for(Record project:entryProject){
                if(project!=null&&StringUtil.isNotBlank(project.getStr("id"))){
                    for (Record record : records) {
                        if (Integer.valueOf(record.get("model")) >= project.getInt("assembly_specs")){
                            Record record1 = new Record().setColumns(record);
                            record1.set("projectId",project.getStr("id"));
                            sysAssemblyList.add(record1);
                        }
                    }
                }
            }
            model.addAttribute("sysAssemblyList", sysAssemblyList);
            model.addAttribute("entryProject",entryProject);
            model.addAttribute("entryProjectNum",entryProjectNum);
            model.addAttribute("entryDesigns",entryDesigns);
            model.addAttribute("entrySurveys",entrySurveys);
            return "modules/yangguang/customer/entry/toExamineFormHR";
        }
        if(PartnerConstants.PARTNER_ID_GF.equals(entry.getPartnerId())){
            List<RoofSetFormVo> GfRoofTypeFormSet=FormSetService.getGfFormSetByRoofType();
            model.addAttribute("GfRoofTypeFormSet",new Gson().toJson(GfRoofTypeFormSet));
        }
        return "modules/yangguang/customer/entry/toExamineForm";
    }



    @RequestMapping(value = "togdtExamineForm")
    public String togdtExamineForm(HttpServletRequest request, Model model) {
        String entryId = request.getParameter("entryId");

        CustomerEntry entry = customerService.getById(entryId);
        model.addAttribute("entry", entry);

        CrmProjectSetting pro = projectService.getById(entry.getProjectId());
        model.addAttribute("pro", pro);
        //地址信息
        List<Record> pros = addressService.getProvinces();
        model.addAttribute("pros", pros);
        String province = entry.getProvince();
        String city = entry.getCity();
        //根据省查询下面的
        List<Record> citys = AddressUtils.getCityByProName(province);
        List<Record> areas = AddressUtils.getAreaByCityName(city);
        model.addAttribute("faccitys", citys);
        model.addAttribute("areas", areas);
        CrmTrader trader = traderService.getById(entry.getDistributorId());

        model.addAttribute("trader", trader);
        //获取所有项目信息
        model.addAttribute("project", memberService.getProjectByTraderLists(trader.getId()));
        //获取安装方式
        model.addAttribute("insta", projectInstallService.findProjectInstalls());

        //获取方案
        model.addAttribute("plan", planService.findAllPlan());
        if(CustomerEntryConstants.SCHEME_TYPE_TWO.equals(entry.getSchemeType())){
            model.addAttribute("compose", customerService.findByEntryId(entryId));
            model.addAttribute("comPlan",planService.findPlanByAssembly("","",""));
            if(entry.getDesignCapacity() == null){
                entry.setDesignCapacity(0);
            }
            //根据组件规格和组件块数查找电气配置
            if(StringUtil.isNotBlank(entry.getComponentSpec())&& entry.getDesignCapacity()!= null&& entry.getDesignCapacity()>0){
                model.addAttribute("elect",planService.findElectricPlan(entry.getComponentSpec(),entry.getDesignCapacity().toString()));
            }
            // planService.findPlanByAssembly(entry.getComponentSpec(),"",entry);

        }
        // 获取电站电器材料
        List<Record> componentList = customerEntryComponentService.findByEntryId(entryId);
        List<Record> assemblyList = componentList.stream().filter(r -> r.getStr("item_type").equals("3")).collect(Collectors.toList());
        List<Record> inverterList = componentList.stream().filter(r -> r.getStr("item_type").equals("1")).collect(Collectors.toList());
        List<Record> gridConnectionList = componentList.stream().filter(r -> r.getStr("item_type").equals("2")).collect(Collectors.toList());
        List<Record> gridSupportList = componentList.stream().filter(r -> r.getStr("item_type").equals("4")).collect(Collectors.toList());
        // 获取系统设置的电器材料
        List<Record> allElectric = planService.findAllElectric();
        List<Record> sysAssemblyList = allElectric.stream().filter(r -> r.getStr("type").equals("3")).collect(Collectors.toList());
        List<Record> sysInverterList = allElectric.stream().filter(r -> r.getStr("type").equals("1")).collect(Collectors.toList());
        List<Record> sysGridConnectionList = allElectric.stream().filter(r -> r.getStr("type").equals("2")).collect(Collectors.toList());
        List<Record> sysGridSupportList = allElectric.stream().filter(r -> r.getStr("type").equals("4")).collect(Collectors.toList());
        model.addAttribute("assemblyList", assemblyList);
        model.addAttribute("inverterList", inverterList);
        model.addAttribute("gridConnectionList", gridConnectionList);
        model.addAttribute("sysAssemblyList", sysAssemblyList);
        model.addAttribute("sysInverterList", sysInverterList);
        model.addAttribute("sysGridConnectionList", sysGridConnectionList);
        model.addAttribute("sysGridSupportList", sysGridSupportList);
        model.addAttribute("gridSupportList", gridSupportList);

        //获取所欲逆变器和并网箱
        model.addAttribute("inverters",planService.getElectricSet("1"));
        model.addAttribute("boxs",planService.getElectricSet("2"));
        return "modules/yangguang/customer/entry/gdt/togdtExamineForm";
    }
    /**
     * 设计审核 通过
     */
    @ResponseBody
    @RequestMapping("toExamine")
    public Object toExamine(@RequestBody CustomerEntry entry, HttpServletRequest request) {
        logger.info("into toExamine, entry::{}", entry);
//        String id = request.getParameter("id");
//        String remarks = request.getParameter("remarks");
//        String palnId = request.getParameter("palnId");
//        String composePlanList = request.getParameter("composePlanList");
//        String schemeRemarks = request.getParameter("schemeRemarks");
//        String componentCount = request.getParameter("componentCount");
//        String componentSpec = request.getParameter("componentSpec");
//        String schemeType = request.getParameter("schemeType");
//
//        String cageOne = request.getParameter("cageOne");
//        String cageTwo = request.getParameter("cageTwo");
//        String cageThree = request.getParameter("cageThree");
//        String inverterOne = request.getParameter("inverterOne");
//        String inverterTwo = request.getParameter("inverterTwo");
//        String inverterThree = request.getParameter("inverterThree");
//
//        if (StringUtil.isBlank(id)) {
//            return Result.fail("201", "参数id为空");
//        }
//        if (CustomerEntryConstants.SCHEME_TYPE_ONE.equals(schemeType) && StringUtil.isBlank(palnId)) {
//            return Result.fail("201", "请选择匹配方案");
//        }
        User user = UserUtils.getUser();
        Operator operator = Operator.of(user.getId(),CrmUtils.getUserXM(user),user.getUserType());
        try {
            customerService.toExamine(entry.getId(), entry.getExamineRemarks(), operator, user);

        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(e.getMessage());
        }
        return Result.ok();
    }

    /**
     * 审核不通过
     */
    @ResponseBody
    @RequestMapping("failedCustomerEntry")
    public Object failedCustomerEntry(HttpServletRequest request) {
        String id = request.getParameter("id");
        String remarks = request.getParameter("remarks");
        if (StringUtil.isBlank(id)) {
            return Result.fail("202", "参数id为空");
        }
        User user = UserUtils.getUser();
        Operator operator = Operator.of(user.getId(),CrmUtils.getUserXM(user) ,user.getUserType());
        try {
            customerService.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();
    }

    /**
     * 国电投审核
     */
    @ResponseBody
    @RequestMapping("gdtToExamine")
    public Object gdtToExamine(HttpServletRequest request) {
        String id = request.getParameter("id");
        String type = request.getParameter("type");
        String remarks = request.getParameter("remarks");
        if (StringUtil.isBlank(id)) {
            return Result.fail("202", "参数id为空");
        }
        User user = UserUtils.getUser();
        Operator operator = Operator.of(user.getId(),CrmUtils.getUserXM(user) ,user.getUserType());
        try {
            customerService.gdtToExamine(id, remarks,operator,type);
        } catch (Exception e) {
            Result result = new Result();
            e.printStackTrace();
            result.setCode("505");
            result.setMsg("Exception" + e);
            throw e;
        }
        return Result.ok();
    }


    /**
     * 手动准入白名单
     */
    @ResponseBody
    @RequestMapping("shoudongCustomerEntry")
    public Object shoudongCustomerEntry(HttpServletRequest request) {
        String id = request.getParameter("id");

        if (StringUtil.isBlank(id)) {
            return Result.fail("202", "参数id为空");
        }
        Result result;
        try {
            result = customerService.shoudongCustomerEntry(id);
        } catch (Exception e) {
            result = new Result();
            e.printStackTrace();
            result.setCode("505");
            result.setMsg("Exception" + e);
            throw e;
        }
        return result;
    }



    /**
     * 待下订单
     */
    @RequestMapping("/waitOrder")
    public String waitOrderList(Model model) {
        setCommonData(model);
        return "modules/yangguang/customer/entry/waitOrderList";
    }

    /**
     * 待收货项目
     */
    @RequestMapping("/waitReceive")
    public String waitReceiveList(Model model) {
        setCommonData(model);
        return "modules/yangguang/customer/entry/waitReceiveList";
    }

    /**
     * 电站安装
     */
    @RequestMapping("/waitInstall/{partner}")
    public String waitInstall(@PathVariable("partner")String partner ,Model model) {
        setCommonData(model);
        model.addAttribute("partner",partner);
        model.addAttribute("wgBtnPermission","XMGL_DZAZ_WG_B_"+partner);
        return "modules/yangguang/customer/entry/waitInstallList";
    }

    /**
     * 安装验收
     */
    @RequestMapping("/fixAccept/{partner}")
    public String fixAccept(@PathVariable("partner")String partner ,Model model) {
        setCommonData(model);
        model.addAttribute("partner",partner);
        model.addAttribute("ptysBtnPermission","XMGL_AZYS_YS_B_"+partner);
        model.addAttribute("dlsysBtnPermission","XMGL_AZYS_AZZS_B_"+partner);
        return "modules/yangguang/customer/entry/waitFixAcceptList";
    }
    /**
     * 批量派工页面
     *
     */
    @RequestMapping(value = "toBatchDispatchPage")
    public String toBatchDispatchPage(String entryIds, Model model) {
        logger.info("entryIds={}", entryIds);
        model.addAttribute("entryIds", entryIds);
        return "modules/yangguang/customer/entry/batchDispatchPage";
    }

    /**
     * 批量派工-员工数据
     */
    @ResponseBody
    @RequestMapping(value = "ajaxForDispatchEngineer")
    public Object ajaxForDispatchEngineer(HttpServletRequest request) {
        LayuiPage<Record> page = new LayuiPage<>(request);
        Map<String, String> params = getParams(request);
        String traderId = CrmUtils.getCurrentTraderId(UserUtils.getUser().getId());
        page.setData(traderEmployeService.getTaderEmployeData(params, traderId));
        return page.renderJson();
    }

    /**
     * 批量派工
     * userType=6可操作
     */
    @ResponseBody
    @RequestMapping(value = "batchDispatch")
    public Result batchDispatch(@RequestBody BatchDispatchReq req) {
        logger.info("into batchDispatch, req={}", req);
        customerService.batchDispatch(req);
        return Result.ok();
    }

    //撤销派工
    @ResponseBody
    @RequestMapping(value = "turnbackDispatch")
    public Result turnbackDispatch(String ids) {
        logger.info("into turnbackDispatch, ids={}", ids);
        customerService.turnbackDispatch(ids);
        return Result.ok();
    }

    /**
     * 电站并网
     */
    @RequestMapping("/waitMerge/{partner}")
    public String waitMerge(@PathVariable("partner")String partner ,Model model) {
        setCommonData(model);
        model.addAttribute("partner",partner);
        return "modules/yangguang/customer/entry/waitMergeList";
    }
    /**
     * 发票上传
     */
    @RequestMapping(value = "uploadBill")
    public String uploadBill(Model model){
        setCommonData(model);
        return "modules/yangguang/customer/entry/uploadBillList";
    }

    /**
     * 合同签署
     */
    @RequestMapping(value = "signContract")
    public String signContract(Model model){
        setCommonData(model);
        return "modules/yangguang/customer/entry/signContractList";
    }

    /**
     * 待验收项目
     * 代理商只能查看自己的数据
     * 系统工程师和项目工程师能查看角色数据权限范围内的数据
     * 只有项目工程师能操作验收
     */
    @RequestMapping("/waitAccept/{partner}")
    public String waitAccept(@PathVariable("partner")String partner  ,Model model) {
        setCommonData(model);
        model.addAttribute("partner",partner);
        return "modules/yangguang/customer/entry/waitAcceptList";
    }
    /**
     * 待交付项目
     */
    @RequestMapping("/waitDeliver")
    public String waitDeliver(Model model) {
        setCommonData(model);
        //项目工程师列表
        List<Record> empList = siteEmployeeService.findProjectEmpList("2,d");
        model.addAttribute("empList", empList);
        return "modules/yangguang/customer/entry/waitDeliverList";
    }

    /**
     * 项目归档
     */
    @RequestMapping("/inDoc")
    public String inDoc(Model model) {
        setCommonData(model);
        //项目工程师列表
        List<Record> empList = siteEmployeeService.findProjectEmpList("2,d");
        model.addAttribute("empList", empList);
        return "modules/yangguang/customer/entry/inDocList";
    }

    /**
     * 已完成项目
     */
    @RequestMapping("/completeList/{partner}")
    public String completeList(@PathVariable("partner")String partner ,Model model) {
        setCommonData(model);
        //项目工程师列表
        List<Record> empList = siteEmployeeService.findProjectEmpList("2,d");
        String today = DateUtils.formatDate(new Date(), "yyyy-MM-dd");
        String monthAgo = DateUtils.subDate(new Date(), 30);
        model.addAttribute("empList", empList);
        model.addAttribute("today", today);
        model.addAttribute("monthAgo", monthAgo);
        model.addAttribute("partner",partner);
        return "modules/yangguang/customer/entry/completeList";
    }

    /**
     * 电站档案查询
     */
    @RequestMapping("/totalList/{partner}")
    public String totalList(Model model,@PathVariable("partner") String partner) {
        setCommonData(model);
        User user = UserUtils.getUser();
        //项目工程师列表
        List<Record> empList = siteEmployeeService.findProjectEmpList("2,d");
        String today = DateUtils.formatDate(new Date(), "yyyy-MM-dd");
        String monthAgo = DateUtils.subDate(new Date(), 30);
        model.addAttribute("empList", empList);
        //系统工程师
        List<Record> empXtList = siteEmployeeService.findProjectEmpList("1,b,c");
        model.addAttribute("empXtList", empXtList);
        model.addAttribute("today", today);
        model.addAttribute("monthAgo", monthAgo);
        if(User.USER_TYPE_KJ.equals(user.getUserType())){
            String traderId = CrmUtils.getUserRelId(user);
            model.addAttribute("traderEmp",traderEmployeService.getTaderEmployeData(null,traderId));
        }
        List<Record> pros = addressService.getProvinces();
        model.addAttribute("province", pros);
        model.addAttribute("partner",partner);

        return "modules/yangguang/customer/entry/totalList";
    }

    /**
     * 待接收项目
     */
    @RequestMapping(value = "waitReceiveProjects")
    public String waitReceiveProjects(Model model) {
        setCommonData(model);
        return "modules/yangguang/customer/entry/hzsWaitReceiveList";
    }


    @ResponseBody
    @RequestMapping("/ajaxForWaitOrder")
    public Object ajaxForWaitOrder(HttpServletRequest request){
        Date now = new Date();
        String sn = DateUtils.formatDate(now, "yyyyMMddHHmmss");
        // System.out.println("获取项目信息列表 时间统计----" + sn);
        long s1 = System.currentTimeMillis();
        LayuiPage<Record> page = new LayuiPage<>(request);
        Map<String, String> map = getParams(request);
        User user = UserUtils.getUser();
        if(User.USER_TYPE_HZS.equals(user.getUserType())){
            String parId = CrmUtils.getPartnerId(user.getId());
            CrmPartner partner = partnerService.getById(parId);
            map.put("authorizedId", partner.getAuthorizedId());
        }else if(User.USER_TYPE_PARTNER.equals(user.getUserType())){
            CrmPartner partner = partnerService.findByUserId(user.getId());
            map.put("authorizedId", partner.getAuthorizedId());
        } else if (User.USER_TYPE_ADVISOR.equals(user.getUserType())) {
            CrmTraderEmploye employe = traderEmployeService.findByUserId(user.getId());
            map.put("engineerId", employe.getId());
        }
        Operator operator = Operator.of(user.getId(), CrmUtils.getUserXM(user),user.getUserType());
        customerService.listWaitOrder(page, map, operator);
        long s2 = System.currentTimeMillis();
        logger.info(" >>获取项目信息列表 时间统计  [{}] end doSave use {}ms ", sn, (s2 - s1));
        return page.renderJson();
    }

    /**
     * 回收站
     */
    @RequestMapping("/findRecycleBinList/{partner}")
    public String findRecycleBinList(@PathVariable("partner")String partner ,Model model) {
        setCommonData(model);
        //项目工程师列表
        List<Record> empList = siteEmployeeService.findProjectEmpList("2,d");
        String today = DateUtils.formatDate(new Date(), "yyyy-MM-dd");
        String monthAgo = DateUtils.subDate(new Date(), 30);
        model.addAttribute("empList", empList);
        model.addAttribute("today", today);
        model.addAttribute("monthAgo", monthAgo);
        model.addAttribute("partner",partner);
        return "modules/yangguang/customer/entry/recycleBinList";
    }
    @ResponseBody
    @RequestMapping("/findRecycleBinOrders")
    public Object findRecycleBinOrders(HttpServletRequest request){
        LayuiPage<Record> page = new LayuiPage<>(request);
        Map<String, String> map = getParams(request);
        User user = UserUtils.getUser();
        Operator operator = Operator.of(user.getId(), CrmUtils.getUserXM(user),user.getUserType());
        customerService.findRecycleBinOrders(page, map, operator);
        return page.renderJson();
    }


    /**
     * 申请重审订单
     */
    @RequestMapping("/findRetrialList")
    public String findRetrialList(Model model) {
        setCommonData(model);
        //项目工程师列表
        List<Record> empList = siteEmployeeService.findProjectEmpList("2,d");
        String today = DateUtils.formatDate(new Date(), "yyyy-MM-dd");
        String monthAgo = DateUtils.subDate(new Date(), 30);
        model.addAttribute("empList", empList);
        model.addAttribute("today", today);
        model.addAttribute("monthAgo", monthAgo);
        return "modules/yangguang/customer/entry/retrialList";
    }

    @ResponseBody
    @RequestMapping("/findRetrialPage")
    public Object findRetrialPage(HttpServletRequest request){
        LayuiPage<Record> page = new LayuiPage<>(request);
        Map<String, String> map = getParams(request);
        User user = UserUtils.getUser();
        Operator operator = Operator.of(user.getId(), CrmUtils.getUserXM(user),user.getUserType());
        customerService.findRetrialPage(page, map, operator,"1");
        return page.renderJson();
    }


    /**
     * 申请整改订单
     */
    @RequestMapping("/findChangeList")
    public String findChangeList(Model model) {
        setCommonData(model);
        //项目工程师列表
        List<Record> empList = siteEmployeeService.findProjectEmpList("2,d");
        String today = DateUtils.formatDate(new Date(), "yyyy-MM-dd");
        String monthAgo = DateUtils.subDate(new Date(), 30);
        model.addAttribute("empList", empList);
        model.addAttribute("today", today);
        model.addAttribute("monthAgo", monthAgo);
        model.addAttribute("partner",PartnerConstants.PARTNER_ID_YX);
        return "modules/yangguang/customer/entry/changeList";
    }

    /**
     * 广发电站整改
     */
    @RequestMapping("/findChangeListGF")
    public String findChangeListGF(Model model) {
        setCommonData(model);
        //项目工程师列表
        List<Record> empList = siteEmployeeService.findProjectEmpList("2,d");
        String today = DateUtils.formatDate(new Date(), "yyyy-MM-dd");
        String monthAgo = DateUtils.subDate(new Date(), 30);
        model.addAttribute("empList", empList);
        model.addAttribute("today", today);
        model.addAttribute("monthAgo", monthAgo);
        model.addAttribute("partner", PartnerConstants.PARTNER_ID_GF);
        return "modules/yangguang/customer/entry/changeList";
    }

    @ResponseBody
    @RequestMapping("/findChangePage")
    public Object findChangePage(HttpServletRequest request){
        LayuiPage<Record> page = new LayuiPage<>(request);
        Map<String, String> map = getParams(request);
        User user = UserUtils.getUser();
        Operator operator = Operator.of(user.getId(), CrmUtils.getUserXM(user),user.getUserType());
        customerService.findRetrialPage(page, map, operator,"2");
        return page.renderJson();
    }

    /**
     * 跳转重新审核页面选择原因
     */
    @RequestMapping("/entryRetrialDetail")
    public String entryRetrialDetail(String ids,  Model model) {

        //获取重审原因
        List<Record> list = applicationService.getApplicationList();
        model.addAttribute("list", list);
        model.addAttribute("ids", ids);
        return "modules/yangguang/customer/entry/retrialDetail";
    }

    /**
     * 保存申请重审
     */
    @ResponseBody
    @RequestMapping("/saveRetrial")
    public Result saveRetrial(HttpServletRequest request){

        String ids = request.getParameter("ids");
        if(StringUtil.isBlank(ids)){
            return Result.fail("2001","申请的项目信息为空");
        }
        String applyReasonId = request.getParameter("applyReasonId");
        if(StringUtil.isBlank(applyReasonId)){
            return Result.fail("2001","请选择申请原因");
        }
        String applyReasonName = request.getParameter("applyReasonName");
        User user = UserUtils.getUser();
        Operator operator = Operator.of(user.getId(), CrmUtils.getUserXM(user),user.getUserType());

        customerService.saveRetrial(ids,applyReasonId,applyReasonName,operator);
        return Result.ok();
    }

    @RequestMapping("/examineRetrialDetail")
    public String examineRetrialDetail(String ids,  Model model) {

        //获取重审原因
        List<Record> list = applicationService.getApplicationList();
        model.addAttribute("list", list);
        model.addAttribute("ids", ids);
        return "modules/yangguang/customer/entry/retrialDetail";
    }

    @RequestMapping("/applyChangeDetail")
    public String applyChangeDetail(String ids,  Model model) {
        model.addAttribute("ids", ids);
        model.addAttribute("list", rectificationSettingService.getList(null));
        return "modules/yangguang/customer/entry/applyChange";
    }

    /**
     * 保存变更申请
     */
    @ResponseBody
    @RequestMapping("/saveApplyChange")
    public Result saveApplyChange(HttpServletRequest request) {
        String ids = request.getParameter("ids");
        // 变更类型
        String rectificationId = request.getParameter("rectificationId");
        if (StringUtil.isBlank(ids)) {
            return Result.fail("2001", "申请整改的项目信息为空");
        } else if (StringUtil.isBlank(rectificationId)) {
            return Result.fail("2002", "变更类型不能为空");
        }
        // 申请原因
        String applyReasonName = request.getParameter("applyReasonName");
        User user = UserUtils.getUser();
        Operator operator = Operator.of(user.getId(), CrmUtils.getUserXM(user), user.getUserType());
        try {
            return customerService.saveApplyChange(ids, applyReasonName, rectificationId, operator);
        }catch (IllegalArgumentException i){
            return Result.fail(i.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            logger.info("申请整改失败:{}", e);
            return Result.fail("205", "申请整改失败");
        }
    }


    @ResponseBody
    @RequestMapping("/examineRetrial")
    public Result examineRetrial(HttpServletRequest request){

        String id = request.getParameter("id");
        if(StringUtil.isBlank(id)){
            return Result.fail("2001","项目信息为空");
        }
        String type = request.getParameter("type");
        String objType = request.getParameter("objType");
        String examineRemarks = request.getParameter("examineRemarks");
        User user = UserUtils.getUser();
        Operator operator = Operator.of(user.getId(), CrmUtils.getUserXM(user),user.getUserType());

        customerService.examineRetrial(id,operator,type,examineRemarks,objType);
        return Result.ok();
    }

    /**
     * 变更审核
     */
    @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");
        User user = UserUtils.getUser();
        String auditComments = request.getParameter("auditComments");
        Operator operator = Operator.of(user.getId(), CrmUtils.getUserXM(user), user.getUserType());

        try {
            if ("1".equals(type)) {
                // 变更类型
                String rectificationId = request.getParameter("rectificationId");
                return customerService.approved(id, operator, rectificationId, auditComments);
            } else {
                return customerService.auditFailed(id, operator, auditComments);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("变更审核失败:{}", e);
            return Result.fail("操作失败");
        }
    }

    @RequestMapping(value = "getFlagcustomerEntry")
    public String getFlagcustomerEntry(HttpServletRequest request,Model model){
        String customerEntryId = request.getParameter("customerEntryId");
        model.addAttribute("customerEntryId",customerEntryId);
        model.addAttribute("typeList", markSettingService.getAllMarkType("2"));
        return "modules/yangguang/customer/entry/flagCustomerEntry";
    }

    @RequestMapping(value = "getexamineRetrial")
    public String getexamineRetrial(HttpServletRequest request,Model model){
        String customerEntryId = request.getParameter("customerEntryId");
        String objType = request.getParameter("objType");
        CustomerEntry customerEntry = customerService.getById(customerEntryId);
        model.addAttribute("customerEntry", customerEntry);
        model.addAttribute("objType",objType);
        return "modules/yangguang/customer/entry/examineRetrial";
    }

    /**
     * 变更审核弹窗
     */
    @RequestMapping(value = "getRectificationAudit")
    public String getRectificationAudit(HttpServletRequest request, Model model) {
        String customerEntryId = request.getParameter("customerEntryId");
        CustomerEntry customerEntry = customerService.getById(customerEntryId);
        model.addAttribute("customerEntry", customerEntry);
        model.addAttribute("list", rectificationSettingService.getList(null));
        return "modules/yangguang/customer/entry/rectificationAudit";
    }

    /**
     * 标记工单
     */
    @ResponseBody
    @RequestMapping(value = "flagCustomerEntry")
    public Object flagCustomerEntry(HttpServletRequest request){
        String customerEntryId = request.getParameter("customerEntryId");
        String flag = request.getParameter("flag");
        if(StringUtil.isBlank(customerEntryId)){
            return Result.fail("505","项目信息ID为空");
        }
        return customerService.flagCustomerEntry(customerEntryId,flag);
    }


    /**
     * 电站详情
     */
    @RequestMapping("/entryDetail")
    public String entryDetail(String entryId, String opt, Model model) {
        CustomerEntry customerEntry = customerService.getById(entryId);
        if ("1".equals(customerEntry.getTenantType())) {
            if (PartnerConstants.PARTNER_ID_HR.equals(customerEntry.getPartnerId())){
                model.addAttribute("authorizationUrl", customerService.getContractPath(customerEntry.getTenantType(), customerEntry.getIdCode(), customerEntry.getPartnerId(),customerEntry.getFilingType()));
            }else {
                model.addAttribute("authorizationUrl", customerService.getContractPath(customerEntry));
            }
        }
        CrmPartner crmPartner = partnerService.getById(customerEntry.getPartnerId());
        model.addAttribute("partner", crmPartner);
        CustomerEntrySurveyRecord surveyRecord = surveyRecordDao.findOneByEntryId(entryId);
        if (surveyRecord == null) {
            surveyRecord = new CustomerEntrySurveyRecord();
            if ("1".equals(customerEntry.getFilingType())&&"1".equals(crmPartner.getIsOpenBankCard())) {
                surveyRecord.setRepaymentMethod("1");
            }
            else {
                surveyRecord.setRepaymentMethod("0");
            }
        }
        User user = UserUtils.getUser();
        String traderId="";  //代理商不能看到平台的审批信息
        CrmTrader trader = traderService.getById(customerEntry.getDistributorId());

        if(User.USER_TYPE_ADVISOR.equals(user.getUserType()) || User.USER_TYPE_KJ.equals(user.getUserType())){
            traderId = user.getTraderId();
        }
        List<Record> optList = customerEntryMsgService.listOptRecordByEntryId(entryId,traderId);
        if(StringUtil.isNotBlank(customerEntry.getProjectId())){
            CrmProjectSetting projectSetting = projectService.getById(customerEntry.getProjectId());
            model.addAttribute("project", projectSetting);
        }

        model.addAttribute("user", UserUtils.getUser());
        model.addAttribute("customerEntry", customerEntry);
        IsInteger str = new IsInteger();

        if(str.isInteger(customerEntry.getStatus())&& (customerEntry.getStatus().equals("0")|| customerEntry.getStatus().equals("1") || customerEntry.getStatus().equals("2") || customerEntry.getStatus().equals("3") || customerEntry.getStatus().equals("4")) ){
            String stationName=customerEntry.getProvince()+customerEntry.getArea()+customerEntry.getTenantName()+(new BigDecimal(customerEntry.getDesignCapacity()).divide(new BigDecimal(1000),3, RoundingMode.DOWN).stripTrailingZeros().toPlainString())+"KW光伏电站";
            model.addAttribute("stationName", stationName);
        }else{
            String stationName=customerEntry.getProvince()+customerEntry.getArea()+customerEntry.getTenantName()+(customerEntry.getActualCapacity().divide(new BigDecimal(1000),3, RoundingMode.DOWN).stripTrailingZeros().toPlainString())+"KW光伏电站";
            model.addAttribute("stationName", stationName);
        }
        model.addAttribute("mobile",customerEntry.getMobile());
        model.addAttribute("idCode",customerEntry.getIdCode());
        model.addAttribute("opt", opt);
        model.addAttribute("optList", optList);
        model.addAttribute("trader", trader);
        CrmTenantYxBankCard card=tenantYxBankCardDao.getByIdCard(customerEntry.getIdCode(),
                customerEntry.getManagementType(), customerEntry.getPartnerId());
        model.addAttribute("card",card);
        model.addAttribute("bankName",linkNumberSettingService.findBankNUmberName(customerEntry.getTssBankNum()));
        model.addAttribute("quaimgsCount",0);
        model.addAttribute("surveyRecord", surveyRecord);
        if (StringUtil.isNotBlank(surveyRecord.getHouseOwnership())) {
            String[] arr = surveyRecord.getHouseOwnership().split(",");
            model.addAttribute("quaimgs", arr);
            model.addAttribute("quaimgsCount", arr.length);
        }
        // 获取单位资料信息
//        if (Objects.equals("2", customerEntry.getTenantType())) {
            model.addAttribute("orgFiles", orgFilesDao.findOneByEntryId(customerEntry.getId()));
//        }
        if(!PartnerConstants.PARTNER_ID_HR.equals(customerEntry.getPartnerId())){
            // 安装物料
            Map<String, Object> maps = customerService.findUsedMaterial(customerEntry.getId());
            model.addAttribute("zjList", maps.get("zj"));
            model.addAttribute("nbqList", maps.get("nbq"));
            model.addAttribute("otherList", maps.get("other"));
        }

        // 获取并网信息
        if(StrKit.notBlank(customerEntry.getReceivingReportId())){
            // 验收报告
            CrmAcceptingReport report = customerService.getReportById(customerEntry.getReceivingReportId());
            model.addAttribute("report", report);
            // 保险单
            model.addAttribute("insurances", insuranceDao.getByEntryIds(customerEntry.getId()));
            // 电力公司
            model.addAttribute("powerCompany", AddressUtils.findProCodeNameByCode(customerEntry.getProvinceCode()));
        }
        //合同信息
        CrmCustomerContractManagement contractManagement=contractManagementDao.getContractByEntryId(entryId);
        model.addAttribute("contractManagement",contractManagement);
        // 获取表单设置 信息登记阶段
        model.addAttribute("info1",formSetService.getListByCondition("01", customerEntry.getPartnerId()) );
        model.addAttribute("info2",formSetService.getListByCondition("02", customerEntry.getPartnerId()) );
        model.addAttribute("info5",formSetService.getListByCondition("05", customerEntry.getPartnerId()) );
        model.addAttribute("info3",formSetService.getListByCondition("03", customerEntry.getPartnerId()) );
        model.addAttribute("info4",formSetService.getListByCondition("04", customerEntry.getPartnerId()) );
        //房屋偏向
        List<Record> angleAzimuthList = sysCapitalDictDao.getDictionaryList("angle_azimuth", customerEntry.getPartnerId());
        model.addAttribute("angleAzimuthList",angleAzimuthList);
        //竣工信息
        Record compInfo = completionDao.getCrmCompletionInfoByEntryId(entryId);
        model.addAttribute("compInfo",compInfo);

        if(PartnerConstants.PARTNER_ID_YX.equals(customerEntry.getPartnerId())){
            //获取历史设置的汇流方式
            Record recordBox=combinerBoxGroupDao.getEntryCombinerBoxSet(entryId);
            model.addAttribute("recordBox",recordBox);
            //获取一户多站的信息
            Record oneToAnyBoxSet=combinerBoxGroupDao.getOneToAnyBoxSet(customerEntry.getIdCode(),customerEntry.getRegno(),customerEntry.getCreateTraderId(),customerEntry.getTenantType());
            model.addAttribute("oneToAnyBoxSet",oneToAnyBoxSet);
        }
        String contractUrlFlag = "0";
        if(PartnerConstants.PARTNER_ID_GF.equals(customerEntry.getPartnerId()) && "1".equals(customerEntry.getIsHistory())){
            contractUrlFlag = "1";
        }
        model.addAttribute("contractUrlFlag",contractUrlFlag);
        if(PartnerConstants.PARTNER_ID_HR.equals(crmPartner.getId())){
            List<Record> projectList = projectInfoSettingService.getEntryProjectByEntryId(entryId);
            model.addAttribute("projectList",projectList);
            //华融多产品-勘测返回
            List<Record>  surveyDetail =  recordDetailService.getEntryDetail(entryId);
        /*    List<Record> components = customerEntryComponentService.findByEntryIdByProjectId(entryId,record.getStr("projectId"));
            model.addAttribute("componentList",components);*/
            List<CrmCustomerEntryDesign> designs = crmCustomerEntryDesignDao.findByEntryId(entryId);
            Boolean isDesignShow = false;
            if(designs!=null&&!designs.isEmpty()){
                for(CrmCustomerEntryDesign design:designs){
                    if(StringUtil.isNotBlank(design.getSchemeId())){
                        isDesignShow = true;
                    }
                }
            }
            model.addAttribute("projectDetailList",surveyDetail);
            List<Record> entryProject = crmCustomerEntryProjectDao.getProjectsByEntryId(customerEntry.getId());
            for(Record record : projectList){
                Map<String, Object> map = customerService.findUsedMaterialByprojectId(customerEntry.getId(),record.getStr("projectId"));
                CrmAcceptingReportDetail acceptReport = crmAcceptingReportDetailDao.findByEntryIdAndProjectId(customerEntry.getId(),record.getStr("projectId"));
                record.set("zjList", map.get("zj"));
                record.set("nbqList", map.get("nbq"));
                record.set("otherList", map.get("other"));
                record.set("acceptReport", acceptReport);
            }
            model.addAttribute("formSet", formSetService.getListByCondition("03", customerEntry.getPartnerId()));
            model.addAttribute("entryProject",entryProject);
            model.addAttribute("entryProject",entryProject);
            model.addAttribute("isDesignShow",isDesignShow);
            return "modules/yangguang/customer/entry/entryHrDetail";
        }else {
            if(PartnerConstants.PARTNER_ID_GF.equals(customerEntry.getPartnerId())){
                List<RoofSetFormVo> GfRoofTypeFormSet=FormSetService.getGfFormSetByRoofType();
                model.addAttribute("GfRoofTypeFormSet",new Gson().toJson(GfRoofTypeFormSet));
            }
            return "modules/yangguang/customer/entry/entryDetail";
        }
    }

    /*
     * 判断是否为整数
     * @param str 传入的字符串
     * @return 是整数返回true,否则返回false
     */
    public  boolean isInteger(String str) {
        String pattern = "^\\d+$";
        return str.matches(pattern);
    }


        @RequestMapping("/batchPage")
    public String batchPage(String ids, Model model) {
        User user = UserUtils.getUser();
        // 查询汇总下单物料信息
        String[] split = ids.split(",");
        List<Record> list = customerEntryComponentService.findByEntryIds(Arrays.asList(split.clone()));
        // 查询代理商仓库信息
        List<Record> warehouseList;
        if (Objects.equals(TraderConstants.TYPE_TWO, user.getTraderType())) {
            warehouseList = MaterialUtils.findWarehouseBySecondTrader(user.getTraderId());
        } else {
            warehouseList = MaterialUtils.findMaterialWarehouseByAscriptionId(user.getTraderId());
        }
        model.addAttribute("details", list);
        model.addAttribute("warehouseList", warehouseList);
        model.addAttribute("ids", ids);
        return "modules/yangguang/customer/entry/batchOrder";
    }


    // 确认下单
    @ResponseBody
    @RequestMapping("/batchOrder")
    public Result<Void> batchOrder(HttpServletRequest request) {
        // 获取参数
        String ids = request.getParameter("ids");
        String[] split = ids.split(",");
        String warehouseId = request.getParameter("warehouseId");
        String remark = request.getParameter("remark");
        User currentUser = UserUtils.getUser();
        customerService.batchOrder(Arrays.asList(split.clone()), Operator.of(currentUser.getId(), CrmUtils.getUserXM(currentUser),currentUser.getUserType()),
                warehouseId, remark);
        return Result.ok();
    }

    /**
     * 确认收货
     */
    @ResponseBody
    @RequestMapping("/batchReceive")
    public Result<Void> batchReceive(@RequestBody List<String> ids) {
        User currentUser = UserUtils.getUser();
        customerService.batchReceive(ids, Operator.of(currentUser.getId(), CrmUtils.getUserXM(currentUser),currentUser.getUserType()));
        return Result.ok();
    }

    /**
     * 去完工页面
     */
    @RequestMapping("/toCompleteInstallPage")
    public String toCompleteInstallPage(String id,Model model){
        CustomerEntry customerEntry = customerService.getById(id);
        // 安装物料
        Map<String, Object> maps = customerService.findUsedMaterial(customerEntry.getId());
        model.addAttribute("zjList", maps.get("zj"));
        model.addAttribute("nbqList", maps.get("nbq"));
        model.addAttribute("otherList", maps.get("other"));
        // 验收报告
        CrmAcceptingReport report = new CrmAcceptingReport();
        if(!PartnerConstants.PARTNER_ID_HR.equals(customerEntry.getPartnerId())) {
            if (StringUtil.isNotBlank(customerEntry.getReceivingReportId())) {
                report = customerService.getReportById(customerEntry.getReceivingReportId());
            }
        }
        model.addAttribute("report", report);
        // 查询勘测信息
        CustomerEntrySurveyRecord surveyRecord = surveyRecordDao.findOneByEntryId(customerEntry.getId());
        model.addAttribute("surveyRecord",surveyRecord );
        int filingDocumentPhotoCount = 0;
        if(surveyRecord != null){
            if(StringUtil.isNotBlank(surveyRecord.getFilingDocumentPhoto())){
                String[] arr=surveyRecord.getFilingDocumentPhoto().split(",");
                filingDocumentPhotoCount = arr.length;
            }
        }
        model.addAttribute("filingDocumentPhotoCount", filingDocumentPhotoCount);

        int otherFilesCount = 0;
        if(StringUtil.isNotBlank(report.getOtherFiles())){
            String[] arr=report.getOtherFiles().split(",");
            otherFilesCount = arr.length;
        }
        int kgConditionFilesCount = 0;
        if(StringUtil.isNotBlank(report.getKgConditionFiles())){
            String[] arr=report.getKgConditionFiles().split(",");
            kgConditionFilesCount = arr.length;
        }
        int videoCount = 0;
        if(StringUtil.isNotBlank(report.getSupplementVideoUrl())){
            String[] arr=report.getSupplementVideoUrl().split(",");
            videoCount = arr.length;
        }

        String schemeTypeId = customerEntry.getSchemeTypeId();
        List<ProjectTypeDetailVo> reflist=projectInstallService.getProjectReference2(schemeTypeId);
        if(reflist.size()==0){
            reflist = Lists.newArrayList();
        }
        //示例图
        model.addAttribute("reflist",reflist);
        model.addAttribute("otherFilesCount", otherFilesCount);
        model.addAttribute("kgConditionFilesCount", kgConditionFilesCount);
        model.addAttribute("videoCount", videoCount);
        model.addAttribute("customerEntry", customerEntry);
//        CrmProjectSetting pro = projectService.getById(customerEntry.getProjectId());
//        model.addAttribute("project", pro);
        //表单设置
        model.addAttribute("formSet", formSetService.getListByCondition("03", customerEntry.getPartnerId()));
        String contractUrlFlag = "0";
        if(PartnerConstants.PARTNER_ID_GF.equals(customerEntry.getPartnerId()) && "1".equals(customerEntry.getIsHistory())){
            contractUrlFlag = "1";
        }
        model.addAttribute("contractUrlFlag",contractUrlFlag);
        if(PartnerConstants.PARTNER_ID_HR.equals(customerEntry.getPartnerId())){
            List<Record> projectList = projectInfoSettingService.getEntryProjectByEntryId(customerEntry.getId());
            List<Record> entryProject = crmCustomerEntryProjectDao.getProjectsByEntryId(customerEntry.getId());
            for(Record record : projectList){
                Map<String, Object> map = customerService.findUsedMaterialByprojectId(customerEntry.getId(),record.getStr("projectId"));
                CrmAcceptingReportDetail acceptReport = crmAcceptingReportDetailDao.findByEntryIdAndProjectId(customerEntry.getId(),record.getStr("projectId"));
                record.set("zjList", map.get("zj"));
                record.set("nbqList", map.get("nbq"));
                record.set("otherList", map.get("other"));
                record.set("acceptReport", acceptReport);
            }
            model.addAttribute("projectList",projectList);
            model.addAttribute("entryProject",entryProject);
            return "modules/yangguang/customer/entry/completeInstallHR";
        }else{
            return "modules/yangguang/customer/entry/completeInstall";
        }
    }

    /**
     * 完工暂存
     */
    @ResponseBody
    @RequestMapping("/installZc")
    public Result<Void> installZc(AddReportZcReq req) {
        GuardUtils.notBlank(req.getEntryId(), "entryId不能为空");
        User user = UserUtils.getUser();
        Operator operator = Operator.of(user);
        try {
            customerService.batchInstallZc(req, operator);
            return Result.ok();
        } catch (Exception e) {
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 完工暂存(华融)
     */
    @ResponseBody
    @RequestMapping("/installZcHr")
    public Result<Void> installZcHr(@RequestBody AddReportZcReq req) {
        GuardUtils.notBlank(req.getEntryId(), "entryId不能为空");
        User user = UserUtils.getUser();
        Operator operator = Operator.of(user);
        try {
            customerService.batchInstallZcHr(req, operator);
            return Result.ok();
        } catch (Exception e) {
            return Result.fail(e.getMessage());
        }
    }


    /**
     * 完工(华融多产品)
     */
    @ResponseBody
    @RequestMapping("/installHr")
    public Result<Void> installHr(@RequestBody AddReportReq req) {
        GuardUtils.notBlank(req.getEntryId(), "entryId不能为空");
        User user = UserUtils.getUser();
        Operator operator = Operator.of(user);
        try {
            customerService.batchHrInstall(req, operator);
            return Result.ok();
        } catch (Exception e) {
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 完工
     */
    @ResponseBody
    @RequestMapping("/install")
    public Result<Void> install(AddReportReq req) {
        GuardUtils.notBlank(req.getEntryId(), "entryId不能为空");
        User user = UserUtils.getUser();
        Operator operator = Operator.of(user);
        try {
            customerService.batchInstall(req, operator);
            return Result.ok();
        } catch (Exception e) {
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 安装完成
     */
    @ResponseBody
    @RequestMapping("/batchInstall")
    public Result<Void> batchInstall(@RequestBody List<String> ids) {
        User currentUser = UserUtils.getUser();
        //customerService.batchInstall(ids, Operator.of(currentUser.getId(), CrmUtils.getUserXM(currentUser),currentUser.getUserType()));
        return Result.ok();
    }

    @ResponseBody
    @RequestMapping("/batchMerge")
    public Result<Void> batchMerge(@RequestBody List<String> ids) {
        User currentUser = UserUtils.getUser();
        customerService.batchMerge(ids, Operator.of(currentUser.getId(), CrmUtils.getUserXM(currentUser),currentUser.getUserType()));
        return Result.ok();
    }

    /**
     * 交付
     */
    @ResponseBody
    @RequestMapping("/accept")
    public Result<Void> accept(String id, String deliverFile,String generatorNo){
        GuardUtils.notBlank(id, "id不能为空");
        //  GuardUtils.notBlank(generatorNo, "发电户号不能为空");
        GuardUtils.notBlank(deliverFile, "交付签收表不能为空");
        User currentUser = UserUtils.getUser();
        //customerService.accept(id, deliverFile, Operator.of(currentUser.getId(), CrmUtils.getUserXM(currentUser),currentUser.getUserType()));
        return Result.ok();
    }

    /**
     * 已交付退回
     */
    @ResponseBody
    @RequestMapping("/returnEntry")
    public Result<Void> returnEntry(String id){
        GuardUtils.notBlank(id, "id不能为空");
        customerService.returnEntry(id);
        return Result.ok();
    }


    /**
     * 去交付页面
     */
    @RequestMapping("/toDeliverPage")
    public String toDeliverPage(String id, Model model){
        model.addAttribute("id", id);
        return "modules/yangguang/customer/entry/sureDeliver";
    }

    /**
     * 电站接入云平台
     * @param id entry id
     */
    @RequestMapping("/toJoinCloud")
    public String toJoinCloud(String id, Model model){
        model.addAttribute("id", id);
        return "modules/yangguang/customer/entry/toJoinCloud";
    }

    /**
     * 电站接入云平台
     */
    @RequestMapping("/joinCloud")
    public Result<Void> joinCloud(@RequestBody JoinCloudReq req) {
        customerService.joinCloud(req);
        return Result.ok();
    }

    /**
     * 去并网验收页面
     */
    @RequestMapping("/toMergeAccept")
    public String toMergeAccept(String id, Model model,HttpServletRequest request){
        CustomerEntry customerEntry = customerService.getById(id);
        CustomerEntrySurveyRecord surveyRecord = surveyRecordDao.findOneByEntryId(id);
        if (surveyRecord == null) {
            surveyRecord = new CustomerEntrySurveyRecord();
        }
        User user = UserUtils.getUser();
        String traderId="";  //代理商不能看到平台的审批信息
        CrmTrader trader = traderService.getById(customerEntry.getDistributorId());

        if(User.USER_TYPE_ADVISOR.equals(user.getUserType()) || User.USER_TYPE_KJ.equals(user.getUserType())){
            traderId = user.getTraderId();
        }
        List<Record> optList = customerEntryMsgService.listOptRecordByEntryId(id,traderId);
        CrmProjectSetting projectSetting = projectService.getById(customerEntry.getProjectId());

        model.addAttribute("user", UserUtils.getUser());
        model.addAttribute("customerEntry", customerEntry);
        model.addAttribute("mobile",customerEntry.getMobile());
        model.addAttribute("idCode",customerEntry.getIdCode());
        model.addAttribute("optList", optList);
        model.addAttribute("project", projectSetting);
        model.addAttribute("trader", trader);
        CrmTenantYxBankCard card=tenantYxBankCardDao.getByIdCard(customerEntry.getIdCode(),customerEntry.getManagementType(),customerEntry.getPartnerId());
        model.addAttribute("card",card);
        model.addAttribute("bankName",linkNumberSettingService.findBankNUmberName(customerEntry.getTssBankNum()));
        model.addAttribute("quaimgsCount",0);
        model.addAttribute("surveyRecord", surveyRecord);
        //房屋偏向
        List<Record> angleAzimuthList = sysCapitalDictDao.getDictionaryList("angle_azimuth", customerEntry.getPartnerId());
        model.addAttribute("angleAzimuthList",angleAzimuthList);
        if (StringUtil.isNotBlank(surveyRecord.getHouseOwnership())) {
            String[] arr = surveyRecord.getHouseOwnership().split(",");
            model.addAttribute("quaimgs", arr);
            model.addAttribute("quaimgsCount", arr.length);
        }
        // 获取单位资料信息
        if (Objects.equals("2", customerEntry.getTenantType())) {
            model.addAttribute("orgFiles", orgFilesDao.findOneByEntryId(customerEntry.getId()));
        }
        // 获取并网信息
        if(StrKit.notBlank(customerEntry.getReceivingReportId())){
            // 验收报告
            CrmAcceptingReport report = customerService.getReportById(customerEntry.getReceivingReportId());
            model.addAttribute("report", report);
            // 保险单
            model.addAttribute("insurances",insuranceDao.getByEntryIds(customerEntry.getId()));
            // 电力公司
            model.addAttribute("powerCompany", AddressUtils.findProCodeNameByCode(customerEntry.getProvinceCode()));
        }
        String opt=request.getParameter("opt");
        model.addAttribute("opt",opt);
        model.addAttribute("info1",formSetService.getListByCondition("01", customerEntry.getPartnerId()) );
        model.addAttribute("info2",formSetService.getListByCondition("02", customerEntry.getPartnerId()) );
        model.addAttribute("info5",formSetService.getListByCondition("05", customerEntry.getPartnerId()) );
        model.addAttribute("info3",formSetService.getListByCondition("03", customerEntry.getPartnerId()) );
        model.addAttribute("info4", formSetService.getListByCondition("04", customerEntry.getPartnerId()));
        IsInteger str = new IsInteger();
        if(str.isInteger(customerEntry.getStatus())&& (customerEntry.getStatus().equals("0")|| customerEntry.getStatus().equals("1") || customerEntry.getStatus().equals("2") || customerEntry.getStatus().equals("3") || customerEntry.getStatus().equals("4")) ){
            String stationName=customerEntry.getProvince()+customerEntry.getArea()+customerEntry.getTenantName()+(new BigDecimal(customerEntry.getDesignCapacity()).divide(new BigDecimal(1000),3, RoundingMode.DOWN).stripTrailingZeros().toPlainString())+"KW光伏电站";
            model.addAttribute("stationName", stationName);
        }else{
            String stationName=customerEntry.getProvince()+customerEntry.getArea()+customerEntry.getTenantName()+(customerEntry.getActualCapacity().divide(new BigDecimal(1000),3, RoundingMode.DOWN).stripTrailingZeros().toPlainString())+"KW光伏电站";
            model.addAttribute("stationName", stationName);
        }
        if(PartnerConstants.PARTNER_ID_YX.equals(customerEntry.getPartnerId())){
            //获取历史设置的汇流方式
            Record recordBox=combinerBoxGroupDao.getEntryCombinerBoxSet(customerEntry.getId());
            model.addAttribute("recordBox",recordBox);
        }

        if(PartnerConstants.PARTNER_ID_HR.equals(customerEntry.getPartnerId())){
            List<Record> projectList = projectInfoSettingService.getEntryProjectByEntryId(customerEntry.getId());
            List<Record> entryProject = crmCustomerEntryProjectDao.getProjectsByEntryId(customerEntry.getId());
            List<Record>  surveyDetail =  recordDetailService.getEntryDetail(customerEntry.getId());
            for(Record record : projectList){
                Map<String, Object> map = customerService.findUsedMaterialByprojectId(customerEntry.getId(),record.getStr("projectId"));
                CrmAcceptingReportDetail acceptReport = crmAcceptingReportDetailDao.findByEntryIdAndProjectId(customerEntry.getId(),record.getStr("projectId"));
                record.set("zjList", map.get("zj"));
                record.set("nbqList", map.get("nbq"));
                record.set("otherList", map.get("other"));
                record.set("acceptReport", acceptReport);
            }
            model.addAttribute("formSet", formSetService.getListByCondition("03", customerEntry.getPartnerId()));
            model.addAttribute("projectList",projectList);
            model.addAttribute("entryProject",entryProject);
            model.addAttribute("projectDetailList",surveyDetail);
            return "modules/yangguang/customer/entry/checkHrMergeAccept";
        }else{
            return "modules/yangguang/customer/entry/checkMergeAccept";
        }
    }

    /**
     * 去验收页面
     */
    @RequestMapping("/toCheckAccept")
    public String toCheckAccept(String id, Model model) {
        CustomerEntry customerEntry = customerService.getById(id);
        CustomerEntrySurveyRecord surveyRecord = surveyRecordDao.findOneByEntryId(id);
        if (surveyRecord == null) {
            surveyRecord = new CustomerEntrySurveyRecord();
        }
        User user = UserUtils.getUser();
        String traderId="";  //代理商不能看到平台的审批信息
        CrmTrader trader = traderService.getById(customerEntry.getDistributorId());

        if(User.USER_TYPE_ADVISOR.equals(user.getUserType()) || User.USER_TYPE_KJ.equals(user.getUserType())){
            traderId = user.getTraderId();
        }
        List<Record> optList = customerEntryMsgService.listOptRecordByEntryId(id,traderId);
        CrmProjectSetting projectSetting = projectService.getById(customerEntry.getProjectId());

        model.addAttribute("user", UserUtils.getUser());
        model.addAttribute("customerEntry", customerEntry);
        model.addAttribute("mobile",customerEntry.getMobile());
        model.addAttribute("idCode",customerEntry.getIdCode());
        model.addAttribute("optList", optList);
        model.addAttribute("project", projectSetting);
        model.addAttribute("trader", trader);
        CrmTenantYxBankCard card=tenantYxBankCardDao.getByIdCard(customerEntry.getIdCode(),customerEntry.getManagementType(),customerEntry.getPartnerId());
        model.addAttribute("card",card);
        model.addAttribute("bankName",linkNumberSettingService.findBankNUmberName(customerEntry.getTssBankNum()));
        model.addAttribute("quaimgsCount",0);
        model.addAttribute("surveyRecord", surveyRecord);
        if (StringUtil.isNotBlank(surveyRecord.getHouseOwnership())) {
            String[] arr = surveyRecord.getHouseOwnership().split(",");
            model.addAttribute("quaimgs", arr);
            model.addAttribute("quaimgsCount", arr.length);
        }
        // 获取单位资料信息
        if (Objects.equals("2", customerEntry.getTenantType())) {
            model.addAttribute("orgFiles", orgFilesDao.findOneByEntryId(customerEntry.getId()));
        }
        // 获取并网信息
        if(StrKit.notBlank(customerEntry.getReceivingReportId())){
            // 验收报告
            CrmAcceptingReport report = customerService.getReportById(customerEntry.getReceivingReportId());
            model.addAttribute("report", report);
            // 保险单
            model.addAttribute("insurances", insuranceDao.getByEntryIds(customerEntry.getId()));
            // 电力公司
            model.addAttribute("powerCompany", AddressUtils.findProCodeNameByCode(customerEntry.getProvinceCode()));
        }

        IsInteger str = new IsInteger();
        String stationName = customerEntry.getProvince()+customerEntry.getArea()+customerEntry.getTenantName();
        if(str.isInteger(customerEntry.getStatus())&& (customerEntry.getStatus().equals("0")|| customerEntry.getStatus().equals("1") || customerEntry.getStatus().equals("2") || customerEntry.getStatus().equals("3") || customerEntry.getStatus().equals("4")) ){
            stationName = stationName +
                    (new BigDecimal(customerEntry.getDesignCapacity()).divide(new BigDecimal(1000),3, RoundingMode.DOWN).stripTrailingZeros().toPlainString());
        }else{
            stationName= stationName +
                    (customerEntry.getActualCapacity().divide(new BigDecimal(1000),3, RoundingMode.DOWN).stripTrailingZeros().toPlainString());
        }
        stationName = stationName + "KW光伏电站";
        model.addAttribute("stationName", stationName);
        //获取表单设置  勘测设计
        model.addAttribute("info2", formSetService.getListByCondition("02", customerEntry.getPartnerId()));
        model.addAttribute("info3",formSetService.getListByCondition("03", customerEntry.getPartnerId()) );
        Map<String, Object> maps = customerService.findUsedMaterial(customerEntry.getId());
        model.addAttribute("zjList", maps.get("zj"));
        model.addAttribute("nbqList", maps.get("nbq"));
        model.addAttribute("otherList", maps.get("other"));
        String contractUrlFlag = "0";
        if(PartnerConstants.PARTNER_ID_GF.equals(customerEntry.getPartnerId()) && "1".equals(customerEntry.getIsHistory())){
            contractUrlFlag = "1";
        }
        model.addAttribute("contractUrlFlag",contractUrlFlag);
        if(PartnerConstants.PARTNER_ID_HR.equals(customerEntry.getPartnerId())){
            List<Record> projectList = projectInfoSettingService.getEntryProjectByEntryId(customerEntry.getId());
            List<Record> entryProject = crmCustomerEntryProjectDao.getProjectsByEntryId(customerEntry.getId());
            List<Record>  surveyDetail =  recordDetailService.getEntryDetail(customerEntry.getId());
            for(Record record : projectList){
                Map<String, Object> map = customerService.findUsedMaterialByprojectId(customerEntry.getId(),record.getStr("projectId"));
                CrmAcceptingReportDetail acceptReport = crmAcceptingReportDetailDao.findByEntryIdAndProjectId(customerEntry.getId(),record.getStr("projectId"));
                record.set("zjList", map.get("zj"));
                record.set("nbqList", map.get("nbq"));
                record.set("otherList", map.get("other"));
                record.set("acceptReport", acceptReport);
            }
            model.addAttribute("formSet", formSetService.getListByCondition("03", customerEntry.getPartnerId()));
            model.addAttribute("projectList",projectList);
            model.addAttribute("entryProject",entryProject);
            model.addAttribute("projectDetailList",surveyDetail);
            return "modules/yangguang/customer/entry/checkHrAccept";
        }else {
            return "modules/yangguang/customer/entry/checkAccept";
        }
    }


    /**
     * 去并网页面
     */
    @RequestMapping("/toStationBWPage")
    public String toStationBWPage(String id, String opt, Model model){
        CustomerEntry entry = customerService.getById(id);
        String reportId = entry.getReceivingReportId();
        if(StrKit.notBlank(reportId)){
            CrmAcceptingReport report = customerService.getReportById(reportId);
            model.addAttribute("report", report);
        }
        CustomerEntryToExamine examine = examineService.findEntryId(entry.getId());
        model.addAttribute("examine", examine);
        Map<String,Object> map = Maps.newHashMap();
        String brand = "";//组件品牌
        String nbqSpecOne = "";//逆变器一
        String nbqSpecTwo = "";//逆变器二
        String bwxBrand = "";//并网箱
        String zjBrand ="";
        List<Record> zhijialist = Lists.newArrayList();
        //获取使用的物料
        int bwxCOunt=0;
        int zujCOunt=0;
        List<Record> list = customerService.findMaterialListByEntryId(entry.getId());
        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());

        if(entry.getSn().indexOf(",")>0){
            String[] sns = entry.getSn().split(",");
            if(sns.length>1){
                map.put("snOne", sns[0]);
                map.put("snTwo", sns[1]);
            }else{
                map.put("snOne", entry.getSn());
            }
        }else{
            map.put("snOne", entry.getSn());
        }
        if(StringUtil.isNotBlank(entry.getNbqSn()) && entry.getNbqSn().indexOf(",")>0){
            String[] sns = entry.getNbqSn().split(",");
            if(sns.length>1){
                map.put("nbqSnOne", sns[0]);
                map.put("nbqSnTwo", sns[1]);
            }else{
                map.put("nbqSnOne", entry.getNbqSn());
            }
        }else{
            map.put("nbqSnOne", entry.getNbqSn());
        }
        model.addAttribute("map", map);
        CrmProjectSetting project = projectService.getById(entry.getProjectId());
        CrmTrader trader = traderService.getById(entry.getDistributorId());
        User user = UserUtils.getUser();
        model.addAttribute("opt", opt);
        model.addAttribute("entry", entry);
        model.addAttribute("entryStatus", CustomerEntryUtil.parseStatus(entry.getStatus()));
        model.addAttribute("entryFilingType", CustomerEntryUtil.parseFilingType(entry.getFilingType()));
        List<CrmCustomerIncomingApplicationInsurance> insurances = insuranceDao.getByEntryIds(entry.getId());
        model.addAttribute("insurance",insurances==null||insurances.isEmpty()?null:insurances.get(0));
        model.addAttribute("user", user);
        model.addAttribute("project", project);
        model.addAttribute("trader", trader);
        model.addAttribute("nowDt", new Date());
        model.addAttribute("nowName", CrmUtils.getUserXM(user));

        //地址信息
        List<Record> pros = addressService.getProvinces();
        model.addAttribute("pros", pros);
        String province = entry.getElectricProvince();
        String city = entry.getElectricCity();
        //根据省查询下面的
        List<Record> citys = AddressUtils.getCityByProName(province);
        List<Record> areas = AddressUtils.getAreaByCityName(city);
        model.addAttribute("faccitys", citys);
        model.addAttribute("areas", areas);
        //
        List<Record> procodes = addressService.getProviceCodeList();
        model.addAttribute("procodes", procodes);
        //获取表单设置
        model.addAttribute("info4", formSetService.getListByCondition("04", entry.getPartnerId()));

        int videoCount = 0;
        if(StringUtil.isNotBlank(entry.getContractVideoUrl())){
            String[] arr = entry.getContractVideoUrl().split(",");
            videoCount = arr.length;
        }
        model.addAttribute("videoCount", videoCount);
        if (Objects.equals("merge", opt)||Objects.equals("TwoMergeAccept", opt)) {//
            model.addAttribute("insuranceName", null);
            CrmProjectSetting projectSetting = projectService.getById(entry.getProjectId());
            if (projectSetting != null && "1".equals(projectSetting.getBuyInsuranceFlag())) {//有保险
                CrmInsuranceList insuranceList = insuranceListDao.get(projectSetting.getInsuranceId());
                if (insuranceList != null && "0".equals(insuranceList.getStatus())) {
                    model.addAttribute("insuranceName", insuranceList.getName());
                }
            }
            return "modules/yangguang/customer/entry/toStationBWPage";
        } else {
            return "modules/yangguang/customer/entry/report";
        }
    }

    /**
     * 国电投安装验收页面
     */
    @RequestMapping("/toGdtazMergeAccept")
    public String toGdtazMergeAccept(String id, String opt, Model model){
        CustomerEntry entry = customerService.getById(id);
        String reportId = entry.getReceivingReportId();
        if(StrKit.notBlank(reportId)){
            CrmAcceptingReport report = customerService.getReportById(reportId);
            model.addAttribute("report", report);
        }
        CustomerEntryToExamine examine = examineService.findEntryId(entry.getId());
        model.addAttribute("examine", examine);
        Map<String,Object> map = Maps.newHashMap();
        String brand = "";//组件品牌
        String nbqSpecOne = "";//逆变器一
        String nbqSpecTwo = "";//逆变器二
        String bwxBrand = "";//并网箱
        String zjBrand ="";
        List<Record> zhijialist = Lists.newArrayList();
        //获取使用的物料
        int bwxCOunt=0;
        int zujCOunt=0;
        List<Record> list = customerService.findMaterialListByEntryId(entry.getId());
        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("bwxUnit", re.getStr("unit"));
                }
            }

        }
        map.put("zhijialist", zhijialist);
        map.put("bwxCOunt", bwxCOunt);
        map.put("zujCOunt", zujCOunt);
        map.put("zjCount", zhijialist.size());

        if(entry.getSn().indexOf(",")>0){
            String[] sns = entry.getSn().split(",");
            if(sns.length>1){
                map.put("snOne", sns[0]);
                map.put("snTwo", sns[1]);
            }else{
                map.put("snOne", entry.getSn());
            }
        }else{
            map.put("snOne", entry.getSn());
        }
        if(StringUtil.isNotBlank(entry.getNbqSn()) && entry.getNbqSn().indexOf(",")>0){
            String[] sns = entry.getNbqSn().split(",");
            if(sns.length>1){
                map.put("nbqSnOne", sns[0]);
                map.put("nbqSnTwo", sns[1]);
            }else{
                map.put("nbqSnOne", entry.getNbqSn());
            }
        }else{
            map.put("nbqSnOne", entry.getNbqSn());
        }
        model.addAttribute("map", map);
        CrmProjectSetting project = projectService.getById(entry.getProjectId());
        CrmTrader trader = traderService.getById(entry.getDistributorId());
        User user = UserUtils.getUser();
        model.addAttribute("opt", opt);
        model.addAttribute("entry", entry);
        model.addAttribute("user", user);
        model.addAttribute("project", project);
        model.addAttribute("trader", trader);
        model.addAttribute("nowDt", new Date());
        model.addAttribute("nowName", CrmUtils.getUserXM(user));
        return "modules/yangguang/customer/entry/gdt/GdtAzReport";
    }


    /**
     * 国电投并网验收页面
     */
    @RequestMapping("/togdtMergeAccept")
    public String togdtMergeAccept(String id, String opt, Model model){
        CustomerEntry entry = customerService.getById(id);
        String reportId = entry.getReceivingReportId();
        if(StrKit.notBlank(reportId)){
            CrmAcceptingReport report = customerService.getReportById(reportId);
            model.addAttribute("report", report);
        }
        CustomerEntryToExamine examine = examineService.findEntryId(entry.getId());
        model.addAttribute("examine", examine);
        Map<String,Object> map = Maps.newHashMap();
        String brand = "";//组件品牌
        String nbqSpecOne = "";//逆变器一
        String nbqSpecTwo = "";//逆变器二
        String bwxBrand = "";//并网箱
        String zjBrand ="";
        List<Record> zhijialist = Lists.newArrayList();
        //获取使用的物料
        int bwxCOunt=0;
        int zujCOunt=0;
        List<Record> list = customerService.findMaterialListByEntryId(entry.getId());
        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("bwxUnit", re.getStr("unit"));
                }
            }

        }
        map.put("zhijialist", zhijialist);
        map.put("bwxCOunt", bwxCOunt);
        map.put("zujCOunt", zujCOunt);
        map.put("zjCount", zhijialist.size());

        if(entry.getSn().indexOf(",")>0){
            String[] sns = entry.getSn().split(",");
            if(sns.length>1){
                map.put("snOne", sns[0]);
                map.put("snTwo", sns[1]);
            }else{
                map.put("snOne", entry.getSn());
            }
        }else{
            map.put("snOne", entry.getSn());
        }
        if(StringUtil.isNotBlank(entry.getNbqSn()) && entry.getNbqSn().indexOf(",")>0){
            String[] sns = entry.getNbqSn().split(",");
            if(sns.length>1){
                map.put("nbqSnOne", sns[0]);
                map.put("nbqSnTwo", sns[1]);
            }else{
                map.put("nbqSnOne", entry.getNbqSn());
            }
        }else{
            map.put("nbqSnOne", entry.getNbqSn());
        }
        model.addAttribute("map", map);
        CrmProjectSetting project = projectService.getById(entry.getProjectId());
        CrmTrader trader = traderService.getById(entry.getDistributorId());
        User user = UserUtils.getUser();
        model.addAttribute("opt", opt);
        model.addAttribute("entry", entry);
        model.addAttribute("user", user);
        model.addAttribute("project", project);
        model.addAttribute("trader", trader);
        model.addAttribute("nowDt", new Date());
        model.addAttribute("nowName", CrmUtils.getUserXM(user));
        return "modules/yangguang/customer/entry/gdt/GdtBwReport";
    }

    /**
     * 单个生成验收报告文件
     */
    @ResponseBody
    @RequestMapping("/createEntryPdf")
    public Result<Void> createEntryPdf(String id){
        GuardUtils.notBlank(id, "id不能为空");
        CustomerEntry entry = customerService.getById(id);
        CustomerEntryToExamine examine = examineService.findEntryId(entry.getId());
        Map<String,Object> map = Maps.newHashMap();
        String brand = "";//组件品牌
        String nbqSpecOne = "";//逆变器一
        String nbqSpecTwo = "";//逆变器二
        String bwxBrand = "";//并网箱
        String zjBrand ="";
        List<Record> zhijialist = Lists.newArrayList();
        //获取使用的物料
        int bwxCOunt=0;
        int zujCOunt=0;
        List<Record> list = customerService.findMaterialListByEntryId(entry.getId());
        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("bwxUnit", re.getStr("unit"));
                }
            }

        }
        map.put("zhijialist", zhijialist);
        map.put("bwxCOunt", bwxCOunt);
        map.put("zujCOunt", zujCOunt);
        map.put("zjCount", zhijialist.size());

        if(entry.getSn().indexOf(",")>0){
            String[] sns = entry.getSn().split(",");
            if(sns.length>1){
                map.put("snOne", sns[0]);
                map.put("snTwo", sns[1]);
            }else{
                map.put("snOne", entry.getSn());
            }
        }else{
            map.put("snOne", entry.getSn());
        }
        if(StringUtil.isNotBlank(entry.getNbqSn()) && entry.getNbqSn().indexOf(",")>0){
            String[] sns = entry.getNbqSn().split(",");
            if(sns.length>1){
                map.put("nbqSnOne", sns[0]);
                map.put("nbqSnTwo", sns[1]);
            }else{
                map.put("nbqSnOne", entry.getNbqSn());
            }
        }else{
            map.put("nbqSnOne", entry.getNbqSn());
        }

        customerService.createEntryPdf(null,entry,"1",examine,map,zhijialist);
        return Result.ok();
    }


    /**
     * 上传验收报告至 浙银
     */
    @ResponseBody
    @RequestMapping("/uploadAttachment")
    public Result<Void> uploadAttachment(String id){
        GuardUtils.notBlank(id, "id不能为空");
        customerService.uploadAttachment(id,"");
        return Result.ok();
    }

    /**
     * 上传第二次进件申请附件验收报告至 浙银
     */
    @ResponseBody
    @RequestMapping("/uploadTwoAttachment")
    public Result<Void> uploadTwoAttachment(String id,String type){
        GuardUtils.notBlank(id, "id不能为空");
        customerService.uploadTwoAttachmentTh(id,type,"");
        return Result.ok();
    }

    /**
     * 确认归档
     */
    @ResponseBody
    @RequestMapping("/sureInDoc")
    public Result<Void> sureInDoc(String id){
        GuardUtils.notBlank(id, "id不能为空");
        User user = UserUtils.getUser();
        Operator operator = Operator.of(user.getId(), CrmUtils.getUserXM(user),user.getUserType());
        customerService.sureInDoc(id, operator);
        return Result.ok();
    }

    /**
     * 归档退回
     */
    @ResponseBody
    @RequestMapping("/refuseInDoc")
    public Result<Void> refuseInDoc(String id, String reason){
        GuardUtils.notBlank(id, "id不能为空");
        GuardUtils.notBlank(reason, "reason不能为空");
        User user = UserUtils.getUser();
        Operator operator = Operator.of(user.getId(), CrmUtils.getUserXM(user),user.getUserType());
        customerService.refuseInDoc(id, reason, operator);
        return Result.ok();
    }

    /**
     * 下载物料
     */
    @RequestMapping(value = "exportsMaterial")
    public void exportsMaterial(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String id = request.getParameter("id");
        String fileName = "物料清单" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
        List<Record> materials = planService.listMatchedMaterialByPlanId(id);
        List<MaterialExcel> list = new ArrayList<>();
        int sort=1;
        for (Record rd : materials) {
            MaterialExcel platformOrderExcel = new MaterialExcel();
            platformOrderExcel.setSort(sort);
            platformOrderExcel.setCode(rd.getStr("code"));
            platformOrderExcel.setName(rd.getStr("name"));
            platformOrderExcel.setAmount(rd.getBigDecimal("amount").intValue());
            platformOrderExcel.setSpec(rd.getStr("spec"));
            platformOrderExcel.setUnit(rd.getStr("unit"));
            list.add(platformOrderExcel);
            sort++;
        }
        new ExportExcel("物料清单", MaterialExcel.class)
                .setDataList(list)
                .write(response, fileName)
                .dispose();
    }


    /**
     * 代理商查看统计数据
     * 待审核、待验收、待交付、已交付
     */
    @ResponseBody
    @RequestMapping("/statisticEntry")
    public Object statisticEntry(HttpServletRequest request){
        User user = UserUtils.getUser();
        if(user == null){
            throw new BusinessException("账号登录过期，请重新登录");
        }
        Record record;
        String factime =  cacheService.hget("userIdRepairTime",user.getId());
        String time = DateUtils.getDate("yyyy-MM-dd HH:mm:ss");
        long diff = DateUtils.getTwoTime(factime,time);
        if(diff<60&& diff>0){
            String faccount =  cacheService.hget("userId",user.getId());
            if (StringUtil.isNotBlank(faccount)) {
                Record rd = new Gson().fromJson(faccount, new TypeToken<Record>() {
                }.getType());
                return rd;
            }
        }
        cacheService.hdel("userId",user.getId());
        if(User.USER_TYPE_KJ.equals(user.getUserType())){
            // CrmTrader trader = traderService.getTraderBuserId(user.getId());
            record = customerService.statisticForPCTrader();
        }else if(User.USER_TYPE_ADVISOR.equals(user.getUserType())){
            String trdderId = CrmUtils.getUserRelId(user);
            CrmTrader trader = traderService.getById(trdderId);
            record = customerService.statisticForTrader(trader.getId(),user.getId());
        }else if(User.USER_TYPE_GYS.equals(user.getUserType())) {
            Ascription ascription = CrmUtils.getAscription();
            List<String> list = Lists.newArrayList();
            list.add(ascription.getAscriptionId());
            record = customerService.statisticForSupply(list);
        } else if (User.USER_TYPE_WXG.equals(user.getUserType()) || User.USER_TYPE_YYS.equals(user.getUserType())) {
            // 平台或者平台员工
            String type = CrmUtils.getPlatEmployeRole(user.getId());
            if (!EmpRoleConstants.SUPERVISOR.equals(type)) {// 非监造员
                record = customerService.statisticForSupplyChain();
            }else if(EmpRoleConstants.SYSTEM_EMGINEER.equals(type) || EmpRoleConstants.PROJECT_EMGINEER.equals(type)){
                Map<String,String> map = Maps.newHashMap();
                EmployeRoleUtils.getRoleDataAuthority(user.getId(),  map);
                record = customerService.statisticForPlaft(map);
            } else {
                String userRelId=CrmUtils.getUserRelId(user);  //
                //获取所有供应商
                List<String>  lists = MaterialUtils.findSupplierIdsList(userRelId);
                record = customerService.statisticForSupply(lists);
            }
        }else {
            Map<String,String> map = Maps.newHashMap();
            //平台人员
            if ("4".equals(user.getUserType())) {
                EmployeRoleUtils.getRoleDataAuthority(user.getId(),  map);
            }
            record = customerService.statisticForPlaft(map);
        }

        cacheService.hset("userId",user.getId(),new Gson().toJson(record));
        cacheService.hset("userIdRepairTime",user.getId(),time);

        return record;
    }

    /**
     * 去并网验收页面
     */
    @RequestMapping("/downloadReport")
    public String downloadReport(String id, String opt, Model model){
        CustomerEntry entry = customerService.getById(id);
        String reportId = entry.getReceivingReportId();
        if(StrKit.notBlank(reportId)){
            CrmAcceptingReport report = customerService.getReportById(reportId);
            model.addAttribute("report", report);
        }
        CustomerEntryToExamine examine = examineService.findEntryId(entry.getId());
        model.addAttribute("examine", examine);
        Map<String,Object> map = Maps.newHashMap();
        String brand = "";//组件品牌
        String nbqSpecOne = "";//逆变器一
        String nbqSpecTwo = "";//逆变器二
        String bwxBrand = "";//并网箱
        String zjBrand ="";
        List<Record> zhijialist = Lists.newArrayList();
        //获取使用的物料
        int bwxCOunt=0;
        int zujCOunt=0;
        List<Record> list = customerService.findMaterialListByEntryId(entry.getId());
        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("bwxUnit", re.getStr("unit"));
                }
            }

        }
        map.put("zhijialist", zhijialist);
        map.put("bwxCOunt", bwxCOunt);
        map.put("zujCOunt", zujCOunt);
        map.put("zjCount", zhijialist.size());

        if(StringUtil.isNotBlank(entry.getSn()) && entry.getSn().indexOf(",")>0){
            String[] sns = entry.getSn().split(",");
            if(sns.length>1){
                map.put("snOne", sns[0]);
                map.put("snTwo", sns[1]);
            }else{
                map.put("snOne", entry.getSn());
            }
        }else{
            map.put("snOne", entry.getSn());
        }
        if(StringUtil.isNotBlank(entry.getNbqSn()) && entry.getNbqSn().indexOf(",")>0){
            String[] sns = entry.getNbqSn().split(",");
            if(sns.length>1){
                map.put("nbqSnOne", sns[0]);
                map.put("nbqSnTwo", sns[1]);
            }else{
                map.put("nbqSnOne", entry.getNbqSn());
            }
        }else{
            map.put("nbqSnOne", entry.getNbqSn());
        }
        model.addAttribute("map", map);
        CrmProjectSetting project = projectService.getById(entry.getProjectId());
        CrmTrader trader = traderService.getById(entry.getDistributorId());
        User user = UserUtils.getUser();
        model.addAttribute("opt", "view");
        model.addAttribute("entry", entry);
        model.addAttribute("user", user);
        model.addAttribute("project", project);
        model.addAttribute("trader", trader);
        List<Record> procodes = addressService.getProviceCodeList();
        model.addAttribute("procodes", procodes);
//        return "modules/yangguang/customer/entry/downloadReport";
        return "modules/yangguang/customer/entry/report";
    }


    @RequestMapping(value = "downLoadPDF")
    public void downLoadPDF(HttpServletResponse response,HttpServletRequest request){
        String id = request.getParameter("id");
        if(StringUtil.isNotBlank(id)){
            Date now = new Date();
            String sn = DateUtils.formatDate(now, "yyyyMMddHHmmss");

            long s1 = System.currentTimeMillis();
            CustomerEntry entry = customerService.getById(id);
            String reportId = entry.getReceivingReportId();
            CrmAcceptingReport report = customerService.getReportById(reportId);
            CustomerEntryToExamine examine = examineService.findEntryId(entry.getId());
            String fileName = entry.getTenantName()+"-"+entry.getPowerStationCode()+"-户用电站验收报告.pdf";
            OutputStream outputStream = null;
            try {
                Map<String,Object> map = Maps.newHashMap();
                String brand = "";//组件品牌
                String nbqSpecOne = "";//逆变器一
                String nbqSpecTwo = "";//逆变器二
                String bwxBrand = "";//并网箱
                String zjBrand ="";
                List<Record> zhijialist = Lists.newArrayList();
                //获取使用的物料
                int bwxCOunt=0;
                int zujCOunt=0;
                List<Record> list = customerService.findMaterialListByEntryId(entry.getId());
                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("bwxUnit", re.getStr("unit"));
                        }
                    }

                }
                map.put("zhijialist", zhijialist);
                map.put("bwxCOunt", bwxCOunt);
                map.put("zujCOunt", zujCOunt);
                map.put("zjCount", zhijialist.size());

                if(entry.getSn().indexOf(",")>0){
                    String[] sns = entry.getSn().split(",");
                    if(sns.length>1){
                        map.put("snOne", sns[0]);
                        map.put("snTwo", sns[1]);
                    }else{
                        map.put("snOne", entry.getSn());
                    }
                }else{
                    map.put("snOne", entry.getSn());
                }
                if(StringUtil.isNotBlank(entry.getNbqSn()) && entry.getNbqSn().indexOf(",")>0){
                    String[] sns = entry.getNbqSn().split(",");
                    if(sns.length>1){
                        map.put("nbqSnOne", sns[0]);
                        map.put("nbqSnTwo", sns[1]);
                    }else{
                        map.put("nbqSnOne", entry.getNbqSn());
                    }
                }else{
                    map.put("nbqSnOne", entry.getNbqSn());
                }

                // 防止中文乱码
                fileName = URLEncoder.encode(fileName, "UTF-8");
                response.reset();
                response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
                response.setContentType("application/octet-stream;charset=UTF-8");
                outputStream = new BufferedOutputStream(response.getOutputStream());
                //生成pdf文件
                PdfReport.createBusinessInfoPDF(outputStream,report,entry,examine,map,zhijialist);
                outputStream.flush();
                long s2 = System.currentTimeMillis();
                logger.info(" >>下载验收报告 时间统计  [{}] end downLoadPDF use {}ms ", sn, (s2 - s1));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                logger.error("UnsupportedEncodingException --------------:{}",e);
            } catch (IOException e) {
                e.printStackTrace();
                logger.error("IOException ---->>>>>>>>>>----------:{}",e);
            } finally {
                try {
                    if (outputStream != null) {
                        outputStream.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 匹配合同
     */
    @ResponseBody
    @RequestMapping("matchingContract")
    public Result matchingContract(){

        customerService.matchingContract();

        return Result.ok();
    }

    /**
     * 导入弹框
     */
    @RequestMapping(value = "importPowerStationCodeForm")
    public String importPowerStationCodeForm(){
        return "modules/yangguang/customer/entry/importPowerStationCode";
    }

    @ResponseBody
    @RequestMapping(value = "checkImportPowerStationCode")
    public Object checkImportPowerStationCode(MultipartFile file) throws IOException {
        Map<String, String> params = Maps.newHashMap();
        params.put("extName", StringUtil.getFileExtName(file.getOriginalFilename()));
        Map<String, Object> retMap = customerService.checkImportPowerStationCode(params, file.getInputStream());
        return JSONObject.fromObject(retMap);
    }

    @RequestMapping(value = "importPowerStationCode")
    @ResponseBody
    public JSONObject importPowerStationCode(MultipartFile file) throws IOException {
        Map<String, String> params = Maps.newHashMap();
        params.put("fileName", file.getOriginalFilename());
        Map<String, Object> retMap = customerService.importPowerStationCode(params, file.getInputStream());
        return JSONObject.fromObject(retMap);
    }
    @RequestMapping(value = "getPlanBySchemeId")
    @ResponseBody
    public Object getPlanBySchemeId(HttpServletRequest request){
        String scheme_id = request.getParameter("schemeId");
        Record plan = planService.getPlanById(scheme_id);

        return plan.getColumns();
    }



    @RequestMapping(value = "findOauthToken")
    @ResponseBody
    public Object findOauthToken(HttpServletRequest request){
        String key = request.getParameter("key");
        //  customerService.findOauthToken();
        cacheService.del(key);
        return 200;
    }


    @RequestMapping(value = "getPlanByToken")
    @ResponseBody
    public Object getPlanByToken(HttpServletRequest request){

        return cacheService.get("zyAccessToken");
    }


    @ResponseBody
    @RequestMapping(value = "doReceive")
    public Result doReceive(String ids) {
        GuardUtils.notBlank(ids, "id不能为空");
        customerService.doReceive(ids);
        return Result.ok();
    }

    private void setCommonData(Model model) {
        User user = UserUtils.getUser();
        //项目编码
        List<Record> projectList = null;
        CrmPartner partner;
        if(User.USER_TYPE_HZS.equals(user.getUserType())){
            String parId = CrmUtils.getPartnerId(user.getId());
            partner = partnerService.getById(parId);
            String staff = staffService.getStaffIsBrowse(user.getId());
            model.addAttribute("staff",staff);
            model.addAttribute("partner", partner);
            projectList = memberService.getProjectListByIds(partner.getAuthorizedId());
        }else if(User.USER_TYPE_PARTNER.equals(user.getUserType())){
            partner= partnerService.findByUserId(user.getId());
            projectList = memberService.getProjectListByIds(partner.getAuthorizedId());
            model.addAttribute("partner", partner);

        }else{
            projectList = memberService.getProjectLists();
        }

        String traderId=user.getTraderId();
        model.addAttribute("ifTop",user.getTraderType());
        List<Record> twoTrader=traderService.getTwoTrader(traderId);
        model.addAttribute("twoTrader",twoTrader);

        //安装方式
        List<Record> installWays = projectInstallService.findProjectInstalls();
        //匹配方案
        List<Record> plans = planService.findAllPlan();

        model.addAttribute("projectList", projectList);
        model.addAttribute("installWays", installWays);
        model.addAttribute("plans", plans);
        model.addAttribute("user", user);
        model.addAttribute("trader", traderService.getTraderBuserId(user.getId()));
        model.addAttribute("typeList", markSettingService.getAllMarkType("2"));
        //代理商列表
        List<Record> traderList = traderService.getTopTrader();
        model.addAttribute("traderList", traderList);
        List<Record> pros = addressService.getProvinces();
        model.addAttribute("pros", pros);
    }

    @ResponseBody
    @RequestMapping(value = "findCustomerEntryCount")
    public Object findCustomerEntryCount(HttpServletRequest request) {
        Map<String,Object> msp = Maps.newHashMap();
        Map<String, String> map = getParams(request);
        User user = UserUtils.getUser();
        if(User.USER_TYPE_HZS.equals(user.getUserType())){
            String parId = CrmUtils.getPartnerId(user.getId());
            CrmPartner partner = partnerService.getById(parId);
            map.put("authorizedId", partner.getAuthorizedId());
        }else{
            CrmPartner partner = partnerService.findByUserId(user.getId());
            map.put("authorizedId", partner.getAuthorizedId());
        }
        Operator operator = Operator.of(user.getId(), CrmUtils.getUserXM(user),user.getUserType());
        List<Map<String,Object>> listmap= Lists.newArrayList();
        List<String> listString= Lists.newArrayList();
        List<BigDecimal> listRong= Lists.newArrayList();
        List<Record> list = customerService.findCustomerEntryCount(map,operator);
        BigDecimal rongCount =BigDecimal.ZERO;
        for(Record rd:list){
            Map<String,Object> data = Maps.newHashMap();
            String name = rd.getStr("project_name").substring(0,2)+"项目";
            data.put("name",name);
            data.put("value",rd.getBigDecimal("capacity"));
            listmap.add(data);
            listString.add(name);
            listRong.add(rd.getBigDecimal("capacity"));
            rongCount= rongCount.add(rd.getBigDecimal("capacity"));
        }
        msp.put("rongCount",rongCount.divide(BigDecimal.ONE,0, BigDecimal.ROUND_HALF_UP));
        msp.put("listmap",listmap);
        msp.put("listString",listString);
        msp.put("listRong",listRong);
        return msp;
    }


    @ResponseBody
    @RequestMapping(value = "findCustomerEntryGroupProvince")
    public Object findCustomerEntryGroupProvince(HttpServletRequest request) {
        Map<String,Object> msp = Maps.newHashMap();
        Map<String, String> map = getParams(request);
        User user = UserUtils.getUser();
        if(User.USER_TYPE_HZS.equals(user.getUserType())){
            String parId = CrmUtils.getPartnerId(user.getId());
            CrmPartner partner = partnerService.getById(parId);
            map.put("authorizedId", partner.getAuthorizedId());
        }else{
            CrmPartner partner = partnerService.findByUserId(user.getId());
            map.put("authorizedId", partner.getAuthorizedId());
        }
        Operator operator = Operator.of(user.getId(), CrmUtils.getUserXM(user),user.getUserType());
        List<Record> list = customerService.findCustomerEntryGroupProvince(map,operator);
        BigDecimal azCount =BigDecimal.ZERO;
        BigDecimal jhCount =BigDecimal.ZERO;
        BigDecimal ysCount =BigDecimal.ZERO;
        BigDecimal ysl;  //验收率 = 验收量 /  计划量
        for(Record rd:list){
            BigDecimal jhl = new BigDecimal(rd.getStr("jhl"));
            BigDecimal azl = rd.getBigDecimal("anl");
            String province= rd.getStr("province");
        /*    if("安徽省".equals(province)){
                azl = new BigDecimal("196.25");
            }else if("河南省".equals(province)){
                azl = new BigDecimal("206.05");
            }else if("山西省".equals(province)){
                azl = new BigDecimal("14.4");
            }else if("河北省".equals(province)){
                azl = new BigDecimal("251.06");
            }else if("江西省".equals(province)){
                azl = new BigDecimal("20.73");
            }else if("山东省".equals(province)){
                azl = new BigDecimal("266.5");
            }*/

            rd.set("anl",azl);
            azCount= azCount.add(azl);
            jhCount= jhCount.add(jhl);
            ysCount= ysCount.add(rd.getBigDecimal("ysl"));
            if(jhl.compareTo(BigDecimal.ZERO)==0){
                jhl=BigDecimal.ONE;
            }
            rd.set("wcl",azl.divide(jhl, 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)));
            BigDecimal yslui =rd.getBigDecimal("ysl").divide(jhl, 4, BigDecimal.ROUND_HALF_UP);
            rd.set("yslui",(yslui.compareTo(BigDecimal.ONE)>0?BigDecimal.ONE:yslui).multiply(new BigDecimal(100)));
        }
        ysl = ysCount.divide(jhCount,0, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100));

        BigDecimal wclui = azCount.divide(jhCount,0, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100));
        msp.put("azCount",azCount);
        msp.put("jhCount",jhCount);
        msp.put("ysCount",ysCount.divide(BigDecimal.ONE,0, BigDecimal.ROUND_HALF_UP));
        msp.put("listmap",list);
        msp.put("ysl",(ysl.compareTo(new BigDecimal(100))>0?new BigDecimal(100):ysl));
        msp.put("wclui",wclui);
        return msp;
    }

    /**
     * 上传发用电合同
     */
    @ResponseBody
    @RequestMapping(value = "uploadContract")
    public Result uploadContract(@RequestBody @Valid UploadEntryFileReq req){
        customerService.uploadContract(req.getEntryId(), req.getPath(), Operator.of(UserUtils.getUser()));
        return Result.ok();
    }


    /**
     * 签署完成
     */
    @ResponseBody
    @RequestMapping(value = "signFinish")
    public Result signFinish(String entryId){
        GuardUtils.notBlank(entryId, "entryId不能为空");
        customerService.signFinish(entryId, Operator.of(UserUtils.getUser()));
        return Result.ok();
    }

    /**
     * 上传发票
     */
    @ResponseBody
    @RequestMapping(value = "uploadBillAndNo")
    public Result uploadBillAndNo(@RequestBody @Valid UploadBillReq req) {
        customerService.uploadBillAndNo(req, Operator.of(UserUtils.getUser()));
        return Result.ok();
    }

    /**
     * 安装验收通过
     */
    @ResponseBody
    @RequestMapping(value = "fixAcceptPass")
    public Result fixAcceptPass(String id, String fixConclusion){
        GuardUtils.notBlank(id, "id不能为空");
        DLock dLock = new DLock("fixAcceptPass" + id, jedisPool);
        dLock.lock();
        try {
            customerService.fixAcceptPass(id, fixConclusion, Operator.of(UserUtils.getUser()),fixConclusion);
        } finally {
            dLock.unlock();
        }
        return Result.ok();
    }

    /**
     * 平台安装验收通过
     */
    @ResponseBody
    @RequestMapping(value = "toNetAcceptPass")
    public Result toNetAcceptPass(String id, String type, String fixConclusionSh, String materialFixFlag){
        DLock dLock = new DLock("toNetAcceptPass" + id, jedisPool);
        Result result = Result.ok();
        try {
            GuardUtils.notBlank(id, "id不能为空");
            int lockTimeOut = 2*60*1000; // 锁定2分钟
            dLock.lock(lockTimeOut,lockTimeOut);
            User user = UserUtils.getUser();
            customerService.toNetAcceptPass(id, type, fixConclusionSh, materialFixFlag, Operator.of(user), user);
            try {
                customerService.insertInterFace(id);
            }catch (Exception e) {
                customerService.saveSysRecord(id,"安装验收通过 逆变器新增新的电站接入记录 失败",
                        "", e.getMessage(), "1");
            }
        } catch (BusinessException | IllegalArgumentException e) {
            result = Result.fail(e.getMessage());
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            result = Result.fail("操作失败");
        } finally {
            dLock.unlock();
        }
        return result;
    }

    /**
     * 平台安装验收 驳回
     */
    @ResponseBody
    @RequestMapping(value = "fixAcceptRefuse")
    public Result fixAcceptRefuse(String id, String fixConclusion,String materialFixFlag, String zfFixConclusion){
        GuardUtils.notBlank(id, "id不能为空");
        GuardUtils.notBlank(fixConclusion, "备注不能为空");
        User user= UserUtils.getUser();
        if (StringUtil.isBlank(materialFixFlag)) {
            materialFixFlag = "0";
        }
        customerService.fixAcceptRefuse(id, fixConclusion, materialFixFlag, Operator.of(user), user);
        return Result.ok();
    }

    /**
     * 国电投安装验收
     */
    @ResponseBody
    @RequestMapping(value = "GdtMergeAccept")
    public Result GdtMergeAccept(String id, String mergeConclusion,String type){
        GuardUtils.notBlank("id", "id不能为空");
        GuardUtils.notBlank("mergeConclusion", "验收意见不能为空");
        DLock dLock = new DLock("GdtMergeAccept" + id, jedisPool);
        dLock.lock();
        try {
            customerService.GdtMergeAccept(id, mergeConclusion, Operator.of(UserUtils.getUser()),type);
        } catch (BusinessException c) {
            return Result.fail(c.getMessage());
        } finally {
            dLock.unlock();
        }
        return Result.ok();
    }

    /**
     * 国电投并网验收
     */
    @ResponseBody
    @RequestMapping(value = "GdtBwMergeAccept")
    public Result GdtBwMergeAccept(String id, String mergeConclusion,String type){
        GuardUtils.notBlank("id", "id不能为空");
        GuardUtils.notBlank("mergeConclusion", "验收意见不能为空");
        customerService.GdtBwMergeAccept(id, mergeConclusion, Operator.of(UserUtils.getUser()),type);
        return Result.ok();
    }

    /**
     * 并网提交国网授权
     */
    @ResponseBody
    @RequestMapping(value = "merge")
    public Result merge(@RequestBody AddReportSecondReq req){
        customerService.merge(req, Operator.of(UserUtils.getUser()),true);
        return Result.ok();
    }

    /**
     * 并网暂存
     */
    @ResponseBody
    @RequestMapping(value = "mergeTmp")
    public Result mergeTmp(@RequestBody AddReportSecondReq req){
        customerService.merge(req, Operator.of(UserUtils.getUser()),true);
        return Result.ok();
    }

    /**
     * 并网提交
     */
    @ResponseBody
    @RequestMapping(value = "mergeSubmit")
    public Result mergeSubmit(@RequestBody AddReportSecondReq req){
        customerService.merge(req, Operator.of(UserUtils.getUser()), false);
        return Result.ok();
    }

    /**
     * 并网验收通过
     */
    @ResponseBody
    @RequestMapping(value = "mergeAcceptPass")
    public Result mergeAcceptPass(String id, String mergeConclusion, String finalConclusion,String zfMergeConclusion){
        GuardUtils.notBlank("id", "id不能为空");
        DLock dLock = new DLock("mergeAcceptPass" + id, jedisPool);
        dLock.lock();
        try {
            customerService.mergeAcceptPass(id, mergeConclusion, mergeConclusion, Operator.of(UserUtils.getUser()),mergeConclusion);
        } catch (BusinessException e){
            return Result.fail(e.getMessage());
        } finally {
            dLock.unlock();
        }
        return Result.ok();
    }

    /**
     * 退回待安装
     */
    @ResponseBody
    @RequestMapping(value = "backAzForEntry")
    public Result backAzForEntry(String id, int step, String remarks) {
        GuardUtils.notBlank("id", "id不能为空");
        DLock dLock = new DLock("backAzForEntry" + id, jedisPool);
        dLock.lock();
        Result result;
        try {
            User user = UserUtils.getUser();
            result = customerService.backAzForEntry(id, user, step, remarks);
        } catch (IllegalAccessException e) {
            result = Result.fail(e.getMessage());
        } catch (Exception e){
            logger.error(e.getMessage(), e);
            result = Result.fail("操作失败！"+e.getMessage());
        } finally {
            dLock.unlock();
        }
        return result;
    }


    /**
     * 并网验收驳回
     */
    @ResponseBody
    @RequestMapping(value = "mergeAcceptRefuse")
    public Result mergeAcceptRefuse(String id, String mergeConclusion,String zfMergeConclusion){
        GuardUtils.notBlank("id", "id不能为空");
        GuardUtils.notBlank("mergeConclusion", "验收意见不能为空");
        customerService.mergeAcceptRefuse(id, mergeConclusion, Operator.of(UserUtils.getUser()),mergeConclusion);
        return Result.ok();
    }


    /**
     * 并网验收二次审核
     */
    @ResponseBody
    @RequestMapping(value = "twoMergeAcceptRefuse")
    public Result twoMergeAcceptRefuse(String id, String type, String finalConclusion,
                                       String materialMergeFlag, String powerCapacityUrl){
        GuardUtils.notBlank("id", "id不能为空");
        DLock dLock = new DLock("twoMergeAcceptRefuse" + id, jedisPool);
        dLock.lock();
        try {
            User user= UserUtils.getUser();
            customerService.twoMergeAcceptRefuse(id, type, finalConclusion, materialMergeFlag,
                    powerCapacityUrl, Operator.of(user), user);
        } finally {
            dLock.unlock();
        }
        return Result.ok();
    }
    /**
     * 业主定位
     */
    @RequestMapping(value = "toPositionPage")
    public String toPositionPage() {
        return "modules/yangguang/customer/entry/positionMap";
    }



    /**
     * 销售基础表
     */
    @RequestMapping("/esalesBasisList")
    public String esalesBasisList(Model model) {
        setCommonData(model);
        return "modules/yangguang/customer/entry/waitReceiveList";
    }

    @ResponseBody
    @RequestMapping("/esalesBasisPage")
    public Object esalesBasisPage(HttpServletRequest request){
        LayuiPage<Record> page = new LayuiPage<>(request);
        Map<String, String> map = getParams(request);
        User user = UserUtils.getUser();
        Operator operator = Operator.of(user.getId(), CrmUtils.getUserXM(user),user.getUserType());
        customerService.esalesBasisPage(page, map, operator);
        return page.renderJson();
    }

    @RequestMapping("/outWaitConfirm")
    public String outWaitConfirm(Model model) {
        setCommonData(model);
        User user = UserUtils.getUser();
        model.addAttribute("user", user);

        List<Record> traderList = traderService.listTraderRecords(null, new HashMap<>());
        model.addAttribute("traderList", traderList);
        return "modules/yangguang/customer/entry/outWaitConfirmList";
    }

    @RequestMapping("/outConfirm")
    public String outConfirm(Model model) {
        setCommonData(model);
        User user = UserUtils.getUser();
        model.addAttribute("user", user);

        List<Record> traderList = traderService.listTraderRecords(null, new HashMap<>());
        model.addAttribute("traderList", traderList);
        return "modules/yangguang/customer/entry/outConfirmList";
    }

    @ResponseBody
    @RequestMapping("/outWaitConfirmData")
    public Object outWaitConfirmData(HttpServletRequest request){
        LayuiPage<Record> page = new LayuiPage<>(request);
        Map<String, String> map = getParams(request);
        User user = UserUtils.getUser();

        Operator operator = Operator.of(user.getId(), CrmUtils.getUserXM(user),user.getUserType());
        customerService.outConfirmData(page, map, operator);
        return page.renderJson();
    }

    @ResponseBody
    @RequestMapping("/batchConfirm")
    public Result<Void> batchConfirm(String ids) {
        return customerService.doConfirm(ids);
    }

    @RequestMapping("materialList")
    public String materialList(String id, Model model){
        List<Record> details = customerService.selectMaterialList(id);
        model.addAttribute("details", details);
        return "modules/yangguang/customer/entry/materialList";
    }

    @RequestMapping("detailToMaterialList")
    public String detailToMaterialList(String id, Model model){
        List<Record> details = customerService.selectMaterialList(id);
        model.addAttribute("details", details);
        return "modules/yangguang/customer/entry/detailMaterialList";
    }

    @RequestMapping("/entryDetailFromOut")
    public String entryDetailFromOut(String entryId, String outId, Model model) {
        CustomerEntry customerEntry = customerService.getById(entryId);

        CustomerEntrySurveyRecord surveyRecord = surveyRecordDao.findOneByEntryId(entryId);

        CrmProjectSetting projectSetting = projectService.getById(customerEntry.getProjectId());

        model.addAttribute("customerEntry", customerEntry);
        model.addAttribute("mobile",customerEntry.getMobile());
        model.addAttribute("idCode", customerEntry.getIdCode());
        model.addAttribute("outId", outId);

        model.addAttribute("project", projectSetting);
        return "modules/yangguang/customer/entry/entryDetail2";
    }

    //进件详情页面
    @RequestMapping(value = "jjDetail")
    public String jjDetail(HttpServletRequest request,Model model){
        String entryId=request.getParameter("entryId");
        CustomerEntry entry = customerService.getById(entryId);
        model.addAttribute("entry",entry);
        int i=0;
        CrmYxIncomingProcess process1=crmYxIncomingProcessDao.getProcess(entryId,"1");
        model.addAttribute("process1",process1);
        if("4".equals(entry.getCredit())){
            i=1;
        }
        if(process1!=null&& ("0".equals(process1.getItemStatus()) || "2".equals(process1.getAuditStatus())))i=1;
        CrmYxIncomingProcess process2=crmYxIncomingProcessDao.getProcess(entryId,"2");
        model.addAttribute("process2",process2);
        if(process2!=null&& ("0".equals(process2.getItemStatus()) || "2".equals(process2.getAuditStatus())))i=2;
        CrmYxIncomingProcess process3=crmYxIncomingProcessDao.getProcess(entryId,"3");
        model.addAttribute("process3",process3);
        if(process3!=null&& ("0".equals(process3.getItemStatus()) || "2".equals(process3.getAuditStatus())))i=3;
        CrmYxIncomingProcess process4=crmYxIncomingProcessDao.getProcess(entryId,"4");
        model.addAttribute("process4",process4);
        if(process4!=null&& ("0".equals(process4.getItemStatus()) || "2".equals(process4.getAuditStatus())))i=4;
        CrmYxIncomingProcess process5=crmYxIncomingProcessDao.getProcess(entryId,"5");
        model.addAttribute("process5",process5);
        if(process5!=null&& ("0".equals(process5.getItemStatus()) || "2".equals(process5.getAuditStatus())))i=5;
        model.addAttribute("sort",i);
        String companyName="";
        if(StringUtil.isNotBlank(entry.getManagementType())){
            companyName=CrmUtils.getCompanySetName(entry.getManagementType());
        }
        model.addAttribute("companyName",companyName);
        User user=UserUtils.getUser();
        model.addAttribute("user",user);
        CrmCustomerIncomingApplication incomingApplication=applicationDao.getNoDeleteApplication(entryId);
        model.addAttribute("incomingApplication",incomingApplication);
        List<Record> logs=yxIncomingLogDao.getLogByEntryId(entryId);
        model.addAttribute("logs",logs);
        if(PartnerConstants.PARTNER_ID_GF.equals(entry.getPartnerId())){
            return "modules/yangguang/customer/entry/jjGfDetail";
        } else if (PartnerConstants.PARTNER_ID_HR.equals(entry.getPartnerId())) {
            return "modules/yangguang/customer/entry/jjHRDetail";
        }
        return "modules/yangguang/customer/entry/jjDetail";
    }

    //广发存量电站 进件详情页面
    @RequestMapping(value = "jjDetail2")
    public String jjDetail2(HttpServletRequest request,Model model){
        String entryId=request.getParameter("entryId");
        CustomerEntry entry = customerService.getById(entryId);
        model.addAttribute("entry",entry);
        int i=0;
        CrmYxIncomingProcess process1=crmYxIncomingProcessDao.getProcess(entryId,"1");
        model.addAttribute("process1",process1);
        if(process1!=null&& ("0".equals(process1.getItemStatus()) || "2".equals(process1.getAuditStatus())))i=1;
        CrmYxIncomingProcess process2=crmYxIncomingProcessDao.getProcess(entryId,"2");
        model.addAttribute("process2",process2);
        if(process2!=null&& ("0".equals(process2.getItemStatus()) || "2".equals(process2.getAuditStatus())))i=2;
        model.addAttribute("sort",i);
        String companyName="";
        if(StringUtil.isNotBlank(entry.getManagementType())){
            companyName=CrmUtils.getCompanySetName(entry.getManagementType());
        }
        model.addAttribute("companyName",companyName);
        User user=UserUtils.getUser();
        model.addAttribute("user",user);
        CrmCustomerIncomingApplication incomingApplication=applicationDao.getNoDeleteApplication(entryId);
        model.addAttribute("incomingApplication",incomingApplication);
        List<Record> logs=yxIncomingLogDao.getLogByEntryId(entryId);
        model.addAttribute("logs",logs);
        return "modules/yangguang/customer/entry/stock/historyEntryjjDetail";
    }

    @RequestMapping(value = "auditOneselfList")
    public String auditOneselfList(HttpServletRequest request, Model model) {
        setCommonData(model);
        return "modules/yangguang/customer/entry/auditOneselfList";
    }

    @ResponseBody
    @RequestMapping(value = "getAuditOneself")
    public Object getAuditOneself(HttpServletRequest request) {
        LayuiPage<Record> page = new LayuiPage<>(request);
        Map<String, String> params = getParams(request);
        params.put("status", "2,h");
        User user = UserUtils.getUser();
        Operator operator = Operator.of(user.getId(), CrmUtils.getUserXM(user),user.getUserType());
        customerService.listWaitOrder(page, params, operator);
        return page.renderJson();
    }

    /**
     * 自审退回
     */
    @ResponseBody
    @RequestMapping(value = "auditBack")
    public Result<Void> auditBack(@RequestBody AuditOperateReq req) {
        if (StringUtil.isBlank(req.getAuditRemarks())){
            return Result.fail("审核备注不能为空");
        }
        try {
            User user = UserUtils.getUser();
            customerService.auditBack(req,user);
            return Result.ok();
        } catch (IllegalArgumentException e) {
            return Result.fail(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(e.getMessage());
        }
    }

    /**
     * 批量自审
     */
    @ResponseBody
    @RequestMapping(value = "batchOneselfAudit")
    public Result<Void> batchOneselfAudit(@RequestBody BatchOperateReq req) {
        customerService.batchOneselfAudit(req);
        return Result.ok();
    }

    /**
     * 安装自审
     */
    @RequestMapping("/fixAcceptZS")
    public String fixAcceptZS(Model model) {
        setCommonData(model);
        return "modules/yangguang/customer/entry/waitFixAcceptZSList";
    }


    @RequestMapping("/toMergeAcceptZS")
    public String toMergeAcceptZS(String id, Model model){
        CustomerEntry customerEntry = customerService.getById(id);
        CustomerEntrySurveyRecord surveyRecord = surveyRecordDao.findOneByEntryId(id);
        if (surveyRecord == null) {
            surveyRecord = new CustomerEntrySurveyRecord();
        }
        User user = UserUtils.getUser();
        String traderId="";  //代理商不能看到平台的审批信息
        CrmTrader trader = traderService.getById(customerEntry.getDistributorId());

        if(User.USER_TYPE_ADVISOR.equals(user.getUserType()) || User.USER_TYPE_KJ.equals(user.getUserType())){
            traderId = user.getTraderId();
        }
        List<Record> optList = customerEntryMsgService.listOptRecordByEntryId(id,traderId);
        CrmProjectSetting projectSetting = projectService.getById(customerEntry.getProjectId());

        // 电站名称
        IsInteger str = new IsInteger();
        String stationName = customerEntry.getProvince()+customerEntry.getArea()+customerEntry.getTenantName();
        if(str.isInteger(customerEntry.getStatus())&& (customerEntry.getStatus().equals("0")|| customerEntry.getStatus().equals("1") || customerEntry.getStatus().equals("2") || customerEntry.getStatus().equals("3") || customerEntry.getStatus().equals("4")) ){
            stationName = stationName +
                    (new BigDecimal(customerEntry.getDesignCapacity()).divide(new BigDecimal(1000),3, RoundingMode.DOWN).stripTrailingZeros().toPlainString());
        }else{
            stationName= stationName +
                    (customerEntry.getActualCapacity().divide(new BigDecimal(1000),3, RoundingMode.DOWN).stripTrailingZeros().toPlainString());
        }
        stationName = stationName + "KW光伏电站";
        model.addAttribute("stationName", stationName);

        model.addAttribute("user", UserUtils.getUser());
        model.addAttribute("customerEntry", customerEntry);
        model.addAttribute("mobile",customerEntry.getMobile());
        model.addAttribute("idCode",customerEntry.getIdCode());
        model.addAttribute("optList", optList);
        model.addAttribute("project", projectSetting);
        model.addAttribute("trader", trader);
        CrmTenantYxBankCard card=tenantYxBankCardDao.getByIdCard(customerEntry.getIdCode(),customerEntry.getManagementType(),customerEntry.getPartnerId());
        model.addAttribute("card",card);
        model.addAttribute("bankName",linkNumberSettingService.findBankNUmberName(customerEntry.getTssBankNum()));
        model.addAttribute("quaimgsCount",0);
        model.addAttribute("surveyRecord", surveyRecord);
        if (StringUtil.isNotBlank(surveyRecord.getHouseOwnership())) {
            String[] arr = surveyRecord.getHouseOwnership().split(",");
            model.addAttribute("quaimgs", arr);
            model.addAttribute("quaimgsCount", arr.length);
        }
        // 获取单位资料信息
        if (Objects.equals("2", customerEntry.getTenantType())) {
            model.addAttribute("orgFiles", orgFilesDao.findOneByEntryId(customerEntry.getId()));
        }
        // 获取并网信息
        if(StrKit.notBlank(customerEntry.getReceivingReportId())){
            // 验收报告
            CrmAcceptingReport report = customerService.getReportById(customerEntry.getReceivingReportId());
            model.addAttribute("report", report);
            // 保险单
            model.addAttribute("insurances", insuranceDao.getByEntryIds(customerEntry.getId()));
            // 电力公司
            model.addAttribute("powerCompany", AddressUtils.findProCodeNameByCode(customerEntry.getProvinceCode()));
        }
        //获取表单设置  勘测设计
        model.addAttribute("info2", formSetService.getListByCondition("02", customerEntry.getPartnerId()));
        //房屋偏向
        List<Record> angleAzimuthList = sysCapitalDictDao.getDictionaryList("angle_azimuth", customerEntry.getPartnerId());
        model.addAttribute("angleAzimuthList",angleAzimuthList);
        Map<String, Object> maps = customerService.findUsedMaterial(customerEntry.getId());
        model.addAttribute("zjList", maps.get("zj"));
        model.addAttribute("nbqList", maps.get("nbq"));
        model.addAttribute("otherList", maps.get("other"));
        model.addAttribute("info3",formSetService.getListByCondition("03", customerEntry.getPartnerId()) );
        String contractUrlFlag = "0";
        if(PartnerConstants.PARTNER_ID_GF.equals(customerEntry.getPartnerId()) && "1".equals(customerEntry.getIsHistory())){
            contractUrlFlag = "1";
        }
        model.addAttribute("contractUrlFlag",contractUrlFlag);
        if(PartnerConstants.PARTNER_ID_HR.equals(customerEntry.getPartnerId())){
            List<Record> projectList = projectInfoSettingService.getEntryProjectByEntryId(customerEntry.getId());
            List<Record> entryProject = crmCustomerEntryProjectDao.getProjectsByEntryId(customerEntry.getId());
            List<Record>  surveyDetail =  recordDetailService.getEntryDetail(customerEntry.getId());
            for(Record record : projectList){
                Map<String, Object> map = customerService.findUsedMaterialByprojectId(customerEntry.getId(),record.getStr("projectId"));
                CrmAcceptingReportDetail acceptReport = crmAcceptingReportDetailDao.findByEntryIdAndProjectId(customerEntry.getId(),record.getStr("projectId"));
                record.set("zjList", map.get("zj"));
                record.set("nbqList", map.get("nbq"));
                record.set("otherList", map.get("other"));
                record.set("acceptReport", acceptReport);
            }
            model.addAttribute("formSet", formSetService.getListByCondition("03", customerEntry.getPartnerId()));
            model.addAttribute("projectList",projectList);
            model.addAttribute("entryProject",entryProject);
            model.addAttribute("projectDetailList",surveyDetail);

            return "modules/yangguang/customer/entry/checkHrAcceptSelf";
        }else{
            return "modules/yangguang/customer/entry/checkAcceptSelf";
        }

    }

    @ResponseBody
    @RequestMapping(value = "acceptZS")
    public Result acceptZS(String id){
        User user = UserUtils.getUser();
        customerService.acceptZS(id,user);
        return Result.ok();
    }

    @ResponseBody
    @RequestMapping(value = "acceptZSRefuse")
    public Result acceptZSRefuse(String id,String remarks){
        User user = UserUtils.getUser();
        customerService.acceptZSRefuse(id,remarks,user);
        return Result.ok();
    }

    //获取授权的合同签署链接
    @ResponseBody
    @RequestMapping(value = "getEsignUrl")
    public Result getEsignUrl(String idCode,String mobile,String patnerId){
        Map<String,String> resultMap=askAuthContractService.getEsignUrl(idCode,mobile,patnerId);
        return Result.success(resultMap);
    }

    //因为修改了手机号，重新发起授权合同  参数：entryId 电站id,idCode 身份证号，mobile:手机号  userId 用户id
    @ResponseBody
    @RequestMapping(value = "resetMobileVsAuthPc")
    public Result resetMobileVsAuthPc(String idCode, String mobile,String entryId){
        User user = UserUtils.getUser();
        Operator operator = Operator.of(user.getId(), CrmUtils.getUserXM(user),user.getUserType());
        askAuthContractService.resetMobileVsAuth(idCode,mobile,entryId,operator);
        return Result.ok();
    }

    /**
     * 查看完工信息
     */
    @RequestMapping("/toCompleteInfoPage")
    public String toCompleteInfoPage(String id, Model model) {
        CustomerEntry customerEntry = customerService.getById(id);
        // 安装物料
        Map<String, Object> maps = customerService.findUsedMaterial(customerEntry.getId());
        model.addAttribute("zjList", maps.get("zj"));
        model.addAttribute("nbqList", maps.get("nbq"));
        model.addAttribute("otherList", maps.get("other"));
        // 验收报告
        CrmAcceptingReport report = new CrmAcceptingReport();
        if (StringUtil.isNotBlank(customerEntry.getReceivingReportId())) {
            report = customerService.getReportById(customerEntry.getReceivingReportId());
        }
        model.addAttribute("report", report);
        // 查询勘测信息
        model.addAttribute("surveyRecord", surveyRecordDao.findOneByEntryId(customerEntry.getId()));
        model.addAttribute("customerEntry", customerEntry);
        model.addAttribute("info3",formSetService.getListByCondition("03", customerEntry.getPartnerId()) );
        String contractUrlFlag = "0";
        if(PartnerConstants.PARTNER_ID_GF.equals(customerEntry.getPartnerId()) && "1".equals(customerEntry.getIsHistory())){
            contractUrlFlag = "1";
        }
        model.addAttribute("contractUrlFlag",contractUrlFlag);
        if(PartnerConstants.PARTNER_ID_HR.equals(customerEntry.getPartnerId())){
            List<Record> projectList = projectInfoSettingService.getEntryProjectByEntryId(customerEntry.getId());
            List<Record> entryProject = crmCustomerEntryProjectDao.getProjectsByEntryId(customerEntry.getId());
            List<Record>  surveyDetail =  recordDetailService.getEntryDetail(customerEntry.getId());
            for(Record record : projectList){
                Map<String, Object> map = customerService.findUsedMaterialByprojectId(customerEntry.getId(),record.getStr("projectId"));
                CrmAcceptingReportDetail acceptReport = crmAcceptingReportDetailDao.findByEntryIdAndProjectId(customerEntry.getId(),record.getStr("projectId"));
                record.set("zjList", map.get("zj"));
                record.set("nbqList", map.get("nbq"));
                record.set("otherList", map.get("other"));
                record.set("acceptReport", acceptReport);
            }
            model.addAttribute("formSet", formSetService.getListByCondition("03", customerEntry.getPartnerId()));
            model.addAttribute("projectList",projectList);
            model.addAttribute("entryProject",entryProject);
            model.addAttribute("projectDetailList",surveyDetail);
            return "modules/yangguang/customer/entry/completeInfoHr";
        }else {
            return "modules/yangguang/customer/entry/completeInfo";
        }
    }

    @ResponseBody
    @RequestMapping(value = "getSysAssembly")
    public Result getSysAssembly(HttpServletRequest request) {
        String projectId = request.getParameter("projectId");
        CrmProjectSetting pro = projectDao.get(projectId);
        List<Record> records = planService.getElectricSet("3");
        List<Record> sysAssemblyList = new ArrayList<>();
        for (Record record : records) {
            if (Integer.valueOf(record.get("model")) >= pro.getAssemblySpecs()){
                sysAssemblyList.add(record);
            }
        }
        return Result.success(sysAssemblyList);
    }

    /**
     * 获取项目详细信息
     */
    @ResponseBody
    @RequestMapping(value = "getProjectInfoById")
    public Result getCityListByTraderId(HttpServletRequest request) {
        String projectId = request.getParameter("projectId");
        CrmProjectSetting crmProjectSetting = projectDao.get(projectId);
        return Result.success(crmProjectSetting);
    }

    /**
     * 获取项目详细信息
     */
    @ResponseBody
    @RequestMapping(value = "getProjectByTraderLists2")
    public Result getProjectByTraderLists2(HttpServletRequest request) {
        String filingType = request.getParameter("filingType");
        String traderId = request.getParameter("traderId");
        String management = request.getParameter("management");
        List<Record> projectList = new ArrayList<>();
        projectList = memberService.getProjectByTraderLists2(traderId,filingType,management);
        return Result.success(projectList);
    }


    /**
     * 获取业务属性
     */
    @ResponseBody
    @RequestMapping(value = "getProductLineAttribute")
    public Result getProductLineAttribute(HttpServletRequest request) {
        String id = request.getParameter("id");
        String attribute = productLineSetService.getProductLineAttribute(id);
        return Result.success(attribute);
    }



    /**
     * 获取代理商 产品对应的项目公司
     */
    @ResponseBody
    @RequestMapping(value = "getProjectInfo")
    public Result getProjectInfo(HttpServletRequest request) {
        String projectId = request.getParameter("projectId");
        Object projectInfo = null;
        if (StringUtil.isNotBlank(projectId)){
            projectInfo = customerService.getProjectInfo(projectId);
        }
        return Result.success(projectInfo);
    }

    @ResponseBody
    @RequestMapping(value = "getPressureLevel")
    public Result getPressureLevel(HttpServletRequest request){
        Map<String, String> map = getParams(request);
        Record record = null;
        if (map.get("area") != null && !Objects.equals(map.get("area"), "")){
            record = windSnowPressureLevelService.findPressureLevel(map.get("province"),map.get("city"),map.get("area"));
            if (record == null){
                record= new Record();
                record.set("wind_pressure","");
                record.set("snow_pressure", "");
                record.set("pressure_level", "");
            }
        }
        return Result.success(record);
    }

    /**
     * 获取代理商安装地址下的授权产品
     */
    @ResponseBody
    @RequestMapping(value = "getProjectByArea")
    public Result getProjectByArea(HttpServletRequest request) {
        Map<String, String> map = getParams(request);
        String traderId = map.get("traderId");
        if (StringUtil.isNotBlank(traderId)) {
            CrmTrader trader = traderService.getById(traderId);
            if (trader != null && "2".equals(trader.getType())) {
                map.put("traderId", trader.getParentId());
            }
        }
        List<Record> projectByArea = new ArrayList<>();
        if (map.get("area") != null && !Objects.equals(map.get("area"), "")){
            projectByArea = projectService.getProjectByArea(map);
        }
        return Result.success(projectByArea);
    }
    @ResponseBody
    @RequestMapping(value = "getProjectByArea2")
    public Result getProjectByArea2(String traderId,String  filingType ,String  management ,String province ,String city ,String area ) {
        List<Record> records = memberService.getProjectByTraderLists3(traderId, filingType, management, province, city, area);
        return Result.success(records);
    }

    /**
     * 获取安装地址下的项目公司
     */
    @ResponseBody
    @RequestMapping(value = "getCompanyByArea")
    public Result getCompanyByArea(HttpServletRequest request) {
        Map<String, String> map = getParams(request);
        List<Record> projectInfoByArea = new ArrayList<>();
        if (map.get("area") != null && !Objects.equals(map.get("area"), "")){
            projectInfoByArea = projectCompanyDao.getCompanyByArea(map);
        }
        return Result.success(projectInfoByArea);
    }

    @ResponseBody
    @RequestMapping("isByIdCode")
    public Result isByIdCode(HttpServletRequest request){
        String idCode = request.getParameter("idCode");
        String tenantType = request.getParameter("tenantType");
        User user = UserUtils.getUser();
        String traderId = CrmUtils.getCurrentTraderId(user);
        Map<String,String> map = new HashMap<>();//平台员工
        List<Record> customerEntry = customerService.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;
                }
                String distributorId = entry.getStr("trader_id");
                map.put("mobile",entry.getStr("mobile"));
                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);
    }

    /**
     * 历史电站信息页面
     */
    @RequestMapping("historyEntryManagement")
    public String historyEntryManagement(Model model){
        setCommonData(model);
        return "modules/yangguang/customer/entry/stock/historyEntryList";
    }

    /**
     * 历史电站信息列表数据
     */
    @ResponseBody
    @RequestMapping("getHistoryEntryList")
    public Object getHistoryEntryList(HttpServletRequest request){
        LayuiPage<Record> page = new LayuiPage<>(request);
        Map<String, String> map = getParams(request);
        User user = UserUtils.getUser();
        Operator operator = Operator.of(user.getId(), CrmUtils.getUserXM(user),user.getUserType());
        customerService.getHistoryEntryList(page, map, operator);
        return page.renderJson();
    }

    /**
     * 历史电站审核查询
     */
    @RequestMapping("historyEntryJjsh")
    public String historyEntryJjsh(Model model){
        setCommonData(model);
        return "modules/yangguang/customer/entry/stock/historyEntryJjsh";
    }

    /**
     * 历史电站审核查询列表数据
     */
    @ResponseBody
    @RequestMapping(value = "getHistoryEntryJjsh")
    public Object getHistoryEntryJjsh(HttpServletRequest request) {
        Map<String, String> map = getParams(request);
        LayuiPage page = new LayuiPage(request);
        User user = UserUtils.getUser();
        Operator operator = Operator.of(user);
        customerService.getHistoryEntryJjsh(page, map, operator);
        return page.renderJson();
    }

    @RequestMapping("approvalRecordPage")
    public String approvalRecordPage(HttpServletRequest request, Model model){
        String entryId = request.getParameter("entryId");
        List<CustomerEntryMsgVo> customerEntryMsgList = new ArrayList<>();
        List<String> typeList = new ArrayList<>();
        //新增资方意见 51,52,506,515,516,518
        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) {
            CustomerEntryMsgVo customerEntryMsg = new CustomerEntryMsgVo();
            String type = record.getInt("type").toString();
            if (typeList.contains(type)){
                customerEntryMsg.setId(record.getStr("id"));
                customerEntryMsg.setCustomerEntryId(record.getStr("customer_entry_id"));
                String typeStr = record.getInt("type").toString();
                if("85".equals(typeStr)){
                    typeStr = "提交踏勘";
                }
                if("87".equals(typeStr)){
                    typeStr = "提交档案";
                }
                if("88".equals(typeStr) || "89".equals(typeStr)){
                    typeStr = "档案审核";
                }
                if("90".equals(typeStr) || "11".equals(typeStr)){
                    typeStr = "设计审核";
                }
                if("6".equals(typeStr)){
                    typeStr = "提交完工";
                }
                if("62".equals(typeStr) || "63".equals(typeStr)){
                    typeStr = "安装验收";
                }
                if("65".equals(typeStr)){
                    typeStr = "并网提交";
                }
                if("661".equals(typeStr) || "662".equals(typeStr)){
                    typeStr = "并网验收";
                }
                if("91".equals(typeStr) || "92".equals(typeStr)){
                    typeStr = "设计自审";
                }
                if("93".equals(typeStr) || "94".equals(typeStr)){
                    typeStr = "安装自审";
                }
                if("511".equals(typeStr)){
                    typeStr = "设计暂存";
                }
                if("512".equals(typeStr)){
                    typeStr = "提交自审";
                }
                if("513".equals(typeStr)){
                    typeStr = "驳回勘测";
                }
                if("514".equals(typeStr)){
                    typeStr = "提交设计";
                }
                //新增开始 51,52,502,519,506,507,515,516
                if("51".equals(typeStr)){
                    typeStr = "进件审核";
                }
                if("52".equals(typeStr)){
                    typeStr = "进件审核";
                }
                if("502".equals(typeStr)){
                    typeStr = "进件审核";
                }
                if("519".equals(typeStr)){
                    typeStr = "进件审核";
                }
                if("506".equals(typeStr)){
                    typeStr = "资方预审";
                }
                if("507".equals(typeStr)){
                    typeStr = "资方预审";
                }
                if("515".equals(typeStr)){
                    typeStr = "投放审核";
                }
                if("516".equals(typeStr)){
                    typeStr = "投放审核";
                }
                //变更
                if("508".equals(typeStr)){
                    typeStr = "提交变更";
                }
                if("505".equals(typeStr)){
                    typeStr = "变更审核";
                }
                if("509".equals(typeStr)){
                    typeStr = "取消变更";
                }
                if("510".equals(typeStr)){
                    typeStr = "变更审核";
                }
                customerEntryMsg.setType(type);
                customerEntryMsg.setTypeStr(typeStr);
                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);
            }
        }
        model.addAttribute("customerEntryMsgList", customerEntryMsgList);
        return "modules/yangguang/customer/entry/approvalRecordPage";
    }

    /**
     * 电站审批记录
     */
    @ResponseBody
    @RequestMapping("getOptListData")
    public Result getOptListData(HttpServletRequest request){
        String entryId = request.getParameter("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");
        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);
            }
        }
        return Result.success(customerEntryMsgList);
    }

    /**
     * 广发取消进件页面
     */
    @RequestMapping("/toCancelGFApplyPage")
    public String toCancelGFApplyPage(HttpServletRequest request,Model model) {
        String id = request.getParameter("entryId");
        model.addAttribute("id",id);
        return "modules/yangguang/customer/entry/cancelGFApplyPage";
    }

    /**
     *广发取消进件
     * cancelType 10.终止进件 20.退回合规 30.退回完工
     */
    @ResponseBody
    @RequestMapping(value = "cancelGFApply")
    public Result cancelGFApply(String entryId, String returnType,String reason){
//        if (StringUtil.isBlank(returnType)){
//            return Result.fail("退回类型不能为空");
//        }
        if (StringUtil.isBlank(reason)){
            return Result.fail("终止进件原因不能为空");
        }
       return customerService.cancelGFApply(entryId, returnType, reason);
    }

    /**
     * 竣工整改
     * @param model
     * @return
     */
    @RequestMapping(value = "completionRectificationList")
    public String completionRectificationList(Model model){
        setCommonData(model);
        User user = UserUtils.getUser();
        String userType = user.getUserType();
        model.addAttribute("userType", userType);
        //项目工程师列表
        List<Record> empList = siteEmployeeService.findProjectEmpList("2,d");
        String today = DateUtils.formatDate(new Date(), "yyyy-MM-dd");
        String monthAgo = DateUtils.subDate(new Date(), 30);
        model.addAttribute("empList", empList);
        //系统工程师
        List<Record> empXtList = siteEmployeeService.findProjectEmpList("1,b,c");
        model.addAttribute("empXtList", empXtList);
        model.addAttribute("today", today);
        model.addAttribute("monthAgo", monthAgo);
        if(User.USER_TYPE_KJ.equals(user.getUserType())){
            String traderId = CrmUtils.getUserRelId(user);
            model.addAttribute("traderEmp",traderEmployeService.getTaderEmployeData(null,traderId));
        }
        List<Record> pros = addressService.getProvinces();
        model.addAttribute("province", pros);
        model.addAttribute("partner","03");
        return "modules/yangguang/customer/entry/completionRectificationList";
    }

    /**
     * 退回勘测
     */
    @ResponseBody
    @RequestMapping("/returnToSurvey")
    public Result returnToSurvey(String id) {
        User user = UserUtils.getUser();
        Operator operator = Operator.of(user.getId(), CrmUtils.getUserXM(user),user.getUserType());
        customerService.returnToSurvey(operator,id);
        return Result.ok();
    }

    /**
     * 待安装退回勘测
     */
    @ResponseBody
    @RequestMapping("/azReturnToSurvey")
    public Result azReturnToSurvey(String id) {
        User user = UserUtils.getUser();
        Operator operator = Operator.of(user.getId(), CrmUtils.getUserXM(user),user.getUserType());
        return customerService.azReturnToSurvey(operator,id);
    }

    //设为历史电站
    @ResponseBody
    @RequestMapping("/setHistoryEntry")
    public Result<Void> setHistoryEntry(@RequestBody List<String> ids) {
        User user = UserUtils.getUser();
        Operator operator = Operator.of(user.getId(), CrmUtils.getUserXM(user),user.getUserType());
        for(String id:ids){
            customerService.setHistoryEntry(id,operator);
        }
        return Result.ok();
    }

    /**
     * 验收审核暂存
     */
    @ResponseBody
    @RequestMapping(value = "twoMergeAcceptTemp")
    public Result twoMergeAcceptTemp(String id, String finalConclusion, String fixConclusionSh, String materialMergeFlag, String materialFixFlag){
        GuardUtils.notBlank("id", "id不能为空");
        DLock dLock = new DLock("twoMergeAcceptTemp" + id, jedisPool);
        dLock.lock();
        try {
            customerService.twoMergeAcceptTemp(id,finalConclusion,fixConclusionSh,materialMergeFlag,materialFixFlag);
        } finally {
            dLock.unlock();
        }
        return Result.ok();
    }

    /**
     * 设计审核暂存
     */
    @ResponseBody
    @RequestMapping("tempCustomerEntry")
    public Object tempCustomerEntry(HttpServletRequest request) {
        String id = request.getParameter("id");
        String remarks = request.getParameter("remarks");
        if (StringUtil.isBlank(id)) {
            return Result.fail("202", "参数id为空");
        }
        User user = UserUtils.getUser();
        Operator operator = Operator.of(user.getId(),CrmUtils.getUserXM(user) ,user.getUserType());
        try {
            customerService.tempCustomerEntry(id, remarks,operator);
        } catch (Exception e) {
            Result result = new Result();
            e.printStackTrace();
            result.setCode("505");
            result.setMsg("Exception" + e);
            throw e;
        }
        return Result.ok();
    }

    /**
     * 电站拆除标记
     * @param ids,removeSign
     * @return
     */
    @ResponseBody
    @RequestMapping("removeSign")
    public Result removeSign(@RequestParam("ids") String ids, @RequestParam("removeSign") String removeSign) {
        String[] idArr = ids.split(",");
        for(String id : idArr){
            customerService.removeSign(id,removeSign);
        }
        return Result.ok();
    }

    @ResponseBody
    @RequestMapping("removeSign2")
    public Result removeSign2(@RequestParam("ids") String ids, @RequestParam("removeSign") String removeSign) {
        String[] idArr = ids.split(",");
        for(String id : idArr){
            customerService.removeSign2(id,removeSign);
        }
        return Result.ok();
    }

    //下载地址
    //获取二维码地址
    @ResponseBody
    @RequestMapping(value = "getQrCodeUrl")
    public Result getQrCodeUrl(String entryId) throws IOException {
        String url = guangFaManagemnetService.getQrCodeUrl(entryId);
        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("url", url);
        return Result.success(resultMap);
    }
}
