package com.palmnest.service.impl;

import cn.superdesk.libs.common.json.JsonUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.palmnest.application.AppConstants;
import com.palmnest.application.CodeConstants;
import com.palmnest.application.GoodsCodeConstants;
import com.palmnest.application.core.util.CollectionUtils;
import com.palmnest.application.core.util.StringUtil;
import com.palmnest.application.dto.OrgDto;
import com.palmnest.application.dto.OrgMeetDto;
import com.palmnest.application.dto.UserDto;
import com.palmnest.application.dto.output.UserInfoTokenDto;
import com.palmnest.model.Element;
import com.palmnest.model.Role;
import com.palmnest.model.User;
import com.palmnest.model.estateserve.AppUser;
import com.palmnest.model.property.TbOrganization;
import com.palmnest.model.property.VirtualArchitecture;
import com.palmnest.service.AppUserService;
import com.palmnest.service.ElementGroupManager;
import com.palmnest.service.OrganizationManager;
import com.palmnest.service.UserManager;
import com.palmnest.service.estateserve.AppUserManager;
import com.palmnest.service.estateserve.VirtualArchManager;
import com.palmnest.service.redis.BaseRedisService;
import com.palmnest.service.washcar.manager.WashCarOrderManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.hibernate.mapping.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


@Slf4j
@Service("appUserService")
public class AppUserServiceImpl implements AppUserService {


	@Autowired
	private BaseRedisService    baseRedisService;
	@Autowired
	private UserManager         userManager;
	@Autowired
	private ElementGroupManager elementGroupManager;
	@Autowired
	private WashCarOrderManager washCarOrderManager;
	@Autowired
	private OrganizationManager organizationManager;
	@Autowired
	private AppUserManager      appUserManager;
	@Autowired
	private VirtualArchManager  virtualArchManager;

	@Override
	public List<OrgDto> getUserOrgs(Long userId) {
		String json = baseRedisService.get(AppConstants.USERMANAGEORG + userId);

		log.info("AppUserServiceImpl getUserOrgs userId:{" + userId + "}");
		//log.info("AppUserServiceImpl getUserOrgs List<OrgDto> json:{" + json + "}");
		List<OrgDto> dtos = new ArrayList<OrgDto>();
		if (StringUtils.isNotBlank(json)) {
			JSONArray jsonArray = JSON.parseArray(json);
			for (int i = 0; i < jsonArray.size(); i++) {
				com.alibaba.fastjson.JSONObject object = (com.alibaba.fastjson.JSONObject) jsonArray.get(i);
				dtos.add(new OrgDto(object.getInteger("id"), object.getString("name")));
			}

		}
		return dtos;
	}

	@Override
	public List<OrgMeetDto> getUserOrgsByName(Long userId, String orgName) {
		String           json = baseRedisService.get(AppConstants.USERMANAGEORG + userId);
		List<OrgMeetDto> dtos = new ArrayList<OrgMeetDto>();
		if (StringUtils.isNotBlank(json)) {
			JSONArray jsonArray = JSON.parseArray(json);
			for (int i = 0; i < jsonArray.size(); i++) {
				com.alibaba.fastjson.JSONObject object = (com.alibaba.fastjson.JSONObject) jsonArray.get(i);
				if (StringUtil.isNotEmpty(orgName)) {
					if (object.getString("name").indexOf(orgName) != -1) {
						dtos.add(new OrgMeetDto(object.getInteger("id"), object.getString("name"), object.getString("meetCode")));
					}
				} else {
					dtos.add(new OrgMeetDto(object.getInteger("id"), object.getString("name"), object.getString("meetCode")));
				}
			}
		}
		return dtos;
	}

