package com.yeejoin.amos.boot.module.hygf.biz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yeejoin.amos.boot.biz.common.entity.BaseEntity;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.hygf.api.Enum.*;
import com.yeejoin.amos.boot.module.hygf.api.dto.*;
import com.yeejoin.amos.boot.module.hygf.api.entity.*;
import com.yeejoin.amos.boot.module.hygf.api.mapper.*;
import com.yeejoin.amos.boot.module.hygf.api.service.IPeasantHouseholdService;
import com.yeejoin.amos.boot.module.hygf.api.service.IWxService;
import com.yeejoin.amos.boot.module.hygf.api.util.BeanDtoUtils;
import com.yeejoin.amos.boot.module.hygf.api.util.NumberUtil;
import com.yeejoin.amos.boot.module.hygf.biz.vo.RouthPathVO;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.component.robot.AmosRequestContext;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.*;
import com.yeejoin.amos.feign.privilege.util.DesUtil;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.RegionModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.rdbms.annotation.Condition;
import org.typroject.tyboot.core.rdbms.annotation.Operator;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.spec.AlgorithmParameterSpec;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 农户信息服务实现类
 *
 * @author system_generator
 * @date 2023-07-07
 */
@Service
@Slf4j
public class PeasantHouseholdServiceImpl extends BaseService<PeasantHouseholdDto,PeasantHousehold,PeasantHouseholdMapper> implements IPeasantHouseholdService {
    @Autowired
    RedisUtils redisUtils;

    private static final String regionRedis="app_region_redis";
    public static final String SECRETKEY = "qaz";
    @Autowired
    SurveyInformationServiceImpl surveyInformationService;
    @Autowired
    private  FinancingInfoServiceImpl financingInfoService;
    @Autowired
    SurveyDetailsServiceImpl surveyDetailsService;
    @Autowired
    InformationServiceImpl informationService;
    @Autowired
    ExtendedInformationServiceImpl extendedInformationService;
    @Autowired
    CommercialServiceImpl commercialService;
    @Autowired
    DesignInformationServiceImpl designInformationService;
    @Autowired
    PeasantHouseholdMapper peasantHouseholdMapper;
    @Autowired
    HouseholdContractMapper householdContractMapper;
    @Autowired
    PowerStationEngineeringInfoMapper powerStationEngineeringInfoMapper;
    @Autowired
    SurveyInformationServiceImpl surveyInformationServiceImpl;
    @Autowired
    HouseholdContractServiceImpl householdContractServiceImpl;
    @Autowired
    PersonnelBusinessMapper personnelBusinessMapper;
    @Autowired
    UnitInfoServiceImpl unitInfoServiceImpl;
    @Autowired
    AmosRequestContext requestContext;
    @Autowired
    ToDoTasksServiceImpl toDoTasksServiceImpl;
    @Autowired
    RegionalCompaniesMapper regionalCompaniesMapper;
    @Autowired
    PowerStationServiceImpl powerStationService;
    private Long TOKEN_TIME = 1209600l;
//    @Autowired
//    CommonServiceImpl commonService;
    @Autowired
    HygfOnGridServiceImpl hygfOnGridService;
    @Autowired
    PowerStationConstructionDataServiceImpl powerStationConstructionDataService;
    @Autowired
    PowerStationEngineeringInfoServiceImpl powerStationEngineeringInfoService;
    @Autowired
    FinancingAuditingServiceImpl financingAuditingService;
    @Value("${amos.system.user.product}")
    private String product;

    @Value("${amos.system.user.app-key}")
    private String appKey;

    @Value("${login.environment}")
    private String loginEnvironment;

    @Value("${farmer.orgCode}")
    private String orgCode;

    @Value("${farmer.sequenceNbr}")
    private Long orgSequenceNbr;

    @Value("${farmer.orgNamesWithoutRole:智信能源科技有限公司}")
    private String orgNamesWithoutRole;

    @Value("${dealer.appcode}")
    private String appCodes;

    @Value("${platform.access.loginId}")
    private String platfromAccessLoginId;

    @Value("${platform.access.password}")
    private String platfromAccessPassword;

    @Value("${farmer.roleId:1678211468450885633}")
    private String farmerRoleId;

    @Value("${farmer.registerPassword}")
    private String registerPassword;


    @Autowired
    private IWxService wxService;

    @Autowired
    private  UnitInfoServiceImpl unitInfoService;

    @Transactional(rollbackFor = Exception.class)
    public PeasantHouseholdWxDto  savePeasantHousehold(PeasantHouseholdDto model, MobileLoginParamDto mobileLoginParam,PeasantHousehold household) {
        log.info("校验通过生成平台账号");
        //注册并登录 生成农户信息表数据
        PeasantHouseholdWxDto peasantHouseholdWxDto = this.registerAndLogin(mobileLoginParam);

        BeanDtoUtils.copyPropertiesAllNonNull(peasantHouseholdWxDto.getPeasantHousehold(), model);
        log.info("生成农户属性");
        model.setPeasantHouseholdNo(this.getPeasantHouseholdNo(model.getRegionalCompaniesSeq()));
        model.setIsCertified(1);// 这里就实名认证
        model.setSurveyOrNot(0);
        model.setReview(0);
        JSONArray regionName = getRegionName();
        List<RegionModel> list = JSONArray.parseArray(regionName.toJSONString(), RegionModel.class);
        // 处理项目地址
        String area = "";
        if (model.getProjectAddress() != null && model.getProjectAddress().size() != 0) {
            for (Integer reg : model.getProjectAddress())
                for (RegionModel re : list) {
                    if (re.getRegionCode().equals(Integer.valueOf(reg))) {
                        area = area + re.getRegionName() + "/";
                    }
                }
            model.setProjectAddressName(area.length() > 2 ? area.substring(0, area.length() - 1) : area);
            if ("1".equals(model.getIsPermanent()) || "true".equals(model.getIsPermanent())) {
                model.setPermanentAddress(model.getProjectAddress());
                model.setPermanentAddressDetail(model.getProjectAddressDetail());
                model.setPermanentAddressName(area.length() > 2 ? area.substring(0, area.length() - 1) : area);
            } else {
                // 处理常住地址
                String permanent = "";
                if (model.getPermanentAddress() != null && model.getPermanentAddress().size() != 0) {
                    for (Integer reg : model.getPermanentAddress())
                        for (RegionModel re : list) {
                            if (re.getRegionCode().equals(Integer.valueOf(reg))) {
                                permanent = permanent + re.getRegionName() + "/";
                            }
                        }
                    model.setPermanentAddressName(permanent.length() > 2 ? permanent.substring(0, permanent.length() - 1) : permanent);
                }
            }
        }
        log.info("更新农户信息");
        BeanDtoUtils.copyPropertiesAllNonNull(model, household);

        SurveyInformationDto surveyInformationDto = new SurveyInformationDto();
        surveyInformationDto.setSurveyNumber(this.getkcNo(model.getRegionalCompaniesSeq()));
        surveyInformationServiceImpl.createWithModel(surveyInformationDto);

        model.setSurveyInformationId(surveyInformationDto.getSequenceNbr());
        model.setSurveyOrNot(0);
        model.setReview(0);
        if (model.getCreationTime() == null) {
            model.setCreationTime(new Date());
        }
        model.setPeasantHouseholdNo(this.getPeasantHouseholdNo(model.getRegionalCompaniesSeq()));
        model.setIsCertified(model.getIsCertified() == null ? 0 : model.getIsCertified());// 未认证

        if (model.getSequenceNbr() == null) {
            List<PeasantHousehold> peasantHouseholds = this.query().eq("telephone", model.getTelephone()).orderByDesc("rec_date").list();
            PeasantHousehold phd = peasantHouseholds.size() > 0 ? peasantHouseholds.get(0) : null;
            if (phd != null) {
                model.setSequenceNbr(phd.getSequenceNbr());
            }
        }

        PeasantHousehold peasantHousehold = new PeasantHousehold();
        BeanUtils.copyProperties(model, peasantHousehold);
        peasantHousehold.setConstructionState(ArrivalStateeEnum.待勘察.getCode());
        this.saveOrUpdate(peasantHousehold);
        //生成合同
        HouseholdContract householdContract=new HouseholdContract();
        householdContract.setPartyA(peasantHousehold.getOwnersName());
        householdContract.setPeasantHouseholdNumber(peasantHousehold.getPeasantHouseholdNo());
        householdContract.setPeasantHouseholdCard(peasantHousehold.getIdCard());
        householdContract.setDealerId(peasantHousehold.getDeveloperId());
        householdContract.setDealerCode(peasantHousehold.getDeveloperCode());
        householdContract.setDealerName(peasantHousehold.getDeveloperName());
        householdContract.setPeasantHouseholdId(peasantHousehold.getSequenceNbr());
        householdContract.setRegionalCompaniesCode(peasantHousehold.getRegionalCompaniesCode());
        householdContract.setRegionalCompaniesName(peasantHousehold.getRegionalCompaniesName());
        householdContract.setRegionalCompaniesSeq(peasantHousehold.getRegionalCompaniesSeq());
        householdContract.setPeasantHouseholdPhone(peasantHousehold.getTelephone());
        householdContract.setProjectAddressDetail(peasantHousehold.getProjectAddressDetail());
        householdContract.setProjectAddressName(peasantHousehold.getProjectAddressName());
        householdContract.setPermanentAddressDetail(peasantHousehold.getPermanentAddressDetail());
        householdContract.setPermanentAddressName(peasantHousehold.getPermanentAddressName());
        householdContract.setProjectUserId(peasantHousehold.getAmosUserId());
        householdContractServiceImpl.addHouseholdContract(householdContract);

        //生成待办任务
        List<String> todoUserIds = new ArrayList<>();
        todoUserIds.add(peasantHousehold.getDeveloperUserId());
        RouthPathVO routhPathVO = new RouthPathVO();
        routhPathVO.setRouthPathId(String.valueOf(peasantHousehold.getSequenceNbr()));
        String routhPath = toDoTasksServiceImpl.getRouthPath(TaskTypeStationEnum.勘察.getCode(),HygfRouthTypeEnum.HYGF_DZKC.getCode(), routhPathVO);
        String wxRouthPath = toDoTasksServiceImpl.getWxRouthPath(TaskTypeStationEnum.勘察.getCode(),HygfRouthTypeEnum.HYGF_DZKC.getCode(), routhPathVO);
        ToDoTasks toDoTasks=  new ToDoTasks (TaskTypeStationEnum.勘察.getCode(),  peasantHousehold.getSequenceNbr(),   householdContract.getPartyA()+"待勘察",householdContract.getDealerCode(),routhPath,wxRouthPath);
        toDoTasksServiceImpl.addToDoTasksByUserIds(todoUserIds,toDoTasks);

        RouthPathVO routhPathVO1 = new RouthPathVO();
        routhPathVO1.setRouthPathId(String.valueOf(householdContract.getSequenceNbr()));
        String routhPath1 = toDoTasksServiceImpl.getRouthPath(TaskTypeStationEnum.合同.getCode(), HygfRouthTypeEnum.HYGF_HTFQ.getCode(), routhPathVO1);
        String wxRouthPath1 = toDoTasksServiceImpl.getWxRouthPath(TaskTypeStationEnum.合同.getCode(), HygfRouthTypeEnum.HYGF_HTFQ.getCode(), routhPathVO1);
        ToDoTasks toDoTasks1=  new ToDoTasks (TaskTypeStationEnum.合同.getCode(),  householdContract.getSequenceNbr(),  householdContract.getPartyA()+"待合同发起",householdContract.getDealerCode(),routhPath1,wxRouthPath1);
        toDoTasksServiceImpl.addToDoTasksByUserIds(todoUserIds,toDoTasks1);
        return peasantHouseholdWxDto;
    }

