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

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
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.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.utils.RedisUtils;
import com.yeejoin.amos.boot.module.hygf.api.Enum.BusinessTypeEnum;
import com.yeejoin.amos.boot.module.hygf.api.Enum.DealerReviewEnum;
import com.yeejoin.amos.boot.module.hygf.api.Enum.FlowStatusEnum;
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.fegin.IdxFeginService;
import com.yeejoin.amos.boot.module.hygf.api.fegin.PrivilegeFeginService;
import com.yeejoin.amos.boot.module.hygf.api.mapper.*;
import com.yeejoin.amos.boot.module.hygf.api.service.IDealerReviewService;
import com.yeejoin.amos.boot.module.hygf.api.service.IUnitInfoService;
import com.yeejoin.amos.boot.module.standard.api.entity.PublicAgencyUser;
import com.yeejoin.amos.boot.module.standard.api.mapper.PublicAgencyUserMapper;
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.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.CompanyModel;
import com.yeejoin.amos.feign.privilege.model.RoleModel;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.RegionModel;
import com.yeejoin.amos.feign.systemctl.model.SmsRecordModel;
import com.yeejoin.amos.feign.workflow.model.ActWorkflowBatchDTO;
import com.yeejoin.amos.feign.workflow.model.ActWorkflowStartDTO;
import com.yeejoin.amos.feign.workflow.model.ProcessTaskDTO;
import com.yeejoin.amos.feign.workflow.model.TaskResultDTO;
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.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.exception.BaseException;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 经销商人员信息服务实现类
 *
 * @author system_generator
 * @date 2023-07-07
 */
@Service
public class UnitInfoServiceImpl extends BaseService<UnitInfoDto,UnitInfo,UnitInfoMapper> implements IUnitInfoService {

    String COMPANY_TREE_REDIS_KEY = "REGULATOR_UNIT_TREE";

    @Value("${regulator.unit.code}")
    private String code;

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

    @Autowired
    RedisUtils redisUtil;

    @Autowired
    PrivilegeFeginService privilegeFeginService;

    @Autowired
    CommerceInfoServiceImpl commerceInfoService;
    @Autowired
    RegionalCompaniesServiceImpl regionalCompaniesService;
    @Autowired
    UnitInfoMapper unitInfoMapper;
    @Autowired
    PeasantHouseholdMapper peasantHouseholdMapper;
    @Autowired
    PowerStationEngineeringInfoMapper powerStationEngineeringInfoMapper;
    @Autowired
    HouseholdContractMapper householdContractMapper;
    @Autowired
    CommerceInfoMapper commerceInfoMapper;
    @Autowired
    RegionalCompaniesMapper regionalCompaniesMapper;
    @Autowired
    PublicAgencyUserMapper publicAgencyUserMapper;
    @Autowired
    IDealerReviewService dealerReviewService;
    @Value("${hygf.user.group.id}")
    private long userGroupId;
    @Value("${regionalCompanies.company.seq}")
    private Long regionalCompanies;
    @Autowired
    IdxFeginService idxFeginService;
    private static final String regionRedis="app_region_redis";
    private static final String OPERATION_TYPE_SUBMIT="submit";
    private static final String OPERATION_TYPE_APPLY="apply";
    private static final String IDX_REQUEST_STATE="200";
    private static final String VERIFY_RESULT_YES="0";
    private static final String VERIFY_RESULT_NO="1";
    @Autowired
    DealerReviewMapper dealerReviewMapper;

    @Value("${power.station.examine.pageId}")
    private long pageId;
    @Autowired
    AmosRequestContext requestContext;
    @Value("${unitInfo.station.examine.planId}")
    private String planId;

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

    @Value("${hygf.sms.tempCodeJXS}")
    private String smsTempCode;


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

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

    @Autowired
    PersonnelBusinessMapper personnelBusinessMapper;

//    @Autowired
//    WorkflowImpl workflow;
    @Autowired
    WorkFlowService workFlowService;
    @Autowired
    AmosRequestContext amosRequestContext;

    @Autowired
    UserEmpowerMapper userEmpowerMapper;

    private  static final  String SMSTEMPCODENO="SMS_HYGF_0003";

    private  static final  String SMSTEMPCODEYES="SMS_HYGF_0004";
    /**
     * 分页查询
     */
    public Page<UnitInfoDto> queryForUnitInfoPage(Page<UnitInfoDto> page)   {
        return this.queryForPage(page, null, false);
    }

    /**
     * 列表查询 示例
     */
    public List<UnitInfoDto> queryForUnitInfoList()   {
        return this.queryForList("" , false);
    }

    @Override
    public Collection getManagementUnitTree(String orgCode) {
        List<LinkedHashMap> companyModels = (List<LinkedHashMap>) redisUtil.get(COMPANY_TREE_REDIS_KEY);
        if (ValidationUtil.isEmpty(companyModels)) {
            companyModels = creatTree();
        }
        if (!ValidationUtil.isEmpty(orgCode)) {
            companyModels = findNodesByCondition(companyModels, "orgCode", orgCode, "children");
            companyModels = (List<LinkedHashMap>) companyModels.get(0).get("children");
        }
        return companyModels;
    }

