package com.yeejoin.amos.boot.module.hygf.biz.controller;

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.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.hygf.api.config.UserLimits;
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.hwsms.SendSmsCode;
import com.yeejoin.amos.boot.module.hygf.api.mapper.*;
import com.yeejoin.amos.boot.module.hygf.api.util.CommonResponseNewUtil;
import com.yeejoin.amos.boot.module.hygf.biz.service.impl.DealerReviewServiceImpl;
import com.yeejoin.amos.boot.module.hygf.biz.service.impl.UnitInfoServiceImpl;
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.config.InnerInvokException;
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.GroupModel;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.RegionModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;

/**
 * 经销商人员信息
 *
 * @author system_generator
 * @date 2023-07-07
 */
@RestController
@Api(tags = "经销商单位信息Api")
@RequestMapping(value = "/unit-info")
public class UnitInfoController extends BaseController {

    @Autowired
    UnitInfoServiceImpl unitInfoServiceImpl;

	@Autowired
	AmosRequestContext requestContext;

	@Autowired
	RedisUtils redisUtil;

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

    @Value("${regionalCompanies.company.seq}")
    private Long regionalCompanies;
    @Value("${dealer.group}")
    private Long group;


    @Autowired
    RegionalCompaniesMapper regionalCompaniesMapper;

	@Autowired
	SendSmsCode sendSmsCode;

	public static final String HYGF_USER_TEL = "hygf_tel_";
    @Autowired
    DealerReviewServiceImpl dealerReviewServiceImpl;
    @Autowired
    CommerceInfoMapper commerceInfoMapper;
    @Autowired
    UnitInfoMapper unitInfoMapper;

    @Autowired
    PublicAgencyUserMapper publicAgencyUserMapper;
    @Autowired
    PersonnelBusinessMapper personnelBusinessMapper;
    @Autowired
    PeasantHouseholdMapper peasantHouseholdMapper;

	/**
	 * 验证码过期时间
	 */
	private long time = 180L;

	/**
     * 根据sequenceNbr更新
     *
     * @param sequenceNbr 主键
     * @return
     */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PutMapping(value = "/{sequenceNbr}")
	@ApiOperation(httpMethod = "PUT", value = "根据sequenceNbr更新经销商人员信息", notes = "根据sequenceNbr更新经销商人员信息")
	public ResponseModel<UnitInfoDto> updateBySequenceNbrUnitInfo(@RequestBody UnitInfoDto model,@PathVariable(value = "sequenceNbr") Long sequenceNbr) {
	    model.setSequenceNbr(sequenceNbr);
	    return ResponseHelper.buildResponse(unitInfoServiceImpl.updateWithModel(model));
	}

	/**
     * 根据sequenceNbr删除
     *
     * @param sequenceNbr 主键
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @DeleteMapping(value = "/{sequenceNbr}")
    @ApiOperation(httpMethod = "DELETE", value = "根据sequenceNbr删除经销商人员信息", notes = "根据sequenceNbr删除经销商人员信息")
    public ResponseModel<Boolean> deleteBySequenceNbr(HttpServletRequest request, @PathVariable(value = "sequenceNbr") Long sequenceNbr){
        return ResponseHelper.buildResponse(unitInfoServiceImpl.removeById(sequenceNbr));
    }

    /**
     * 根据sequenceNbr查询
     *
	 * @param sequenceNbr  主键
     * @return
     */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/{sequenceNbr}")
	@ApiOperation(httpMethod = "GET",value = "根据sequenceNbr查询单个经销商人员信息",  notes = "根据sequenceNbr查询单个经销商人员信息")
	public ResponseModel<UnitInfoDto> selectOne(@PathVariable Long sequenceNbr) {
	    return ResponseHelper.buildResponse(unitInfoServiceImpl.queryBySeq(sequenceNbr));
	}


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getOne/{sequenceNbr}")
    @ApiOperation(httpMethod = "GET",value = "根据sequenceNbr查询单个经销商人员信息",  notes = "根据sequenceNbr查询单个经销商人员信息")
    public ResponseModel<UnitInfoData> getOne(@PathVariable String sequenceNbr) {

        UnitInfo unitInfo=  unitInfoServiceImpl.getById(sequenceNbr);
        unitInfo.setHeadCardPhotoBackList(toCommonFile(unitInfo.getHeadCardPhotoBack()));
        unitInfo.setHeadCardPhotoFrontList(toCommonFile(unitInfo.getHeadCardPhotoFront()));
        CommerceInfo commerceInfo= commerceInfoMapper.selectOne(new QueryWrapper<CommerceInfo>().eq("unit_seq", sequenceNbr));
        commerceInfo.setLegalPersonCardPhotoBackList(toCommonFile(commerceInfo.getLegalPersonCardPhotoBack()));
        commerceInfo.setBusinessLicensePhotoList(toCommonFile(commerceInfo.getBusinessLicensePhoto()));
        commerceInfo.setLegalPersonCardPhotoFrontList(toCommonFile(commerceInfo.getLegalPersonCardPhotoFront()));
        UnitInfoData unitInfoData=new UnitInfoData(unitInfo,  unitInfo,  commerceInfo);
        return ResponseHelper.buildResponse(unitInfoData);
    }