    public boolean deletePeasantHouseholdBySequenceNbr(Long sequenceNbr){
        PeasantHouseholdDto peasantHouseholdDto = this.queryBySeq(sequenceNbr);
        Long surveyInformationId = peasantHouseholdDto.getSurveyInformationId();
        //删除勘察基本信息
        surveyInformationService.deleteBySeq(surveyInformationId);
        //删除扩展信息
        QueryWrapper<ExtendedInformation> extendedInformationDeleteWrapper = new QueryWrapper<>();
        extendedInformationDeleteWrapper.lambda().eq(ExtendedInformation::getSurveyInformationId,surveyInformationId);
        extendedInformationService.getBaseMapper().delete(extendedInformationDeleteWrapper);
        //删除勘察明细
        QueryWrapper<SurveyDetails> surveyDetailsDeleteWrapper = new QueryWrapper<>();
        surveyDetailsDeleteWrapper.lambda().eq(SurveyDetails::getSurveyInformationId,surveyInformationId);
        surveyDetailsService.getBaseMapper().delete(surveyDetailsDeleteWrapper);
        //删除商务信息
        QueryWrapper<Commercial> commercialDeleteWrapper = new QueryWrapper<>();
        commercialDeleteWrapper.lambda().eq(Commercial::getSurveyInformationId,surveyInformationId);
        commercialService.getBaseMapper().delete(commercialDeleteWrapper);
       //删除资料归档信息
        QueryWrapper<Information> informationDeleteWrapper = new QueryWrapper<>();
        informationDeleteWrapper.lambda().eq(Information::getSurveyInformationId,surveyInformationId);
        informationService.getBaseMapper().delete(informationDeleteWrapper);

        QueryWrapper<PowerStationConstructionData> powerStationConstructionDataQueryWrapper = new QueryWrapper<>();
        powerStationConstructionDataQueryWrapper.lambda().eq(PowerStationConstructionData::getWorkOrderPowerStationId,sequenceNbr);
        powerStationConstructionDataService.getBaseMapper().delete(powerStationConstructionDataQueryWrapper);

        QueryWrapper<HygfOnGrid> hygfOnGridQueryWrapper = new QueryWrapper<>();
        hygfOnGridQueryWrapper.lambda().eq(HygfOnGrid::getPeasantHouseholdId,sequenceNbr);
        hygfOnGridService.getBaseMapper().delete(hygfOnGridQueryWrapper);

        QueryWrapper<DesignInformation> designInformationQueryWrapper = new QueryWrapper<>();
        designInformationQueryWrapper.lambda().eq(DesignInformation::getPeasantHouseholdId,sequenceNbr);
        designInformationService.getBaseMapper().delete(designInformationQueryWrapper);

        QueryWrapper<PowerStationEngineeringInfo> powerStationEngineeringInfoQueryWrapper = new QueryWrapper<>();
        powerStationEngineeringInfoQueryWrapper.lambda().eq(PowerStationEngineeringInfo::getWorkOrderPowerStationId,sequenceNbr);
        powerStationEngineeringInfoService.getBaseMapper().delete(powerStationEngineeringInfoQueryWrapper);
        //删除农户信息
        return this.deleteBySeq(sequenceNbr);
    }
    public String getkcNo(Long sequenceNbr) {
        RegionalCompanies da= regionalCompaniesMapper.selectRegionName(sequenceNbr);
        if(da.getCompanyCode()==null||da.getCompanyCode().isEmpty()){
            throw new BadRequest("区域公司编号为空, 请设置编号");
        }
        if(da.getRegionalAddress()==null||da.getRegionalAddress().isEmpty()){
            throw new BadRequest("区域公司省市区为空, 请设置省市区");
        }
        String code=  NumberUtil.getCode(CodeEnum.勘察.getCode(),da.getCompanyCode(),da.getRegionalAddress());
        return code;
    }



    /**
     * 分页查询
     */

    public Page<PeasantHousehold> queryForPeasantHouseholdPage(Page<PeasantHousehold> page,String developerCode, String ownersName,Long developerId, Integer isCertified,String preparationMoneyState, String peasantHouseholdNo,String province,String isHistory,String regionalCompaniesSeq,String routhPathId)   {
        int current = (int)page.getCurrent();
        int size = (int)page.getSize();

        PageHelper.startPage(current,size);

        if (null != developerId ){
            UnitInfo unitInfo = unitInfoService.getBaseMapper().selectById(developerId);
            developerId = unitInfo.getAmosCompanySeq();
        }

        List<PeasantHousehold> records = peasantHouseholdMapper.queryForPage( developerCode,ownersName,developerId, isCertified,preparationMoneyState, peasantHouseholdNo,province,isHistory,regionalCompaniesSeq,routhPathId);
        PageInfo<PeasantHousehold> objectPageInfo = new PageInfo<PeasantHousehold>(records);


        List<PeasantHousehold> newRecords = records.stream().map(item -> {
//            查询该条数据能否被删除, 0不能删除, 1可以删除
            item.setIsAllRevoke(BooleanUtil.toInteger(peasantHouseholdMapper.selectIsAllRevokePassCount(item.getPeasantHouseholdNo()) == peasantHouseholdMapper.selectIsAllRevoke(item.getPeasantHouseholdNo())));


            if(item.getSurveyOrNot() != null){
                if (item.getSurveyOrNot() == 0) {
                    item.setSurveyOrNotText("待勘察");
                } else if (item.getSurveyOrNot() == 1) {
                    item.setSurveyOrNotText("已勘察");
                } else if (item.getSurveyOrNot() == 2) {
                    item.setSurveyOrNotText("审核中");
                } else if (item.getSurveyOrNot() == 3) {
                    item.setSurveyOrNotText("审核完成");
                }
            }

            if (!StringUtils.isEmpty(item.getProjectAddressName())) {
                item.setProjectAddressText(Arrays.asList(item.getProjectAddressName().split("/")));
            }
            if(!StringUtils.isEmpty(item.getPermanentAddressName())){
                item.setPermanentAddressText(Arrays.asList(item.getPermanentAddressName().split("/")));
            }
            if(item.getProjectAddressDetail()!=null){
                item.setProjectAddressName(item.getProjectAddressName()+"/"+item.getProjectAddressDetail());
            }

            return item;
        }).collect(Collectors.toList());
        Page<PeasantHousehold> pagenew = new Page<PeasantHousehold>();
        pagenew.setCurrent(current);
        pagenew.setTotal(objectPageInfo.getTotal());
        pagenew.setSize(size);

        if(newRecords != null && newRecords.size() > 0) {
            newRecords.forEach(e -> {
                if(e.getPeasantHouseholdNo() != null) {
                    e.setScale(householdContractMapper.getHygfCommercialScale(e.getPeasantHouseholdNo()));
                    if ("1".equals(e.getIsHistory())){
                        e.setRealScale(powerStationEngineeringInfoMapper.getRealScaleByPeasantHouseholdNoIsHisotry(e.getPeasantHouseholdNo()));
                    }else {
                        e.setRealScale(powerStationEngineeringInfoMapper.getRealScaleByPeasantHouseholdNo(e.getPeasantHouseholdNo()));
                    }
                }
            });
        }

        pagenew.setRecords(newRecords);

        return pagenew;
    }

    /**
     * 列表查询 示例
     */
    public List<PeasantHouseholdDto> queryForPeasantHouseholdList(@Condition(Operator.eq) Integer isCertified)   {
        return this.queryForList("" , false, isCertified);
    }

    public Boolean doAuthenticate(Long sequenceNbr) {
        // 判断是否注册过
        PeasantHousehold peasantHousehold = this.getById(sequenceNbr);
        if (null == peasantHousehold) {
            throw new BadRequest("认证失败, 农户信息不存在");
        }
        peasantHousehold.setIsCertified(1);// 认证
        return this.updateById(peasantHousehold);
    }