    @Override
    public UnitRegisterDto registerUnit(UnitRegisterDto model) {

        UnitInfoDto regUnitInfo = model.getUnitInfoDto();
        regUnitInfo.setRoleId(roleId);
        regUnitInfo.setManagementUnitId(managementUnitId);
        regUnitInfo.setManagementUnit("经销商");
        try {
            // 1. 调用平台进行创建单位、用户信息
          //  this.createCompanyAndUser(regUnitInfo);
            // 2.插入单位表
          //  regUnitInfo = this.createWithModel(regUnitInfo);
            regUnitInfo = this.createWithModelnew(regUnitInfo);
            CommerceInfoDto commerceInfo = model.getCommerceInfoDto();
            commerceInfo.setUnitSeq(regUnitInfo.getSequenceNbr());
            commerceInfo = commerceInfoService.createWithModel(commerceInfo);

            List<RegionalCompanies> regionalCompanies= regUnitInfo.getRegionalCompanies();
            for (RegionalCompanies regionalCompany : regionalCompanies) {
                regionalCompany.setUnitId(regUnitInfo.getAmosCompanySeq());
                regionalCompany.setUnitInfoId(regUnitInfo.getSequenceNbr());
            }
            regionalCompaniesService.saveBatch(regionalCompanies);

            //新增人员基础信息表


//            PublicAgencyUser publicAgencyUser=new PublicAgencyUser();
//            publicAgencyUser.setAmosUserId(regUnitInfo.getAdminUserId());
//            publicAgencyUser.setAmosUserName(regUnitInfo.getAdminLoginName());
//            publicAgencyUser.setRealName(regUnitInfo.getAdminLoginName());
//            publicAgencyUser.setRole("["+regUnitInfo.getRoleId()+"]");
//            publicAgencyUser.setEmergencyTelephone(regUnitInfo.getAdminPhone());
//            publicAgencyUser.setLockStatus("LOCK");
//            publicAgencyUserMapper.insert(publicAgencyUser);
//
//            PersonnelBusiness re=new PersonnelBusiness();
//            re.setAmosDealerId(regUnitInfo.getAmosCompanySeq());
//            re.setAmosUnitId(regUnitInfo.getAmosCompanySeq());
//            re.setAmosUnitName(regUnitInfo.getName());
//            re.setAmosUnitOrgCode(regUnitInfo.getAmosCompanyCode());
//            re.setFoundationId(publicAgencyUser.getSequenceNbr());
//            re.setUserType("2");
//            personnelBusinessMapper.insert(re);
            model.setCommerceInfoDto(commerceInfo);
            model.setUnitInfoDto(regUnitInfo);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            // 失败后回滚：删除已经创建的企业信息
//            if (!ObjectUtils.isEmpty(regUnitInfo.getAmosCompanySeq())) {
//                FeignClientResult<CompanyModel> feignClientResult = Privilege.companyClient
//                        .seleteOne(regUnitInfo.getAmosCompanySeq());
//                if (feignClientResult != null) {
//                    Privilege.companyClient.deleteCompany(regUnitInfo.getAmosCompanySeq().toString());
//                }
//            }
//            // 失败后回滚：删除已经创建的管理员账号
//            if (StringUtils.isNotEmpty(regUnitInfo.getAdminUserId())) {
//                FeignClientResult<AgencyUserModel> feignClientResult = Privilege.agencyUserClient
//                        .queryByUserId(regUnitInfo.getAdminUserId());
//                if (feignClientResult != null) {
//                    Privilege.agencyUserClient.multDeleteUser(regUnitInfo.getAdminUserId());
//                }
//            }
            throw new BadRequest(e.getMessage());
        }
        return model;
    }

    private static List<LinkedHashMap> findNodesByCondition(List<LinkedHashMap> nodes, String conditionName,
                                                           String condition, String childName) {
        return nodes.stream()
                .flatMap(node -> Stream.concat(
                        node.get(conditionName).equals(condition) ? Stream.of(node) : Stream.empty(),
                        node.get(childName) != null ? findNodesByCondition((List<LinkedHashMap>) node.get(childName),
                                conditionName, condition, condition).stream() :
                                Stream.empty()
                ))
                .collect(Collectors.toList());
    }

    private List<LinkedHashMap> creatTree() {
        FeignClientResult tree = privilegeFeginService.tree(RequestContext.getToken(),RequestContext.getAppKey(),RequestContext.getProduct());
        List<LinkedHashMap> result = (List<LinkedHashMap>) tree.getResult();
        List<LinkedHashMap> treeData = deleteRegulatorTreeData(result);
        List<LinkedHashMap> supervisionTree = treeData.stream().filter(e -> code.equals(e.get("orgCode"))).collect(Collectors.toList());
        List<LinkedHashMap> resultTree = updateNullChildren(supervisionTree);
        redisUtil.set(COMPANY_TREE_REDIS_KEY, resultTree);
        return resultTree;
    }

    /**
     * 将管辖机构树中children为[]的修改为null
     *
     * @param result
     * @return
     */
    private List<LinkedHashMap> updateNullChildren(List<LinkedHashMap> result) {
        Iterator it = result.iterator();
        while (it.hasNext()) {
            LinkedHashMap e = (LinkedHashMap) it.next();
            //将管辖机构树中children为[]的修改为null
            if (e.get("children") != null) {
                if (((List<LinkedHashMap>) e.get("children")).size() == 0) {
                    e.put("children", null);
                }
            }
            if (!ObjectUtils.isEmpty(e.get("children"))) {
                updateNullChildren((List<LinkedHashMap>) e.get("children"));
            }
        }
        return result;
    }

    /**
     * 删除管辖机构树中level为使用单位的数据
     * @param result 管辖机构树
     * @return 筛选过滤后不包含使用单位的管辖机构树
     */
    private List<LinkedHashMap> deleteRegulatorTreeData(List<LinkedHashMap> result) {
        Iterator it = result.iterator();
        while (it.hasNext()) {
            LinkedHashMap e = (LinkedHashMap) it.next();
            //删除使用单位
            if ("company".equals(e.get("level"))) {
                it.remove();
            }
            if (e.get("companyName").toString().contains("行政审批局")) {
                it.remove();
            }
            if (!ObjectUtils.isEmpty(e.get("children"))) {
                deleteRegulatorTreeData((List<LinkedHashMap>) e.get("children"));
            }
        }
        return result;
    }


    private void createCompanyAndUsernew(UnitInfo regUnitInfo) {
        CompanyModel companyInfo = new CompanyModel();
        FeignClientResult<AgencyUserModel> userResult = null;
        try {
            //FeignClientResult<List<RoleModel>> roleListResult = Privilege.roleClient.queryRoleList(null, null);
            //  List<RoleModel> allRoleList = roleListResult.getResult();
            List<RoleModel> userRoleList = new ArrayList<>();
            List<Long> roleIds = new ArrayList<>();
            // 1创建公司
            companyInfo.setAddress(regUnitInfo.getRegisterPcd());
            companyInfo.setAgencyCode("JXIOP");
            companyInfo.setParentId(Long.parseLong(regUnitInfo.getManagementUnitId()));
            companyInfo.setLevel("station");
            companyInfo.setCompanyName(regUnitInfo.getName());
            //  companyInfo.setCompanyCode(regUnitInfo.getUnitType());
            companyInfo.setContact(regUnitInfo.getHeadName());
            companyInfo.setCompanyType(regUnitInfo.getUnitType());
            companyInfo.setLandlinePhone(regUnitInfo.getHeadPhone());
            FeignClientResult<CompanyModel> companyResult = Privilege.companyClient.create(companyInfo);

            if (companyResult == null || companyResult.getStatus()!=200) {
                throw new BadRequest("单位注册失败！"+companyResult.getDevMessage());
            }

            String adminUserName = regUnitInfo.getAdminUserName();
            String loginName = regUnitInfo.getAdminLoginName();
            String pwd = regUnitInfo.getAdminLoginPwd();
            String adminTel = regUnitInfo.getAdminPhone();
            // 2 创建平台用户
            companyInfo = companyResult.getResult();
            AgencyUserModel agencyUserModel = new AgencyUserModel();
            agencyUserModel.setUserName(loginName);
            agencyUserModel.setRealName(adminUserName);
            agencyUserModel.setLockStatus("UNLOCK");
            agencyUserModel.setPassword(pwd);
            agencyUserModel.setRePassword(pwd);
            agencyUserModel.setAgencyCode("JXIOP");
            agencyUserModel.setMobile(adminTel);
            List<String> split = Arrays.asList(StringUtils.split(appCodes, ','));
            Map<Long, List<Long>> roleSeqMap = new HashMap<>();
            Map<Long, List<RoleModel>> orgRoles = new HashMap<>();
//            userRoleList = allRoleList.stream().filter(r -> r.getSequenceNbr().toString().equals(regUnitInfo.getRoleId()))
//                    .collect(Collectors.toList());
//            userRoleList.forEach(r -> {
//                if (!roleIds.contains(r.getSequenceNbr())) {
//                    roleIds.add(r.getSequenceNbr());
//                }
//            });
            // roleIds.add(Long.valueOf(regUnitInfo.getRoleId()));

            roleIds.add(userGroupId);
            roleSeqMap.put(companyInfo.getSequenceNbr(), roleIds);
            orgRoles.put(companyInfo.getSequenceNbr(), userRoleList);
            agencyUserModel.setOrgRoles(orgRoles);
            agencyUserModel.setOrgRoleSeqs(roleSeqMap);
            userResult = Privilege.agencyUserClient.create(agencyUserModel);

            if (userResult == null || userResult.getStatus()!=200) {
                throw new BadRequest("单位注册失败！"+userResult.getDevMessage());
            }
            regUnitInfo.setAdminUserId(userResult.getResult().getUserId());
            regUnitInfo.setAmosCompanySeq(companyInfo.getSequenceNbr());
            regUnitInfo.setAmosCompanyCode(companyInfo.getOrgCode());
            List<String> userId = new ArrayList<>();
            userId.add(userResult.getResult().getUserId());
            // 将创建用户加入用户组
            Privilege.groupUserClient.create(userGroupId, userId);
        } catch (Exception e) {
            // 删除已经创建的 企业信息
            if (companyInfo != null && companyInfo.getSequenceNbr() != null) {
                Privilege.companyClient.deleteCompany(companyInfo.getSequenceNbr() + "");
            }
            if (userResult != null && userResult.getResult() != null
                    && StringUtils.isNotEmpty(userResult.getResult().getUserId())) {
                Privilege.agencyUserClient.multDeleteUser(userResult.getResult().getUserId());
            }
            log.error(e.getMessage(), e);
            e.printStackTrace();
            throw new BadRequest(e.getMessage());
        }
    }


