package com.yeejoin.amos.boot.module.tzs.flc.biz.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yeejoin.amos.boot.biz.common.constants.CommonConstant;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.biz.common.entity.DataDictionary;
import com.yeejoin.amos.boot.biz.common.service.impl.DataDictionaryServiceImpl;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.common.api.dto.OrgMenuDto;
import com.yeejoin.amos.boot.module.common.api.dto.OrgPersonDto;
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.tzs.flc.api.dto.UnitInfoDto;
import com.yeejoin.amos.boot.module.tzs.flc.api.dto.UnitPersonInfoDto;
import com.yeejoin.amos.boot.module.tzs.flc.api.entity.UnitInfo;
import com.yeejoin.amos.boot.module.tzs.flc.api.service.IUnitInfoService;
import com.yeejoin.amos.boot.module.tzs.flc.api.service.IUnitPersonService;
import com.yeejoin.amos.boot.module.tzs.flc.biz.service.impl.UnitInfoChangeServiceImpl;
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.ApplicationModel;
import com.yeejoin.amos.feign.privilege.model.CompanyModel;
import com.yeejoin.amos.feign.privilege.model.RoleModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
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.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 企业人员
 *
 * @author system_generator
 * @date 2021-11-11
 */
@RestController
@Api(tags = "企业人员Api")
@RequestMapping(value = "/flc-unit-person")
public class UnitPersonController extends BaseController {

	@Autowired
	RedisUtils redisUtils;

	@Autowired
	IUnitPersonService iUnitPersonService;

    @Autowired
    OrgUsrServiceImpl iOrgUsrService;

	@Autowired
	UnitInfoChangeServiceImpl unitInfoChangeServiceImpl;

	@Autowired
	DataDictionaryServiceImpl iDataDictionaryService;

	@Autowired
	IUnitInfoService iUnitInfoService;


