package com.yeejoin.amos.boot.module.jczs.flc.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.RedisKey;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.common.api.entity.OrgUsr;
import com.yeejoin.amos.boot.module.common.biz.service.impl.OrgUsrServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.utils.CommonResponseUtil;
import com.yeejoin.amos.boot.module.jczs.flc.biz.service.impl.UnitInfoChangeServiceImpl;
import com.yeejoin.amos.boot.module.jczs.flc.biz.service.impl.UnitInfoServiceImpl;
import com.yeejoin.amos.boot.module.jczs.biz.service.impl.TzsAuthServiceImpl;
import com.yeejoin.amos.boot.module.jczs.biz.utils.BeanDtoVoUtils;
import com.yeejoin.amos.boot.module.jczs.flc.api.dto.UnitInfoApproveDto;
import com.yeejoin.amos.boot.module.jczs.flc.api.dto.UnitInfoDto;
import com.yeejoin.amos.boot.module.jczs.flc.api.entity.UnitInfo;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
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.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.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
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 java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * 企业信息表
 *
 * @author system_generator
 * @date 2021-11-11
 */
@RestController
@Api(tags = "企业信息表Api")
@RequestMapping(value = "/flc-unit-info")
public class UnitInfoController extends BaseController {

	@Autowired
	RedisUtils redisUtils;

	/**
	 * token 过期时间，wechat 系统为7200 ，tzs 系统小于7200 防止获取到无效token
	 */
	private long time = 600l;

	/**
	 * 企业管理员变更缓存key前缀
	 */
	private final  String adminChange = "ADMIN_CHANGE_";

    @Autowired
    UnitInfoServiceImpl unitInfoServiceImpl;

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


	@Autowired
	private TzsAuthServiceImpl tzsAuthServiceImpl;

    @Autowired
    OrgUsrServiceImpl iOrgUsrService;

	@Autowired
    UnitInfoChangeServiceImpl unitInfoChangeServiceImpl;

	/**
	 * 获取组织机构树
	 *
	 * @return
	 */
	//@TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
	@TycloudOperation(ApiLevel = UserType.ANONYMOUS, needAuth = false)
	@GetMapping(value = "/region/tree")
	@ApiOperation(httpMethod = "GET", value = "获取组织机构树", notes = "获取组织机构树")
	public ResponseModel<Collection<RegionModel>> getRegionTree(@RequestParam(value = "parentId",required = false) Long parentId) {
		tzsAuthServiceImpl.setRequestContext();
		Collection<RegionModel> result = null;
		if(parentId == null) {
			result = Systemctl.regionClient.queryForTree(null).getResult();
		} else {
			result = Systemctl.regionClient.querySubAgencyTree(parentId).getResult();
		}
		despace(result);
		return ResponseHelper.buildResponse(result);
	}

	/**
	 * 去区域树中level多余空格
	 * @param result
	 */
	public void despace(Collection<RegionModel> result){
		Iterator<RegionModel> iterator = result.iterator();
		while(iterator.hasNext()) {
			RegionModel regionModel = iterator.next();
			regionModel.setLevel(regionModel.getLevel().trim());
			regionModel.setLevelName(regionModel.getLevelName().trim());
			if(!ValidationUtil.isEmpty(regionModel.getChildren())) {
				despace(regionModel.getChildren());
			}
		}
	}

	/**
	 * 获取管辖单位树
	 *
	 * @return
	 */
	@TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/managerment/tree")
	@ApiOperation(httpMethod = "GET", value = "获取管辖单位树", notes = "获取管辖单位树")
	public ResponseModel<Collection<CompanyModel>> getManagermentTree() {
		Collection<CompanyModel> result = null;
		result = Privilege.companyClient.companyTreeWithoutAuth().getResult();
		// 隐藏company 数据
		Iterator<CompanyModel> it = result.iterator();
		while(it.hasNext()) {
			CompanyModel temp = it.next();
			if("emergencyCenter".equals(temp.getLevel())  || "company".equals(temp.getLevel())) {
				it.remove();
			} else {
				this.dealCompanyTree(temp);
			}
		}
		return ResponseHelper.buildResponse(result);
	}