    private void createCompanyAndUser(UnitInfoDto regUnitInfo) {
        CompanyModel companyInfo = new CompanyModel();
        FeignClientResult<AgencyUserModel> userResult = null;
        try {
            //FeignClientResult<List<RoleModel>> roleListResult = Privilege.roleClient.queryRoleList(null, null);
          //  List<RoleModel> allRoleList = roleListResult.getResult();
            List<RoleModel> userRoleList = new ArrayList<>();
            List<Long> roleIds = new ArrayList<>();
            // 1创建公司
            companyInfo.setAddress(regUnitInfo.getRegisterPcd());
            companyInfo.setAgencyCode("JXIOP");
            companyInfo.setParentId(Long.parseLong(regUnitInfo.getManagementUnitId()));
            companyInfo.setLevel("station");
            companyInfo.setCompanyName(regUnitInfo.getName());
          //  companyInfo.setCompanyCode(regUnitInfo.getUnitType());
            companyInfo.setContact(regUnitInfo.getHeadName());
            companyInfo.setCompanyType(regUnitInfo.getUnitType());
            companyInfo.setLandlinePhone(regUnitInfo.getHeadPhone());
            FeignClientResult<CompanyModel> companyResult = Privilege.companyClient.create(companyInfo);

            if (companyResult == null || companyResult.getStatus()!=200) {
                throw new BadRequest("单位注册失败！"+companyResult.getDevMessage());
            }

            String adminUserName = regUnitInfo.getAdminUserName();
            String loginName = regUnitInfo.getAdminLoginName();
            String pwd = regUnitInfo.getAdminLoginPwd();
            String adminTel = regUnitInfo.getAdminPhone();
            // 2 创建平台用户
            companyInfo = companyResult.getResult();
            AgencyUserModel agencyUserModel = new AgencyUserModel();
            agencyUserModel.setUserName(loginName);
            agencyUserModel.setRealName(adminUserName);
            agencyUserModel.setLockStatus("LOCK");
            agencyUserModel.setPassword(pwd);
            agencyUserModel.setRePassword(pwd);
            agencyUserModel.setAgencyCode("JXIOP");
            agencyUserModel.setMobile(adminTel);
            List<String> split = Arrays.asList(StringUtils.split(appCodes, ','));
            Map<Long, List<Long>> roleSeqMap = new HashMap<>();
            Map<Long, List<RoleModel>> orgRoles = new HashMap<>();
//            userRoleList = allRoleList.stream().filter(r -> r.getSequenceNbr().toString().equals(regUnitInfo.getRoleId()))
//                    .collect(Collectors.toList());
//            userRoleList.forEach(r -> {
//                if (!roleIds.contains(r.getSequenceNbr())) {
//                    roleIds.add(r.getSequenceNbr());
//                }
//            });
           // roleIds.add(Long.valueOf(regUnitInfo.getRoleId()));

            roleIds.add(userGroupId);
            roleSeqMap.put(companyInfo.getSequenceNbr(), roleIds);
            orgRoles.put(companyInfo.getSequenceNbr(), userRoleList);
            agencyUserModel.setOrgRoles(orgRoles);
            agencyUserModel.setOrgRoleSeqs(roleSeqMap);
            userResult = Privilege.agencyUserClient.create(agencyUserModel);

            if (userResult == null || userResult.getStatus()!=200) {
                throw new BadRequest("单位注册失败！"+userResult.getDevMessage());
            }
            regUnitInfo.setAdminUserId(userResult.getResult().getUserId());
            regUnitInfo.setAmosCompanySeq(companyInfo.getSequenceNbr());
            regUnitInfo.setAmosCompanyCode(companyInfo.getOrgCode());
            List<String> userId = new ArrayList<>();
            userId.add(userResult.getResult().getUserId());
            // 将创建用户加入用户组
            Privilege.groupUserClient.create(userGroupId, userId);
        } catch (Exception e) {
            // 删除已经创建的 企业信息
            if (companyInfo != null && companyInfo.getSequenceNbr() != null) {
                Privilege.companyClient.deleteCompany(companyInfo.getSequenceNbr() + "");
            }
            if (userResult != null && userResult.getResult() != null
                    && StringUtils.isNotEmpty(userResult.getResult().getUserId())) {
                Privilege.agencyUserClient.multDeleteUser(userResult.getResult().getUserId());
            }
            log.error(e.getMessage(), e);
            throw new BadRequest(e.getMessage());
        }
    }


   public UnitInfoDto  createWithModelnew(UnitInfoDto regUnitInfo){
       regUnitInfo.setBlacklist(1);
       regUnitInfo.setAuditStatus(1);
       regUnitInfo.setManagementUnit("经销商事业部");
       regUnitInfo= this.createWithModel(regUnitInfo);
       this.submitExamine(regUnitInfo);
       return regUnitInfo;
   }


