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

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.DealerReviewEnum;
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 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.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
    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
    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
    @Transactional
    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);
            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());
            // 插入记录表
            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(),"任务明细：经销商已上传信息");

        } 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());
            dealerReview.setFlowTaskId(basicGridAcceptance.getNextTaskId());
            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());
                }
            }


            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
    public Boolean updateUnitDataDto(UnitDataDto unitDataDto){
        //验证二维码
        UnitInfo unitInfo=new UnitInfo();
        unitInfo= unitInfoMapper.selectById(unitDataDto.getUnitInformation().getSequenceNbr());
       List<String> lisk=new ArrayList<>();
       UnitInformation unitInformation= unitDataDto.getUnitInformation();
       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<Long> dis= unitInformation.getRegionalCompaniesSeq();
       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);

       //区域公司
       LambdaQueryWrapper<RegionalCompanies> qu=new LambdaQueryWrapper<>();
       qu.eq(RegionalCompanies::getUnitId,unitInfo.getAmosCompanySeq());
       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(companyModel!=null&&!companyModel.isEmpty()&&lisd!=null&&!lisd.isEmpty()){
           for (Object aLong : lisd) {
               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);
       }


        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>  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);
        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(  Long unitInfoId,
                                                             Long regionalCompaniesSeq,
                                                             int pageNum,
                                                             int pageSize,
                                                             String peasantHouseholdNo,
                                                             String ownersName,
                                                                  String ids){
        PageHelper.startPage(pageNum, pageSize);
        List<PeasantHousehold>  list=peasantHouseholdMapper.selectPeasantHouseholdListsg(unitInfoId,regionalCompaniesSeq,peasantHouseholdNo,ownersName,ids);
        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;
    }
}