    @Transactional(rollbackFor = Exception.class)
    public PeasantHouseholdWxDto wxUserLogin(MobileLoginParamDto wxDTO) {
        // 通过手机号和验证码调用平台接口进行验证
        String phoneNo ;
        try{
           phoneNo = this.parsePhoneNo(wxDTO);
        } catch (Exception e){
            throw new RuntimeException("解析手机号失败");
                    }
        if (phoneNo == null) {
                log.error("获取手机号失败!");
                throw new RuntimeException("解析手机号失败");
        }
        log.info("用户手机号码 => {} 开始登录", phoneNo);
        wxDTO.setPhoneNo(phoneNo);
        // 机器人token
        RequestContext.setAppKey("AMOS_STUDIO");
        RequestContext.setProduct("AMOS_STUDIO_WEB");
        RequestContext.setToken(requestContext.getToken());

        //判断是否非农户 如果存在即为非农户角色
        List<Map<String, Object>> maps = peasantHouseholdMapper.selectUserIsHouse(phoneNo);
        if (CollectionUtil.isNotEmpty(maps)){
            throw new RuntimeException("该用户非农户，请切换后登录");
        }
        AgencyUserModel registerUserModel = null;
        // region 判断有无在平台内部注册过用户 没有注册则去平台注册
        FeignClientResult<LoginInfoModel> loginInfo = Privilege.agencyUserClient.getLoginInfo(phoneNo);

        if (loginInfo != null && 200 == loginInfo.getStatus()) {
            LoginInfoModel loginInfoModel = loginInfo.getResult();
            if (loginInfoModel == null || !StringUtils.isNotBlank(loginInfoModel.getLoginId())) {
                // 没有认证过, 去注册用户
                if (StringUtils.isEmpty(wxDTO.getAmosUserId())){
                    throw new RuntimeException("请扫描经销商开发人员区域二维码进行注册");
                }
//                FeignClientResult<AgencyUserModel> registerUserModelRestult = doRegister(wxDTO);
//                if (registerUserModelRestult == null || registerUserModelRestult.getStatus() != 200) {
//                    log.error("用户手机号码 => " + phoneNo + " 调用平台创建用户信息失败: " + registerUserModelRestult.getDevMessage());
//                    throw new RuntimeException(registerUserModelRestult.getMessage());
//                }
//                registerUserModel = registerUserModelRestult.getResult();
            }
        }
        // endregion
        // 登录
        PeasantHouseholdWxDto loginResult;
        try {
            loginResult = doLogin(wxDTO, registerUserModel);
            // 查询农户信息
            List<PeasantHousehold> peasantHouseholds = this.query().eq("telephone", phoneNo).orderByDesc("rec_date").list();
            PeasantHousehold peasantHousehold = peasantHouseholds.size() > 0 ? peasantHouseholds.get(0) : null;
//            if (null == peasantHousehold) {
//                peasantHousehold = new PeasantHousehold();
//                peasantHousehold.setIsCertified(0);
//                peasantHousehold.setSurveyOrNot(0);
//                peasantHousehold.setReview(0);
//                peasantHousehold.setTelephone(phoneNo);
//                PeasantHouseholdDto peasantHouseholdDto = buildDefaultPeasantHouseholdDto(wxDTO.getAmosUserId(), wxDTO.getQrCodeType(), phoneNo);
//                peasantHousehold.setDeveloperCode(Optional.ofNullable(peasantHouseholdDto).map(PeasantHouseholdDto::getDeveloperCode).orElse(null));// 开发方code
//                peasantHousehold.setDeveloperId(Optional.ofNullable(peasantHouseholdDto).map(PeasantHouseholdDto::getDeveloperId).orElse(null));// 开发方id
//                peasantHousehold.setDeveloperName(Optional.ofNullable(peasantHouseholdDto).map(PeasantHouseholdDto::getDeveloperName).orElse(null));// 开发方名称
//                peasantHousehold.setDeveloper(Optional.ofNullable(peasantHouseholdDto).map(PeasantHouseholdDto::getDeveloper).orElse(null));// 开发人
//                peasantHousehold.setDeveloperUserId(Optional.ofNullable(peasantHouseholdDto).map(PeasantHouseholdDto::getDeveloperUserId).orElse(null));
//                peasantHousehold.setRegionalCompaniesSeq(Optional.ofNullable(peasantHouseholdDto).map(PeasantHouseholdDto::getRegionalCompaniesSeq).orElse(null));
//                peasantHousehold.setRegionalCompaniesCode(Optional.ofNullable(peasantHouseholdDto).map(PeasantHouseholdDto::getRegionalCompaniesCode).orElse(null));
//                peasantHousehold.setRegionalCompaniesName(Optional.ofNullable(peasantHouseholdDto).map(PeasantHouseholdDto::getRegionalCompaniesName).orElse(null));
//                peasantHousehold.setIsCertified(0);
//                // 过滤传给前端的数据
//                this.save(peasantHousehold);
//            }
            /*else {
                // 场景：扫码未实名认证的情况下, 关掉小程序第二次扫另一个区域经销商的二维码
                //
                wxDTO.getAmosUserId();// 二维码携带的经销商userId
                PeasantHouseholdDto peasantHouseholdDto = buildDefaultPeasantHouseholdDto(wxDTO.getAmosUserId(), wxDTO.getQrCodeType(), phoneNo);
                Long newRegionalCompaniesSeq = Optional.ofNullable(peasantHouseholdDto).map(PeasantHouseholdDto::getRegionalCompaniesSeq).orElse(null);
                if (newRegionalCompaniesSeq.compareTo()) {
                    throw new RuntimeException("");
                }
            }*/
            log.debug("返回给前端数据, 手机号码 => {}, 农户信息 => {}", phoneNo, peasantHousehold);
            // 装载农户信息
            loginResult.setPeasantHousehold(peasantHousehold);
            return loginResult;
        } catch (Exception e) {
            log.error(e.getMessage());
            if (null != registerUserModel) {
                log.error("调用平台接口回滚注册的用户 => {}", e, registerUserModel.getUserId());
                // 调用平台接口回滚注册的用户
                RequestContext.setAppKey("AMOS_STUDIO");
                RequestContext.setProduct("AMOS_STUDIO_WEB");
                RequestContext.setToken(requestContext.getToken());
                Privilege.agencyUserClient.multDeleteUser(registerUserModel.getUserId());
            }
            if (e instanceof BadRequest || e.getCause() instanceof BadRequest) {
                throw new RuntimeException("解析手机号失败");
            }
            throw new RuntimeException("解析手机号失败");
        }
    }


    public Map<String,Object>  getRegisterPhone(MobileLoginParamDto wxDTO){
        // 机器人token
        RequestContext.setAppKey("AMOS_STUDIO");
        RequestContext.setProduct("AMOS_STUDIO_WEB");
        RequestContext.setToken(requestContext.getToken());
        PeasantHouseholdDto peasantHouseholdDto = this.buildDefaultPeasantHouseholdDto(wxDTO.getAmosUserId(), wxDTO.getQrCodeType(), wxDTO.getPhoneNo());
        String phoneNo = null;
        Map<String, Object> resultMap = BeanUtil.beanToMap(peasantHouseholdDto);
        resultMap.put("isRegister",1);
       try {
           phoneNo = this.parsePhoneNo(wxDTO);
       }catch (Exception e){
           resultMap.put("telephone","");
           return resultMap;
       }

        //判断是否非农户 如果存在即为非农户角色
        List<Map<String, Object>> maps = peasantHouseholdMapper.selectUserIsHouse(phoneNo);
        if (CollectionUtil.isNotEmpty(maps)){
            throw new BadRequest("该手机号已注册");
        }
        if (StringUtils.isNotEmpty(phoneNo)){
            resultMap.put("telephone",phoneNo);
            FeignClientResult<LoginInfoModel> loginInfo = Privilege.agencyUserClient.getLoginInfo(phoneNo);
            List<PeasantHousehold> peasantHouseholds = this.query().eq("telephone", phoneNo).eq("is_certified","1").orderByDesc("rec_date").list();

            if (loginInfo != null && 200 == loginInfo.getStatus()&& null!= loginInfo.getResult()
                    &&(peasantHouseholds.size()>0 || CollectionUtil.isNotEmpty(peasantHouseholds))){
                resultMap.put("isRegister",0);
            }
        }else {
            resultMap.put("telephone","");
        }

        return resultMap;
    }

    public PeasantHouseholdWxDto registerAndLogin(MobileLoginParamDto wxDTO){
        // 机器人token
        RequestContext.setAppKey("AMOS_STUDIO");
        RequestContext.setProduct("AMOS_STUDIO_WEB");
        RequestContext.setToken(requestContext.getToken());
        wxDTO.setPhoneNo(wxDTO.getPeasantHouseholdDto().getTelephone());
        AgencyUserModel registerUserModel = null;
        // region 判断有无在平台内部注册过用户 没有注册则去平台注册
        FeignClientResult<LoginInfoModel> loginInfo = Privilege.agencyUserClient.getLoginInfo(wxDTO.getPhoneNo());

        if (loginInfo != null && 200 == loginInfo.getStatus()) {
            LoginInfoModel loginInfoModel = loginInfo.getResult();
            if (loginInfoModel == null || !StringUtils.isNotBlank(loginInfoModel.getLoginId())) {
                // 没有认证过, 去注册用户
                if (StringUtils.isEmpty(wxDTO.getAmosUserId())){
                    throw new RuntimeException("请扫描经销商开发人员区域二维码进行注册");
                }
                FeignClientResult<AgencyUserModel> registerUserModelRestult = doRegister(wxDTO);
                if (registerUserModelRestult == null || registerUserModelRestult.getStatus() != 200||registerUserModelRestult.getResult() == null) {
                    log.error("用户手机号码 => " + wxDTO.getPhoneNo() + " 调用平台创建用户信息失败: " + registerUserModelRestult.getDevMessage());
                    throw new RuntimeException(registerUserModelRestult.getMessage());
                }
                registerUserModel = registerUserModelRestult.getResult();
            }
        }
        // endregion
        // 登录
        PeasantHouseholdWxDto loginResult;

            loginResult = doLogin(wxDTO, registerUserModel);
            // 查询农户信息
            List<PeasantHousehold> peasantHouseholds = this.query().eq("telephone", wxDTO.getPhoneNo()).orderByDesc("rec_date").list();
            PeasantHousehold peasantHousehold = peasantHouseholds.size() > 0 ? peasantHouseholds.get(0) : null;
            if (null == peasantHousehold) {
                peasantHousehold = new PeasantHousehold();
                BeanUtils.copyProperties(wxDTO.getPeasantHouseholdDto(),peasantHousehold);
                peasantHousehold.setIsCertified(0);
                peasantHousehold.setSurveyOrNot(0);
                peasantHousehold.setReview(0);
                peasantHousehold.setAmosUserId(registerUserModel.getUserId());
                peasantHousehold.setTelephone(wxDTO.getPhoneNo());
                PeasantHouseholdDto peasantHouseholdDto = buildDefaultPeasantHouseholdDto(wxDTO.getAmosUserId(), wxDTO.getQrCodeType(), wxDTO.getPhoneNo());
                peasantHousehold.setDeveloperCode(Optional.ofNullable(peasantHouseholdDto).map(PeasantHouseholdDto::getDeveloperCode).orElse(null));// 开发方code
                peasantHousehold.setDeveloperId(Optional.ofNullable(peasantHouseholdDto).map(PeasantHouseholdDto::getDeveloperId).orElse(null));// 开发方id
                peasantHousehold.setDeveloperName(Optional.ofNullable(peasantHouseholdDto).map(PeasantHouseholdDto::getDeveloperName).orElse(null));// 开发方名称
                peasantHousehold.setDeveloper(Optional.ofNullable(peasantHouseholdDto).map(PeasantHouseholdDto::getDeveloper).orElse(null));// 开发人
                peasantHousehold.setDeveloperUserId(Optional.ofNullable(peasantHouseholdDto).map(PeasantHouseholdDto::getDeveloperUserId).orElse(null));
                peasantHousehold.setRegionalCompaniesSeq(Optional.ofNullable(peasantHouseholdDto).map(PeasantHouseholdDto::getRegionalCompaniesSeq).orElse(null));
                peasantHousehold.setRegionalCompaniesCode(Optional.ofNullable(peasantHouseholdDto).map(PeasantHouseholdDto::getRegionalCompaniesCode).orElse(null));
                peasantHousehold.setRegionalCompaniesName(Optional.ofNullable(peasantHouseholdDto).map(PeasantHouseholdDto::getRegionalCompaniesName).orElse(null));
                peasantHousehold.setIsCertified(0);
                this.save(peasantHousehold);
            }
        loginResult.setPeasantHousehold(peasantHousehold);
        return  loginResult;

    }