    private void submitExamine( UnitInfoDto regUnitInfo) {



        String taskId = null;
        Map<String, Object> objectMap = new HashMap<>(1);
        objectMap.put("describe", "经销商已上传信息");
        // 第一步启动工作流
        DealerReview dealerReview = new DealerReview();
        // 保存并审核
        try {

            //发起工作流
            // 调用工作流执行第一个节点
//            ProcessDto processDto = new ProcessDto();
//            processDto.setBusinessKey(String.valueOf(regUnitInfo.getSequenceNbr()));
//            processDto.setProcessDefinitionKey("JXS_SH");
//            StartProcessDto startProcessDto = new StartProcessDto();
//            List<ProcessDto> process=new ArrayList<>();
//            process.add(processDto);
//            startProcessDto.setProcess(process);
            BasicGridAcceptance basicGridAcceptance=new BasicGridAcceptance();
//            workflow.startProcessnew(AMOS_STUDIO, AMOS_STUDIO_WEB,requestContext.getToken(),basicGridAcceptance, startProcessDto,requestContext.getUserId());
            //开启工作流 并执行一步
            ActWorkflowBatchDTO actWorkflowBatchDTO = new ActWorkflowBatchDTO();
            List<ActWorkflowStartDTO> list = new ArrayList<>();
            ActWorkflowStartDTO dto = new ActWorkflowStartDTO();
            dto.setProcessDefinitionKey(BusinessTypeEnum.HYGF_JXS_SH.getCode());
            dto.setBusinessKey(String.valueOf(regUnitInfo.getSequenceNbr()));
            dto.setCompleteFirstTask(true);
            list.add(dto);
            actWorkflowBatchDTO.setProcess(list);
            List<ProcessTaskDTO> processTaskDTOS = workFlowService.startBatchNew(amosRequestContext.getAppKey(), amosRequestContext.getProduct(), amosRequestContext.getToken(), actWorkflowBatchDTO);
            workFlowService.getBasicGridAcceptance(basicGridAcceptance, processTaskDTOS, amosRequestContext.getUserId());

            // 插入记录表
            dealerReview.setPlanInstanceId(planId);
            dealerReview.setUnitInfoId(regUnitInfo.getSequenceNbr());
            dealerReview.setTaskId(basicGridAcceptance.getNextTaskId());
            dealerReview.setProcessInstanceId(basicGridAcceptance.getInstanceId());
            dealerReview.setFlowTaskId(basicGridAcceptance.getNextTaskId());
            dealerReview.setNodeRole(basicGridAcceptance.getNextExecutorIds());
            dealerReview.setNextProcessNode(DealerReviewEnum.经销商管理员审核.getCode());
            dealerReviewService.saveDealerReview(dealerReview, true, false, regUnitInfo.getName(), "任务明细：经销商已上传信息");
            //添加待办
//            List<WorkflowResultDto> workflowResultDtos = workFlowService.buildWorkFlowInfo(processTaskDTOS);
//            commonService.buildTaskModel(commonService.buildTaskModelDto(dealerReview, workflowResultDtos.get(0), BusinessTypeEnum.HYGF_JXS_SH));

        } catch (Exception e){
            throw new BaseException("获取工作流节点失败！","400","获取工作流节点失败！");
        }




//
//        String taskId = null;
//        Map<String, Object> objectMap = new HashMap<>(1);
//        objectMap.put("describe", "经销商已上传信息");
//        // 第一步启动工作流
//        DealerReview dealerReview = new DealerReview();
//        // 保存并审核
//        try {
//            FeignClientResult<String> submit = idxFeginService.tokenSubmit(AMOS_STUDIO, AMOS_STUDIO_WEB,requestContext.getToken(),pageId, taskId, planId, null, "DEALER_EXAMINE", null, objectMap);
//
//
//            System.out.println("发起"+AMOS_STUDIO+"@"+AMOS_STUDIO_WEB+"@"+requestContext.getToken());
//            if (IDX_REQUEST_STATE.equals(String.valueOf(submit.getStatus()))) {
//                String code = submit.getResult();
//                // 插入记录表
//                dealerReview.setPlanInstanceId(planId);
//                dealerReview.setUnitInfoId(regUnitInfo.getSequenceNbr());
//                // 获取流程信息
//                FeignClientResult<JSONObject> record = idxFeginService.getRecordtoken(AMOS_STUDIO, AMOS_STUDIO_WEB,requestContext.getToken(),code);
//                if (IDX_REQUEST_STATE.equals(String.valueOf(record.getStatus()))) {
//                    JSONObject resultObj = record.getResult();
//                    String taskIdNew = String.valueOf(resultObj.get("taskId"));
//                    String processInstanceId = String.valueOf(resultObj.get("processInstanceId"));
//                    String flowTaskId = String.valueOf(resultObj.get("flowTaskId"));
//                    dealerReview.setTaskId(taskIdNew);
//                    dealerReview.setProcessInstanceId(processInstanceId);
//                    dealerReview.setFlowTaskId(flowTaskId);
//                    dealerReview.setNextProcessNode(DealerReviewEnum.经销商管理员审核.getCode());
//                }
//                dealerReviewService.saveDealerReview(dealerReview,true,false,regUnitInfo.getName(),"任务明细：经销商已上传信息");
//            }else{
//                throw new BaseException("获取工作流节点失败！","400","获取工作流节点失败！");
//            }
//        } catch (Exception e){
//            throw new BaseException("获取工作流节点失败！","400","获取工作流节点失败！");
//        }
    }