	/**
     * 列表分页查询
     *
     * @param current 当前页
     * @param current 每页大小
     * @return
     */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/page")
	@ApiOperation(httpMethod = "GET",value = "经销商人员信息分页查询",  notes = "经销商人员信息分页查询")
	public ResponseModel<Page<UnitInfoDto>> queryForPage(@RequestParam(value = "current") int current,@RequestParam
                    (value = "size") int size) {
	    Page<UnitInfoDto> page = new Page<UnitInfoDto>();
	    page.setCurrent(current);
	    page.setSize(size);
	    return ResponseHelper.buildResponse(unitInfoServiceImpl.queryForUnitInfoPage(page));
	}


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/queryForDealerReviewPage")
    @ApiOperation(httpMethod = "GET",value = "经销商人员信息分页查询",  notes = "经销商人员信息分页查询")
    public ResponseModel<Page<ReviewDto>> queryForDealerReviewPage(@RequestParam(value = "current") int current, @RequestParam
            (value = "size") int size,  ReviewDto reviewDto) {
        Page<ReviewDto> page=dealerReviewServiceImpl.queryForDealerReviewPage(current,size,reviewDto);
        return ResponseHelper.buildResponse(page);
    }



	/**
	 * 列表全部数据查询
     *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "GET",value = "经销商人员信息列表全部数据查询",   notes = "经销商人员信息列表全部数据查询")
	@GetMapping(value = "/list")
	public ResponseModel<List<UnitInfoDto>> selectForList() {
	    return ResponseHelper.buildResponse(unitInfoServiceImpl.queryForUnitInfoList());
	}


	/**
	 * 管理员身份证图片上传 无token
	 *
	 * @return
	 */
	@TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/uploadFile")
	@ApiOperation(httpMethod = "POST", value = "管理员身份证图片上传 无token", notes = "管理员身份证图片上传 无token")
	public ResponseModel<String> uploadFile(@ApiParam(value = "文件", required = true)@RequestParam MultipartFile file) {
		if (ValidationUtil.isEmpty(file)){
			throw new BadRequest("参数校验失败.");
		}
		RequestContext.setAppKey("AMOS_STUDIO");
		RequestContext.setProduct("AMOS_STUDIO_WEB");
		RequestContext.setToken(requestContext.getToken());
		FeignClientResult<Map<String, String>> date = Systemctl.fileStorageClient.updateCommonFile(file);
		String urlString="";
		if (date != null) {
			Map<String, String> map = date.getResult();
			Iterator<String> it = map.keySet().iterator();
			while (it.hasNext()) {
				urlString=it.next();
			}
		}
		return ResponseHelper.buildResponse(urlString);
	}

