package com.palmnest.service.estateserve.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang.StringUtils;
import org.apache.http.client.CookieStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.palmnest.application.CodeConstants;
import com.palmnest.application.Constants;
import com.palmnest.application.bean.AppResultDto;
import com.palmnest.application.core.util.AppResultUtil;
import com.palmnest.application.core.util.FileUploadUtils;
import com.palmnest.application.dto.OrgKoalaInfoVo;
import com.palmnest.dao.estateserve.AppUserDao;
import com.palmnest.model.estateserve.AppUser;
import com.palmnest.service.estateserve.FaceClientManager;
import com.palmnest.service.estateserve.MemberManager;
import com.palmnest.service.impl.GenericManagerImpl;
import com.palmnest.service.redis.BaseRedisService;
import com.palmnest.service.ws.FacePlusClient;

@Slf4j
@Service("memberManager")
public class MemberManagerImpl extends GenericManagerImpl<Object, Integer>
		implements MemberManager {

	
	@Autowired
	private BaseRedisService    baseRedisService;

	
	@Autowired
	private AppUserDao appUserDao;
	
	@Autowired
	private FaceClientManager faceClientManager;

	@Override
	public String uploadKoalaPhoto(HttpServletRequest request) {

		String imageUrl = request.getParameter("imageBase64");
		String orgId = request.getParameter("orgId");
		JSONObject jsonObject = new JSONObject();
		String relativePath = "";		

		 log.info("uploadKoalaPhoto.orgId :{} ",orgId);
		 
		if (StringUtils.isEmpty(orgId)) {
			jsonObject.put("desc", "项目参数错误,请重新登录");
			jsonObject.put("flag", false);
			return jsonObject.toString();
		}
		orgId = orgId.replaceAll("\"", "");
		
		try {
			relativePath = FileUploadUtils.getBase64ImageUrl(imageUrl);
			if (StringUtils.isNotBlank(relativePath)
					&& StringUtils.isNotBlank(orgId)) {
				
				// 从缓存中取face++账号信息
				//CookieStore cookieStore = Constants.FaceMap.get("org_cookiestore_" + orgId);
				
				
				CookieStore cookieStore = faceClientManager.getCookieStoreByOrgId(Integer.valueOf(orgId));
				
				OrgKoalaInfoVo orgKoalaInfoVo = getOrgKoalaInfoVoByOrgId(Integer.valueOf(orgId));
				
				/*
				 * if(cookieStore == null){ cookieStore =
				 * FacePlusClient.authLogin(Constants.KOALOA_PLUS_USER,
				 * Constants.KOALOA_PLUS_PASSWORD); }
				 */
				if (cookieStore != null) {
					// 如果有相关账号信息 则直接进行图片上传 同步face++
					Map<String, Object> map = FacePlusClient.photos(Constants.IMAGE_ROOT + relativePath, cookieStore,orgKoalaInfoVo);
					if (map != null  && Integer.valueOf(500).equals((Integer)map.get("code"))) {
						//FileUploadUtils.deleteFileByPath(Constants.IMAGE_ROOT+ relativePath);//暂不删除
						//jsonObject.put("desc", "没有检测到人脸！");
						jsonObject.put("desc", map.get("desc"));
						jsonObject.put("flag", false);
					} else if(map != null  && Integer.valueOf(200).equals((Integer)map.get("code"))) {
						jsonObject.put("imageUrl", relativePath);
						//jsonObject.put("url",Constants.KOALOA_PLUS_URL+ map.get("url") + "");
						jsonObject.put("url",orgKoalaInfoVo.getKoalaAuthUrl()+ map.get("url") + "");
						jsonObject.put("id", map.get("id"));// imgId
						jsonObject.put("flag", true);
					}
				} else {
					jsonObject.put("flag", false);
					jsonObject.put("desc", "koala帐号初始化失败！");
				}

			} else {
				jsonObject.put("flag", false);
				jsonObject.put("desc", "没有检测到图片！");
			}
		} catch (Exception e) {
			FileUploadUtils.deleteFileByPath(Constants.IMAGE_ROOT
					+ relativePath);
			log.error("检测图片接口错误:" + e.getMessage());
			jsonObject.put("flag", false);
			jsonObject.put("desc", "网络超时！");
		}
		return jsonObject.toString();

	}

	
	
    public  OrgKoalaInfoVo getOrgKoalaInfoVoByOrgId(Integer orgId){

        OrgKoalaInfoVo orgKoalaInfoVo = new OrgKoalaInfoVo();
        String data = baseRedisService.get("User.id:"+ CodeConstants.RSA_REDIS_ORGKOALA_KEY + "_"+orgId);
        log.info("根据orgId:{}找到koala信息:{}",orgId,data);
        if(StringUtils.isNotEmpty(data)){
            orgKoalaInfoVo = JSON.parseObject(data, OrgKoalaInfoVo.class);
        }

        return orgKoalaInfoVo;
    }
	
	
	@Override
	public AppResultDto updateKoalaImg(Integer userId, String imgId, String imgUrl) {

		AppUser appUser = appUserDao.get(userId);
		int orgId = appUser.getOrganizationId();
		

		try {
			CookieStore cookieStore = faceClientManager.getCookieStoreByOrgId(orgId);
			
			OrgKoalaInfoVo orgKoalaInfoVo = getOrgKoalaInfoVoByOrgId(orgId);
			//CookieStore cookieStore = Constants.FaceMap.get("org_cookiestore_"+ orgId);
			/*
			 * if(cookieStore == null){ cookieStore =
			 * FacePlusClient.authLogin(Constants.KOALOA_PLUS_USER,
			 * Constants.KOALOA_PLUS_PASSWORD); }
			 */
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("orgId", orgId);
			
			if (cookieStore != null) {				
				
				String userStr = FacePlusClient.getSubject(appUser.getFacePlusUserId(), paramMap,orgKoalaInfoVo);
				if (StringUtils.isNotEmpty(userStr)) {// 有用户

					List<Integer> photo_ids = new ArrayList<Integer>();
					if(StringUtils.isNotEmpty(imgId)){
						photo_ids.add(Integer.valueOf(imgId));
					}				
					
					Integer updateUserId = FacePlusClient.updateKoalasubject(appUser, photo_ids, paramMap,orgKoalaInfoVo);
					if (null == updateUserId) {
						return AppResultUtil.createErrorDto("100","更新koala用户失败");
					}

				} else {// 没有用户 新增及同步图片id

					List<Integer> photo_ids = new ArrayList<Integer>();
					if(StringUtils.isNotEmpty(imgId)){
						photo_ids.add(Integer.valueOf(imgId));
					}

					paramMap.put("subjectType", 0);
					paramMap.put("extra_id", String.valueOf(userId));
					paramMap.put("name", appUser.getUserName());
					paramMap.put("photo_ids", photo_ids);// 图库Id
					Integer updateUserId = FacePlusClient.koalaSubject(paramMap,orgKoalaInfoVo);
					appUser.setFacePlusUserId(updateUserId);
					if (null == updateUserId) {
						return AppResultUtil.createErrorDto("100","新增koala用户失败");
					}
				}
			} else {
				return AppResultUtil.createSuccesDto("koala账号初始化失败");
			}

		} catch (Exception e) {
			log.error("koala接口错误:" + e.getMessage());
		}

		
		if(StringUtils.isNotEmpty(imgId)){
			appUser.setFacePlusImageId(Integer.valueOf(imgId));
		}else{
			appUser.setFacePlusImageId(null);
		}	
	
		appUser.setImageUrl01(imgUrl);
		appUserDao.updateObj(appUser);

		return AppResultUtil.createSuccesDto("操作成功");
	}

}