    @Override
    @Transactional
    public String powerStationExamine(long pageId, String nodeCode, String stationId, String taskId, String planInstanceId, Map<String, Object> kv) {

        // 2.更新审核记录表
        UnitInfo  unitInfo=null;
        try{
            DealerReview  dealerReview= dealerReviewMapper.selectOne(new QueryWrapper<DealerReview>().eq("unit_info_id", stationId));
            unitInfo= this.getById(stationId);
            DealerReviewEnum nodeByCode = DealerReviewEnum.getNodeByCode(nodeCode);
            String approvalStatue="";
            if (DealerReviewEnum.经销商管理员审核.getCode().equals(nodeCode)) {
                String result = String.valueOf(kv.get("approvalStatus"));
                if (VERIFY_RESULT_NO.equals(result)) {
                    // 1. 更新经销商状态
                    unitInfo.setAuditStatus(3);
                    //发送断线
                    Boolean flag = true;
                    HashMap<String, String> params = new HashMap<>(3);
                    String meg= String.valueOf(kv.get("approveInfo"));
                    params.put("code","不通过");
                    params.put("mobile",unitInfo.getAdminPhone());
                    params.put("smsCode", SMSTEMPCODENO);
                    approvalStatue="任务明细："+DealerReviewEnum.经销商管理员审核.getName()+"审核不通过";
                 //   FeignClientResult<SmsRecordModel> date= Systemctl.smsClient.sendCommonSms(params);
                //    System.out.println("短信通知============================"+JSON.toJSONString(date));
                }else{
                    // 1. 更新经销商状态
                    unitInfo.setAuditStatus(2);
                    unitInfo.setBlacklist(0);


                    this.createCompanyAndUsernew(unitInfo);
                    PublicAgencyUser publicAgencyUser=new PublicAgencyUser();
                    publicAgencyUser.setAmosUserId(unitInfo.getAdminUserId());
                    publicAgencyUser.setAmosUserName(unitInfo.getAdminLoginName());
                    publicAgencyUser.setRealName(unitInfo.getAdminLoginName());
                    publicAgencyUser.setRole("["+unitInfo.getRoleId()+"]");
                    publicAgencyUser.setEmergencyTelephone(unitInfo.getAdminPhone());
                    publicAgencyUser.setLockStatus("UNLOCK");
                    publicAgencyUserMapper.insert(publicAgencyUser);

                    List<String> lis=new ArrayList<>();
//                    lis.add(unitInfo.getAmosCompanyCode());
                    LambdaQueryWrapper<RegionalCompanies> queryWrapper = new LambdaQueryWrapper<RegionalCompanies>();
                    queryWrapper.eq(RegionalCompanies::getUnitInfoId, unitInfo.getSequenceNbr());
                    List<RegionalCompanies> list=  regionalCompaniesMapper.selectList(queryWrapper);
                    for (RegionalCompanies companies : list) {
                        companies.setUnitId(unitInfo.getAmosCompanySeq());
                        lis.add(companies.getRegionalCompaniesCode());
                    }
                    regionalCompaniesService.saveOrUpdateBatch(list);

                    PersonnelBusiness re=new PersonnelBusiness();
                    re.setAmosDealerId(unitInfo.getAmosCompanySeq());
                    re.setAmosUnitId(unitInfo.getAmosCompanySeq());
                    re.setAmosUnitName(unitInfo.getName());
                    re.setAmosUnitOrgCode(unitInfo.getAmosCompanyCode());
                    re.setFoundationId(publicAgencyUser.getSequenceNbr());
                    re.setUserType("2");
                    personnelBusinessMapper.insert(re);

                    //管理员绑定角色权限
                    StdUserEmpower  stdUserEmpower=new StdUserEmpower();
                    stdUserEmpower.setAmosUserId(unitInfo.getAdminUserId());
                    stdUserEmpower.setAmosOrgCode(lis);
                    stdUserEmpower.setPermissionType("HYGF");
                    userEmpowerMapper.insert(stdUserEmpower);

                    // Privilege.agencyUserClient.unlockUsers(unitInfo.getAdminUserId());
                    approvalStatue="任务明细："+DealerReviewEnum.经销商管理员审核.getName()+"审核通过";
//                    HashMap<String, String> params = new HashMap<>(3);
//                    params.put("code","通过");
//                    params.put("mobile",unitInfo.getAdminPhone());
//                    params.put("smsCode", SMSTEMPCODEYES);
//                    FeignClientResult<SmsRecordModel> date= Systemctl.smsClient.sendCommonSms(params);
//                    System.out.println("短信通知============================"+JSON.toJSONString(date));

                }
            }
            // 2. 更新流程状态
            String code = null;
            // 3. 工作流执行

            //执行工作流
            BasicGridAcceptance basicGridAcceptance=new BasicGridAcceptance();

//            StandardDto standardDto = new StandardDto();
//            standardDto.setComment(kv.get("approvalInfo")!=null?String.valueOf(kv.get("approvalInfo")):"");
//            standardDto.setResult(String.valueOf(kv.get("approvalStatus")));
//            standardDto.setTaskId(dealerReview.getFlowTaskId());
//            VariableDto variable = new VariableDto();
//            variable.setApprovalStatus(String.valueOf(kv.get("approvalStatus")));
//            variable.setComment(kv.get("approvalInfo")!=null?String.valueOf(kv.get("approvalInfo")):"");
//            variable.setOperationTime(String.valueOf(kv.get("approveDate")));
//            variable.setOperator(String.valueOf(kv.get("approveName")));
//            standardDto.setVariable(variable);
//            BasicGridAcceptance workBasicGridAcceptance = workflow.standard(basicGridAcceptance, standardDto, requestContext.getUserId());
            //执行工作流
            TaskResultDTO taskResultDTO = new TaskResultDTO();
            taskResultDTO.setComment(kv.get("approvalInfo") != null ? String.valueOf(kv.get("approvalInfo")) : "");
            taskResultDTO.setResult(String.valueOf(kv.get("approvalStatus")));
            taskResultDTO.setTaskId(dealerReview.getFlowTaskId());
            HashMap<String, Object> variableMap = new HashMap<>();
            variableMap.put("approvalStatus", String.valueOf(kv.get("approvalStatus")));
            variableMap.put("comment", kv.get("approvalInfo") != null ? String.valueOf(kv.get("approvalInfo")) : "");
            variableMap.put("operationTime", String.valueOf(kv.get("approveDate")));
            variableMap.put("operator", String.valueOf(kv.get("approveName")));
            taskResultDTO.setVariable(variableMap);
            ProcessTaskDTO processTaskDTO = workFlowService.standard(basicGridAcceptance, taskResultDTO, amosRequestContext.getUserId());

            dealerReview.setFlowTaskId(basicGridAcceptance.getNextTaskId());
            dealerReviewService.saveDealerReview(dealerReview,false,true,unitInfo.getName(),approvalStatue);

            this.saveOrUpdate(unitInfo);
            //更新待办
//            WorkflowResultDto workflowResultDto = workFlowService.buildWorkFlowInfo(CollectionUtil.newArrayList(processTaskDTO)).get(0);
//            workflowResultDto.setInstanceId(dealerReview.getProcessInstanceId());
//            commonService.updateTaskModelAndAddTask(unitInfo, workflowResultDto,BusinessTypeEnum.HYGF_JXS_SH);


        }catch (Exception e){

            if (!ObjectUtils.isEmpty(unitInfo.getAmosCompanySeq())) {
                FeignClientResult<CompanyModel> feignClientResult = Privilege.companyClient
                        .seleteOne(unitInfo.getAmosCompanySeq());
                if (feignClientResult != null) {
                    Privilege.companyClient.deleteCompany(unitInfo.getAmosCompanySeq().toString());
                }
            }
            // 失败后回滚：删除已经创建的管理员账号
            if (StringUtils.isNotEmpty(unitInfo.getAdminUserId())) {
                FeignClientResult<AgencyUserModel> feignClientResult = Privilege.agencyUserClient
                        .queryByUserId(unitInfo.getAdminUserId());
                if (feignClientResult != null) {
                    Privilege.agencyUserClient.multDeleteUser(unitInfo.getAdminUserId());
                }
            }


             e.printStackTrace();

            throw new  BaseException("获取工作流节点失败！","400","获取工作流节点失败！");

        }




//        // 2.更新审核记录表
//        UnitInfo  unitInfo=null;
//        try{
//        DealerReview  dealerReview= dealerReviewMapper.selectOne(new QueryWrapper<DealerReview>().eq("unit_info_id", stationId));
//          unitInfo= this.getById(stationId);
//        DealerReviewEnum nodeByCode = DealerReviewEnum.getNodeByCode(nodeCode);
//        String approvalStatue="";
//        if (DealerReviewEnum.经销商管理员审核.getCode().equals(nodeCode)) {
//            String result = String.valueOf(kv.get("approvalStatus"));
//            if (VERIFY_RESULT_NO.equals(result)) {
//                // 1. 更新经销商状态
//                unitInfo.setAuditStatus(3);
//                //发送断线
//                Boolean flag = true;
//                HashMap<String, String> params = new HashMap<>(3);
//                String meg= String.valueOf(kv.get("approveInfo"));
//                params.put("code","不通过");
//                params.put("mobile",unitInfo.getAdminPhone());
//                params.put("smsCode", smsTempCode);
//                approvalStatue="任务明细："+DealerReviewEnum.经销商管理员审核.getName()+"审核不通过";
//                FeignClientResult<SmsRecordModel> date= Systemctl.smsClient.sendCommonSms(params);
//            }else{
//                // 1. 更新经销商状态
//                unitInfo.setAuditStatus(2);
//                unitInfo.setBlacklist(0);
//
//
//            this.createCompanyAndUsernew(unitInfo);
//            PublicAgencyUser publicAgencyUser=new PublicAgencyUser();
//            publicAgencyUser.setAmosUserId(unitInfo.getAdminUserId());
//            publicAgencyUser.setAmosUserName(unitInfo.getAdminLoginName());
//            publicAgencyUser.setRealName(unitInfo.getAdminLoginName());
//            publicAgencyUser.setRole("["+unitInfo.getRoleId()+"]");
//            publicAgencyUser.setEmergencyTelephone(unitInfo.getAdminPhone());
//            publicAgencyUser.setLockStatus("UNLOCK");
//            publicAgencyUserMapper.insert(publicAgencyUser);
//
//                List<String> lis=new ArrayList<>();
//                lis.add(unitInfo.getAmosCompanyCode());
//            LambdaQueryWrapper<RegionalCompanies> queryWrapper = new LambdaQueryWrapper<RegionalCompanies>();
//            queryWrapper.eq(RegionalCompanies::getUnitInfoId, unitInfo.getSequenceNbr());
//            List<RegionalCompanies> list=  regionalCompaniesMapper.selectList(queryWrapper);
//                for (RegionalCompanies companies : list) {
//                    companies.setUnitId(unitInfo.getAmosCompanySeq());
//                    lis.add(companies.getRegionalCompaniesCode());
//                }
//             regionalCompaniesService.saveOrUpdateBatch(list);
//
//            PersonnelBusiness re=new PersonnelBusiness();
//            re.setAmosDealerId(unitInfo.getAmosCompanySeq());
//            re.setAmosUnitId(unitInfo.getAmosCompanySeq());
//            re.setAmosUnitName(unitInfo.getName());
//            re.setAmosUnitOrgCode(unitInfo.getAmosCompanyCode());
//            re.setFoundationId(publicAgencyUser.getSequenceNbr());
//            re.setUserType("2");
//            personnelBusinessMapper.insert(re);
//
//            //管理员绑定角色权限
//                StdUserEmpower  stdUserEmpower=new StdUserEmpower();
//                stdUserEmpower.setAmosUserId(unitInfo.getAdminUserId());
//                stdUserEmpower.setAmosOrgCode(lis);
//                userEmpowerMapper.insert(stdUserEmpower);
//
//             // Privilege.agencyUserClient.unlockUsers(unitInfo.getAdminUserId());
//             approvalStatue="任务明细："+DealerReviewEnum.经销商管理员审核.getName()+"审核通过";
//            }
//        }
//             // 2. 更新流程状态
//               String code = null;
//            // 3. 工作流执行
//            FeignClientResult<String> submit = idxFeginService.submit(pageId, taskId, planInstanceId, null, "DEALER_EXAMINE", null, kv);
//            if (IDX_REQUEST_STATE.equals(String.valueOf(submit.getStatus()))) {
//                code = submit.getResult();
//                // 获取流程信息
//                FeignClientResult<JSONObject> record = idxFeginService.getRecord(code);
//                if (IDX_REQUEST_STATE.equals(String.valueOf(record.getStatus()))) {
//                    JSONObject resultObj = record.getResult();
//                    String flowTaskId = String.valueOf(resultObj.get("flowTaskId"));
//                    dealerReview.setFlowTaskId(flowTaskId);
//                }
//                dealerReviewService.saveDealerReview(dealerReview,false,true,unitInfo.getName(),approvalStatue);
//            }
//            this.saveOrUpdate(unitInfo);
//        }catch (Exception e){
//
//                        if (!ObjectUtils.isEmpty(unitInfo.getAmosCompanySeq())) {
//                FeignClientResult<CompanyModel> feignClientResult = Privilege.companyClient
//                        .seleteOne(unitInfo.getAmosCompanySeq());
//                if (feignClientResult != null) {
//                    Privilege.companyClient.deleteCompany(unitInfo.getAmosCompanySeq().toString());
//                }
//            }
//            // 失败后回滚：删除已经创建的管理员账号
//            if (StringUtils.isNotEmpty(unitInfo.getAdminUserId())) {
//                FeignClientResult<AgencyUserModel> feignClientResult = Privilege.agencyUserClient
//                        .queryByUserId(unitInfo.getAdminUserId());
//                if (feignClientResult != null) {
//                    Privilege.agencyUserClient.multDeleteUser(unitInfo.getAdminUserId());
//                }
//            }
//
//
//
//
//            throw new  BaseException("获取工作流节点失败！","400","获取工作流节点失败！");
//
//        }
        return code;
    }