	/**
	 * 企业信息图片上传 无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("参数校验失败.");
		}
		tzsAuthServiceImpl.setRequestContext();
		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 = "/hasExistUnit/{organizationCode}")
	@ApiOperation(httpMethod = "GET", value = "判断组织机构是否存在", notes = "判断组织机构是否存在")
	public ResponseModel<Boolean> hasExistUnit( @PathVariable(value = "organizationCode") String organizationCode) {
		Boolean flag = false;
		UnitInfo temp = unitInfoServiceImpl.getOne(new LambdaQueryWrapper<UnitInfo>().eq(UnitInfo::getIsDelete,false).eq(UnitInfo::getOrganizationCode,organizationCode).eq(UnitInfo::getUnitStatus,"1").
				or().eq(UnitInfo::getIsChange,true).eq(UnitInfo::getOrganizationCode,organizationCode));
		if(temp != null) {
			flag = true;
		}
		return ResponseHelper.buildResponse(flag);
	}

	/**
	 * 判断组织机构是否存在
	 *
	 * @return
	 */
	@TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/hasExistUnit/{unitId}/{organizationCode}")
	@ApiOperation(httpMethod = "GET", value = "判断组织机构是否存在-更新", notes = "判断组织机构是否存在-更新")
	public ResponseModel<Boolean> hasExistUnitWithId( @PathVariable(value = "unitId") Long unitId,@PathVariable(value = "organizationCode") String organizationCode) {
		Boolean flag = false;
		UnitInfo temp = unitInfoServiceImpl.getOne(new LambdaQueryWrapper<UnitInfo>().eq(UnitInfo::getIsDelete,false).eq(UnitInfo::getOrganizationCode,organizationCode).ne(UnitInfo::getSequenceNbr,unitId).eq(UnitInfo::getUnitStatus,"1").or().eq(UnitInfo::getIsChange,true));
		if(temp != null) {
			flag = true;
		}
		return ResponseHelper.buildResponse(flag);
	}



	/**
	 * 判断用户是否存在
	 *
	 * @return
	 */
	@TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/hasExistUser/{userName}")
	@ApiOperation(httpMethod = "GET", value = "判断用户是否存在", notes = "判断用户是否存在")
	public ResponseModel<Boolean> hasExistUser( @PathVariable(value = "userName") String userName) {
		Boolean flag = false;
		AgencyUserModel user = Privilege.agencyUserClient.queryByUserName(userName).getResult();
		if(user != null ) {
			flag = true;
		}
		return ResponseHelper.buildResponse(flag);
	}

	/**
	 * 发送手机号验证码
	 *
	 * @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 = false;
		HashMap<String, String> params = new HashMap<>();
		String code = this.getRandomCode();
		params.put("code",code);
		params.put("mobile",tel);
		params.put("smsCode", smsTempCode);
		try {
			Systemctl.smsClient.sendCommonSms(params).getResult();
			flag = true;
   		} catch (Exception e) {
			throw new BadRequest("发送短信失败：" + e.getMessage());
		}
		String Key = ObjectUtils.isEmpty(type) ? RedisKey.FLC_USER_TEL : adminChange;
		// code 保存到缓存中
		redisUtils.set(Key + tel, code,time);
		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 tel,
												@PathVariable(value = "code") String code,
												@RequestParam(value = "type", required = false) String type) {
		Boolean flag = false;
		if (ValidationUtil.isEmpty(tel) || ValidationUtil.isEmpty(code)) {
			throw new BadRequest("参数校验失败.");
		}
		String Key = ObjectUtils.isEmpty(type) ? RedisKey.FLC_USER_TEL : adminChange;
		if(redisUtils.hasKey(Key + tel)) {
			String redisCode = redisUtils.get(Key + tel).toString();
			if(code.equals(redisCode)) {
				flag = true;
			}
		}
		// “超级验证码",压测使用
		if ("88888888".equals(code)) {
			flag = true;
		}
		return ResponseHelper.buildResponse(flag);
	}



    /**
     * 新增企业信息表
     *
     * @return
     */
    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/save")
	@ApiOperation(httpMethod = "POST", value = "新增企业信息表", notes = "新增企业信息表")
	public ResponseModel<UnitInfoDto> save(@RequestBody UnitInfoDto model) {
	    model = unitInfoServiceImpl.saveUnitInfo(model);
	    return ResponseHelper.buildResponse(model);
	}