	/**
	 * 新增人员信息
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@ApiOperation(httpMethod = "POST", value = "新增人员信息", notes = "新增人员信息")
	public ResponseModel<?> saveOrgUsr(@RequestBody UnitPersonInfoDto unitPersonInfoDto)  {
		if (ValidationUtil.isEmpty(unitPersonInfoDto.getParentId())) {
			throw new BadRequest("参数校验失败.");
		}
		return ResponseHelper.buildResponse( iUnitPersonService.saveUser(unitPersonInfoDto));
	}

	/**
	 * 新增人员信息
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@RequestMapping(value = "/saveSup", method = RequestMethod.POST)
	@ApiOperation(httpMethod = "POST", value = "新增监管人员信息", notes = "新增监管人员信息")
	public ResponseModel<?> saveSupOrgUsr(@RequestBody UnitPersonInfoDto unitPersonInfoDto)  {
		if (ValidationUtil.isEmpty(unitPersonInfoDto.getParentId()) ) {
			throw new BadRequest("参数校验失败.");
		}
		return ResponseHelper.buildResponse( iUnitPersonService.saveSupUser(unitPersonInfoDto));
	}

	/**
	 * 根据当前登录人获取企业信息列表 所在单位 以及  所属组织
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/companyTree")
	@ApiOperation(httpMethod = "GET",value = "根据当前登录人获取企业树（所在单位以及所属组织）",  notes = "根据当前登录人获取企业树（所在单位以及所属组织）")
	public ResponseModel<List<OrgMenuDto>> getUserUnit()  throws Exception {
		List<OrgMenuDto> menus = new ArrayList<>();
		OrgUsr temp = getMyUnit();
		if(temp != null) {
			menus = iOrgUsrService.getTreeFlc(Long.parseLong(temp.getAmosOrgId()), iOrgUsrService.selectCompanyDepartmentMsg(), OrgUsr.class.getName(), "getSequenceNbr", 2, "getBizOrgName", "getAmosOrgId", "getBizOrgType");
		}
		return ResponseHelper.buildResponse(menus);
	}


    /**
     * 根据所在单位生成人员code
     * @param companyId
     * @return
     * @throws Exception
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/getOrgCode/{companyId}")
    @ApiOperation(httpMethod = "GET",value = "根据所在单位生成人员code",  notes = "根据所在单位生成人员code")
    public ResponseModel<String> getOrgCode(@PathVariable Long companyId)  {
        OrgUsr company = iOrgUsrService.getById(companyId);
        String code = company.getBizOrgCode() + iOrgUsrService.getOrgCodeStr();
        return ResponseHelper.buildResponse(code);
    }

	/**
	 * 获取资质证书种类
	 * @return
	 * @throws Exception
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/getLicenceType")
	@ApiOperation(httpMethod = "GET",value = "获取资质证书种类",  notes = "获取资质证书种类")
	public ResponseModel<List<DataDictionary>> getLicenceType() {
		List<DataDictionary>  list = iDataDictionaryService.list(new LambdaQueryWrapper<DataDictionary>().eq(DataDictionary::getIsDelete,false).eq(DataDictionary::getType,"PERSON_QUALITY_TYPE").isNull(DataDictionary::getParent));
		return ResponseHelper.buildResponse(list);
	}

	/**
	 * 根据证书种类编号获取相关项目及代号
	 * @return
	 * @throws Exception
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/getProjectInfo/{licenceTypes}")
	@ApiOperation(httpMethod = "GET",value = "根据证书种类编号获取相关项目及代号",  notes = "根据证书种类编号获取相关项目及代号")
	public ResponseModel<List<DataDictionary>> getProjectInfo(@PathVariable String licenceTypes) {
		String[] licenceType = licenceTypes.split(",");
		List<DataDictionary>  list = iDataDictionaryService.list(new LambdaQueryWrapper<DataDictionary>().eq(DataDictionary::getIsDelete,false).eq(DataDictionary::getType,"PERSON_QUALITY_TYPE").in(DataDictionary::getParent,licenceType));
		return ResponseHelper.buildResponse(list);
	}

	/**
	 * 根据sequenceNbr查询
	 *
	 * @param sequenceNbr  主键
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/{sequenceNbr}")
	@ApiOperation(httpMethod = "GET",value = "根据sequenceNbr查询单个用户信息",  notes = "根据sequenceNbr查询单个用户信息")
	public ResponseModel<UnitPersonInfoDto> selectOne(@PathVariable Long sequenceNbr) {
		return ResponseHelper.buildResponse( iUnitPersonService.getPersonById(sequenceNbr));
	}

	/**
	 * 根据当前登录人获取人员信息 带分页搜索
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/listMyUnitPerson")
	@ApiOperation(httpMethod = "GET",value = "企业端-根据当前登录人获取人员信息 带分页搜索",  notes = "企业端-根据当前登录人获取人员信息 带分页搜索")
	public ResponseModel<Object> listMyUnitPerson(@RequestParam(required = false) Map<String, Object> requestBody)  {
		List<Long> unitIds = getMyUnitList();
		List<Long> parentIds = new ArrayList<>();
		unitIds.stream().forEach( id-> {
			OrgUsr unit = iOrgUsrService.getOne(new LambdaQueryWrapper<OrgUsr>().eq(OrgUsr::getIsDelete,false).eq(OrgUsr::getAmosOrgId,id));
			if(unit != null) {
				parentIds.add(unit.getSequenceNbr());
			}
		});
		if(parentIds.size() == 0) {
			parentIds.add(-1l);
		}
		return ResponseHelper.buildResponse(iUnitPersonService.pagePerson(parentIds,requestBody.get("pageNum").toString(),requestBody.get("pageSize").toString(), requestBody));
	}

	/**
	 * 企业端-根据当前登录人获取人员信息不分页
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/listMyUnitPersonAll")
	@ApiOperation(httpMethod = "GET",value = "企业端-根据当前登录人获取人员信息不分页",  notes = "企业端-据当前登录人获取人员信息不分页")
	public ResponseModel<Object> listMyUnitPerson()  {
		List<Long> unitIds = getMyUnitList();
		List<Long> parentIds = new ArrayList<>();
		unitIds.stream().forEach( id-> {
			OrgUsr unit = iOrgUsrService.getOne(new LambdaQueryWrapper<OrgUsr>().eq(OrgUsr::getIsDelete,false).eq(OrgUsr::getAmosOrgId,id));
			if(unit != null) {
				parentIds.add(unit.getSequenceNbr());
			}
		});
		if(parentIds.size() == 0) {
			parentIds.add(-1l);
		}
		return ResponseHelper.buildResponse(iUnitPersonService.pagePerson(parentIds,"1",Integer.MAX_VALUE+"", new HashMap<String, Object>()));
	}


	/**
	 * 获取本单位拥有的角色信息
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/listMyUnitRoles")
	@ApiOperation(httpMethod = "GET",value = "获取本单位拥有的角色信息",  notes = "获取本单位拥有的角色信息")
	public ResponseModel<List<RoleModel>> listMyUnitRoles() {
		FeignClientResult<List<RoleModel>> roleListResult = Privilege.roleClient.queryRoleList(null,null);
		List<RoleModel> userRoleList = new ArrayList<>();
		OrgUsr myUnit =  getMyUnit();
		if(myUnit != null) {
			UnitInfoDto unitInfo = iUnitInfoService.getDtoByOrgId(myUnit.getSequenceNbr());
			String unitType = unitInfo.getUnitType();
			String[] roles = unitType.split(",");
			List<RoleModel> allRoleList = roleListResult.getResult();
			allRoleList.stream().forEach(t -> {
				for(String roleName : roles) {
					if(t.getRoleName().equals(roleName)) {
						userRoleList.add(t);
					}
				}
			});
		}
		return ResponseHelper.buildResponse(userRoleList);
	}

	/**
	 * 获取本单位拥有的应用信息
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/listMyUnitApp")
	@ApiOperation(httpMethod = "GET",value = "获取本单位拥有的应用信息",  notes = "获取本单位拥有的应用信息")
	public ResponseModel<List<ApplicationModel>> listMyUnitApp() {
		List<ApplicationModel> allApp = Privilege.applicationClient.queryAgencyApplications().getResult();
		Set<String> appSet = new HashSet<>();
		OrgUsr myUnit =  getMyUnit();
		if(myUnit != null) {
			UnitInfoDto unitInfo = iUnitInfoService.getDtoByOrgId(myUnit.getSequenceNbr());
			String unitTypeCode = unitInfo.getUnitTypeCode();
			String[] unitTypeCodes = unitTypeCode.split(",");
			for(String code : unitTypeCodes) {
				DataDictionary unitType = iDataDictionaryService.getOne(new LambdaQueryWrapper<DataDictionary>().eq(DataDictionary::getCode,code));
				String appCode = unitType.getTypeDesc();
				String[] appCodes = appCode.split(",");
				for(String tempCode : appCodes) {
					appSet.add(tempCode);
				}
			}
		}
		allApp = allApp.stream().filter(t ->appSet.contains(t.getAppCode())).peek(System.out::println).collect(Collectors.toList());
		return ResponseHelper.buildResponse(allApp);
	}

	/**
	 * 获取本单位信息
	 * @return
	 */
	private OrgUsr getMyUnit() {
		OrgUsr myUnit = null;
		AgencyUserModel user = Privilege.agencyUserClient.getme().getResult();
		List<CompanyModel> companys = user.getCompanys();
		for(CompanyModel c : companys) {
			myUnit = iOrgUsrService.getOne(new LambdaQueryWrapper<OrgUsr>().eq(OrgUsr::getIsDelete,false).eq(OrgUsr::getAmosOrgId,c.getSequenceNbr()));
		}
		return myUnit;
	}