    @Override
    public IPage<CompanyDto> getCompanyDto(CompanyDto dto) {
        //列表数据组装
        IPage<CompanyDto> pag = unitInfoMapper.getCompanyDto( dto);
//        List<CompanyDto> pag = unitInfoMapper.getCompanyDto( (page.getCurrent()-1)*page.getSize(),page.getSize(),dto);
////        Map<String,Integer> count = unitInfoMapper.getCompanyDtoCount(dto);
////        page.setTotal(count.get("num"));
////        page.setRecords(pag);
        return pag;
    }

    //单位详情
    public UnitDataDto getUnitDataDto(Long id){

        LambdaQueryWrapper<UnitInfo> queryWrapper = new LambdaQueryWrapper<UnitInfo>();
        queryWrapper.eq(UnitInfo::getAmosCompanySeq, id);
        UnitInfo unitInfo= unitInfoMapper.selectOne(queryWrapper);
        LambdaQueryWrapper<CommerceInfo> queryWrapper1 = new LambdaQueryWrapper<CommerceInfo>();
        queryWrapper1.eq(CommerceInfo::getUnitSeq, unitInfo.getSequenceNbr());
        CommerceInfo commerceInfo= commerceInfoMapper.selectOne(queryWrapper1);
        //单位管理
        UnitInformation unitInformation=new UnitInformation();
        //工商信息
        CommerceDto commerceDto=new CommerceDto();
        //管理员账号
        Account cccount=new Account();
        BeanUtils.copyProperties(unitInfo,unitInformation);
        unitInformation.setHeadCardPhotoBack(unitInformation.getHeadCardPhotoBack());
        unitInformation.setHeadCardPhotoFront(unitInformation.getHeadCardPhotoFront());
        unitInformation.setRegisterPcdCode((unitInformation.getRegisterPcdCode()!=null&&!"".equals(unitInformation.getRegisterPcdCode()))?unitInformation.getRegisterPcdCode():null);
        unitInformation.setWorkPcdCode((unitInformation.getWorkPcdCode()!=null&&!"".equals(unitInformation.getWorkPcdCode()))?unitInformation.getWorkPcdCode():null);
        BeanUtils.copyProperties(commerceInfo,commerceDto);
        commerceDto.setBusinessLicensePhoto(commerceDto.getBusinessLicensePhoto());
        commerceDto.setLegalPersonCardPhotoBack(commerceDto.getLegalPersonCardPhotoBack());
        commerceDto.setLegalPersonCardPhotoFront(commerceDto.getLegalPersonCardPhotoFront());

        BeanUtils.copyProperties(unitInfo,cccount);
        UnitDataDto unitDataDt = new UnitDataDto(unitInformation,commerceDto,cccount);
        return unitDataDt;
    }





