package com.yeejoin.precontrol.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;

import org.apache.commons.collections4.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.privilege.model.DepartmentModel;
import com.yeejoin.amos.feign.privilege.model.RoleModel;
import com.yeejoin.precontrol.common.entity.Company;
import com.yeejoin.precontrol.common.entity.MessageException;
import com.yeejoin.precontrol.common.entity.Person;
import com.yeejoin.precontrol.common.entity.PersonAscription;
import com.yeejoin.precontrol.common.entity.Project;
import com.yeejoin.precontrol.common.service.ICompanyService;
import com.yeejoin.precontrol.common.service.IMessageExceptionService;
import com.yeejoin.precontrol.common.service.IPersonAscriptionService;
import com.yeejoin.precontrol.common.service.IPersonService;
import com.yeejoin.precontrol.common.service.IProjectService;
import com.yeejoin.precontrol.common.utils.PlatformUtils;
import com.yeejoin.precontrol.common.utils.StringUtil;

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

/**
 * 项目信息
 *
 * @author duanwei
 * @date 2020-06-30
 */
@RestController
@Api(tags = "平台接口")
@RequestMapping(value = "/platform", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class PlatformController {

	/**
	 * 江西电建公司id
	 */
	@Value("${jxdj.id}")
	private String companyId;

	@Autowired
	private IPersonService iPersonService;

	@Autowired
	private PlatformUtils platformUtils;

	@Autowired
	private IPersonAscriptionService iPersonAscriptionService;

	@Autowired
	private IProjectService iProjectService;

	@Autowired
	private IMessageExceptionService iMessageExceptionService;

	@Autowired
	private ICompanyService iCompanyService;

	/**
	 * 列表分页查询
	 *
	 * @return
	 */
	@RequestMapping(value = "/projectList", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "项目部一级部门查询", notes = "项目部一级部门查询")
	public Object projectList() {
		FeignClientResult<Collection<DepartmentModel>> collectionFeignClientResult = Privilege.departmentClient
				.treeByUser(null, Long.valueOf(companyId));
		Collection<DepartmentModel> result = new ArrayList<>();
		if (StringUtil.isNotEmpty(collectionFeignClientResult)) {
			result = collectionFeignClientResult.getResult();
			// List<DepartmentModel> project = result.stream().filter(res ->
			// "project".equals(res.getLevel())).collect(Collectors.toList());
		}
		return result;
	}

	@RequestMapping(value = "/initNewOrg", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "项目部一级部门查询", notes = "项目部一级部门查询")
	public void initNewOrg() {
		iMessageExceptionService
				.remove(new LambdaQueryWrapper<MessageException>().eq(MessageException::getMethod, "init_orgcode"));
		Long companySeq = Long.valueOf(companyId);
		platformUtils.setPlatFormAccess();
		List<Person> list = iPersonService.list(new LambdaQueryWrapper<Person>().eq(Person::getIsJxdj, 0L));
		FeignClientResult<Collection<DepartmentModel>> deptModel = Privilege.departmentClient.queryDeptTree(null,
				companySeq);
		DepartmentModel pltfbs = null;
		for (DepartmentModel departmentModel : deptModel.getResult()) {
			if ("fbs".equals(departmentModel.getLevel())) {
				pltfbs = departmentModel;
				break;
			}
		}
		if (pltfbs == null) {
			DepartmentModel newfbs = new DepartmentModel();
			newfbs.setCompanySeq(companySeq);
			newfbs.setDepartmentName("分包商");
			newfbs.setLevel("fbs");
			newfbs.setParentId(1L);
			FeignClientResult<DepartmentModel> fdfbs = Privilege.departmentClient.create(newfbs);
			pltfbs = fdfbs.getResult();
		}
		Long platDeptId = pltfbs.getSequenceNbr();
		int i = 0;
		for (Person person : list) {
			if (person.getUserId() == null) {
				continue;
			}
			FeignClientResult<AgencyUserModel> fa = Privilege.agencyUserClient
					.queryByUserId(person.getUserId().toString());
			if (fa == null) {
				continue;
			}
			AgencyUserModel usr = fa.getResult();
			if (usr == null || usr.getOrgRoleSeqs() == null) {
				continue;
			}
			Map<Long, List<Long>> seqs = usr.getOrgRoleSeqs();
			Long deptId;
			List<Long> roleIds = null;
			for (Long deptId1 : seqs.keySet()) {
				deptId = deptId1;
				roleIds = seqs.get(deptId1);
				break;
			}
			Long newDeptId = null;
			String orgCode = null;
			if (person.getOrgCode() != null) {
				orgCode = person.getOrgCode();
			} else {
				PersonAscription ascription = iPersonAscriptionService.getOne(
						new LambdaQueryWrapper<PersonAscription>().eq(PersonAscription::getPersonId, person.getId()));
				Project project = iProjectService.getById(ascription.getProjectId());
				orgCode = project != null ? project.getOrgCode() : null;
			}

			if (orgCode != null) {
				FeignClientResult<DepartmentModel> fd = Privilege.departmentClient.queryByOrgcode(orgCode);
				DepartmentModel dept = fd.getResult();
				if (dept != null && "project".equals(dept.getLevel())) {
					FeignClientResult<Collection<DepartmentModel>> fc = Privilege.departmentClient
							.querySubAgencyTree(dept.getSequenceNbr());
					Collection<DepartmentModel> collect = fc.getResult();
					DepartmentModel fbs = null;
					for (DepartmentModel departmentModel : collect) {
						if ("fbs".equals(departmentModel.getLevel())) {
							fbs = departmentModel;
							break;
						}
					}
					if (fbs == null) {
						DepartmentModel newfbs = new DepartmentModel();
						newfbs.setCompanySeq(companySeq);
						newfbs.setDepartmentName("分包商");
						newfbs.setLevel("fbs");
						newfbs.setParentId(dept.getSequenceNbr());
						FeignClientResult<DepartmentModel> fdfbs = Privilege.departmentClient.create(newfbs);
						fbs = fdfbs.getResult();
					}
					newDeptId = fbs.getSequenceNbr();
				} else {
					newDeptId = platDeptId;
				}

			} else {
				newDeptId = platDeptId;
			}

			Map<Long, List<Long>> newSeqs = new HashedMap<>();
			newSeqs.put(newDeptId, roleIds);
			Object old = usr.getOrgRoleSeqs();
			usr.setOrgRoleSeqs(newSeqs);
			try {
				Privilege.agencyUserClient.update(usr, usr.getUserId());
			} catch (Exception e) {
				MessageException message = new MessageException();
				message.setJson(JSONObject.toJSONString(usr));
				message.setMessage(JSONObject.toJSONString(old));
				message.setMethod("init_orgcode");
				iMessageExceptionService.save(message);
				System.out.println(JSONObject.toJSONString(usr));
				e.printStackTrace();
			}

			System.out.println("==========================================" + ++i + "/" + list.size());
			System.out.println("==========================================" + i + "/" + list.size());
			System.out.println("==========================================" + i + "/" + list.size());
		}
	}

	@RequestMapping(value = "/deparments", method = RequestMethod.DELETE)
	@ApiOperation(httpMethod = "GET", value = "项目部一级部门查询", notes = "项目部一级部门查询")
	public void deparments() {
		platformUtils.setPlatFormAccess();
		FeignClientResult<Collection<CompanyModel>> result1 = Privilege.companyClient
				.querySubAgencyTree(Long.valueOf(companyId));
		Collection<CompanyModel> collections1 = result1.getResult();
		int i = 0;
		StringBuffer sb = new StringBuffer();
		for (CompanyModel companyModel : collections1) {
			FeignClientResult<Collection<DepartmentModel>> result2 = Privilege.departmentClient.queryDeptTree(null,
					companyModel.getSequenceNbr());
			Collection<DepartmentModel> collections2 = result2.getResult();
			StringBuffer sd = new StringBuffer();
			for (DepartmentModel departmentModel : collections2) {
				sd.append(departmentModel.getSequenceNbr());
				sd.append(",");
			}
			if (sd.toString().contains(",")) {
				sd.deleteCharAt(sd.length() - 1);
				Privilege.departmentClient.delete(sd.toString());
			}
			System.out.println("==========================================" + ++i + "/" + collections1.size());
			System.out.println("==========================================" + i + "/" + collections1.size());
			System.out.println("==========================================" + i + "/" + collections1.size());
			sb.append(companyModel.getSequenceNbr());
			sb.append(",");
		}
		if (sb.toString().contains(",")) {
			sb.deleteCharAt(sb.length() - 1);
			Privilege.companyClient.deleteCompany(sb.toString());
		}

	}

	@RequestMapping(value = "/updateNewOrg", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "项目部一级部门查询", notes = "项目部一级部门查询")
	public void updateNewOrg() {
		iMessageExceptionService
				.remove(new LambdaQueryWrapper<MessageException>().eq(MessageException::getMethod, "update_orgcode"));
		Long companySeq = Long.valueOf(companyId);
		platformUtils.setPlatFormAccess();
		List<Person> list = iPersonService.list(new LambdaQueryWrapper<Person>());
		int i = 0;
		Company company = null;
		Project project = null;
		for (Person p : list) {
			System.out.println("==========================================" + ++i + "/" + list.size());
			System.out.println("==========================================" + i + "/" + list.size());
			System.out.println("==========================================" + i + "/" + list.size());
			if (p.getUserId() == null || p.getUserId().equals("")) {
				MessageException message = new MessageException();
				message.setJson(p.getName());
				message.setPath(p.getPhone());
				// message.setExtend1(extend1);
				// message.setExtend2(extend2);
				message.setMessage("userId is null");
				message.setMethod("update_orgcode");
				iMessageExceptionService.save(message);
				System.out.println(JSONObject.toJSONString(message));
				continue;
			}
			try {
				FeignClientResult<AgencyUserModel> result = Privilege.agencyUserClient
						.queryByUserId(p.getUserId().toString());
				AgencyUserModel usr = result.getResult();
				try {
					if (usr == null) {
						MessageException message = new MessageException();
						message.setJson(p.getName());
						message.setPath(p.getPhone());
						// message.setExtend1(extend1);
						// message.setExtend2(extend2);
						message.setMessage("user is null");
						message.setMethod("update_orgcode");
						iMessageExceptionService.save(message);
						continue;
					}
					Map<Long, List<Long>> map = usr.getOrgRoleSeqs();
					if (!map.isEmpty()) {
						continue;
					}
					PersonAscription personAscription = iPersonAscriptionService.getOne(
							new LambdaQueryWrapper<PersonAscription>().eq(PersonAscription::getPersonId, p.getId()));
					company = iCompanyService.getById(personAscription.getCompanyId());
					project = iProjectService.getById(personAscription.getProjectId());
					if (p.getRoles() == null) {
						MessageException message = new MessageException();
						message.setJson(p.getName());
						message.setPath(p.getPhone());
						message.setExtend1(company != null ? company.getName() : null);
						message.setExtend2(project != null ? project.getName() : null);
						message.setMessage("roles is null");
						message.setMethod("update_orgcode");
						iMessageExceptionService.save(message);
						continue;
					}
					String roles = p.getRoles().replace("[", "").replace("]", "");
					String[] roles1 = roles.split(",");
					List<Long> roles2 = Arrays.asList(roles1).stream().map(m -> Long.valueOf(m))
							.collect(Collectors.toList());
					if (p.getIsJxdj() == 1) {
						if (personAscription.getDepartmentId() == null) {
							MessageException message = new MessageException();
							message.setJson(p.getName());
							message.setPath(p.getPhone());
							message.setExtend1(company != null ? company.getName() : null);
							message.setExtend2(project != null ? project.getName() : null);
							message.setMessage("jxdj departmentId is null");
							message.setMethod("update_orgcode");
							iMessageExceptionService.save(message);
							continue;
						}
						map.put(personAscription.getDepartmentId(), roles2);
					} else {
						Long newDeptId = null;
						String orgCode = null;
						if (p.getOrgCode() != null) {
							orgCode = p.getOrgCode();
						} else {
							orgCode = project != null ? project.getOrgCode() : null;
						}
						if (orgCode != null) {
							FeignClientResult<DepartmentModel> fd = Privilege.departmentClient.queryByOrgcode(orgCode);
							DepartmentModel dept = fd.getResult();
							FeignClientResult<Collection<DepartmentModel>> fc = Privilege.departmentClient
									.querySubAgencyTree(dept.getSequenceNbr());
							Collection<DepartmentModel> collect = fc.getResult();
							DepartmentModel fbs = null;
							for (DepartmentModel departmentModel : collect) {
								if ("fbs".equals(departmentModel.getLevel())) {
									fbs = departmentModel;
									break;
								}
							}
							if (fbs == null) {
								DepartmentModel newfbs = new DepartmentModel();
								newfbs.setCompanySeq(companySeq);
								newfbs.setDepartmentName("分包商");
								newfbs.setLevel("fbs");
								newfbs.setParentId(dept.getSequenceNbr());
								FeignClientResult<DepartmentModel> fdfbs = Privilege.departmentClient.create(newfbs);
								fbs = fdfbs.getResult();
							}
							newDeptId = fbs.getSequenceNbr();
							map.put(newDeptId, roles2);
						} else {
							MessageException message = new MessageException();
							message.setJson(p.getName());
							message.setPath(p.getPhone());
							message.setExtend1(company != null ? company.getName() : null);
							message.setExtend2(project != null ? project.getName() : null);
							message.setMessage("orgcode is null");
							message.setMethod("update_orgcode");
							iMessageExceptionService.save(message);
							continue;
						}
					}
					usr.setOrgRoleSeqs(map);
					Privilege.agencyUserClient.update(usr, usr.getUserId());
				} catch (Exception e) {
					MessageException message = new MessageException();
					message.setJson(p.getName());
					message.setPath(p.getPhone());
					message.setExtend1(company != null ? company.getName() : null);
					message.setExtend2(project != null ? project.getName() : null);
					message.setMessage("uppdate user error");
					message.setMethod("update_orgcode");
					iMessageExceptionService.save(message);
					System.out.println(JSONObject.toJSONString(usr));
					e.printStackTrace();
				}
			} catch (Exception e) {
				MessageException message = new MessageException();
				message.setJson(p.getName());
				message.setPath(p.getPhone());
				message.setExtend1(company != null ? company.getName() : null);
				message.setExtend2(project != null ? project.getName() : null);
				message.setMessage("get user error");
				message.setMethod("update_orgcode");
				iMessageExceptionService.save(message);
				System.out.println(JSONObject.toJSONString(message));
			}
		}
	}

	@RequestMapping(value = "/updateApps", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "项目部一级部门查询", notes = "项目部一级部门查询")
	public void updateApps() {
		iMessageExceptionService
				.remove(new LambdaQueryWrapper<MessageException>().eq(MessageException::getMethod, "update_apps"));
		platformUtils.setPlatFormAccess();
		List<Person> list = iPersonService.list(new LambdaQueryWrapper<Person>());
		int i = 0;
		List<String> codes = new ArrayList<>();
		List<String> codesjxdj = new ArrayList<>();
		codesjxdj.add("studio_normalapp_2135110");
		codesjxdj.add("studio_normalapp_2075166");
		codesjxdj.add("studio_normalapp_2941403");
		for (Person p : list) {
			System.out.println("==========================================" + ++i + "/" + list.size());
			System.out.println("==========================================" + i + "/" + list.size());
			System.out.println("==========================================" + i + "/" + list.size());
			if (p.getUserId() == null || p.getUserId().equals("")) {
				MessageException message = new MessageException();
				message.setJson(JSONObject.toJSONString(p));
				message.setMessage("userId is null");
				message.setMethod("update_apps");
				iMessageExceptionService.save(message);
				System.out.println(JSONObject.toJSONString(message));
				continue;
			}
			FeignClientResult<AgencyUserModel> result = Privilege.agencyUserClient
					.queryByUserId(p.getUserId().toString());
			AgencyUserModel usr = result.getResult();
			if (usr == null) {
				MessageException message = new MessageException();
				message.setJson(JSONObject.toJSONString(p));
				message.setMessage("user is null");
				message.setMethod("update_apps");
				iMessageExceptionService.save(message);
				continue;
			}
			if (p.getIsJxdj() == 1L) {
				usr.setAppCodes(codesjxdj);
			} else {
				usr.setAppCodes(codes);
			}
			try {
				Privilege.agencyUserClient.update(usr, usr.getUserId());
			} catch (Exception e) {
				MessageException message = new MessageException();
				message.setJson(JSONObject.toJSONString(p));
				message.setMessage("update user error");
				message.setMethod("update_apps");
				iMessageExceptionService.save(message);
			}
		}
	}

	@RequestMapping(value = "/updateAdmin", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "项目部一级部门查询", notes = "项目部一级部门查询")
	public void updateAdmin() {
		platformUtils.setPlatFormAccess();
		FeignClientResult<List<RoleModel>> roleList = Privilege.roleClient.queryRoleList(null, null);
		RoleModel admin = null, operation = null, director = null;
		for (RoleModel roleModel : roleList.getResult()) {
			if (roleModel.getRoleName().equals("admin")) {
				admin = roleModel;
				continue;
			} else if (roleModel.getRoleName().equals("operation")) {
				operation = roleModel;
				continue;
			} else if (roleModel.getRoleName().equals("director")) {
				director = roleModel;
				continue;
			}
		}

		String[] s = { "管理员", "杜广锋", "贺曦", "赵峰", "祝昌贵", "吴江" };
		List<Person> list = iPersonService.list(new LambdaQueryWrapper<Person>().like(Person::getRoleKey, "admin")
				.notLike(Person::getRoleKey, "fbs_admin").notIn(Person::getName, s));
		List<Person> list2 = iPersonService
				.list(new LambdaQueryWrapper<Person>().like(Person::getRoleKey, "operation").notIn(Person::getName, s));
		List<Person> list3 = iPersonService
				.list(new LambdaQueryWrapper<Person>().like(Person::getRoleName, "admin").notIn(Person::getName, s));
		List<Person> list4 = iPersonService
				.list(new LambdaQueryWrapper<Person>().like(Person::getRoleName, "运维").notIn(Person::getName, s));
		list.addAll(list2);
		list.addAll(list3);
		list.addAll(list4);
		HashSet<Person> set = new HashSet(list);
		for (Person p : set) {
			FeignClientResult<AgencyUserModel> result = Privilege.agencyUserClient
					.queryByUserId(p.getUserId().toString());
			AgencyUserModel usr = result.getResult();
			if (usr == null) {
				continue;
			}
			Map<Long, List<Long>> map = usr.getOrgRoleSeqs();
			for (Entry<Long, List<Long>> a : map.entrySet()) {
				a.getValue().remove(admin.getSequenceNbr());
				a.getValue().remove(operation.getSequenceNbr());
				if (a.getValue().size() == 0) {
					a.getValue().add(director.getSequenceNbr());
				}
				String roleName = "";
				String roleKey = "";
				String roles = Arrays.toString(a.getValue().toArray());
				if (StringUtils.isNotEmpty(roles)) {
					// 去除[]
					if(roles.contains("[")) 
					{
						roles = roles.substring(1, roles.length() - 1);
					}
					// 去除空格
					roles = roles.replaceAll(" ", "");
					FeignClientResult<List<RoleModel>> listFeignClientResult = Privilege.roleClient.queyrForMult(roles);
					List<RoleModel> result1 = listFeignClientResult.getResult();
					if (StringUtil.isNotEmpty(result1)) {
						for (RoleModel roleModel : result1) {
							String roleDesc = roleModel.getRoleDesc();
							roleName += roleDesc + ",";
							roleKey += roleModel.getRoleName() + ",";
						}
						if (roleName.lastIndexOf(",") > 0) {
							roleName = roleName.substring(0, roleName.length() - 1);
						}
						if (roleKey.lastIndexOf(",") > 0) {
							roleKey = roleKey.substring(0, roleKey.length() - 1);
						}
					}
					p.setRoleKey(roleKey);
					p.setRoles(roles);
					p.setRoleName(roleName);
				}
				break;
			}
			FeignClientResult<AgencyUserModel> result1 = Privilege.agencyUserClient.update(usr, usr.getUserId());
			iPersonService.updateById(p);
		}
	}
}
