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

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.yeejoin.amos.boot.module.jxiop.api.service.IPermissionService;
import com.yeejoin.amos.boot.module.jxiop.biz.entity.PrivilegeCompany;
import com.yeejoin.amos.boot.module.jxiop.biz.service.impl.IPermissionServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
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.jxiop.api.dto.ListCompanyModel;
import com.yeejoin.amos.boot.module.jxiop.biz.amosprojectmapper.UserEmpowerMapper;
import com.yeejoin.amos.boot.module.jxiop.biz.entity.StdUserEmpower;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.CompanyModel;
import com.yeejoin.amos.feign.privilege.model.UserOrgTreeModel;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @description:
 * @author: tw
 * @createDate: 2023/4/25
 */
@RestController
@Api(tags = "平台单位部门树")
@RequestMapping(value = "/companyClient")
public class PrivilegeController extends BaseController {
	@Autowired
	private RedisUtils redisUtils;
	@Autowired
	private UserEmpowerMapper userEmpowerMapper;
	@Autowired
	IPermissionService iPermissionService;

	@Autowired
	IPermissionServiceImpl permissionService;
	
	@Value("${yth.qg.id}")
	private Long qgCompanyId;

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/queryOrgTree")
	@ApiOperation(httpMethod = "GET", value = "查询单位、子单位、部门树", notes = "查询单位、子单位、部门树")
	public FeignClientResult<Collection<UserOrgTreeModel>> queryOrgTree() {
		// 获取当前登录人单位
		ReginParams reginParams = JSONObject.parseObject(redisUtils
				.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(),
				ReginParams.class);

		Long companyId = reginParams.getCompany().getSequenceNbr();

		FeignClientResult<Collection<UserOrgTreeModel>> de = Privilege.companyClient.queryOrgTree(companyId);

		return de;
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/subcompany")
	@ApiOperation(httpMethod = "GET", value = "查询单位、子单位", notes = "查询单位、子单位")
	public ResponseModel<Collection<CompanyModel>> subcompany(String orgCode, String type) {
//        Long companyId =null;
//        if(orgCode!=null){
//            LinkedHashMap<Object, Object> l = (LinkedHashMap<Object, Object>) Privilege.companyClient
//                    .queryByOrgcode(orgCode).getResult();
//            for (Map.Entry<Object, Object> it : l.entrySet()) {
//
//                CompanyModel companyModel = JSONObject.parseObject(JSONObject.toJSONString(it.getValue()),
//                        CompanyModel.class);
//                if (companyModel != null) {
//                    companyId = companyModel.getSequenceNbr();
//                }
//                break;
//            }
//
//        }else{
//            ReginParams reginParams = JSONObject.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
//            companyId = reginParams.getCompany().getSequenceNbr();
//        }
//        //获取当前登录人单位
//        List<ListCompanyModel> data = new ArrayList();

//        FeignClientResult<CompanyModel> dat = Privilege.companyClient.seleteOne(companyId);
//        CompanyModel  companyModel=dat.getResult();
//        List<CompanyModel> list =new ArrayList<>();
//        //如果是公司则获取所有片区
////        86*353*328*364
//        if(companyModel.getLevel().equals("departmentorcompany")){
//            Collection<CompanyModel> companyModelList= de.getResult();
//            companyModelList=companyModelList.stream().filter(companyModel1 ->companyModel1.getCompanyName().contains("区域")).collect(Collectors.toList());
//            companyModelList.parallelStream().forEach((companyModel1)->{companyModel1.setChildren(new ArrayList());});
//            return ResponseHelper.buildResponse(companyModelList);
//        }
//        //如果是片区则获取片区
//        if(companyModel.getLevel().equals("area")){
//            list.add(companyModel);
//            return ResponseHelper.buildResponse(list);
//        }
//        if(!"add".equals(type)){
//          if(companyModel.getLevel().equals("station")){
//            FeignClientResult<CompanyModel> areaInfo = Privilege.companyClient.seleteOne(companyModel.getParentId());
//            list.add(areaInfo.getResult());
//        }
//        }
		// 如果是场站获取片区
//        if(companyModel.getLevel().equals("station")){
//            FeignClientResult<CompanyModel> areaInfo = Privilege.companyClient.seleteOne(companyModel.getParentId());
//            list.add(areaInfo.getResult());
//        }
		String companyLevel = "categroy_leve2";
		String companyName = "";
		Long parentId = null;
		ReginParams reginParams = getSelectedOrgInfo();
		String userId = reginParams.getUserModel().getUserId();
		StdUserEmpower stdUserEmpower = userEmpowerMapper
				.selectOne(new QueryWrapper<StdUserEmpower>().eq("amos_user_id", userId).eq("permission_type", "YTH"));
		CompanyModel companyInfo;
		if (ObjectUtils.isEmpty(stdUserEmpower)) {
//			throw new BadRequest("您当前未配置数据权限！");
		} else {
			String permissionOrgCode = stdUserEmpower.getAmosOrgCode().get(0);
			companyInfo = userEmpowerMapper.getCompanyInfoByOrgCode(permissionOrgCode);
			companyLevel = companyInfo.getLevel();
			companyName = companyInfo.getCompanyName();
		}
		FeignClientResult<Collection<CompanyModel>> de = Privilege.companyClient.querySubAgencyTree(qgCompanyId);
		List<CompanyModel> list = new ArrayList<>();
		// 如果是全国
		if (companyLevel.equals("categroy_leve2")) {
			Collection<CompanyModel> companyModelList = de.getResult();
			companyModelList = companyModelList.stream()
					.filter(companyModel1 -> companyModel1.getCompanyName().contains("区域"))
					.collect(Collectors.toList());
			companyModelList.parallelStream().forEach((companyModel1) -> {
				companyModel1.setChildren(new ArrayList());
			});
			return ResponseHelper.buildResponse(companyModelList);
		}
		// 如果是片区则获取片区
		if (companyLevel.equals("area")||(!"add".equals(type)&&companyLevel.equals("station"))) {
			Collection<CompanyModel> companyModelList = de.getResult();
			companyModelList = companyModelList.stream()
					.filter(companyModel1 -> companyModel1.getCompanyName().contains("区域"))
					.collect(Collectors.toList());
			for (CompanyModel companyModel : companyModelList) {
				if (companyModel.getCompanyName().equals(companyName)) {
					list.add(companyModel);
					break;
				}
			}
			list.parallelStream().forEach((companyModel1) -> {
				companyModel1.setChildren(new ArrayList());
			});
			return ResponseHelper.buildResponse(list);
		}
		return ResponseHelper.buildResponse(list);
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/stationTree")
	@ApiOperation(httpMethod = "GET", value = "查询所属场站", notes = "查询所属场站")
	public ResponseModel<Collection<CompanyModel>> stationTree(String orgCode) {
		Long companyId = null;
		if (orgCode != null) {

			LinkedHashMap<Object, Object> l = (LinkedHashMap<Object, Object>) Privilege.companyClient
					.queryByOrgcode(orgCode).getResult();
			for (Map.Entry<Object, Object> it : l.entrySet()) {

				CompanyModel companyModel = JSONObject.parseObject(JSONObject.toJSONString(it.getValue()),
						CompanyModel.class);
				if (companyModel != null) {
					companyId = companyModel.getSequenceNbr();
				}
				break;
			}

		} else {
			ReginParams reginParams = JSONObject.parseObject(redisUtils
					.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(),
					ReginParams.class);
			companyId = reginParams.getCompany().getSequenceNbr();
		}

		List<ListCompanyModel> data = new ArrayList();
		FeignClientResult<Collection<CompanyModel>> de = Privilege.companyClient.querySubAgencyTree(companyId);
		FeignClientResult<CompanyModel> dat = Privilege.companyClient.seleteOne(companyId);
		CompanyModel companyModel = dat.getResult();
		companyModel.setChildren(de.getResult());
		List<CompanyModel> list = new ArrayList<>();
		list.add(companyModel);
		return ResponseHelper.buildResponse(list);
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@GetMapping(value = "/permissionTree")
	@ApiOperation(httpMethod = "GET", value = "查询所属场站", notes = "查询所属场站")
	public ResponseModel<Collection<CompanyModel>> permissionTree(
			@RequestParam(required = false, defaultValue = "86*353*328") String orgCode) {
		Long companyId = null;
		if (orgCode != null) {
			LinkedHashMap<Object, Object> l = (LinkedHashMap<Object, Object>) Privilege.companyClient
					.queryByOrgcode(orgCode).getResult();
			for (Map.Entry<Object, Object> it : l.entrySet()) {

				CompanyModel companyModel = JSONObject.parseObject(JSONObject.toJSONString(it.getValue()),
						CompanyModel.class);
				if (companyModel != null) {
					companyId = companyModel.getSequenceNbr();
				}
				break;
			}

		}
		List<ListCompanyModel> data = new ArrayList();
		FeignClientResult<Collection<CompanyModel>> de = Privilege.companyClient.querySubAgencyTree(companyId);
		FeignClientResult<CompanyModel> dat = Privilege.companyClient.seleteOne(companyId);
		CompanyModel companyModel = dat.getResult();
		companyModel.setChildren(de.getResult());
		List<CompanyModel> list = new ArrayList<>();
		list.add(companyModel);
		return ResponseHelper.buildResponse(list);
	}


	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/judgeUserIsStation")
	@ApiOperation(httpMethod = "GET", value = "查询当前人是否为场站层级", notes = "查询当前人是否为场站层级")
	public ResponseModel<Map<String,String>> judgeUserIsStation() {
	return 	ResponseHelper.buildResponse(iPermissionService.judgeUserIsStation());
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
	@GetMapping(value = "/getAreaCompany")
	@ApiOperation(httpMethod = "GET", value = "查询所有区域公司", notes = "查询所有区域公司")
	public ResponseModel<List<PrivilegeCompany>> getAreaCompany(String type,@RequestParam(required = false) String province) {
		return 	ResponseHelper.buildResponse(permissionService.getAreaCompany(type,province));
	}

}