    /**
     * 农户微信注册
     *
     *
     * @param mobileLoginParamDto mobileLoginParamDto
     * @return {@link  AgencyUserModel}
     * @author Provence
     * @throws
     * @date 2023/8/21 18:05
     */
    public FeignClientResult<AgencyUserModel> doRegister(MobileLoginParamDto mobileLoginParamDto) {
        CompanyModel companyInfo = new CompanyModel();
        companyInfo.setSequenceNbr(orgSequenceNbr);
        companyInfo.setCompanyOrgCode(Integer.valueOf(orgCode));
        RoleModel allRoleList = null;
        FeignClientResult<RoleModel> roleListResult = Privilege.roleClient.seleteOne(Long.valueOf(farmerRoleId));
        if (roleListResult != null && roleListResult.getStatus() == 200) {
            allRoleList = roleListResult.getResult();
        }

        List<RoleModel> userRoleList = new ArrayList<>();
        List<String> split = Arrays.asList(StringUtils.split(appCodes, ','));
        Map<Long, List<Long>> roleSeqMap = new HashMap<>();
        Map<Long, List<RoleModel>> orgRoles = new HashMap<>();
        // 提前建立好一个默认角色
        List<Long> roleIds = new ArrayList<>();
        userRoleList.add(allRoleList);
        roleIds.add(Long.valueOf(farmerRoleId));
        roleSeqMap.put(companyInfo.getSequenceNbr(), roleIds);
        orgRoles.put(companyInfo.getSequenceNbr(), userRoleList);
        // 初始默认密码  a1234560
        String custPassword = DesUtil.encode(registerPassword, SECRETKEY);
        AgencyUserModel agencyUserModel = new AgencyUserModel();
        agencyUserModel.setUserName(mobileLoginParamDto.getPhoneNo());
        agencyUserModel.setRealName(mobileLoginParamDto.getPhoneNo());
        agencyUserModel.setPassword(custPassword);
        agencyUserModel.setRePassword(custPassword);
        // model中有个openId, 传手机号，verifyCode值为手机号加密
        agencyUserModel.setOpenId(mobileLoginParamDto.getPhoneNo());
        agencyUserModel.setVerifyCode(DesUtil.encode(mobileLoginParamDto.getPhoneNo(), SECRETKEY));
        agencyUserModel.setLockStatus("UNLOCK");
        agencyUserModel.setAgencyCode("JXIOP");
        agencyUserModel.setMobile(mobileLoginParamDto.getPhoneNo());
        agencyUserModel.setAppCodes(split);
        agencyUserModel.setOrgRoles(orgRoles);
        agencyUserModel.setOrgRoleSeqs(roleSeqMap);
        log.debug("注册用户入参, agencyUserModel => {}", agencyUserModel);
        FeignClientResult<AgencyUserModel> agencyUserResult = Privilege.agencyUserClient.create(agencyUserModel);
        return agencyUserResult;
    }

    /**
     * 农户微信登录
     *
     *
     * @param param param
     * @return {@link  PeasantHouseholdWxDto}
     * @author Provence
     * @throws
     * @date 2023/8/21 18:05
     */
    public PeasantHouseholdWxDto doLogin(MobileLoginParamDto param, AgencyUserModel registerUserModel) {
        RequestContext.setToken("");
        RequestContext.setProduct("STUDIO_APP_MOBILE");
        RequestContext.setAppKey("studio_normalapp_5133538");
        String phoneNo = param.getPhoneNo();
        if (phoneNo == null) {
            log.error("获取手机号失败!");
            throw new BadRequest("微信授权失败, 请重新授权");
        }
        FeignClientResult loginResult;
        if (!param.getIsNeedVerify() || ("dev".equals(loginEnvironment) && "666666".equals(param.getVerifyCode()))) {
            // 授权登录
            VerifyCodeAuthModel verifyCodeAuthModel = new VerifyCodeAuthModel();
            verifyCodeAuthModel.setLoginId(phoneNo);
            verifyCodeAuthModel.setVerifyCode(DesUtil.encode(phoneNo, SECRETKEY));// 手机号码 + 密码盐
            log.info("微信登录入参 => {}", verifyCodeAuthModel);
            loginResult = Privilege.authClient.Wechat(verifyCodeAuthModel);
        } else {
            // 验证码
            VerifyCodeAuthModel model = new VerifyCodeAuthModel();
            model.setLoginId(phoneNo);
            model.setVerifyCode(param.getVerifyCode());
            loginResult = Privilege.authClient.mobileVerifyCode(model);
        }
        if (loginResult == null || loginResult.getStatus() != 200) {
            log.error("手机号码 => " + phoneNo + " 登录失败: " + loginResult.getDevMessage());
            String message = StringUtils.isEmpty(loginResult.getMessage()) ? "账号或密码错误" : loginResult.getMessage();
            throw new BadRequest(message);
        }
        HashMap resultMap = (HashMap) loginResult.getResult();
        String token = resultMap.get("token").toString();
        // 设置登录信息
        RequestContext.setToken(token);
        // redisUtils.set(model.getPhone() + "_token", token, TOKEN_TIME);
        String userId = (String) resultMap.get("userId");
        // 组装数据
        PeasantHouseholdWxDto peasantHouseholdWxDto = new PeasantHouseholdWxDto();
        peasantHouseholdWxDto.setExpire(Long.valueOf((String) resultMap.get("expire")));
        peasantHouseholdWxDto.setUserId(userId);
        // 组装authInfo数据
        Map<String, Object> authInfo = new HashMap<>();
        authInfo.put("token", token);
        authInfo.put("personId", userId);
        /*authInfo.put("appKey", "STUDIO_APP_MOBILE");
        authInfo.put("product", "studio_normalapp_5133538");*/
        peasantHouseholdWxDto.setAuthInfo(authInfo);

        return peasantHouseholdWxDto;
    }

    /**
     * 通过区域/个人二维码扫描组装信息
     *
     * @param qrCodeType qrCodeType
     * @param userInfo userInfo
     * @return {@link  PeasantHouseholdDto}
     * @author Provence
     * @throws
     */
    public PeasantHouseholdDto buildDefaultPeasantHouseholdDto(String qrCodeType, AgencyUserModel userInfo) {


        if (null == userInfo) {
            log.warn("userId:{} 查询不到经销商信息 或者 查询不到经销商单位信息");
            return null;
        }
        log.info("通过区域/个人二维码扫描组装信息, user => {}, user's companys => {}", userInfo.getUserId(), JSONObject.toJSONString(userInfo.getCompanys()));

        //获取用户所在经销商单位
        UserUnitInformationDto userUnitInformationDto=personnelBusinessMapper.getUserUnitInformationDto(userInfo.getUserId());

//        Long sequenceNbr = userInfo.getCompanys().get(0).getSequenceNbr();
//        String companyOrgCode = userInfo.getCompanys().get(0).getOrgCode();
//        String companyName = userInfo.getCompanys().get(0).getCompanyName();
        Long sequenceNbr = userUnitInformationDto.getAmosDealerId();
        String companyOrgCode = userUnitInformationDto.getAmosDealerOrgCode();
        String companyName = userUnitInformationDto.getAmosDealerName();

        // unitInfoServiceImpl.createCompanyAndUser 创建经销商的时候绑定的平台用户
      //  List<UnitInfo> unitInfos = unitInfoServiceImpl.list(new LambdaQueryWrapper<UnitInfo>().eq(UnitInfo::getAmosCompanySeq, sequenceNbr));
        PeasantHouseholdDto dto = new PeasantHouseholdDto();
        // 先在后台创建一个角色和公司，微信农户新建的用户使用统一的
        // 用户光伏-微信农户
        // 非扫码进入注册页面，默认
        dto.setDeveloperCode(companyOrgCode);// 开发方code
        dto.setDeveloperId(sequenceNbr);// 开发方id
        dto.setDeveloperName(companyName);// 开发方名称
        dto.setDeveloper(userInfo.getRealName());// 开发人
        dto.setDeveloperUserId(userInfo.getUserId());
//        UnitInfo unitInfo;
//        if (!CollectionUtils.isEmpty(unitInfos)) {
//            log.warn("userId:{} 查询不到经销商信息", userInfo.getUserId());
//            unitInfo = unitInfos.get(0);
//           // Long regionalCompaniesSeq = unitInfo.getRegionalCompaniesSeq();
//            String regionalCompaniesCode = unitInfo.getRegionalCompaniesCode();
//            String regionalCompaniesName = unitInfo.getRegionalCompaniesName();
//            dto.setRegionalCompaniesSeq(null);//所属区域公司id
//            dto.setRegionalCompaniesCode(regionalCompaniesCode);//所属区域公司code
//            dto.setRegionalCompaniesName(regionalCompaniesName);//所属区域公司名称
//        }

        dto.setRegionalCompaniesSeq(userUnitInformationDto.getRegionalCompaniesSeq());//所属区域公司id
        dto.setRegionalCompaniesCode(userUnitInformationDto.getRegionalCompaniesCode());//所属区域公司code
        dto.setRegionalCompaniesName(userUnitInformationDto.getRegionalCompaniesName());//所属区域公司名称

        return dto;
    }

    /**
     * 农户通过扫描区域二维码进入注册，查询区域经销商的信息并
     *
     *
     * @param userId userId
     * @param qrCodeType qrCodeType
     * @param phoneNo phoneNo
     * @return {@link  PeasantHouseholdDto}
     * @author Provence
     * @throws
     */
    private PeasantHouseholdDto buildDefaultPeasantHouseholdDto(String userId, String qrCodeType, String phoneNo) {
        // 这里的userId 是解析区域二维码得到的参数, 如果第一次扫码进来会创建一条农户数据然后关联起来
        if (StringUtils.isBlank(userId)) {
            throw new BadRequest("请通过区域二维码扫码进入");
        }
        FeignClientResult<AgencyUserModel> userInfoResult = Privilege.agencyUserClient.queryByUserId(userId);// 获取用户
        if (userInfoResult == null || userInfoResult.getStatus() != 200) {
            return null;
        }
        AgencyUserModel userInfo = userInfoResult.getResult();
        return buildDefaultPeasantHouseholdDto(qrCodeType, userInfo);
    }

