/**
 * Description: CmUser业务实现类
 * Copyright:   Copyright (c)2015
 * Company:     江苏三六五网络股份有限公司
 *
 * @author: 江苏三六五网络股份有限公司
 * @version: 1.0
 * Create at:   2015-08-10 下午 17:06:21
 * <p/>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2015-08-10   江苏三六五网络股份有限公司   1.0         Initial
 */
package com.house365.ws.service.impl;

import com.google.common.base.Strings;
import com.house365.beans.entity.CmCreditRecordEntity;
import com.house365.beans.entity.CmUserEntity;
import com.house365.dao.system.interfaces.Dao;
import com.house365.rest.context.CmConstant;
import com.house365.service.system.impl.DefaultServiceImpl;
import com.house365.web.util.SpringContextUtil;
import com.house365.web.util.StringUtils;
import com.house365.ws.cached.RedisUtilsInterface;
import com.house365.ws.dao.interfaces.ICmCreditRecordDao;
import com.house365.ws.dao.interfaces.ICmUserDao;
import com.house365.ws.service.interfaces.ICmUserService;
import com.house365.ws.util.CmCommonUtils;
import com.house365.ws.util.PhpInterfaceUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * CmUser业务实现类<br>
 *
 * @author 江苏三六五网络股份有限公司
 * @version 1.0, 2015-08-10
 * @see
 * @since 1.0
 */
@Service("cmUserService")
public class CmUserServiceImpl<T extends CmUserEntity> extends DefaultServiceImpl<T> implements ICmUserService<T> {
    private static final Logger LOGGER = LoggerFactory.getLogger("InterfaceLog");

    /**
     * 自动注入的数据访问对象
     */
    @Autowired
    private ICmUserDao<T> cmUserDao;

    @Autowired
    private ICmCreditRecordDao<CmCreditRecordEntity> cmCreditRecordDao;

    //    @Autowired
    //    private RedisUtilsInterface redisUtils;

    //    static RedisUtilsInterface redisUtils = (RedisUtilsInterface) SpringContextUtil.getBean("redisUtils");

    @Override
    protected Dao<T> getDao() {
        return cmUserDao;
    }

    @Override
    public CmUserEntity getUserByUserIdCityKeyUserType(String userId, String cityKey, Integer useridType) {
        if (Strings.isNullOrEmpty(userId)) {
            return null;
        }

        if (StringUtils.isNumeric(String.valueOf(Integer.parseInt(userId)))) {
            return cmUserDao.getUserByUserId(Integer.parseInt(userId), cityKey, useridType);
        } else {
            return null;
        }
    }

    @Override
    public synchronized CmUserEntity registUserByUserId(Map<String, Object> map) {
        if (map.get(CmConstant.USERID) == null) {
            return null;
        }

        String userIdStr = "";
        //header 中传递
        if (map.get(CmConstant.USERID) instanceof String) {
            userIdStr = String.valueOf(map.get(CmConstant.USERID));
        } else {
            userIdStr = ((String[]) map.get(CmConstant.USERID))[0];
        }

        Integer userIdType = Integer.parseInt(((String[]) map.get(CmConstant.USERID_TYPE))[0]);
        String cityKey = CmCommonUtils.getCityFromMap(map);

        //如果不是用户中心的用户，则需要城市字段
        if (Strings.isNullOrEmpty(cityKey) && Objects.equals(CmConstant.USERID_TYPE_OTHER, userIdType)) {
            cityKey = ((String[]) map.get(CmConstant.USER_CITY_KEY))[0];
        }

        //异常userid后面有.0，处理
        if (userIdStr.contains(".")) {
            userIdStr = userIdStr.substring(0, userIdStr.indexOf("."));
        }

        //本地库是否存在
        CmUserEntity cmUser = getUserByUserIdCityKeyUserType(userIdStr, cityKey, userIdType);
        if (cmUser == null) {//不存在
            //用户中心
            if (Objects.equals(userIdType, CmConstant.USERID_TYPE_USER_CENTER)) {
                //注册用户
                cmUser = PhpInterfaceUtils.getUserByRemoteInterface(userIdStr);
                if (cmUser == null) {
                    return null;
                }
                cmUser.setUseridType(CmConstant.USERID_TYPE_USER_CENTER);
                if (!Strings.isNullOrEmpty(cityKey) && Strings.isNullOrEmpty(cmUser.getCityId())) {
                    cmUser.setCity(cityKey);
                    cmUser.setCityId(cityKey);
                }
                cmUser.setCreateTime(new Date());
                cmUser.setUpdateTime(new Date());
                cmUser.setCredits(0);
                int id = cmUserDao.save((T) cmUser);
                cmUser.setId(id);
            } else {//不是用户中心用户
                cmUser = new CmUserEntity();//补全字段
                cmUser.setCity(cityKey);
                String userName = null;
                if (map.get(CmConstant.USER_NAME) != null) {
                    userName = ((String[]) map.get(CmConstant.USER_NAME))[0];
                }
                cmUser.setUserName(userName);
                cmUser.setUserId(userIdStr);
                cmUser.setCreateTime(new Date());
                cmUser.setUpdateTime(new Date());
                cmUser.setUseridType(CmConstant.USERID_TYPE_OTHER);
                cmUser.setCity(cityKey);
                cmUser.setCityId(cityKey);
                int id = cmUserDao.save((T) cmUser);
                cmUser.setId(id);
            }
        } else {
            //20160109日前用户没有保存city字段,补一下CommentHouse
            if (!Strings.isNullOrEmpty(cityKey) && Strings.isNullOrEmpty(cmUser.getCityId())) {
                cmUser.setCityId(cityKey);
            }
            return cmUser;
        }

        String cacheKey = userIdStr;
        clearUserCache(cacheKey);

        return cmUser;
    }