    /**
     * 根据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) {
		if (ValidationUtil.isEmpty(sequenceNbr) ) {
			throw new BadRequest("参数校验失败.");
		}
	    return ResponseHelper.buildResponse(unitInfoServiceImpl.getUnitDtoById(sequenceNbr));
	}


	/**
	 * 列表分页查询
	 *
	 * @param pageNum  当前页
	 * @param pageSize 每页大小
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/list")
	@ApiOperation(httpMethod = "GET", value = "企业审核列表查询", notes = "企业审核列表查询")
	public ResponseModel<IPage<UnitInfoDto>> queryForPage(String pageNum, String pageSize, String sort, UnitInfoDto unitInfoDto) {
		// UnitInfo unitInfo = BeanDtoVoUtils.convert(unitInfoDto, UnitInfo.class);
		Page<UnitInfo> pageBean;
		IPage<UnitInfo> page;
		QueryWrapper<UnitInfo> unitInfoQueryWrapper = new QueryWrapper<UnitInfo>();

		setQueryWrapper(unitInfoQueryWrapper, unitInfoDto, sort);

		if (StringUtils.isBlank(pageNum) || StringUtils.isBlank(pageSize)) {
			pageBean = new Page<>(0, Long.MAX_VALUE);
		} else {
			pageBean = new Page<>(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
		}
		page = unitInfoServiceImpl.page(pageBean, unitInfoQueryWrapper);
		int num= unitInfoServiceImpl.count(unitInfoQueryWrapper);
		pageBean.setTotal(num);
		IPage<UnitInfoDto> unitInfoVoIPage = BeanDtoVoUtils.unitInfoIPageDto(page);
		return ResponseHelper.buildResponse(unitInfoVoIPage);
	}

	/**
	 * 根据企业名称查询详情
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/queryByOrgName")
	@ApiOperation(httpMethod = "GET", value = "根据企业名称查询详情", notes = "根据企业名称查询详情")
	public ResponseModel<UnitInfoDto> queryForPage(@RequestParam(value = "orgName") String orgName) {
		UnitInfoDto unitInfoDto = new UnitInfoDto();
		QueryWrapper<UnitInfo> unitInfoQueryWrapper = new QueryWrapper<UnitInfo>();
		unitInfoDto.setOrgName(orgName);
		setQueryWrapper(unitInfoQueryWrapper, unitInfoDto, null);
		List<UnitInfo> list = unitInfoServiceImpl.list(unitInfoQueryWrapper);
		unitInfoDto = BeanDtoVoUtils.convert(list.get(0), UnitInfoDto.class);
		return ResponseHelper.buildResponse(ValidationUtil.isEmpty(orgName) ? null : unitInfoDto);
	}

	private QueryWrapper<UnitInfo> setQueryWrapper(QueryWrapper<UnitInfo> queryWrapper, UnitInfoDto unitInfoDto,String sort) {
		queryWrapper.eq("is_delete", false);
		if(sort!=null) {  // 排序失效
			String[] date=  sort.split(",");
			if(date[1].equals("ascend")) {
				queryWrapper.orderByAsc(RedisKey.humpToLine(date[0]));
			}else {
				queryWrapper.orderByDesc(RedisKey.humpToLine(date[0]));
			}
		}else {
			queryWrapper.orderByDesc("submit_time");
		}

		if (!ValidationUtil.isEmpty(unitInfoDto.getIsChange())) { // 分类 注册 /  信息变更 0 注册 1 变更
			queryWrapper.eq("is_change",unitInfoDto.getIsChange());

		}

		if(!ValidationUtil.isEmpty(unitInfoDto.getSubmitTimeStart())) { // 提交时间
			queryWrapper.ge("submit_time",unitInfoDto.getSubmitTimeStart());
		}

		if(!ValidationUtil.isEmpty(unitInfoDto.getSubmitTimeEnd())) {  // 提交时间
			queryWrapper.le("submit_time",unitInfoDto.getSubmitTimeEnd());
		}

		if(!ValidationUtil.isEmpty(unitInfoDto.getUnitTypeCode())) {  // 单位类型
			queryWrapper.like("unit_type_code",unitInfoDto.getUnitTypeCode());
		}
		if(!ValidationUtil.isEmpty(unitInfoDto.getOrgName())) {  // 单位名称
			queryWrapper.like("org_name",unitInfoDto.getOrgName());
		}
		if(!ValidationUtil.isEmpty(unitInfoDto.getOrganizationCode())) {  // 组织机构代码/统一信用代码
			queryWrapper.like("organization_code",unitInfoDto.getOrganizationCode());
		}
		if(!ValidationUtil.isEmpty(unitInfoDto.getAdminName())) {  // 管理员
			queryWrapper.like("admin_name",unitInfoDto.getAdminName());
		}
		if(!ValidationUtil.isEmpty(unitInfoDto.getAdminTel())) {  // 管理员电话
			queryWrapper.like("admin_tel",unitInfoDto.getAdminTel());
		}

		if(!ValidationUtil.isEmpty(unitInfoDto.getUnitStatus())) {  // 审核状态
			queryWrapper.eq("unit_status",unitInfoDto.getUnitStatus());
		}

		if(!ValidationUtil.isEmpty(unitInfoDto.getLegalPerson())) {  // 法人
			queryWrapper.like("legal_person",unitInfoDto.getLegalPerson());
		}


		if(!ValidationUtil.isEmpty(unitInfoDto.getLegalPersonTel())) {  // 法人电话
			queryWrapper.like("legal_person_tel",unitInfoDto.getLegalPersonTel());
		}

		return queryWrapper;
	}



	private String getRandomCode(){
		String code = "";
		Random random = new Random();
		for (int i = 0; i < 6; i++) {
			int r = random.nextInt(10); //每次随机出一个数字（0-9）
			code = code + r;  //把每次随机出的数字拼在一起
		}
		return code;

	}


	/**
	 * 审批企业注册
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/approve")
	@ApiOperation(httpMethod = "POST", value = "审批企业注册", notes = "审批企业注册")
	public ResponseModel approve(@RequestBody UnitInfoApproveDto approveDto) {
		if (ValidationUtil.isEmpty(approveDto.getUnitId()) || ValidationUtil.isEmpty(approveDto.getApproveStatus())) {
			throw new BadRequest("参数校验失败.");
		}
		try {
			UnitInfoDto model = unitInfoServiceImpl.approve(approveDto);
			return CommonResponseUtil.success(model);
		} catch (Exception e) {
			return CommonResponseUtil.failure(e.getMessage());
		}
	}


    /**
     * 根据当前登录人获取企业信息
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getUserUnit")
    @ApiOperation(httpMethod = "GET",value = "根据当前登录人获取企业信息",  notes = "根据当前登录人获取企业信息")
    public ResponseModel<UnitInfoDto> getUserUnit() {
        AgencyUserModel user = Privilege.agencyUserClient.getme().getResult();
        List<CompanyModel> companys = user.getCompanys();
        UnitInfoDto result = new UnitInfoDto();
        for(CompanyModel c : companys) {
            OrgUsr temp = iOrgUsrService.getOne(new LambdaQueryWrapper<OrgUsr>().eq(OrgUsr::getIsDelete,false).eq(OrgUsr::getAmosOrgId,c.getSequenceNbr()));
            if(temp != null) {
            	// 企业信息查看判断是否变更 如果变更信息则返回变更中信息
				result = unitInfoServiceImpl.getDtoByOrgId(temp.getSequenceNbr());

            	if(result.getIsChange() && result.getUnitStatus() == 0) {
            		result = unitInfoChangeServiceImpl.findLastChangInfo(result.getSequenceNbr());
				}

                return ResponseHelper.buildResponse(result);
            }
        }
        return ResponseHelper.buildResponse(result);
    }

	/**
	 * 变更企业表
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/change")
	@ApiOperation(httpMethod = "POST", value = "变更企业表", notes = "变更企业表")
	public ResponseModel<UnitInfoDto> change(@RequestBody UnitInfoDto model) {
		try {
			model = unitInfoServiceImpl.changeUnInfo(model);
			return CommonResponseUtil.success(model);
		} catch (Exception e) {
			return CommonResponseUtil.failure(e.getMessage());
		}
	}

	/**
	 * 查询审批数据
	 *
	 * @param sequenceNbr  主键
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/approve/{sequenceNbr}")
	@ApiOperation(httpMethod = "GET",value = "查询审批数据",  notes = "查询审批数据")
	public ResponseModel<UnitInfoDto> getApproveInfo(@PathVariable Long sequenceNbr) {
		if (ValidationUtil.isEmpty(sequenceNbr) ) {
			throw new BadRequest("参数校验失败.");
		}
		return ResponseHelper.buildResponse(unitInfoServiceImpl.getDtoById(sequenceNbr));
	}


	/**
	 * 获取检验机构列表
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/getInspectionUnit")
	@ApiOperation(httpMethod = "GET", value = "获取检验机构列表", notes = "获取检验机构列表")
	public ResponseModel<List<UnitInfoDto>> getInspectionUnit() {
		List<UnitInfoDto> result = unitInfoServiceImpl.getInspectionUnit();
		return ResponseHelper.buildResponse(result);
	}

	/**
	 * 获取使用单位列表
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/getUseUnit")
	@ApiOperation(httpMethod = "POST", value = "获取使用单位列表", notes = "获取使用单位列表")
	public ResponseModel<List<UnitInfoDto>> getUseUnit(@RequestBody UnitInfoDto model) {

		List<UnitInfoDto> result = unitInfoServiceImpl.getUseUnit(model.getUnitType(),model.getAddress(),model.getOrgName(),model.getOrganizationCode());
		return ResponseHelper.buildResponse(result);
	}

	/**
	 * 获取所有单位列表
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/getAllUnit")
	@ApiOperation(httpMethod = "GET", value = "获取所有单位列表", notes = "获取所有单位列表")
	public ResponseModel<List<UnitInfoDto>> getAllUnit() {
		List<UnitInfoDto> result = unitInfoServiceImpl.getAllUnit();
		return ResponseHelper.buildResponse(result);
	}



	/**
	 * 列表分页查询
	 *
	 * @param pageNum  当前页
	 * @param pageSize 每页大小
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/listPassed")
	@ApiOperation(httpMethod = "GET", value = "企业审核列表查询-通过审核", notes = "企业审核列表查询-通过审核")
	public ResponseModel<IPage<UnitInfoDto>> queryForPagePassed(String pageNum, String pageSize, String sort, UnitInfoDto unitInfoDto) {
		unitInfoDto.setUnitStatus(1);
		Page<UnitInfo> pageBean;
		IPage<UnitInfo> page;
		QueryWrapper<UnitInfo> unitInfoQueryWrapper = new QueryWrapper<UnitInfo>();

		setQueryWrapper(unitInfoQueryWrapper, unitInfoDto, sort);

		if (StringUtils.isBlank(pageNum) || StringUtils.isBlank(pageSize)) {
			pageBean = new Page<>(0, Long.MAX_VALUE);
		} else {
			pageBean = new Page<>(Integer.parseInt(pageNum), Integer.parseInt(pageSize));
		}
		page = unitInfoServiceImpl.page(pageBean, unitInfoQueryWrapper);
		int num= unitInfoServiceImpl.count(unitInfoQueryWrapper);
		pageBean.setTotal(num);
		IPage<UnitInfoDto> unitInfoVoIPage = BeanDtoVoUtils.unitInfoIPageDto(page);
		return ResponseHelper.buildResponse(unitInfoVoIPage);
	}

	/**
	 * 判断用户号码是否存在
	 *
	 * @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 CommonResponseUtil.success(Privilege.agencyUserClient.checkLoginId(phone).getResult());
		} catch (Exception e) {
			return CommonResponseUtil.failure("该手机号已经注册");
		}
	}


	/**
	 * 手动生成已通过企业的二维码
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/addQRcode")
	@ApiOperation(httpMethod = "GET", value = "手动生成已通过企业的二维码", notes = "手动生成已通过企业的二维码")
	public ResponseModel<Boolean> addQRcode() {
		Boolean flag = unitInfoServiceImpl.addQRcode();
		return ResponseHelper.buildResponse(flag);
	}



	/**
	 * 根据当前登录人获取企业信息--编辑
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/getUserUnitEdit")
	@ApiOperation(httpMethod = "GET",value = "根据当前登录人获取企业信息--编辑",  notes = "根据当前登录人获取企业信息--编辑")
	public ResponseModel<UnitInfoDto> getUserUnitEdit() {
		AgencyUserModel user = Privilege.agencyUserClient.getme().getResult();
		List<CompanyModel> companys = user.getCompanys();
		UnitInfoDto result = new UnitInfoDto();
		for(CompanyModel c : companys) {
			OrgUsr temp = iOrgUsrService.getOne(new LambdaQueryWrapper<OrgUsr>().eq(OrgUsr::getIsDelete,false).eq(OrgUsr::getAmosOrgId,c.getSequenceNbr()));
			if(temp != null) {
				// 企业信息查看判断是否变更 如果变更信息则返回变更中信息
				result = unitInfoServiceImpl.getDtoByOrgId(temp.getSequenceNbr());
				return ResponseHelper.buildResponse(result);
			}
		}
		return ResponseHelper.buildResponse(result);
	}

	/**
	 * 根据uuid 获取 注册信息
	 *
	 * @return
	 */
	@TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/getUnitInfo/{uuid}")
	@ApiOperation(httpMethod = "GET", value = "根据uuid 获取注册信息", notes = "根据uuid 获取注册信息")
	public ResponseModel hasExistUnitWithId( @PathVariable String uuid) {
		UnitInfo temp = unitInfoServiceImpl.getOne(new LambdaQueryWrapper<UnitInfo>().eq(UnitInfo::getIsDelete,false).eq(UnitInfo::getCallbackId,uuid).eq(UnitInfo::getUnitStatus,"2"));
		if(temp != null) {
			return CommonResponseUtil.success(temp);
		} else {
			return CommonResponseUtil.failure("未找到该企业信息单，请确认链接地址或该单据已重新提交");
		}
	}


	private void dealCompanyTree(CompanyModel company) {
		if(!"emergencyCenter".equals(company.getLevel()) && !"company".equals(company.getLevel())) {
			// 判断子节点是否是headquarter
			Collection children = company.getChildren();
			if (!ValidationUtil.isEmpty(children)) {
				Iterator<Map> it = children.iterator();
				while(it.hasNext()) {
					Map temp =  it.next();
					if("emergencyCenter".equals(company.getLevel())  || "company".equals(company.getLevel())) {
						it.remove();
					} else {
						this.dealCompanyTree(temp);
					}
				}
			}
		}
	}
	private void dealCompanyTree(Map company) {
		// 判断子节点是否是headquarter
		Collection children = (Collection) company.get("children");
		if (!ValidationUtil.isEmpty(children)) {
			Iterator<Map> it = children.iterator();
			while(it.hasNext()) {
				Map temp = it.next();
				if("emergencyCenter".equals(temp.get("level")) || "company".equals(temp.get("level"))) {
					it.remove();
				} else {
					this.dealCompanyTree(temp);
				}
			}
		}
	}
}