    /**
     * 手机号解析
     *
     * @param param MobileLoginParam.class
     * @return String phoneNo
     */
    private String parsePhoneNo(MobileLoginParamDto param) {
        if (param.getRegisterType() == PhoneRegisterTypeEum.WX.getCode()) {
            // 进行验证码解析
            String encryptedData = param.getEncryptedData();
            String iv = param.getIv();
            String code = param.getCode();
            return getPhoneNumber(wxService.getSessionKey(code), encryptedData, iv);
        } else {
            return param.getPhoneNo();
        }
    }

    public String getPhoneNumber(String sessionkey, String encryptedData, String iv) {
        byte[] encrypData = java.util.Base64.getDecoder().decode(encryptedData);
        byte[] ivData = java.util.Base64.getDecoder().decode(iv);
        byte[] sessionKey = java.util.Base64.getDecoder().decode(sessionkey);
        String resultString = null;
        AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivData);
        SecretKeySpec keySpec = new SecretKeySpec(sessionKey, "AES");
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
            resultString = new String(cipher.doFinal(encrypData), "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("getPhoneNumber error:", e);
            throw new BadRequest("微信授权失败, 请重新授权");
        }
        JSONObject object = JSONObject.parseObject(resultString);
        if (object != null) {
            // 拿到手机号码
            String phone = object.getString("phoneNumber");
            return phone;
        }
        return null;
    }


    /**
     * 设置平台接口调用权限
     */
    public void setPlatFormAccess() {
        RequestContext.setProduct(product);
        RequestContext.setAppKey(appKey);
        /*IdPasswordAuthModel authModel = new IdPasswordAuthModel();
        authModel.setLoginId("admin_jxiop");
        authModel.setPassword("AC286A35E74D2DD281EB979789DECF3A");*/

        IdPasswordAuthModel authModel = new IdPasswordAuthModel();
        authModel.setLoginId(platfromAccessLoginId);
        authModel.setPassword(platfromAccessPassword);

        FeignClientResult<Map<String, String>> authResult = Privilege.authClient.idpassword(authModel);
        String token = authResult.getResult().get("token");
        System.out.println("token:" + token);
        RequestContext.setToken(token);
        // 正常情况下，这里应该做缓存
    }

    /**
     * 生成一个农户信息编号
     *
     *
     * @param
     * @return {@link  String}
     * @author Provence
     * @throws
     */
    public String getPeasantHouseholdNo(Long sequenceNbr) {
        RegionalCompanies da= regionalCompaniesMapper.selectRegionName(sequenceNbr);
        if(da.getCompanyCode()==null||da.getCompanyCode().isEmpty()){
            throw new BadRequest("区域公司编号为空, 请设置编号");
        }
        if(da.getRegionalAddress()==null||da.getRegionalAddress().isEmpty()){
            throw new BadRequest("区域公司省市区为空, 请设置省市区");
        }
        //为了去重，暂时这样处理加两位随机数，同时在查询一次
        String code=NumberUtil.getCode(CodeEnum.农户.getCode(),da.getCompanyCode(),da.getRegionalAddress())+ RandomUtil.randomNumbers(2);
        Integer count = peasantHouseholdMapper.selectCount(new LambdaQueryWrapper<PeasantHousehold>().eq(PeasantHousehold::getPeasantHouseholdNo, code));
        if(count>0){
            code=  NumberUtil.getCode(CodeEnum.农户.getCode(),da.getCompanyCode(),da.getRegionalAddress())+ RandomUtil.randomNumbers(2);
        }
        return code;
    }

    private long nextDay() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        calendar.add(Calendar.DAY_OF_MONTH, 1);
        return (calendar.getTimeInMillis() - System.currentTimeMillis()) / 1000;
    }

    @Override
    public List<PeasantHousehold> getInfoByIds(String ids) {
        List<String> strings = Arrays.asList(ids.split(","));
        //有bug string有时候会少查出一个
        List<Long> list = strings.stream().map(Long::valueOf).collect(Collectors.toList());
        return this.getBaseMapper().getInfoByIds(list);

    }

    public List<PeasantHousehold> getInfoByIdsHistory(String ids) {
        List<String> strings = Arrays.asList(ids.split(","));
        List<Long> list = strings.stream().map(Long::valueOf).collect(Collectors.toList());
        return this.getBaseMapper().getInfoByIdsHistory(list);

    }

    @Override
    public Boolean deleteUser(String sequenceNbr, String peasantHouseholdNo) {
//        try {
//            根据sequenceNbr获取农户勘察状态
        PeasantHousehold peasantHousehold = peasantHouseholdMapper.selectReview(sequenceNbr);

        if(peasantHousehold.getReview() != 0) {
                throw new BadRequest("该电站已发起流程, 无法删除！");
            }

            // 查询该条数据能否被删除, 0不能删除, 1可以删除
//            Integer isAllRevok = peasantHouseholdMapper.selectIsAllRevoke(peasantHouseholdNo);
        Integer isAllRevok = BooleanUtil.toInteger(peasantHouseholdMapper.selectIsAllRevokePassCount(peasantHouseholdNo) == peasantHouseholdMapper.selectIsAllRevoke(peasantHouseholdNo));
        if(isAllRevok != 1) {
                throw new BadRequest("该用户有未完成的任务, 无法删除！");
            }
        //删除勘察待办
        LambdaQueryWrapper<ToDoTasks> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ToDoTasks::getBusinessId,peasantHousehold.getSequenceNbr());
        wrapper.eq(ToDoTasks::getType,TaskTypeStationEnum.勘察.getCode());
        toDoTasksServiceImpl.remove(wrapper);
        //删除合同待办
        LambdaQueryWrapper<HouseholdContract> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(HouseholdContract::getPeasantHouseholdId,peasantHousehold.getSequenceNbr());
        List<HouseholdContract> householdContracts = householdContractMapper.selectList(wrapper1);
        if(CollectionUtil.isNotEmpty(householdContracts)){
            for (HouseholdContract householdContract : householdContracts) {
                LambdaQueryWrapper<ToDoTasks> wrapper2 = new LambdaQueryWrapper<>();
                wrapper2.eq(ToDoTasks::getBusinessId,householdContract.getSequenceNbr());
                wrapper2.eq(ToDoTasks::getType,TaskTypeStationEnum.合同.getCode());
                toDoTasksServiceImpl.remove(wrapper2);
            }
        }

//            查询当前用户名下的电站数量
        Integer powerStationNumber = peasantHouseholdMapper.selectPowerStationNumber(peasantHousehold.getAmosUserId());

         if(powerStationNumber > 1) {
             // 删除hygf_peasant_household表中数据
             peasantHouseholdMapper.deleteHphByNo(peasantHouseholdNo);
             // 删除hygf_household_contract表中数据
             peasantHouseholdMapper.deleteHhcByNo(peasantHouseholdNo);
         }else {
             // 删除hygf_peasant_household表中数据
             peasantHouseholdMapper.deleteHphByUserId(peasantHousehold.getAmosUserId());
             // 删除privilege_agency_user表中数据
             peasantHouseholdMapper.deletePauByUserId(peasantHousehold.getAmosUserId());
             // 删除auth_login_info表中数据
             peasantHouseholdMapper.deleteAliByUserId(peasantHousehold.getAmosUserId());
             // 删除hygf_household_contract表中数据
             peasantHouseholdMapper.deleteHhcByUserId(peasantHousehold.getAmosUserId());
         }


            return true;