    @Override
    public void clearUserCache(String userId) {
        userId = "USERINFO:" + userId;
        RedisUtilsInterface redisUtils = (RedisUtilsInterface) SpringContextUtil.getBean("redisUtils");
        if (Strings.isNullOrEmpty(userId.toString()) || redisUtils.getValByKeyNew(
                userId.toString()) == null || Strings.isNullOrEmpty(
                redisUtils.getValByKeyNew(userId.toString())) || "null".equalsIgnoreCase(
                redisUtils.getValByKeyNew(userId.toString()))) {
        } else {
            redisUtils.deleteByKeyNew(userId.toString());
        }
    }

    @Override
    public Integer transGetRegisterScore(CmUserEntity user, String cityKey) throws Exception {
        CmCreditRecordEntity creditRecordEntity = cmCreditRecordDao.saveRegisterRecord(user);
        LOGGER.info("before transGetRegisterScore user: {} credits: {}", user.getUserId(), user.getCredits());
        if (user.getCredits() == null) {
            user.setCredits(0);
        }
        user.setCredits(user.getCredits() + creditRecordEntity.getAmount());
        LOGGER.info("after transGetRegisterScore user: {} credits: {}", user.getUserId(), user.getCredits());
        user.setUpdateTime(new Date());
        cmUserDao.update((T) user);

        clearUserCache(user.getUserId());
        return creditRecordEntity.getAmount();
    }

    @Override
    public Integer transChangeUserCredit(CmUserEntity user, Integer rule, Integer credit) throws Exception {
        CmCreditRecordEntity creditRecordEntity = cmCreditRecordDao.saveChangeCreditsRecord(user, rule, credit);
        LOGGER.info("before transGetRegisterScore user: {} credits: {}", user.getUserId(), user.getCredits());
        if (user.getCredits() == null) {
            user.setCredits(0);
        }
        user.setCredits(user.getCredits() + creditRecordEntity.getAmount());
        LOGGER.info("after transGetRegisterScore user: {} credits: {}", user.getUserId(), user.getCredits());
        user.setUpdateTime(new Date());
        cmUserDao.update((T) user);
        clearUserCache(user.getUserId());
        return creditRecordEntity.getAmount();
    }

    @Override
    public Integer transGetUploadUserPhotoScore(CmUserEntity user, String cityKey) throws Exception {
        CmCreditRecordEntity ccre = cmCreditRecordDao.saveUploadPhotoRecord(user);
        if (user.getCredits() == null) {
            user.setCredits(0);
        }
        user.setCredits(user.getCredits() + ccre.getAmount());
        user.setUpdateTime(new Date());
        cmUserDao.update((T) user);
        clearUserCache(user.getUserId());
        return ccre.getAmount();
    }

    @Override
    public Integer countAllCreditsNotNull() {
        Integer count = cmUserDao.countAllCreditsNotNull();
        return count;
    }

    @Override
    public Integer countAllRemainingCredits() {
        Integer count = cmUserDao.countAllRemainingCredits();
        return count;
    }

    @Override
    public Map getUserCreditTask(String userId) {
        return cmUserDao.getUserCreditTask(userId);
    }

    @Override
    public Integer countDeviceInvite(String deviceId) {
        return cmUserDao.countDeviceInvite(deviceId);
    }

    @Override
    public CmUserEntity getUserEntity(String userId) {
        return cmUserDao.getUserEntity(userId);
    }

    /**
     * 查询事业部榜单
     *
     * @param startTime
     * @param endTime
     * @return
     */
    @Override
    public List<CmUserEntity> selectRanksByDivision(String startTime, String endTime) {
        return cmUserDao.selectRanksByDivision(startTime, endTime);
    }

    /**
     * 查询个人榜单
     *
     * @param startTime
     * @param endTime
     * @return
     */
    @Override
    public List<CmUserEntity> selectRanksByInvite(String startTime, String endTime) {
        return cmUserDao.selectRanksByInvite(startTime, endTime);
    }

    /**
     * 查询个人推荐信息
     *
     * @param startTime
     * @param endTime
     * @return
     */
    @Override
    public CmUserEntity getRankByInvite(Integer userId, String startTime, String endTime) {
        return cmUserDao.getRankByInvite(userId, startTime, endTime);
    }
}