   @Transactional(rollbackFor = Exception.class)
    public Boolean updateUnitDataDto(UnitDataDto unitDataDto){
        //验证二维码
        UnitInfo unitInfo=new UnitInfo();
        unitInfo= unitInfoMapper.selectById(unitDataDto.getUnitInformation().getSequenceNbr());
       UnitInformation unitInformation= unitDataDto.getUnitInformation();
       List<Long> dis= unitInformation.getRegionalCompaniesSeq();
       //区域公司
       LambdaQueryWrapper<RegionalCompanies> qu=new LambdaQueryWrapper<>();
       qu.eq(RegionalCompanies::getUnitId,unitInfo.getAmosCompanySeq());
       List<RegionalCompanies> oldList = regionalCompaniesMapper.selectList(qu);
       List<String> oldDisString = oldList.stream().map((regionalCompanies) -> regionalCompanies.getRegionalCompaniesSeq().toString()).collect(Collectors.toList());
       List<String> newDisString = dis.stream().map((regionalCompaniesSeq) -> regionalCompaniesSeq.toString()).collect(Collectors.toList());
       for(String item:oldDisString){
           if(!newDisString.contains(item)){
               throw new BadRequest("所属区域公司只能增加, 不能删除");
           }
       }

       List<String> lisk=new ArrayList<>();
       JSONArray regionName = getRegionName();
       List<RegionModel> list = JSONArray.parseArray(regionName.toJSONString(), RegionModel.class);
           List<Integer> regist= unitInformation.getRegisterPcdCodeList();
           List<Integer> workP= unitInformation.getWorkPcdCodeList();
           //注册地址
           if(regist!=null&&!regist.isEmpty()){
               StringBuilder codenameRegi=new StringBuilder();
               for (int i = 0, len = regist.size(); i < len; i++) {
                   for (RegionModel regionModel : list) {
                       if (regionModel.getRegionCode().intValue() == regist.get(i).intValue()) {
                           codenameRegi.append(regionModel.getRegionName());
                           if (i != len - 1) {
                               codenameRegi.append("-");
                           }
                       }
                   }
               }
               unitInformation.setRegisterPcd(codenameRegi!=null&&!"".equals(codenameRegi.toString())?codenameRegi.toString():null);
           }

           //办公地址
           if(workP!=null&&!workP.isEmpty()){
               StringBuilder codenamework= new StringBuilder();;
                   for (int i = 0, len = workP.size(); i < len; i++) {
                       for (RegionModel regionModel : list) {
                       if (regionModel.getRegionCode().intValue() == workP.get(i).intValue()) {
                           codenamework.append(regionModel.getRegionName());
                           if (i != len - 1) {
                               codenamework.append("-");
                           }
                       }
                   }
               }
               unitInformation.setWorkPcd(codenamework!=null&&!"".equals(codenamework.toString())?codenamework.toString():null);
           }
       unitInformation.setHeadCardPhotoBackUrl(unitInformation.getHeadCardPhotoBackUrl());
       unitInformation.setHeadCardPhotoFrontUrl(unitInformation.getHeadCardPhotoFrontUrl());
       unitInformation.setRegisterPcdCodeList(unitInformation.getRegisterPcdCodeList());
       unitInformation.setWorkPcdCodeList(unitInformation.getWorkPcdCodeList());


       List<String>  disST=   dis.stream().map(x->x+"").collect(Collectors.toList());
       BeanUtils.copyProperties(unitInformation,unitInfo);
        CommerceInfo commerceInfo=new  CommerceInfo();
        commerceInfo= commerceInfoMapper.selectById(unitDataDto.getCommerceDto().getSequenceNbr());
       CommerceDto commerceDto= unitDataDto.getCommerceDto();
       commerceDto.setBusinessLicensePhotoUrl(commerceDto.getBusinessLicensePhotoUrl());
       commerceDto.setLegalPersonCardPhotoBackUrl(commerceDto.getLegalPersonCardPhotoBackUrl());
       commerceDto.setLegalPersonCardPhotoFrontUrl(commerceDto.getLegalPersonCardPhotoFrontUrl());
        BeanUtils.copyProperties(commerceDto,commerceInfo);
       unitInfo.setRegionalCompaniesSeq(disST);

        unitInfoMapper.updateById(unitInfo);
        commerceInfoMapper.updateById(commerceInfo);


       regionalCompaniesMapper.delete(qu);




       List<RegionalCompanies> regionalComp= new ArrayList<>();
       FeignClientResult<Collection<CompanyModel>> feignClientResult=  Privilege.companyClient.querySubAgencyTree(regionalCompanies);
       List<CompanyModel>  companyModel = (List<CompanyModel>)feignClientResult.getResult();
       List<String>  lisd=unitInfo.getRegionalCompaniesSeq();


       if(oldList==null) {
           oldList = new ArrayList<>();
       }

       if(companyModel!=null&&!companyModel.isEmpty()&&lisd!=null&&!lisd.isEmpty()){
           for (Object aLong : lisd) {
               RegionalCompanies oldRe = oldList.stream().filter(s -> Objects.equals(s.getRegionalCompaniesSeq().toString(), aLong.toString())).findFirst().orElse(null);
               if(oldRe!= null) {
                   lisk.add(oldRe.getRegionalCompaniesCode());
                   regionalComp.add(oldRe);
               }else {
                   for (CompanyModel compan : companyModel) {
                       if(compan.getSequenceNbr().longValue()==Long.valueOf(aLong.toString()).longValue()){
                           RegionalCompanies re=  new RegionalCompanies(Long.valueOf(aLong.toString()), compan.getCompanyName(), compan.getOrgCode(), unitInfo.getAmosCompanySeq(),unitInfo.getSequenceNbr());
                           lisk.add(compan.getOrgCode());
                           regionalComp.add(re);
                           continue;
                       }
                   }
               }


           }
       }






       regionalCompaniesService.saveBatch(regionalComp);

       //修改管理员权限
       //管理员绑定角色权限
       LambdaQueryWrapper<StdUserEmpower> uo=new LambdaQueryWrapper();
       uo.eq(StdUserEmpower::getAmosUserId,unitInfo.getAdminUserId());
       StdUserEmpower  stdUserEmpower= userEmpowerMapper.selectOne(uo);

       if(stdUserEmpower!=null){
           stdUserEmpower.setAmosUserId(unitInfo.getAdminUserId());
           stdUserEmpower.setAmosOrgCode(lisk);
           userEmpowerMapper.updateById(stdUserEmpower);
       }else{
           stdUserEmpower=new StdUserEmpower();
           stdUserEmpower.setAmosUserId(unitInfo.getAdminUserId());
           stdUserEmpower.setAmosOrgCode(lisk);
           stdUserEmpower.setPermissionType("HYGF");
           userEmpowerMapper.insert(stdUserEmpower);
       }

       // region 同步平台的单位信息
       QueryWrapper<PersonnelBusiness> personnelBusinessWrapper = new QueryWrapper<>();
       personnelBusinessWrapper.eq("amos_unit_id", unitInfo.getAmosCompanySeq());
       List<PersonnelBusiness> personnelBusiness = personnelBusinessMapper.selectList(personnelBusinessWrapper);
       Long amosDealerId = personnelBusiness.get(0).getAmosDealerId();
       FeignClientResult<CompanyModel> companyResult = Privilege.companyClient.seleteOne(amosDealerId);
       if (companyResult == null || companyResult.getStatus() != 200) {
           throw new BadRequest("修改单位失败！" + companyResult.getDevMessage());
       }
       CompanyModel updateCompanyModel = companyResult.getResult();
       updateCompanyModel.setCompanyName(unitInfo.getName());
       FeignClientResult<CompanyModel> companyUpdateResult = Privilege.companyClient.update(updateCompanyModel, amosDealerId);
       if (companyUpdateResult == null || companyUpdateResult.getStatus() != 200) {
           throw new BadRequest("修改单位失败！" + companyResult.getDevMessage());
       }
       // endregion
        return true;
    }