	/**
	 * 根据sequenceNbr删除
	 *
			 * @return
			 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@DeleteMapping(value = "/delete_batch")
	@ApiOperation(httpMethod = "DELETE", value = "批量删除人员信息", notes = "批量删除人员信息")
	public ResponseModel<Boolean> deleteBySequenceNbr(@RequestParam(value = "sequenceNbrList") List<Long> sequenceNbrList){
		return ResponseHelper.buildResponse(iUnitPersonService.batchDelete(sequenceNbrList));
	}


	/**
	 * 根据当前登录人获取人员信息 带分页搜索监管端
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/listUnitPerson")
	@ApiOperation(httpMethod = "GET",value = "监管端根据当前登录人获取人员信息 带分页搜索",  notes = "监管端根据当前登录人获取人员信息 带分页搜索")
	public ResponseModel<Object> listUnitPerson(@RequestParam(required = false) Map<String, Object> requestBody)   {

		List<Long> unitIds = getMyUnitList();
		List<Long> parentIds = new ArrayList<>();
		unitIds.stream().forEach( id-> {
			OrgUsr unit = iOrgUsrService.getOne(new LambdaQueryWrapper<OrgUsr>().eq(OrgUsr::getIsDelete,false).eq(OrgUsr::getAmosOrgId,id));
			if(unit != null) {
				parentIds.add(unit.getSequenceNbr());
			}
		});
		if(parentIds.size() == 0) {
			parentIds.add(-1l);
		}
		return ResponseHelper.buildResponse(iUnitPersonService.pagePerson(parentIds,requestBody.get("pageNum").toString(),requestBody.get("pageSize").toString(), requestBody));
	}



	/**
	 * 获取监管单位下子单位信息
	 * @return
	 */
	private List<Long> getMyUnitList() {
		Collection<CompanyModel> companys = Privilege.companyClient.treeByCompany(null).getResult();
		List<Long> companyIds = new ArrayList<Long>();
		for(CompanyModel c : companys) {
			getAllOrgIds(companyIds,c);
		}

		return companyIds;
	}

