package com.house365.ws.interfaces.rest;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.google.common.base.Strings;
import com.house365.ws.util.CmCommonUtils;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.house365.beans.entity.CmCreditRecordEntity;
import com.house365.beans.entity.CmLotteryRuleEntity;
import com.house365.beans.entity.CmUserEntity;
import com.house365.rest.context.CmConstant;
import com.house365.rest.context.Parameter;
import com.house365.rest.exception.IllegalServiceParameterException;
import com.house365.rest.exception.ServiceRunException;
import com.house365.ws.service.interfaces.ICmCreditRecordService;
import com.house365.ws.service.interfaces.ICmLotteryRuleService;
import com.house365.ws.service.interfaces.ICmUserService;
import com.house365.ws.system.ReturnAppResult;

@Component("getUploadUserPhotoCredits")
public class GetUploadUserPhotoCreditsImpl implements IGetUploadUserPhotoCredits {

    @Autowired
    ICmLotteryRuleService<CmLotteryRuleEntity> iCmLotteryRuleService;

    @Autowired
    ICmCreditRecordService<CmCreditRecordEntity> icmCreditRecordService;

    @Autowired
    ICmUserService<CmUserEntity> iCmUserService;

    /**
     * 首次上传图片获取积分接口
     *
     * @param parameter 服务输入，不包含服务配置和控制信息
     * @return credits：积分数量 createTime:产生时间 continuousSignCount:连续签到天数
     * @throws ServiceRunException
     */
    @Override
    public Object exectue(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        Map<String, Object> resultMap = new HashMap<>();
        // 业务校验统一入口
        try {
            checkInterfaceParameter(CmConstant.UPLOAD_USER_PHOTO_CREDITS, map);
        } catch (IllegalServiceParameterException e) {
            resultMap.put("result", ReturnAppResult.APP_FAIL.getResultCode());
            resultMap.put("msg", e.getMessage());
            return JSONObject.fromObject(resultMap).toString();
        }

        // 业务层统一处理
        try {
            String cityKey = null;
            if (map.get(CmConstant.CITY_KEY) != null) {
                cityKey = ((String[]) map.get(CmConstant.CITY_KEY))[0];
            }

            //接口文档中城市为userCityKey，上面取city_key 可能不对，做一次验证
            if (Strings.isNullOrEmpty(cityKey)) {
                cityKey = CmCommonUtils.getCityFromMap(map);
            }

            String userIdStr = ((String[]) map.get(CmConstant.USERID))[0];
            Integer useridType = Integer.parseInt(((String[]) map.get(CmConstant.USERID_TYPE))[0]);
            String userPhoto = ((String[]) map.get(CmConstant.USER_PHOTO))[0];

            //先查看是否存在该用户，没有则说明是第一次注册，可以给予获取头像积分
            CmUserEntity cmUserLocal = iCmUserService.getUserByUserIdCityKeyUserType(userIdStr, cityKey, useridType);
            if (cmUserLocal != null && !Strings.isNullOrEmpty(cmUserLocal.getUserTruePhoto())) {
                throw new ServiceRunException("已获取过头像上传积分!");
            }

            CmUserEntity cmUser = iCmUserService.registUserByUserId(map);
            if (cmUser == null) {
                throw new ServiceRunException("用户中心用户不存在!");
            }

            //如果原来用户没有头像，那么就是首次更新头像，并给积分
            if (Strings.isNullOrEmpty(cmUser.getUserTruePhoto())) {
                Integer registerCredits = iCmUserService.transGetUploadUserPhotoScore(cmUser, cityKey);
                Map<String, Object> dataMap = new HashMap<>();
                dataMap.put("credits", registerCredits);
                dataMap.put("createTime", new Date());
                resultMap.put("data", dataMap);
                resultMap.put("result", ReturnAppResult.APP_SUCCESS.getResultCode());
                resultMap.put("msg", "获取成功！");
                //更新用户头像
                cmUser.setUserPhoto(userPhoto);
                cmUser.setUserTruePhoto(userPhoto);
                iCmUserService.update(cmUser);
            } else {
                //更新用户头像
                cmUser.setUserPhoto(userPhoto);
                cmUser.setUserTruePhoto(userPhoto);
                iCmUserService.update(cmUser);
                throw new ServiceRunException("已上传过头像!");
            }

        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", ReturnAppResult.APP_FAIL.getResultCode());
            resultMap.put("msg", e.getMessage());
        }
        return JSONObject.fromObject(resultMap).toString();
    }


    /**
     * 业务层统校验自己所需参数是否存在
     *
     * @param map 请求参数封装成Map对象
     * @return 统一返回参数
     * @author yangyang
     * @version [v1.0.0, 2015年8月18日]
     * @since [产品/模块版本](可选)
     */
    protected void checkInterfaceParameter(String[] checkParameters, Map<String, Object> map) throws IllegalServiceParameterException {

        // 方法所需参数
        for (String str : checkParameters) {
            // 如果不存在跳出 同时抛出相应异常
            if (!map.containsKey(str)) {
                throw new IllegalServiceParameterException("业务入口参数异常：" + str + "参数为空!");
            }

        }
    }

    @Override
    public boolean isControlService() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean isLogService() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean isMonitorService() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public Object rollback() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void commit() {
        // TODO Auto-generated method stub

    }

}