	/**
	 * 获取组织机构树
	 * @return
	 */
	@TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/region/tree")
	@ApiOperation(httpMethod = "GET", value = "获取组织机构树", notes = "获取组织机构树")
	public ResponseModel<Collection<RegionModel>> getRegionTree() {
		RequestContext.setAppKey("AMOS_STUDIO");
		RequestContext.setProduct("AMOS_STUDIO_WEB");
		RequestContext.setToken(requestContext.getToken());
		return  ResponseHelper.buildResponse(Systemctl.regionClient.queryForTree(null).getResult());
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@GetMapping(value = "/management-unit/tree")
	@ApiOperation(httpMethod = "GET", value = "管辖机构树", notes = "管辖机构树")
	public ResponseModel<Collection<CompanyModel>> managementUnitTree(@RequestParam(required = false)String orgCode) {
		RequestContext.setAppKey("AMOS_STUDIO");
		RequestContext.setProduct("AMOS_STUDIO_WEB");
		RequestContext.setToken(requestContext.getToken());

        FeignClientResult<Collection<CompanyModel>> feignClientResult=  Privilege.companyClient.querySubAgencyTree(regionalCompanies);

        Collection<CompanyModel>  companyModel = (List<CompanyModel>)feignClientResult.getResult();
		return ResponseHelper.buildResponse(companyModel);
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@PostMapping(value = "/unitRegister")
	@ApiOperation(httpMethod = "POST", value = "单位注册", notes = "单位注册")
    @Transactional
	public ResponseModel<UnitRegisterDto> save(@RequestBody UnitRegisterDto model) {
		try {

		    //判断公司名称重复，
            LambdaQueryWrapper<UnitInfo> qudg=new LambdaQueryWrapper<>();
            qudg.eq(UnitInfo::getName,model.getUnitInfoDto().getName());
            qudg.eq(UnitInfo::getIsDelete,0);
            qudg.ne(UnitInfo::getAuditStatus,3);
            List<UnitInfo> unitInfo= unitInfoMapper.selectList(qudg);
            if(unitInfo!=null&&!unitInfo.isEmpty()){

                throw new BadRequest("公司名称重复");
            }

            //判断公司统一信息用代码重复
            List<CommerceInfo> commerceInfo=  commerceInfoMapper.selectListby( model.getCommerceInfoDto().getCreditCode());
            if(commerceInfo!=null&&!commerceInfo.isEmpty()){

                throw new BadRequest("统一信用代码重复");
            }

            //用户名重复
            LambdaQueryWrapper<UnitInfo> qudg1=new LambdaQueryWrapper<>();
            qudg1.eq(UnitInfo::getAdminLoginName,model.getUnitInfoDto().getAdminLoginName());
            qudg1.eq(UnitInfo::getIsDelete,0);
            qudg1.ne(UnitInfo::getAuditStatus,3);
            List<UnitInfo> unitInfo1= unitInfoMapper.selectList(qudg1);
            if(unitInfo1!=null&&!unitInfo1.isEmpty()){

                throw new BadRequest("管理员账户名重复,请更换");
            }

            LambdaQueryWrapper<PublicAgencyUser> qud2=new LambdaQueryWrapper<>();
            qud2.eq(PublicAgencyUser::getAmosUserName,model.getUnitInfoDto().getAdminLoginName());
            List<PublicAgencyUser> publicAgencyUse=  publicAgencyUserMapper.selectList(qud2);
            if(publicAgencyUse!=null&&!publicAgencyUse.isEmpty()){

                throw new BadRequest("管理员账户名重复,请更换");
            }



			RequestContext.setAppKey("AMOS_STUDIO");
			RequestContext.setProduct("AMOS_STUDIO_WEB");
			RequestContext.setToken(requestContext.getToken());
			model = unitInfoServiceImpl.registerUnit(model);
			return ResponseHelper.buildResponse(model);
		} catch (Exception e) {
			ResponseModel<UnitRegisterDto> response = new ResponseModel<>();
			HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
			response.setResult(null);
			response.setDevMessage(e.getMessage());
			response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
			response.setTraceId(RequestContext.getTraceId());
			response.setPath(request.getServletPath());
			return response;
		}

	}

	public List<CommonFile>  toCommonFile(String url){

        List<CommonFile> list=new ArrayList<>();
        CommonFile commonFile=new CommonFile(url, url.substring(url.lastIndexOf(File.separator)+1), UUID.randomUUID().toString(), "done");
        list.add(commonFile);
        return list;
    }




    /**
     * 判断用户名是否存在
     *
     * @return
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/hasExistUserName/{userName}")
    @ApiOperation(httpMethod = "GET", value = "判断用户名是否存在", notes = "判断用户名是否存在")
    public ResponseModel hasExistUserName( @PathVariable(value = "userName") String userName) {
        try {
            return CommonResponseNewUtil.success(unitInfoServiceImpl.hasExistPhoneOrUserName(null, userName));
        } catch (Exception e) {
            return CommonResponseNewUtil.failure("该用户名已经注册");
        }
    }



	/**
	 * 判断用户号码是否存在
	 *
	 * @return
	 */
	@TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/hasExistPhone/{phone}")
	@ApiOperation(httpMethod = "GET", value = "判断用户号码是否存在", notes = "判断用户号码是否存在")
	public ResponseModel hasExistPhone( @PathVariable(value = "phone") String phone) {
		try {
			return CommonResponseNewUtil.success(unitInfoServiceImpl.hasExistPhoneOrUserName(phone, null));
		} catch (Exception e) {
			return CommonResponseNewUtil.failure("该手机号已经注册");
		}
	}

	/**
	 * 发送手机号验证码
	 *
	 * @return
	 */
	@TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/sendTelCode/{tel}")
	@ApiOperation(httpMethod = "GET", value = "发送手机号验证码", notes = "发送手机号验证码")
	public ResponseModel<Boolean> sendTelCode(@PathVariable(value = "tel") String tel,
											  @RequestParam(value = "type", required = false) String type) {

		if (ValidationUtil.isEmpty(tel)) {
			throw new BadRequest("参数校验失败.");
		}
		Boolean flag = true;
		HashMap<String, String> params = new HashMap<>(3);
		String code = this.getRandomCode();
		params.put("code",code);
		params.put("mobile",tel);
		params.put("smsCode", smsTempCode);
		try {
//			sendSmsCode.sendSmsCode(tel, s);
			Systemctl.smsClient.sendCommonSms(params).getResult();
			// code 保存到缓存中
			redisUtil.set(HYGF_USER_TEL + tel, code, time);
		} catch (Exception e) {

			throw new BadRequest("发送短信失败：" + e.getMessage());
		}
		return ResponseHelper.buildResponse(flag);
	}

	/**
	 * 验证手机号验证码是否成功
	 *
	 * @return
	 */
	@TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/verifyTelCode/{tel}/{code}")
	@ApiOperation(httpMethod = "GET", value = "验证手机号验证码是否成功", notes = "验证手机号验证码是否成功")
	public ResponseModel<Boolean> verifyTelCode(@PathVariable(value = "tel") String adminTel, @PathVariable(value = "code") String code) {
		Boolean flag = false;
		if (ValidationUtil.isEmpty(adminTel) || ValidationUtil.isEmpty(code)) {
			throw new BadRequest("参数校验失败.");
		}
		if(redisUtil.hasKey(HYGF_USER_TEL + adminTel)) {
			String redisCode = redisUtil.get(HYGF_USER_TEL + adminTel).toString();
			if(code.equals(redisCode)) {
				flag = true;
			}
		}
		return ResponseHelper.buildResponse(flag);
	}

	private String getRandomCode(){
		String code = "";
		Random random = new Random();
		for (int i = 0; i < 6; i++) {
			int r = random.nextInt(10);
			if(r==0){
			    r=1;
            }
			code = code + r;
		}
		return code;

	}




    /**
     * 列表全部数据查询
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "POST",value = "经销商审核",   notes = "经销商审核")
    @PostMapping(value = "/powerStationExamine")
    public ResponseModel<String> powerStationExamine(@RequestParam(value = "pageId") long pageId,
                                                     @RequestParam(value = "nodeCode") String nodeCode,
                                                     @RequestParam(value = "stationId") String stationId,
                                                     @RequestParam(value = "taskId") String taskId,
                                                     @RequestParam(value = "planInstanceId") String planInstanceId,
                                                     @RequestBody Map<String, Object> kv) {
        return ResponseHelper.buildResponse(unitInfoServiceImpl.powerStationExamine(pageId, nodeCode, stationId, taskId, planInstanceId, kv));
    }




    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET",value = "经销商人员加入黑名单/撤销黑名单",   notes = "经销商人员加入黑名单/撤销黑名单")
    @GetMapping(value = "/updateUser")
    public ResponseModel<Object> updateUser(String adminUserId ,String sequenceNbr ,String type) {
        FeignClientResult<List<String>>  userResult =null;
        UnitInfo unitInfo= unitInfoServiceImpl.getById(sequenceNbr);

           if("LOCK".equals(type)){
               userResult =   Privilege.agencyUserClient.lockUsers(adminUserId);
               unitInfo.setBlacklist(1);
           }else{
               userResult = Privilege.agencyUserClient.unlockUsers(adminUserId);
               unitInfo.setBlacklist(0);
           }
        return ResponseHelper.buildResponse(unitInfoServiceImpl.updateById(unitInfo));
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET",value = "获取经销商单位",   notes = "获取经销商单位")
    @GetMapping(value = "/getUnit")
    public ResponseModel< List<UnitInfo>> getUnit( @RequestParam(required = false)String amosCompanySeq) {

        LambdaQueryWrapper<UnitInfo> unitInfoque=new LambdaQueryWrapper<>();

        unitInfoque.eq(!ValidationUtil.isEmpty(amosCompanySeq),UnitInfo::getAmosCompanySeq,amosCompanySeq);
        unitInfoque.eq(UnitInfo::getAuditStatus,2);
        List<UnitInfo>  list=unitInfoMapper.selectList(unitInfoque);

        return ResponseHelper.buildResponse(list);


    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getUnitDataDto")
    @ApiOperation(httpMethod = "GET", value = "获取组织机构树", notes = "获取组织机构树")
    public ResponseModel<UnitDataDto> getUnitDataDto() {

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

        UnitDataDto unitDataDto = unitInfoServiceImpl.getUnitDataDto(userUnitInformationDto.getAmosDealerId());
        return  ResponseHelper.buildResponse(unitDataDto);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @PostMapping (value = "/updateUnitDataDto")
    @ApiOperation(httpMethod = "POST", value = "修改单位信息", notes = "修改单位信息")
    public ResponseModel<Boolean> updateUnitDataDto(@RequestBody UnitDataDto unitDataDto) {
        return  ResponseHelper.buildResponse(unitInfoServiceImpl.updateUnitDataDto(unitDataDto));
    }

    //获取经销商组织机构
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getUnit/tree")
    @ApiOperation(httpMethod = "GET", value = "管辖机构树", notes = "管辖机构树")
    public ResponseModel<List<CompanyModel>> unitTree() {


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

        CompanyModel companyM= new CompanyModel();

        companyM.setCompanyName(userUnitInformationDto.getAmosDealerName());
        companyM.setSequenceNbr(userUnitInformationDto.getAmosDealerId());
        companyM.setOrgCode(userUnitInformationDto.getAmosDealerOrgCode());

        FeignClientResult<Collection<CompanyModel>> feignClientResult;
        Collection<CompanyModel>  children=null;
        try {
            feignClientResult = Privilege.companyClient.querySubAgencyTree(userUnitInformationDto.getAmosDealerId());
            children =  feignClientResult.getResult();

        } catch (InnerInvokException e) {
            e.printStackTrace();
        }
        companyM.setChildren(children);
        List<CompanyModel> data=new ArrayList<>();
        data.add(companyM);
        return ResponseHelper.buildResponse(data);
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getCompanyModelList")
    @ApiOperation(httpMethod = "GET",value = "分页查询",  notes = "分页查询")
    public ResponseModel<IPage<CompanyDto>> getCompanyModelList(CompanyDto dto) {

        String  userid= getUserInfo().getUserId();
        LambdaQueryWrapper<PublicAgencyUser> qud=new LambdaQueryWrapper<>();
        qud.eq(PublicAgencyUser::getAmosUserId,userid);
        PublicAgencyUser publicAgencyUse=  publicAgencyUserMapper.selectOne(qud);
        LambdaQueryWrapper<PersonnelBusiness> qug=new LambdaQueryWrapper<>();
        qug.eq(PersonnelBusiness::getFoundationId,publicAgencyUse.getSequenceNbr());
        PersonnelBusiness personnelBusines=personnelBusinessMapper.selectOne(qug);
        dto.setComid(personnelBusines.getAmosDealerId());

        Map<String,String> map= personnelBusinessMapper.getorgcode(dto.getCompanyTreeid());
        dto.setOrgCode(map.get("orgCode"));
        return ResponseHelper.buildResponse(unitInfoServiceImpl.getCompanyDto(dto));
    }


    //获取经销商组织机构
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getUnitTree")
    @ApiOperation(httpMethod = "GET", value = "管辖机构树", notes = "管辖机构树")
    public ResponseModel<Collection<CompanyModel>> getUnitTree() {

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

        FeignClientResult<Collection<CompanyModel>> feignClientResult;
        Collection<CompanyModel>  children=null;
        try {
            feignClientResult = Privilege.companyClient.querySubAgencyTree(userUnitInformationDto.getAmosDealerId());
            children =  feignClientResult.getResult();

        } catch (InnerInvokException e) {
            e.printStackTrace();
        }


        return ResponseHelper.buildResponse(children);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getRegionalCompaniesTree")
    @ApiOperation(httpMethod = "GET", value = "区域公司", notes = "区域公司")
    public ResponseModel<List<RegionalCompanies>> getRegionalCompaniesTree() {
        String  userid= getUserInfo().getUserId();
        LambdaQueryWrapper<PublicAgencyUser> qud=new LambdaQueryWrapper<>();
        qud.eq(PublicAgencyUser::getAmosUserId,userid);

        PublicAgencyUser publicAgencyUse=  publicAgencyUserMapper.selectOne(qud);
        LambdaQueryWrapper<PersonnelBusiness> qug=new LambdaQueryWrapper<>();
        qug.eq(PersonnelBusiness::getFoundationId,publicAgencyUse.getSequenceNbr());
        PersonnelBusiness personnelBusines=personnelBusinessMapper.selectOne(qug);

        LambdaQueryWrapper<RegionalCompanies> qu=new LambdaQueryWrapper<>();
        qu.eq(RegionalCompanies::getUnitId,personnelBusines.getAmosDealerId());
        List<RegionalCompanies> data= regionalCompaniesMapper.selectList(qu);
        return ResponseHelper.buildResponse(data);
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getGroupTree")
    @ApiOperation(httpMethod = "GET", value = "经销商用户组", notes = "经销商用户组")
    public ResponseModel<Collection<GroupModel>> getGroupTree() {

        FeignClientResult<Collection<GroupModel>>  feignClientResult= Privilege.groupClient.selectForList(group,null);
        Collection<GroupModel> children =  feignClientResult.getResult();
        Collection<GroupModel> chil =new ArrayList<>();
        for (GroupModel child : children) {
            if("户用光伏-经销商-管理员".equals(child.getGroupName())||"用户光伏-农户".equals(child.getGroupName())||"户用光伏-经销商-空角色".equals(child.getGroupName())){
            //排除其余角色
            }else{
                chil.add(child);
            }
        }
        return ResponseHelper.buildResponse(chil);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getGroupTreeAll")
    @ApiOperation(httpMethod = "GET", value = "经销商用户组全部", notes = "经销商用户组全部")
    public ResponseModel<Collection<GroupModel>> getGroupTreeAll() {

        FeignClientResult<Collection<GroupModel>>  feignClientResult= Privilege.groupClient.selectForList(group,null);
        Collection<GroupModel> children =  feignClientResult.getResult();
        Collection<GroupModel> chil =new ArrayList<>();
        for (GroupModel child : children) {
            if("用户光伏-农户".equals(child.getGroupName())){
                //排除其余角色
            }else{
                chil.add(child);
            }
        }
        return ResponseHelper.buildResponse(chil);
    }


    //根据角色获取区域公司
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getRegionalCompanies")
    @ApiOperation(httpMethod = "GET", value = "根据角色获取区域公司", notes = "根据角色获取区域公司")
    public ResponseModel<Collection<CompanyModel>> getRegionalCompanies() {

        AgencyUserModel agencyUserModel= getUserInfo();
        String org=agencyUserModel.getOrgNames();
        Collection<CompanyModel> companyModel=new ArrayList<>();
        if(org.contains("-经销商")){
            String  userid= agencyUserModel.getUserId();
            LambdaQueryWrapper<PublicAgencyUser> qud=new LambdaQueryWrapper<>();
            qud.eq(PublicAgencyUser::getAmosUserId,userid);

            PublicAgencyUser publicAgencyUse=  publicAgencyUserMapper.selectOne(qud);
            LambdaQueryWrapper<PersonnelBusiness> qug=new LambdaQueryWrapper<>();
            qug.eq(PersonnelBusiness::getFoundationId,publicAgencyUse.getSequenceNbr());
            PersonnelBusiness personnelBusines=personnelBusinessMapper.selectOne(qug);
            if(org.contains("户用光伏-经销商-管理员")){
                //如果是经销商管理员
                LambdaQueryWrapper<RegionalCompanies> qu=new LambdaQueryWrapper<>();
                qu.eq(RegionalCompanies::getUnitId,personnelBusines.getAmosDealerId());
                List<RegionalCompanies> data= regionalCompaniesMapper.selectList(qu);
                if(data!=null&&!data.isEmpty()){
                    for (RegionalCompanies datum : data) {
                        CompanyModel co=new CompanyModel();
                        co.setSequenceNbr(datum.getRegionalCompaniesSeq());
                        co.setCompanyName(datum.getRegionalCompaniesName());
                        co.setOrgCode(datum.getRegionalCompaniesCode());
                        companyModel.add(co);
                    }
                }
            }else{
                //如果是经销商普通员工
                CompanyModel co=new CompanyModel();
                co.setSequenceNbr(personnelBusines.getRegionalCompaniesSeq());
                co.setCompanyName(personnelBusines.getRegionalCompaniesName());
                co.setOrgCode(personnelBusines.getRegionalCompaniesCode());
                companyModel.add(co);
            }
        }else{
        //如果是管理端
            FeignClientResult<Collection<CompanyModel>> feignClientResult=  Privilege.companyClient.querySubAgencyTree(regionalCompanies);

             companyModel = (List<CompanyModel>)feignClientResult.getResult();
        }
       return  ResponseHelper.buildResponse(companyModel);
    }






    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET",value = "获取审核通过的经销商",   notes = "获取审核通过的经销商")
    @GetMapping(value = "/getlistUnitInfo")
    @UserLimits
    public ResponseModel<List<UnitInfo>> getlistUnitInfo() {

//       LambdaQueryWrapper<UnitInfo> qu=new LambdaQueryWrapper();
//        qu.eq(UnitInfo::getIsDelete,false);
//        qu.eq(UnitInfo::getAuditStatus,2);
 //       List<UnitInfo> list=unitInfoMapper.selectList(qu);

        List<UnitInfo> list=unitInfoMapper.getlistUnitInfo();
        return ResponseHelper.buildResponse(list);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET",value = "列表全部数据查询",   notes = "列表全部数据查询")
    @GetMapping(value = "/getRegionalCompanie")
    @UserLimits
    public ResponseModel< List<RegionalCompanies> > getRegionalCompanie(
            @RequestParam(required=false) Long sequenceNbr
    ) {
//       LambdaQueryWrapper<RegionalCompanies> qu=new LambdaQueryWrapper();
//        qu.eq(RegionalCompanies::getUnitInfoId,sequenceNbr);
//        qu.eq(RegionalCompanies::getIsDelete,false);
//        List<RegionalCompanies>  list=regionalCompaniesMapper.selectList(qu);

        List<RegionalCompanies>  list=regionalCompaniesMapper.selectListRegionalCompanies(sequenceNbr);
        return ResponseHelper.buildResponse(list);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET",value = "列表全部数据查询",   notes = "列表全部数据查询")
    @GetMapping(value = "/getRegionalCompanieById")
    public ResponseModel< RegionalCompanies > getRegionalCompanieById(
            @RequestParam(required=false) Long regionalCompaniesSeq,
            @RequestParam(required=false) Long unitInfoId
    ) {
        LambdaQueryWrapper<RegionalCompanies> qu=new LambdaQueryWrapper();
        qu.eq(RegionalCompanies::getRegionalCompaniesSeq,regionalCompaniesSeq);
        qu.eq(RegionalCompanies::getUnitInfoId,unitInfoId);
        qu.eq(RegionalCompanies::getIsDelete,false);
        RegionalCompanies  list=regionalCompaniesMapper.selectOne(qu);
        return ResponseHelper.buildResponse(list);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET",value = "列表全部数据查询",   notes = "列表全部数据查询")
    @GetMapping(value = "/getRegionalCompanieUnitInfo")
    public ResponseModel< List<RegionalCompanies> > getRegionalCompanieUnitInfo(
            @RequestParam(required=false) Long unitInfoId,
            @RequestParam(required=false) Long regionalCompaniesSeq
    ) {
        LambdaQueryWrapper<RegionalCompanies> qu=new LambdaQueryWrapper();
        qu.eq(RegionalCompanies::getRegionalCompaniesSeq,regionalCompaniesSeq);
        qu.eq(RegionalCompanies::getUnitInfoId,unitInfoId);
        RegionalCompanies  list=regionalCompaniesMapper.selectOne(qu);
        UnitInfo unitInfo=unitInfoMapper.selectById(unitInfoId);
        List<RegionalCompanies> date=null;
        if(list!=null&&unitInfo!=null){
            list.setRegionalCompaniesName(unitInfo.getName()+"-"+list.getRegionalCompaniesName());
            date=new ArrayList();
            date.add(list);
        }
        return ResponseHelper.buildResponse(date);
    }
   //获取电站列表

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET",value = "列表全部数据查询",   notes = "列表全部数据查询")
    @GetMapping(value = "/getUnitInfoListData")
    public ResponseModel< List<Map<String,Object>> > getUnitInfoListData(
            @RequestParam(required=false) Long unitInfoId,
            @RequestParam(required=false) Long regionalCompaniesSeq
    ) {
        UnitInfo unitInfo=unitInfoMapper.selectById(unitInfoId);
        List<PeasantHousehold>  list=peasantHouseholdMapper.selectPeasantHouseholdList(unitInfo.getAmosCompanySeq(),regionalCompaniesSeq,null,null,null,null);
        List<Map<String,Object>> date=new ArrayList<>();

        if(list!=null){
            for (PeasantHousehold peasantHousehold : list) {
                Map<String,Object> map=new HashMap<>();
                map.put("children",new ArrayList<>());
                map.put("title",peasantHousehold.getPeasantHouseholdNo()+"-"+peasantHousehold.getOwnersName());
                map.put("value",peasantHousehold.getSequenceNbr());
                map.put("key",peasantHousehold.getSequenceNbr());
                date.add(map);
            }
        }
        return ResponseHelper.buildResponse(date);
    }
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET",value = "列表全部数据查询",   notes = "列表全部数据查询")
    @GetMapping(value = "/getPeasantHouseholdData")
    public ResponseModel<Page<PeasantHousehold>> getPeasantHouseholdData(
            @RequestParam(required=false) Long unitInfoId,
            @RequestParam(required=false) Long regionalCompaniesSeq,
            @RequestParam(value = "current") int current,
            @RequestParam (value = "size") int size,
            @RequestParam (required=false) String peasantHouseholdNo,
             @RequestParam (required=false) String ownersName,
            @RequestParam (required=false) String ids

    ) {
        return ResponseHelper.buildResponse(unitInfoServiceImpl.getPeasantHouseholdData( unitInfoId,regionalCompaniesSeq, current,size,peasantHouseholdNo,ownersName,ids));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET",value = "列表全部数据查询",   notes = "列表全部数据查询")
    @GetMapping(value = "/getPeasantHouseholdDataNew")
    public ResponseModel<Page<PeasantHousehold>> getPeasantHouseholdDataNew(
            @RequestParam(required=false) Long unitInfoId,
            @RequestParam(required=false) Long regionalCompaniesSeq,
            @RequestParam(value = "current") int current,
            @RequestParam (value = "size") int size,
            @RequestParam (required=false) String peasantHouseholdNo,
            @RequestParam (required=false) String ownersName,
            @RequestParam (required=false) String ids

    ) {
        return ResponseHelper.buildResponse(unitInfoServiceImpl.getPeasantHouseholdDataNew(unitInfoId, regionalCompaniesSeq, current, size, peasantHouseholdNo, ownersName, ids));
    }



/**获取当前登录人区域公司*/

@TycloudOperation(ApiLevel = UserType.AGENCY)
@ApiOperation(httpMethod = "GET",value = "列表全部数据查询",   notes = "列表全部数据查询")
@GetMapping(value = "/getRegionalCompanieByuser")
public ResponseModel< List<Map<String,Object>> > getRegionalCompanieByuser(
) {


    UserUnitInformationDto userUnitInformationDto=personnelBusinessMapper.getUserUnitInformationDto( getUserInfo().getUserId());
    List<Map<String,Object>> date=new ArrayList<>();
    if(userUnitInformationDto!=null&&userUnitInformationDto.getRegionalCompaniesSeq()!=null&&userUnitInformationDto.getRegionalCompaniesName()!=null){
        Map<String,Object> map=new HashMap<>();

        map.put("value",userUnitInformationDto.getRegionalCompaniesSeq());
        map.put("name",userUnitInformationDto.getRegionalCompaniesName());
        date.add(map);
    }
    return ResponseHelper.buildResponse(date);
}

    /***获取经销商，区域公司下 工程负责人**/

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET",value = "列表全部数据查询",   notes = "列表全部数据查询")
    @GetMapping(value = "/getuserList")
    public ResponseModel< List<Map<String,Object>> > getuserList( @RequestParam(required=false) Long role,
                                                                  @RequestParam(required=false) Long regionalCompaniesSeq

    ) {
        UserUnitInformationDto userUnitInformationDto=personnelBusinessMapper.getUserUnitInformationDto( getUserInfo().getUserId());
       // List<Map<String,Object>>  date= unitInfoMapper.getuserList(null,role,regionalCompaniesSeq,userUnitInformationDto.getAmosDealerId());
        List<Map<String,Object>>  date= unitInfoMapper.getuserListByOrgCode(null,role,regionalCompaniesSeq,userUnitInformationDto.getAmosDealerOrgCode());
        return ResponseHelper.buildResponse(date);
    }


    /***获取经销商，区域公司下 工程负责人**/

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET",value = "列表全部数据查询",   notes = "列表全部数据查询")
    @GetMapping(value = "/getuserListAll")
    public ResponseModel< List<Map<String,Object>> > getuserListAll( @RequestParam(required=false) Long role,
                                                                  @RequestParam(required=false) Long regionalCompaniesSeq

    ) {
        UserUnitInformationDto userUnitInformationDto=personnelBusinessMapper.getUserUnitInformationDto( getUserInfo().getUserId());
        List<Map<String,Object>>  date= unitInfoMapper.getuserListAllByOrgCode(null,role,regionalCompaniesSeq,userUnitInformationDto.getAmosDealerOrgCode());
        return ResponseHelper.buildResponse(date);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET",value = "列表全部数据查询",   notes = "列表全部数据查询")
    @GetMapping(value = "/getuserTelephone")
    public ResponseModel< Map<String,Object> > getuserTelephone( @RequestParam(required=false) String userName
    ) {      Map<String,Object> data=null;
            if(StringUtils.isNotEmpty(userName)){
                List<Map<String,Object>> date= unitInfoMapper.getuserListtelephone(userName,null,null,null);
                if(date!=null&&!date.isEmpty()){
                    data=date.get(0);
                }
            }


        return ResponseHelper.buildResponse(data);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET",value = "根据userId查询手机号",   notes = "根据userId查询手机号")
    @GetMapping(value = "/getUserTelephoneByUserId")
    public ResponseModel< Map<String,Object> > getUserTelephoneByUserId( @RequestParam(required=false) String userId
    ) {      Map<String,Object> data=null;
        if(StringUtils.isNotEmpty(userId)){
            List<Map<String,Object>> date= unitInfoMapper.getUserTelephoneByUserId(userId);
            if(date!=null&&!date.isEmpty()){
                data=date.get(0);
            }
        }


        return ResponseHelper.buildResponse(data);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @ApiOperation(httpMethod = "GET",value = "列表全部数据查询",   notes = "列表全部数据查询")
    @GetMapping(value = "/selectPeasantHouseholdListsg")
    public ResponseModel<Page<PeasantHousehold>> selectPeasantHouseholdListsg(
            @RequestParam(required=false) Long regionalCompaniesSeq,
            @RequestParam(value = "current") int current,
            @RequestParam (value = "size") int size,
            @RequestParam (required=false) String peasantHouseholdNo,
            @RequestParam (required=false) String ownersName,
            @RequestParam (required=false) String ids

    ) {
        UserUnitInformationDto userUnitInformationDto=personnelBusinessMapper.getUserUnitInformationDto( getUserInfo().getUserId());
        return ResponseHelper.buildResponse(unitInfoServiceImpl.selectPeasantHouseholdListsg( userUnitInformationDto.getAmosDealerOrgCode(),regionalCompaniesSeq, current,size,peasantHouseholdNo,ownersName, ids));
    }

}