//        } catch (Exception e) {
//            throw new BadRequest("删除失败！" + e.getMessage());
//        }
    }


    public PeasantHousehold getDataByState(Long peasantHouseholdId) {
        LambdaQueryWrapper<PeasantHousehold> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PeasantHousehold::getConstructionState,"勘察完成");
        wrapper.eq(BaseEntity::getSequenceNbr,peasantHouseholdId);
        return   this.getBaseMapper().selectOne(wrapper);
    }
    public Map<String, Object> getJxsAndNhData(String nhUserId, String jxsUserId, String qrCodeType) {
        QueryWrapper<PeasantHousehold> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("amos_user_id", nhUserId);
        Map<String, Object> result = new HashMap<>();
        List<PeasantHousehold> peasantHouseholds = this.getBaseMapper().selectList(queryWrapper);
        result.put("nh", peasantHouseholds);
        result.put("jxs", buildDefaultPeasantHouseholdDto(jxsUserId, qrCodeType, null));
        return result;
    }

    public List<PeasantHousehold> getPeasantHouseByUserId(String nhUserId) {
        QueryWrapper<PeasantHousehold> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("amos_user_id", nhUserId);
        return this.getBaseMapper().selectList(queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    public PeasantHouseholdDto addNewPeasantHousehold(PeasantHouseholdDto model) {
        model.setPeasantHouseholdNo(this.getPeasantHouseholdNo(model.getRegionalCompaniesSeq()));
        model.setIsCertified(1);// 这里就实名认证
        model.setSurveyOrNot(0);
        model.setReview(0);
        JSONArray regionName = getRegionName();
        List<RegionModel> list = JSONArray.parseArray(regionName.toJSONString(), RegionModel.class);
        // 处理项目地址
        String area = "";
        if (model.getProjectAddress() != null && model.getProjectAddress().size() != 0) {
            for (Integer reg : model.getProjectAddress())
                for (RegionModel re : list) {
                    if (re.getRegionCode().equals(Integer.valueOf(reg))) {
                        area = area + re.getRegionName() + "/";
                    }
                }
            model.setProjectAddressName(area.length() > 2 ? area.substring(0, area.length() - 1) : area);
            if ("1".equals(model.getIsPermanent()) || "true".equals(model.getIsPermanent())) {
                model.setPermanentAddress(model.getProjectAddress());
                model.setPermanentAddressDetail(model.getProjectAddressDetail());
                model.setPermanentAddressName(area.length() > 2 ? area.substring(0, area.length() - 1) : area);
            } else {
                // 处理常住地址
                String permanent = "";
                if (model.getPermanentAddress() != null && model.getPermanentAddress().size() != 0) {
                    for (Integer reg : model.getPermanentAddress())
                        for (RegionModel re : list) {
                            if (re.getRegionCode().equals(Integer.valueOf(reg))) {
                                permanent = permanent + re.getRegionName() + "/";
                            }
                        }
                    model.setPermanentAddressName(permanent.length() > 2 ? permanent.substring(0, permanent.length() - 1) : permanent);
                }
            }
        }

        SurveyInformationDto surveyInformationDto = new SurveyInformationDto();
        surveyInformationDto.setSurveyNumber(this.getkcNo(model.getRegionalCompaniesSeq()));
        surveyInformationServiceImpl.createWithModel(surveyInformationDto);

        model.setSurveyInformationId(surveyInformationDto.getSequenceNbr());
        model.setSurveyOrNot(0);
        model.setReview(0);
        model.setPeasantHouseholdNo(this.getPeasantHouseholdNo(model.getRegionalCompaniesSeq()));
        model.setIsCertified(model.getIsCertified() == null ? 0 : model.getIsCertified());// 未认证

        PeasantHousehold peasantHousehold = new PeasantHousehold();
        BeanUtils.copyProperties(model, peasantHousehold);
        peasantHousehold.setSequenceNbr(null);
        peasantHousehold.setCreationTime(new Date());
        peasantHousehold.setConstructionState(ArrivalStateeEnum.待勘察.getCode());
        this.save(peasantHousehold);
        //生成合同
        HouseholdContract householdContract = new HouseholdContract();
        householdContract.setPartyA(peasantHousehold.getOwnersName());
        householdContract.setPeasantHouseholdNumber(peasantHousehold.getPeasantHouseholdNo());
        householdContract.setPeasantHouseholdCard(peasantHousehold.getIdCard());
        householdContract.setDealerId(peasantHousehold.getDeveloperId());
        householdContract.setDealerCode(peasantHousehold.getDeveloperCode());
        householdContract.setDealerName(peasantHousehold.getDeveloperName());
        householdContract.setPeasantHouseholdId(peasantHousehold.getSequenceNbr());
        householdContract.setRegionalCompaniesCode(peasantHousehold.getRegionalCompaniesCode());
        householdContract.setRegionalCompaniesName(peasantHousehold.getRegionalCompaniesName());
        householdContract.setRegionalCompaniesSeq(peasantHousehold.getRegionalCompaniesSeq());
        householdContract.setPeasantHouseholdPhone(peasantHousehold.getTelephone());
        householdContract.setProjectAddressDetail(peasantHousehold.getProjectAddressDetail());
        householdContract.setProjectAddressName(peasantHousehold.getProjectAddressName());
        householdContract.setPermanentAddressDetail(peasantHousehold.getPermanentAddressDetail());
        householdContract.setPermanentAddressName(peasantHousehold.getPermanentAddressName());
        householdContract.setProjectUserId(peasantHousehold.getAmosUserId());
        householdContractServiceImpl.addHouseholdContract(householdContract);

        //生成待办任务
        List<String> todoUserIds = new ArrayList<>();
        todoUserIds.add(peasantHousehold.getDeveloperUserId());
        RouthPathVO routhPathVO = new RouthPathVO();
        routhPathVO.setRouthPathId(String.valueOf(peasantHousehold.getSequenceNbr()));
        String routhPath = toDoTasksServiceImpl.getRouthPath(TaskTypeStationEnum.勘察.getCode(), HygfRouthTypeEnum.HYGF_DZKC.getCode(), routhPathVO);
        String wxRouthPath = toDoTasksServiceImpl.getWxRouthPath(TaskTypeStationEnum.勘察.getCode(), HygfRouthTypeEnum.HYGF_DZKC.getCode(), routhPathVO);
        ToDoTasks toDoTasks=  new ToDoTasks (TaskTypeStationEnum.勘察.getCode(),  peasantHousehold.getSequenceNbr(),   householdContract.getPartyA()+"待勘察",householdContract.getDealerCode(),routhPath,wxRouthPath);
        toDoTasksServiceImpl.addToDoTasksByUserIds(todoUserIds,toDoTasks);

        RouthPathVO routhPathVO1 = new RouthPathVO();
        routhPathVO1.setRouthPathId(String.valueOf(householdContract.getSequenceNbr()));
        String routhPath1 = toDoTasksServiceImpl.getRouthPath(TaskTypeStationEnum.合同.getCode(), HygfRouthTypeEnum.HYGF_HTFQ.getCode(), routhPathVO1);
        String wxRouthPath1 = toDoTasksServiceImpl.getWxRouthPath(TaskTypeStationEnum.合同.getCode(), HygfRouthTypeEnum.HYGF_HTFQ.getCode(), routhPathVO1);
        ToDoTasks toDoTasks1=  new ToDoTasks (TaskTypeStationEnum.合同.getCode(),  householdContract.getSequenceNbr(),  householdContract.getPartyA()+"待合同发起",householdContract.getDealerCode(),routhPath1,wxRouthPath1);
        toDoTasksServiceImpl.addToDoTasksByUserIds(todoUserIds,toDoTasks1);

        return model;
    }

    public IPage<PeasantHousehold> getPeasantHousePage(PeasantHouseholdPageDto peasantHouseholdPageDto) {
        QueryWrapper<PeasantHousehold> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("amos_user_id", peasantHouseholdPageDto.getNhUserId());
        queryWrapper.like(StrUtil.isNotEmpty(peasantHouseholdPageDto.getPeasantHouseholdNo()),"peasant_household_no", "%"+peasantHouseholdPageDto.getPeasantHouseholdNo()+"%");
        queryWrapper.like(StrUtil.isNotEmpty(peasantHouseholdPageDto.getRegionalCompaniesName()),"regional_companies_name", "%"+peasantHouseholdPageDto.getRegionalCompaniesName()+"%");
        queryWrapper.like(StrUtil.isNotEmpty(peasantHouseholdPageDto.getDeveloperName()),"developer_name", "%"+peasantHouseholdPageDto.getDeveloperName()+"%");
        queryWrapper.isNull("is_history");
        queryWrapper.orderByDesc("rec_date");
        IPage<PeasantHousehold> peasantHouseholdIPage = this.baseMapper.selectPage(new Page<>(peasantHouseholdPageDto.getCurrent(), peasantHouseholdPageDto.getSize()), queryWrapper);


        if(peasantHouseholdIPage.getRecords() != null && peasantHouseholdIPage.getRecords().size() > 0) {
            peasantHouseholdIPage.getRecords().forEach(e -> {
                if(e.getPeasantHouseholdNo() != null) {
                    e.setScale(householdContractMapper.getHygfCommercialScale(e.getPeasantHouseholdNo()));
                    e.setRealScale(powerStationEngineeringInfoMapper.getRealScaleByPeasantHouseholdNo(e.getPeasantHouseholdNo()));
                }
            });

        }

        return peasantHouseholdIPage;
    }

    public IPage<PeasantHousehold> getPeasantHouseHistoryPage(PeasantHouseholdPageDto peasantHouseholdPageDto) {
        QueryWrapper<PeasantHousehold> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("amos_user_id", peasantHouseholdPageDto.getNhUserId());
        queryWrapper.like(StrUtil.isNotEmpty(peasantHouseholdPageDto.getPeasantHouseholdNo()),"peasant_household_no", "%"+peasantHouseholdPageDto.getPeasantHouseholdNo()+"%");
        queryWrapper.like(StrUtil.isNotEmpty(peasantHouseholdPageDto.getRegionalCompaniesName()),"regional_companies_name", "%"+peasantHouseholdPageDto.getRegionalCompaniesName()+"%");
        queryWrapper.like(StrUtil.isNotEmpty(peasantHouseholdPageDto.getDeveloperName()),"developer_name", "%"+peasantHouseholdPageDto.getDeveloperName()+"%");
        queryWrapper.eq("is_history","1");
        queryWrapper.orderByDesc("rec_date");
        IPage<PeasantHousehold> peasantHouseholdIPage = this.baseMapper.selectPage(new Page<>(peasantHouseholdPageDto.getCurrent(), peasantHouseholdPageDto.getSize()), queryWrapper);


        if(peasantHouseholdIPage.getRecords() != null && peasantHouseholdIPage.getRecords().size() > 0) {
            peasantHouseholdIPage.getRecords().forEach(e -> {
                if(e.getPeasantHouseholdNo() != null) {
                    e.setScale(householdContractMapper.getHygfCommercialScale(e.getPeasantHouseholdNo()));
                    e.setRealScale(powerStationEngineeringInfoMapper.getRealScaleByPeasantHouseholdNo(e.getPeasantHouseholdNo()));
                }
            });

        }

        return peasantHouseholdIPage;
    }

    public JSONArray getRegionName(){
        JSONArray jsonArray = new JSONArray();
        if (redisUtils.hasKey(regionRedis)) {
            jsonArray= JSONArray.parseArray(redisUtils.get(regionRedis).toString());
        }else {
            Collection<RegionModel> regionChild = new ArrayList<>();
            RegionModel regionModel1 = new RegionModel();
            regionChild.add(regionModel1);
            FeignClientResult<Collection<RegionModel>> collectionFeignClientResult = Systemctl.regionClient.queryForTreeParent(610000L);
            Collection<RegionModel> result = collectionFeignClientResult.getResult();
            for (RegionModel regionModel : result) {
                if(null != regionModel && null != regionModel.getChildren()) {
                    for (RegionModel child : regionModel.getChildren()) {
                        if(null != child && null != child.getChildren()) {
                            for (RegionModel childChild : child.getChildren()) {
                                jsonArray.add(childChild);
                            }
                            child.setChildren(regionChild);
                            jsonArray.add(child);
                        }
                    }
                    regionModel.setChildren(regionChild);
                    jsonArray.add(regionModel);
                }
            }

            redisUtils.set(regionRedis,jsonArray);
        }
        return jsonArray;
    }


    public void updateAddress(PeasantHouseholdDto model, Long sequenceNbr) {
        JSONArray regionName = getRegionName();
        List<RegionModel> list = JSONArray.parseArray(regionName.toJSONString(), RegionModel.class);
        if(model.getProjectAddress().size()>0){
            // 处理项目地址
            String projectAddressName = "";
            for (Integer reg : model.getProjectAddress())
                for (RegionModel re : list) {
                    if (re.getRegionCode().equals(Integer.valueOf(reg))) {
                        projectAddressName = projectAddressName + re.getRegionName() + "/";
                    }
                }
            model.setProjectAddressName(projectAddressName.substring(0, projectAddressName.length() - 1));
        }
        if ("1".equals(model.getIsPermanent())) {
            model.setPermanentAddress(model.getProjectAddress());
            model.setPermanentAddressDetail(model.getProjectAddressDetail());
        }
        if(model.getPermanentAddress().size()>0){
            // 处理常驻地址
            String permanentAddressName = "";
            for (Integer reg : model.getPermanentAddress())
                for (RegionModel re : list) {
                    if (re.getRegionCode().equals(Integer.valueOf(reg))) {
                        permanentAddressName = permanentAddressName + re.getRegionName() + "/";
                    }
                }
            model.setPermanentAddressName(permanentAddressName.substring(0, permanentAddressName.length() - 1));
        }
        LambdaUpdateWrapper<PeasantHousehold> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(BaseEntity::getSequenceNbr, sequenceNbr);
        updateWrapper.set(PeasantHousehold::getPermanentAddress, model.getPermanentAddress());
        updateWrapper.set(PeasantHousehold::getPermanentAddressName, model.getPermanentAddressName());
        updateWrapper.set(PeasantHousehold::getPermanentAddressDetail, model.getPermanentAddressDetail());

        updateWrapper.set(PeasantHousehold::getProjectAddress, model.getProjectAddress());
        updateWrapper.set(PeasantHousehold::getProjectAddressDetail, model.getProjectAddressDetail());
        updateWrapper.set(PeasantHousehold::getProjectAddressName, model.getProjectAddressName());
        this.update(updateWrapper);

        LambdaUpdateWrapper<PowerStation> up = new LambdaUpdateWrapper<>();
        up.eq(PowerStation::getPeasantHouseholdId, sequenceNbr);
        up.set(PowerStation::getProjectAddress, model.getProjectAddressName());
        powerStationService.update(up);
    }

//    public void saveHistoryPeasantHousehold(PowerStationEngineeringInfoAllDto surveyInfoAllDto,String operationType) {
//
//        SurveyInformationDto model = surveyInfoAllDto.getSurveyInformation();
//        if (null == model.getDeveloperId()|| null == model.getRegionalCompaniesSeq()){
//            throw new BadRequest("区域公司及经销商不可为空");
//        }
//        if (null == model.getTelephone()){
//            throw new BadRequest("联系电话不可为空");
//        }
//        if (null == model.getOwnersName()){
//            throw new BadRequest("业主姓名不可为空");
//        }
//        if (null == model.getIdCard()){
//            throw new BadRequest("身份证号码不可为空");
//        }
//        if (null == model.getIdCardFront()|| null == model.getIdCardOpposite()){
//            throw new BadRequest("身份证图片不可为空");
//        }
//        if (null == model.getPermanentAddress()){
//            throw new BadRequest("常住地址不可为空");
//        }
//        if ( null == model.getPermanentAddressDetail()){
//            throw new BadRequest("常住详细地址不可为空");
//        }
//        if (null == model.getProjectAddress()){
//            throw new BadRequest("项目地址不可为空");
//        }
//        if (null == model.getProjectAddressDetail()){
//            throw new BadRequest("项目详细地址不可为空");
//        }
//
//
//            List<String> ids = new ArrayList<>();
//        ids.add(String.valueOf(model.getDeveloperId()));
//        ids.add(String.valueOf(model.getRegionalCompaniesSeq()));
////        MobileLoginParamDto mobileLoginParamDto = new MobileLoginParamDto();
////        mobileLoginParamDto.setPhoneNo(model.getTelephone());
////        // 机器人token
////        RequestContext.setAppKey("AMOS_STUDIO");
////        RequestContext.setProduct("AMOS_STUDIO_WEB");
////        RequestContext.setToken(requestContext.getToken());
////        AgencyUserModel registerUserModel = null;
////        // region 判断有无在平台内部注册过用户 没有注册则去平台注册
////        FeignClientResult<LoginInfoModel> loginInfo = Privilege.agencyUserClient.getLoginInfo(mobileLoginParamDto.getPhoneNo());
////
////        if (loginInfo != null && 200 == loginInfo.getStatus()) {
////            LoginInfoModel loginInfoModel = loginInfo.getResult();
////            if (loginInfoModel == null || !StringUtils.isNotBlank(loginInfoModel.getLoginId())) {
////                FeignClientResult<AgencyUserModel> registerUserModelRestult = doRegister(mobileLoginParamDto);
////                if (registerUserModelRestult == null || registerUserModelRestult.getStatus() != 200) {
////                    log.error("用户手机号码 => " + mobileLoginParamDto.getPhoneNo() + " 调用平台创建用户信息失败: " + registerUserModelRestult.getDevMessage());
////                    throw new RuntimeException(registerUserModelRestult.getMessage());
////                }
////                registerUserModel = registerUserModelRestult.getResult();
////            }
////        }
//
//
//
//
//
//        // 更新勘察基本信息
//
//
//        //新增农户电站信息
//        SurveyInformation surveyInformation = BeanDtoUtils.convert(model,
//                SurveyInformation.class);
//        surveyInformation.setSurveyNumber(Optional.ofNullable(surveyInformation).map(SurveyInformation::getSurveyNumber).orElse(this.getkcNo(model.getRegionalCompaniesSeq())));
//        PeasantHousehold peasantHousehold = new PeasantHousehold();
//        if (model.getSequenceNbr() != null ){
//            peasantHousehold.setSequenceNbr(model.getPeasantHouseholdId());
//        }
//        if (model.getPeasantHouseholdNo() == null ){
//            peasantHousehold.setPeasantHouseholdNo(this.getPeasantHouseholdNo(model.getRegionalCompaniesSeq()));
//        }
//        surveyInformationServiceImpl.saveOrUpdate(surveyInformation);
//
//
//
//        peasantHousehold.setIsCertified(1);
//        peasantHousehold.setIsHistory("1");
//        peasantHousehold.setReview(2);
//        peasantHousehold.setSurveyInformationId(surveyInformation.getSequenceNbr());
//        if (operationType.equals("apply")){
//            peasantHousehold.setConstructionState("验收完成");
//            peasantHousehold.setPreparationMoneyState("建档完成");
//            if (peasantHousehold.getSequenceNbr() != null ){
//                //完成后需对投融数据进行处理。
//                LambdaUpdateWrapper<FinancingInfo> wrapper = new LambdaUpdateWrapper<>();
//                wrapper.eq(FinancingInfo::getPeasantHouseholdId,peasantHousehold.getSequenceNbr());
//                wrapper.set(FinancingInfo::getStatus,"待推送");
//                financingInfoService.update(null,wrapper);
//
//                LambdaQueryWrapper<FinancingAuditing> finQuery = new LambdaQueryWrapper<>();
//                finQuery.eq(FinancingAuditing::getPeasantHouseholdId,peasantHousehold.getSequenceNbr());
//                finQuery.orderByDesc(BaseEntity::getRecDate);
//                finQuery.last("limit 1");
//                FinancingAuditing financingAuditing = financingAuditingService.getBaseMapper().selectOne(finQuery);
//                if (!Objects.isNull(financingAuditing)){
//                    financingInfoService.execueFlow(MapBuilder.<String,Object>create().put("instanceId",financingAuditing.getInstanceId()).put("approvalStatus","0").put("isZG","1").build());
//                }
//            }
//
//        }else {
//            if (null !=peasantHousehold.getSequenceNbr() ){
//                PeasantHousehold peasantHousehold1 = this.getBaseMapper().selectById(peasantHousehold.getSequenceNbr());
//                if (peasantHousehold1.getPreparationMoneyState().equals("待提交")){
//                }else {
//                    peasantHousehold.setPreparationMoneyState("暂存中");
//                }
//            }else {
//                peasantHousehold.setPreparationMoneyState("暂存中");
//            }
//        }
//
//    //    peasantHousehold.setAmosUserId(registerUserModel.getUserId());
//        peasantHousehold.setTelephone(model.getTelephone());
//        peasantHousehold.setCreationTime(new Date());
//
//        List<Map<String, Object>> maps = financingInfoService.getBaseMapper().selectCompany(ids);
//        UnitInfo unitInfo = unitInfoService.getBaseMapper().selectById(model.getDeveloperId());
//        if (unitInfo != null){
//                peasantHousehold.setDeveloperCode(unitInfo.getAmosCompanyCode());// 开发方code
//                peasantHousehold.setDeveloperId(unitInfo.getAmosCompanySeq());// 开发方id
//                peasantHousehold.setDeveloperName(unitInfo.getName());// 开发方名称
//                //           peasantHousehold.setDeveloper();// 开发人
//                //           peasantHousehold.setDeveloperUserId();
//        }
//        maps.stream().forEach(e->{
//
//            if (String.valueOf(e.get("SEQUENCE_NBR")) .equals(String.valueOf(model.getRegionalCompaniesSeq()))){
//                peasantHousehold.setRegionalCompaniesCode(e.get("ORG_CODE").toString());// 开发方code
//                peasantHousehold.setRegionalCompaniesSeq(model.getRegionalCompaniesSeq());// 开发方id
//                peasantHousehold.setRegionalCompaniesName(e.get("COMPANY_NAME").toString());// 开发方名称
//            }
//
//        });
//
////        PeasantHouseholdDto peasantHouseholdDto = buildDefaultPeasantHouseholdDto(wxDTO.getAmosUserId(), wxDTO.getQrCodeType(), wxDTO.getPhoneNo());
////
////        peasantHousehold.setRegionalCompaniesSeq(Optional.ofNullable(peasantHouseholdDto).map(PeasantHouseholdDto::getRegionalCompaniesSeq).orElse(null));
////        peasantHousehold.setRegionalCompaniesCode(Optional.ofNullable(peasantHouseholdDto).map(PeasantHouseholdDto::getRegionalCompaniesCode).orElse(null));
////        peasantHousehold.setRegionalCompaniesName(Optional.ofNullable(peasantHouseholdDto).map(PeasantHouseholdDto::getRegionalCompaniesName).orElse(null));
////        peasantHousehold.setIsCertified(1);// 这里就实名认证
//        peasantHousehold.setSurveyOrNot(3);
//        peasantHousehold.setReview(2);
//        JSONArray regionName = commonService.getRegionName();
//        List<RegionModel> list = JSONArray.parseArray(regionName.toJSONString(), RegionModel.class);
////        // 处理项目地址
////        String area = "";
////        if (model.getProjectAddress() != null && model.getProjectAddress().size() != 0) {
////            for (Integer reg : model.getProjectAddress())
////                for (RegionModel re : list) {
////                    if (re.getRegionCode().equals(Integer.valueOf(reg))) {
////                        area = area + re.getRegionName() + "/";
////                    }
////                }
////            model.setProjectAddressName(area.length() > 2 ? area.substring(0, area.length() - 1) : area);
////            if ("1".equals(model.getIsPermanent()) || "true".equals(model.getIsPermanent())) {
////                peasantHousehold.setPermanentAddress(model.getProjectAddress());
////                peasantHousehold.setPermanentAddressDetail(model.getProjectAddressDetail());
////                peasantHousehold.setPermanentAddressName(area.length() > 2 ? area.substring(0, area.length() - 1) : area);
////            } else {
////                // 处理常住地址
////                String permanent = "";
////                if (model.getPermanentAddress() != null && model.getPermanentAddress().size() != 0) {
////                    for (Integer reg : model.getPermanentAddress())
////                        for (RegionModel re : list) {
////                            if (re.getRegionCode().equals(Integer.valueOf(reg))) {
////                                permanent = permanent + re.getRegionName() + "/";
////                            }
////                        }
////                    peasantHousehold.setPermanentAddressName(permanent.length() > 2 ? permanent.substring(0, permanent.length() - 1) : permanent);
////                }
////            }
////        }
//
//
//
//
//
//        surveyInformation.setReview(0);
//            surveyInformation.setCreatorTime(new Date());
//        surveyInformationServiceImpl.saveOrUpdate(surveyInformation);
//
//        // 更新扩展信息
//        ExtendedInformation extendedInformation = BeanDtoUtils.convert(surveyInfoAllDto.getExtendedInformation(),
//                ExtendedInformation.class);
//        extendedInformation.setSurveyInformationId(surveyInformation.getSequenceNbr());
//        // 避免生成多份数据
//        extendedInformationService.saveOrUpdate(extendedInformation, new LambdaQueryWrapper<ExtendedInformation>()
//                .eq(ExtendedInformation::getSurveyInformationId, surveyInformation.getSequenceNbr()));
//        // extendedInformationService.saveOrUpdate(extendedInformation);
//
//        // 更新勘察明细信息
//        SurveyDetailsDto oldSurveyDetails = surveyInfoAllDto.getSurveyDetails();
//        SurveyDetails surveyDetails = BeanDtoUtils.convert(oldSurveyDetails, SurveyDetails.class);
//        surveyDetails.setSurveyInformationId(surveyInformation.getSequenceNbr());
//        // 避免生成多份数据
//        surveyDetailsService.saveOrUpdate(surveyDetails, new LambdaQueryWrapper<SurveyDetails>()
//                .eq(SurveyDetails::getSurveyInformationId, surveyInformation.getSequenceNbr()));
//        // surveyDetailsService.saveOrUpdate(surveyDetails);
//
//        // 更新商务信息
//        CommercialDto oldCommercial = surveyInfoAllDto.getCommercial();
//        Commercial commercial = BeanDtoUtils.convert(oldCommercial, Commercial.class);
//        // 处理省市县
//        String paddressName = "";
//        if (null != surveyInfoAllDto.getSurveyInformation().getProjectAddress()){
//            for (Integer reg : surveyInfoAllDto.getSurveyInformation().getProjectAddress()) {
//                for (RegionModel re : list) {
//                    if (re.getRegionCode().equals(Integer.valueOf(reg))) {
//                        paddressName = paddressName + re.getRegionName() + "/";
//                    }
//                }
//            }
//            commercial.setProjectAddressName(paddressName.substring(0, paddressName.length() - 1));
//        }
//
//        commercial.setSurveyInformationId(surveyInformation.getSequenceNbr());
//        // 避免生成多份数据
//        commercialService.saveOrUpdate(commercial, new LambdaQueryWrapper<Commercial>()
//                .eq(Commercial::getSurveyInformationId, surveyInformation.getSequenceNbr()));
//        // commercialService.saveOrUpdate(commercial);
//        // 勘察后，更新状态
//        // QueryWrapper<PeasantHousehold> peasantHouseholdQueryWrapper = new
//        // QueryWrapper<>();
//        // peasantHouseholdQueryWrapper.eq("survey_information_id",
//        // surveyInformation.getSequenceNbr());
//        // PeasantHousehold peasantHousehold =
//        // peasantHouseholdServiceImpl.getBaseMapper()
//        // .selectOne(peasantHouseholdQueryWrapper);
//
//        // 更新资料归档信息
//        Information information = BeanDtoUtils.convert(surveyInfoAllDto.getInformation(), Information.class);
//        information.setHouseProve(null == commercial ? null
//                : (CollectionUtil.isNotEmpty(commercial.getRealEstateLegal()) ? commercial.getRealEstateLegal()
//                : null));
//        information.setCardFile(null == commercial ? null
//                : (CollectionUtil.isNotEmpty(commercial.getIdCardCredit()) ? commercial.getIdCardCredit() : null));
//        information.setCardFile(commercial.getAgentLegal());
//        information
//                .setArchivesNumber(surveyInformationServiceImpl.getNo(CodeEnum.档案.getCode(), peasantHousehold.getRegionalCompaniesSeq()));
//        information.setFileNumber(surveyInformationServiceImpl.getNo(CodeEnum.文件.getCode(), peasantHousehold.getRegionalCompaniesSeq()));
//        information.setSurveyInformationId(surveyInformation.getSequenceNbr());
//
//        // 避免生成多份数据
//        informationService.saveOrUpdate(information, new LambdaQueryWrapper<Information>()
//                .eq(Information::getSurveyInformationId, surveyInformation.getSequenceNbr()));
//        // informationService.saveOrUpdate(information);
//
//        peasantHousehold.setOwnersName(surveyInfoAllDto.getSurveyInformation().getOwnersName());
//        peasantHousehold.setTelephone(surveyInfoAllDto.getSurveyInformation().getTelephone());
//        peasantHousehold.setIdCard(surveyInfoAllDto.getSurveyInformation().getIdCard());
//        peasantHousehold.setIdCardFront(model.getIdCardFront());
//        peasantHousehold.setIdCardOpposite(model.getIdCardOpposite());
//        peasantHousehold.setMailbox(surveyInfoAllDto.getSurveyInformation().getMailbox());
//        peasantHousehold.setProjectAddress(surveyInfoAllDto.getSurveyInformation().getProjectAddress());
//        peasantHousehold.setProjectAddressDetail(surveyInfoAllDto.getSurveyInformation().getProjectAddressDetail());
//        peasantHousehold.setPermanentAddress(surveyInfoAllDto.getSurveyInformation().getPermanentAddress());
//        peasantHousehold
//                .setPermanentAddressDetail(surveyInfoAllDto.getSurveyInformation().getPermanentAddressDetail());
//        peasantHousehold
//                .setPermanentAddressDetail(surveyInfoAllDto.getSurveyInformation().getPermanentAddressDetail());
//
//        // 处理项目地址
//        String projectAddressName = "";
//        if (null != surveyInfoAllDto.getSurveyInformation().getProjectAddress()){
//            for (Integer reg : surveyInfoAllDto.getSurveyInformation().getProjectAddress()) {
//                for (RegionModel re : list) {
//                    if (re.getRegionCode().equals(Integer.valueOf(reg))) {
//                        projectAddressName = projectAddressName + re.getRegionName() + "/";
//                    }
//                }
//            }
//            peasantHousehold.setProjectAddressName(projectAddressName.substring(0, projectAddressName.length() - 1));
//        }
//        if (null != surveyInfoAllDto.getSurveyInformation().getPermanentAddress()){
//            // 常住地址
//            String permanentAddressName = "";
//            for (Integer reg : surveyInfoAllDto.getSurveyInformation().getPermanentAddress()) {
//                for (RegionModel re : list) {
//                    if (re.getRegionCode().equals(Integer.valueOf(reg))) {
//                        permanentAddressName = permanentAddressName + re.getRegionName() + "/";
//                    }
//                }
//            }
//            peasantHousehold
//                    .setPermanentAddressName(permanentAddressName.substring(0, permanentAddressName.length() - 1));
//
//        }
//
//
//        this.saveOrUpdate(peasantHousehold);
//
//
//
//        //更新施工信息
//        PowerStationConstructionData powerStationConstructionData = surveyInfoAllDto.getPowerStationConstructionData();
//
//        powerStationConstructionData.setWorkOrderPowerStationId(peasantHousehold.getSequenceNbr());
//        // 避免生成多份数据
//        powerStationConstructionDataService.saveOrUpdate(powerStationConstructionData, new LambdaQueryWrapper<PowerStationConstructionData>()
//                .eq(PowerStationConstructionData::getWorkOrderPowerStationId, peasantHousehold.getSequenceNbr()));
//
//        //更新工程
//        PowerStationEngineeringInfo powerStationEngineeringInfo = surveyInfoAllDto.getPowerStationEngineeringInfo();
//        if(Objects.nonNull(powerStationEngineeringInfo)){
//            powerStationEngineeringInfo.setWorkOrderPowerStationId(peasantHousehold.getSequenceNbr());
//            powerStationEngineeringInfoService.saveOrUpdate(powerStationEngineeringInfo, new LambdaQueryWrapper<PowerStationEngineeringInfo>()
//                    .eq(PowerStationEngineeringInfo::getWorkOrderPowerStationId, peasantHousehold.getSequenceNbr()));
//            //更新施工组件信息
//            LambdaUpdateWrapper<PowerStationConstructionData> powerStationConstructionDataWrapper = new LambdaUpdateWrapper<>();
//            powerStationConstructionDataWrapper.set(PowerStationConstructionData::getConstructionComponentInfo, JSONArray.toJSONString(powerStationEngineeringInfo.getConstructionComponentInfo()));
//            powerStationConstructionDataWrapper.set(PowerStationConstructionData::getConstructionInverterInfo,JSONArray.toJSONString(powerStationEngineeringInfo.getConstructionInverterInfo()));
//            powerStationConstructionDataWrapper.set(PowerStationConstructionData::getConstructionCollectorBoxInfo,JSONArray.toJSONString(powerStationEngineeringInfo.getConstructionCollectorBoxInfo()));
//            powerStationConstructionDataWrapper.set(PowerStationConstructionData::getConstructionGridBoxInfo,JSONArray.toJSONString(powerStationEngineeringInfo.getConstructionGridBoxInfo()));
//            powerStationConstructionDataWrapper.eq(PowerStationConstructionData::getWorkOrderPowerStationId, peasantHousehold.getSequenceNbr());
//            powerStationConstructionDataWrapper.eq(PowerStationConstructionData::getSequenceNbr, powerStationConstructionData.getSequenceNbr());
//            powerStationConstructionDataService.update(null,powerStationConstructionDataWrapper);
//
//        }
//        //更新并网信息
//        HygfOnGrid hygfOnGrid = surveyInfoAllDto.getHygfOnGrid();
//            hygfOnGrid.setPeasantHouseholdId( peasantHousehold.getSequenceNbr());
//            // 避免生成多份数据
//            hygfOnGridService.saveOrUpdate(hygfOnGrid, new LambdaQueryWrapper<HygfOnGrid>()
//                    .eq(HygfOnGrid::getPeasantHouseholdId, peasantHousehold.getSequenceNbr()));
//            hygfOnGridService.saveOrUpdate(hygfOnGrid);
//        //更新设计信息
//        DesignInformationDto designInformationDto = surveyInfoAllDto.getDesignInformation();
//
//        DesignInformation    designInformation =  BeanDtoUtils.convert(designInformationDto,
//                    DesignInformation.class);
//            designInformation.setPeasantHouseholdId(String.valueOf(peasantHousehold.getSequenceNbr()));
//            designInformationService.saveOrUpdate(designInformation, new LambdaQueryWrapper<DesignInformation>()
//                    .eq(DesignInformation::getPeasantHouseholdId, peasantHousehold.getSequenceNbr()));
//
//
//    }
}