    public JSONArray getRegionName(){
        JSONArray jsonArray = new JSONArray();
        if (redisUtil.hasKey(regionRedis)) {
            jsonArray= JSONArray.parseArray(redisUtil.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);
                }
            }

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

    public Page<PeasantHousehold>  getPeasantHouseholdDataNew(  Long unitInfoId,
                                                             Long regionalCompaniesSeq,
                                                             int pageNum,
                                                             int pageSize,
                                                             String peasantHouseholdNo,
                                                             String ownersName,
                                                             String ids) {
        UnitInfo unitInfo = unitInfoMapper.selectById(unitInfoId);
        PageHelper.startPage(pageNum, pageSize);
        List<PeasantHousehold>  list=peasantHouseholdMapper.selectPeasantHouseholdList(unitInfo.getAmosCompanySeq(),regionalCompaniesSeq,peasantHouseholdNo,ownersName,ids, "hygf_peasant_household.rec_date DESC");

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


        PageInfo<PeasantHousehold> page = new PageInfo(list);
        Page<PeasantHousehold> pagenew = new Page<PeasantHousehold>();
        pagenew.setCurrent(pageNum);
        pagenew.setTotal(page.getTotal());
        pagenew.setSize(pageSize);
        pagenew.setRecords(page.getList());
        return pagenew;
    }

   public Page<PeasantHousehold>  getPeasantHouseholdData(  Long unitInfoId,
                              Long regionalCompaniesSeq,
                              int pageNum,
                              int pageSize,
                              String peasantHouseholdNo,
                              String ownersName,
                              String ids){
       UnitInfo unitInfo=unitInfoMapper.selectById(unitInfoId);
        PageHelper.startPage(pageNum, pageSize);
        List<PeasantHousehold>  list=peasantHouseholdMapper.selectPeasantHouseholdList(unitInfo.getAmosCompanySeq(),regionalCompaniesSeq,peasantHouseholdNo,ownersName,ids, null);

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

        PageInfo<PeasantHousehold> page = new PageInfo(list);
        Page<PeasantHousehold> pagenew = new Page<PeasantHousehold>();
        pagenew.setCurrent(pageNum);
        pagenew.setTotal(page.getTotal());
        pagenew.setSize(pageSize);
        pagenew.setRecords(page.getList());
        return pagenew;
    }
    public Page<PeasantHousehold>  selectPeasantHouseholdListsg(  String unitInfoCode,
                                                             Long regionalCompaniesSeq,
                                                             int pageNum,
                                                             int pageSize,
                                                             String peasantHouseholdNo,
                                                             String ownersName,
                                                                  String ids){
        PageHelper.startPage(pageNum, pageSize);
        List<PeasantHousehold>  list=peasantHouseholdMapper.selectPeasantHouseholdListsg(unitInfoCode,regionalCompaniesSeq,peasantHouseholdNo,ownersName,ids);

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

        PageInfo<PeasantHousehold> page = new PageInfo(list);
        Page<PeasantHousehold> pagenew = new Page<PeasantHousehold>();
        pagenew.setCurrent(pageNum);
        pagenew.setTotal(page.getTotal());
        pagenew.setSize(pageSize);
        pagenew.setRecords(page.getList());
        return pagenew;
    }

    public Boolean hasExistPhoneOrUserName(String phone, String userName) {
        Integer userListHuiCount = unitInfoMapper.getUserListHuiCount(phone, userName);
        Integer userListPauCount = unitInfoMapper.getUserListPauCount(phone, userName);
        Integer userListSubCount = unitInfoMapper.getUserListSubCount(phone, userName);
        Integer userListAliCount = unitInfoMapper.getUserListAliCount(phone, userName);

        if((userListHuiCount != 0 || userListPauCount != 0 || userListSubCount != 0 || userListAliCount !=0) && phone != null) {
            throw new BadRequest("该手机号已经注册");
        }

        if((userListHuiCount != 0 || userListPauCount != 0 || userListSubCount != 0 || userListAliCount !=0) && userName != null) {
            throw new BadRequest("该用户名已经注册");
        }
        return true;

    }
}