	@Override
	public UserDto convertDto(User user) {
		UserDto userDto = new UserDto(user.getId(), user.getUsername(), user.getTelephone(),
				user.getSex(), user.getAge(), user.getPosition(), user.getProfession(), user.getDeviceType(), user.getDeviceNo());
		userDto.setPhoto(user.getPhotoUrl());
		userDto.setFullName(user.getFullName());
		User user1 = userManager.findByFunctionAndUser(CodeConstants.AUDIT_PERMISSION, user.getId());
		if (user1 != null) {
			userDto.setAuditPermission(2);
		} else {
			userDto.setAuditPermission(1);
		}
		User user2 = userManager.findByFunctionAndUser(CodeConstants.MANAGE_PERMISSION, user.getId());
		if (user2 != null) {
			userDto.setManagePermission(2);
		} else {
			userDto.setManagePermission(1);
		}
		if (user.getIsOnline() == null || user.getIsOnline() == 0 || user.getIsOnline() == 1) {
			userDto.setIsOnline(1);//未签到
		} else {
			userDto.setIsOnline(2);
		}


		//公司职位 显示app首页　by qzy 2018年6月21日
		String position = "";
		if (StringUtils.isNotEmpty(user.getPosition())) {
			Element element = elementGroupManager.getElementId(Long.valueOf(user.getPosition()));
			if (null != element && StringUtils.isNotEmpty(element.getItemname())) {
				position = element.getItemname();
			}
		}
		userDto.setPosition(position);
		List<TbOrganization> list = organizationManager.getUserRelationOrganizationList(user.getId());
		if (list.size() > 0) {
			TbOrganization organization = list.get(0);
			if (organization != null) {
				userDto.setOrgName(organization.getName());
			}
		}
		try {
			String res = washCarOrderManager.isPower(CodeConstants.CARWASH_SERVICE, user.getId().toString());
			if ("HAVE".equals(res)) {
				userDto.setWashCarPermission(1);
			} else {
				userDto.setWashCarPermission(2);
			}
			String manRes = washCarOrderManager.isPower(CodeConstants.CARWASH_MANAGER, user.getId().toString());
			if ("HAVE".equals(manRes)) {
				userDto.setWashPermission(1);
			} else {
				userDto.setWashPermission(2);
			}

			String dormManager = washCarOrderManager.isPower(CodeConstants.DORM_MANAGER, user.getId().toString());
			if ("HAVE".equals(dormManager)) {
				userDto.setDormPermission(1);
			} else {
				userDto.setDormPermission(2);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		User userAir21 = userManager.findByFunctionAndUser(CodeConstants.CSP21_PERMISSION, user.getId());
		User userAir22 = userManager.findByFunctionAndUser(CodeConstants.CSP22_PERMISSION, user.getId());
		User userAir23 = userManager.findByFunctionAndUser(CodeConstants.CSP23_PERMISSION, user.getId());

		//空调加时审批权限
		String airAuditPermission = "";
		/*if (userAir21 != null) {
			airAuditPermission = GoodsCodeConstants.AIR_AUDITKE.toString();
		}
		if (userAir22 != null) {
			//airAuditPermission=airAuditPermission+";"+GoodsCodeConstants.AIR_AUDITKEL.toString();
			airAuditPermission = GoodsCodeConstants.AIR_AUDITKEL.toString();
		}
		if (userAir23 != null) {
			//airAuditPermission=airAuditPermission+";"+GoodsCodeConstants.AIR_AUDITGZL.toString();
			airAuditPermission = GoodsCodeConstants.AIR_AUDITGZL.toString();
		}*/
		userDto.setAirAuditPermission(airAuditPermission);


		Integer    meetingRoleAuthorization = 0;//会议室审核角色ID
		List<User> listUsers                = userManager.findByFunctionAndUserList(CodeConstants.MEETING_AUDIT, user.getId());
		log.info("AppUserServiceImpl luser.getId()===>" + user.getId());
		log.info("AppUserServiceImpl listUsers.size()===>" + listUsers.size());
		if (listUsers.size() == 1) {
			Role role = userManager.findRoleByFunctionAndUser(CodeConstants.MEETING_AUDIT, user.getId());
			meetingRoleAuthorization = role.getId().intValue();
		}
		userDto.setMeetingRolePermissionId(meetingRoleAuthorization);


		User userBsby = userManager.findByFunctionAndUser(CodeConstants.TSBYAUDIT_PERMISSION, user.getId());
		if (userBsby != null) {
			//airAuditPermission=airAuditPermission+";"+GoodsCodeConstants.AIR_AUDITKEL.toString();
			userDto.setTsbyReplyPermission(Integer.decode(CodeConstants.TSBYAUDIT_PERMISSION));
		} else {
			userDto.setTsbyReplyPermission(0);
		}

		User userRenovation = userManager.findByFunctionAndUser(CodeConstants.RENOVATION_PERMISSION, user.getId());
		if (userRenovation != null) {
			userDto.setRenovationPermission(Integer.decode(CodeConstants.RENOVATION_PERMISSION));
		} else {
			userDto.setRenovationPermission(0);
		}

		User repairUser = userManager.findByFunctionAndUser(CodeConstants.AUDIT_REPAIRSERVICE, user.getId());
		if (repairUser != null) {
			userDto.setRepairPermission(Integer.decode(CodeConstants.AUDIT_REPAIRSERVICE));
		} else {
			userDto.setRepairPermission(0);
		}

		return userDto;
	}

	@Override
	public String getAppUser(Integer orgId, Integer wxUserId) {
		String res = "";
		if (appUserManager.exists(wxUserId)) {
			AppUser user = appUserManager.get(wxUserId);
			if (user == null) {
				res = "抱歉，您的手机账号权限不够，请更换有效手机号或请联系管理员!";
				return res;
			}
			if (!StringUtil.isNotEmpty(user.getAddress())) {
				res = "抱歉，您没有订餐地址，请设置订餐地址或请联系管理员!";
				return res;
			}
		} else {
			res = "抱歉，您的手机账号权限不够，请更换有效手机号或请联系管理员!";
		}
		return res;
	}

	@Override
	public AppUser getAUByWxUser(Integer wxUserId) {
		return appUserManager.get(wxUserId);
	}


//	@Override
//	public AppUser getAUByOpenId(String orgId, String openId) {
//		return appUserManager.getAUByOpenId(orgId, openId);
//	}


	@Override
	public List<AppUser> countOrgWhiteUser(String[] orgIds) {
		return appUserManager.countOrgWhiteUser(orgIds);
	}

	@Override
	public boolean checkUserExists(String account) {
		User user = appUserManager.getByAccount(account);
		if (user != null)
			return true;
		return false;
	}

	@Override
	public UserInfoTokenDto convertTokenDto(AppUser appUser) {
		UserInfoTokenDto dto = new UserInfoTokenDto(appUser.getUserMobile(), Integer.parseInt(appUser.getUserType()), appUser.getOrganizationId(), appUser.getVirtualArchId());
		if (appUser.getUserType().equals("0")) {
			dto.setUserType(1);
		} else {
			dto.setUserType(2);
		}
		if (appUser.getOrganizationId() != null) {
			TbOrganization org = organizationManager.getOrganizationById(appUser.getOrganizationId());
			if (org != null) {
				dto.setOrgName(org.getName());
			}
		}
		if (appUser.getVirtualArchId() != null) {
			VirtualArchitecture vir = virtualArchManager.get(appUser.getVirtualArchId());
			if (vir != null) {
				dto.setVirName(vir.getName());
			}
		}
		return dto;
	}
}
