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.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 经销商人员信息
 *
 * @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 = 60L;

	// 常见的手机号正则表达式（以中国大陆手机号为例）
	private static final String PHONE_NUMBER_REGEX = "^1[3-9]\\d{9}$";

	/**
	 * 根据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,
			@ApiParam(value = "主键", example = "1706869110685569025") @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,
			@ApiParam(value = "主键", example = "1706869110685569025") @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(
			@ApiParam(value = "主键", example = "1706869110685569025") @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(
			@ApiParam(value = "主键", example = "1706869110685569025") @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(
			@ApiParam(value = "页码", example = "1") @RequestParam(value = "current") int current,
			@ApiParam(value = "页数大小", example = "20") @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(
			@ApiParam(value = "页码", example = "1") @RequestParam(value = "current") int current,
			@ApiParam(value = "页数大小", example = "20") @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("参数校验失败.");
		}
		List<String> ALLOWED_TYPES =Arrays.asList("jpg","jpeg","png");
		//只支持图片类型
		if (file.getContentType() == null || !file.getContentType().startsWith("image/")) {
			throw new BadRequest("只支持jpg,jpeg,png图片类型上传");
		}
		//判断文件后缀
		String filename = file.getOriginalFilename();
		String extension = filename.substring(filename.lastIndexOf('.') + 1).toLowerCase();
		if(!ALLOWED_TYPES.contains(extension)) 
		{
			throw new BadRequest("只支持jpg,jpeg,png图片类型上传");
		}
		//判断文件大小10M
		 if (file.getSize() > 10 * 1024 * 1024) { 
			 throw new BadRequest("上传文件大小不超过10M");
		 }
		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(
			@ApiParam(value = "区域Code", example = "86*355*443*479") @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(
			@ApiParam(value = "用户名", example = "admin") @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(
			@ApiParam(value = "手机号", example = "15895233587") @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(
			@ApiParam(value = "手机号", example = "15895233587") @PathVariable(value = "tel") String tel,
			@ApiParam(value = "类型", example = "1") @RequestParam(value = "type", required = false) String type) {

		if (ValidationUtil.isEmpty(tel)) {
			throw new BadRequest("参数校验失败");
		}
		Pattern pattern = Pattern.compile(PHONE_NUMBER_REGEX);
		Matcher matcher = pattern.matcher(tel);
		if (!matcher.matches()) {
			throw new BadRequest("请输入单个正确手机号");
		}
		String key = HYGF_USER_TEL + tel;
		if (redisUtil.get(key) != null) {
			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(key, 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(
			@ApiParam(value = "手机号", example = "15895233587") @PathVariable(value = "tel") String adminTel,
			@ApiParam(value = "验证码", example = "258546") @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(
			@ApiParam(value = "分页Id", example = "1706974721737756674") @RequestParam(value = "pageId") long pageId,
			@ApiParam(value = "节点Code", example = "1") @RequestParam(value = "nodeCode") String nodeCode,
			@ApiParam(value = "场站Id", example = "1711627029541031938") @RequestParam(value = "stationId") String stationId,
			@ApiParam(value = "任务Id", example = "1712383951215005697") @RequestParam(value = "taskId") String taskId,
			@ApiParam(value = "计划实例Id", example = "64ddb490-7261-11ef-b7e1-02420a1c0012") @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(@ApiParam(value = "管理员用户Id", example = "8121589") String adminUserId,
			@ApiParam(value = "主键", example = "1813102468876234754") String sequenceNbr,
			@ApiParam(value = "类型", example = "1") 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(
			@ApiParam(value = "经销商公司", example = "1702216914824097794") @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(
			@ApiParam(value = "主键", example = "1702216914824097794") @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(
			@ApiParam(value = "注册公司ID", example = "1702216914824097794") @RequestParam(required = false) Long regionalCompaniesSeq,
			@ApiParam(value = "人员Id", example = "1715318790759149570") @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(
			@ApiParam(value = "人员Id", example = "1715318790759149570") @RequestParam(required = false) Long unitInfoId,
			@ApiParam(value = "注册公司ID", example = "1702216914824097794") @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(
			@ApiParam(value = "人员Id", example = "1715318790759149570") @RequestParam(required = false) Long unitInfoId,
			@ApiParam(value = "注册公司ID", example = "1702216914824097794") @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(
			@ApiParam(value = "人员Id", example = "1715318790759149570") @RequestParam(required = false) Long unitInfoId,
			@ApiParam(value = "注册公司ID", example = "1702216914824097794") @RequestParam(required = false) Long regionalCompaniesSeq,
			@ApiParam(value = "页码", example = "1") @RequestParam(value = "current") int current,
			@ApiParam(value = "页数大小", example = "20") @RequestParam(value = "size") int size,
			@ApiParam(value = "农户ID", example = "1710823964114186242") @RequestParam(required = false) String peasantHouseholdNo,
			@ApiParam(value = "电站名称", example = "admin") @RequestParam(required = false) String ownersName,
			@ApiParam(value = "id", example = "1710823964114186242,1717088938155339777") @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(
			@ApiParam(value = "人员Id", example = "1715318790759149570") @RequestParam(required = false) Long unitInfoId,
			@ApiParam(value = "注册公司ID", example = "1702216914824097794") @RequestParam(required = false) Long regionalCompaniesSeq,
			@ApiParam(value = "页码", example = "1") @RequestParam(value = "current") int current,
			@ApiParam(value = "页数大小", example = "20") @RequestParam(value = "size") int size,
			@ApiParam(value = "农户ID", example = "1710823964114186242") @RequestParam(required = false) String peasantHouseholdNo,
			@ApiParam(value = "电站名称", example = "admin") @RequestParam(required = false) String ownersName,
			@ApiParam(value = "id", example = "1710823964114186242,1717088938155339777") @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(
			@ApiParam(value = "角色Id", example = "6582473") @RequestParam(required = false) Long role,
			@ApiParam(value = "注册区域Id", example = "1710823964114186242") @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(
			@ApiParam(value = "角色Id", example = "6582473") @RequestParam(required = false) Long role,
			@ApiParam(value = "注册区域Id", example = "1710823964114186242") @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(
			@ApiParam(value = "用户名称", example = "admin") @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(
			@ApiParam(value = "用户Id", example = "8542741") @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));
	}

}