	private void getAllOrgIds(List<Long> ids, CompanyModel start) {
		ids.add(start.getSequenceNbr());
		if(start.getChildren() != null) {
			Collection<Map> children = start.getChildren();
			for(Map c : children) {
				getAllOrgIds(ids,  c);
			}
		}
	}

	private void getAllOrgIds(List<Long> ids, Map start) {
		ids.add(Long.parseLong(start.get("sequenceNbr").toString()));
		if(start.get("children") != null) {
			Collection<Map> children = (Collection<Map>) start.get("children");
			for(Map c : children) {
				getAllOrgIds(ids,  c);
			}
		}
	}

    /**
     * 监管端获取本单位人员信息 带分页搜索
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/listSupPerson")
    @ApiOperation(httpMethod = "GET",value = "监管端获取本单位人员信息 带分页搜索",  notes = "监管端获取本单位人员信息 带分页搜索")
    public ResponseModel<Object> listSupPerson(@RequestParam(required = false) Map<String, Object> requestBody)   {
        List<Long> unitIds = getMyUnitList();
        return ResponseHelper.buildResponse(iUnitPersonService.pagePerson(unitIds,requestBody.get("pageNum").toString(),requestBody.get("pageSize").toString(), requestBody));
    }

	/**
	 * 更新企业端人员信息
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@RequestMapping(value = "/updateUser", method = RequestMethod.PUT)
	@ApiOperation(httpMethod = "PUT", value = "更新企业端人员信息", notes = "更新企业端人员信息")
	public ResponseModel<?> updateUser(@RequestBody UnitPersonInfoDto unitPersonInfoDto)  {
		return ResponseHelper.buildResponse( iUnitPersonService.updateUser(unitPersonInfoDto));
	}

	/**
	 * 更新监管端人员信息
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@RequestMapping(value = "/updateSupUser", method = RequestMethod.PUT)
	@ApiOperation(httpMethod = "PUT", value = "更新监管端人员信息", notes = "更新监管端人员信息")
	public ResponseModel<?> updateSupUser(@RequestBody UnitPersonInfoDto unitPersonInfoDto)  {
		return ResponseHelper.buildResponse( iUnitPersonService.updateSupUser(unitPersonInfoDto));
	}



	/**
	 * 监管端-根据当前登录人获取企业列表
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/companyTreeSup")
	@ApiOperation(httpMethod = "GET",value = "监管端-根据当前登录人获取企业列表",  notes = "监管端-根据当前登录人获取企业列表")
	public ResponseModel<List<CompanyModel>> getUserUnitSup()  throws Exception {
		AgencyUserModel user = Privilege.agencyUserClient.getme().getResult();
		List<CompanyModel> companys = user.getCompanys();
		return ResponseHelper.buildResponse(companys);
	}



	/**
	 * 监管端-角色信息
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/listMyUnitRolesSup")
	@ApiOperation(httpMethod = "GET",value = "监管端-获取本单位拥有的角色信息",  notes = "监管端-获取本单位拥有的角色信息")
	public ResponseModel<List<RoleModel>> listMyUnitRolesSup() {
		FeignClientResult<List<RoleModel>> roleListResult = Privilege.roleClient.queryRoleList(null,null);
		List<RoleModel> allRoleList = roleListResult.getResult();
		return ResponseHelper.buildResponse(allRoleList);
	}

	/**
	 * 监管端-应用信息
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/listMyUnitAppSup")
	@ApiOperation(httpMethod = "GET",value = "监管端-获取本单位拥有的应用信息",  notes = "监管端-获取本单位拥有的应用信息")
	public ResponseModel<List<ApplicationModel>> listMyUnitAppSup() {
		List<ApplicationModel> allApp = Privilege.applicationClient.queryAgencyApplications().getResult();
		return ResponseHelper.buildResponse(allApp);
	}


}
