package com.house365.ws.interfaces.rest;

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

import com.house365.ws.service.interfaces.ICmCreditRuleService;
import com.house365.ws.util.CmCommonUtils;
import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.ServiceRunException;
import com.house365.ws.dao.interfaces.ICmUserDao;
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("getSignedCredits")
public class GetSignedCreditsImpl implements IGetSignedCredits {
    private static final Logger LOGGER = LoggerFactory.getLogger("InterfaceLog");

    @Autowired
    private ICmUserDao<CmUserEntity> userDao;

    @Autowired
    ICmLotteryRuleService<CmLotteryRuleEntity> iCmLotteryRuleService;

    @Autowired
    ICmCreditRecordService<CmCreditRecordEntity> icmCreditRecordService;

    @Autowired
    ICmCreditRuleService cmCreditRuleService;

    @Autowired
    ICmUserService<CmUserEntity> iCmUserService;

    @Override
    public Object exectue(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        Map<String, Object> resultMap = new HashMap<>();
        // 业务层统一处理
        try {
            String cityKey = CmCommonUtils.getCityFromMap(map);

            if (!map.containsKey(CmConstant.USERID) || map.get(CmConstant.USERID) == null) {
                resultMap.put("result", ReturnAppResult.APP_FAIL.getResultCode());
                resultMap.put("msg", "用户参数不存在!");
                return JSONObject.fromObject(resultMap).toString();
            }
            
            CmUserEntity cmUser = iCmUserService.registUserByUserId(map);
            if (cmUser == null) {
                throw new ServiceRunException("用户中心用户不存在!");
            }

            //最近签到时间
            Date lastSignTime = cmUser.getLastSignTime();
            //如果签到为空
            if (lastSignTime != null) {
                Calendar cal = Calendar.getInstance();
                cal.setTime(lastSignTime);
                int dayLast = cal.get(Calendar.DAY_OF_YEAR);
                int yearLast = cal.get(Calendar.YEAR);

                Calendar calNow = Calendar.getInstance();
                int dayNow = calNow.get(Calendar.DAY_OF_YEAR);
                int yearNow = calNow.get(Calendar.YEAR);

                if (yearNow == yearLast && dayNow == dayLast) {
                    resultMap.put("result", ReturnAppResult.APP_FAIL.getResultCode());
                    resultMap.put("msg", "今日已签到!");
                    return JSONObject.fromObject(resultMap).toString();
                }

                Calendar fromCalendar = Calendar.getInstance();
                fromCalendar.setTime(lastSignTime);
                fromCalendar.set(Calendar.HOUR_OF_DAY, 0);
                fromCalendar.set(Calendar.MINUTE, 0);
                fromCalendar.set(Calendar.SECOND, 0);
                fromCalendar.set(Calendar.MILLISECOND, 0);

                Calendar toCalendar = Calendar.getInstance();
                toCalendar.setTime(new Date());
                toCalendar.set(Calendar.HOUR_OF_DAY, 0);
                toCalendar.set(Calendar.MINUTE, 0);
                toCalendar.set(Calendar.SECOND, 0);
                toCalendar.set(Calendar.MILLISECOND, 0);

                //和最后一次签到间隔天数
                long day = (toCalendar.getTime().getTime() - fromCalendar.getTime().getTime()) / (1000 * 60 * 60 * 24);

                //连续签到则加1
                if (day == 1) {
                    Integer signCount = cmUser.getContinuousSignCount() == null ? 0 : cmUser.getContinuousSignCount();
                    cmUser.setContinuousSignCount(signCount + 1);
                } else {//否则归为1
                    cmUser.setContinuousSignCount(1);
                }
            } else {//如果签到积分记录不为空
                cmUser.setContinuousSignCount(1);
            }

            Integer resultCredits = iCmLotteryRuleService.transGetSignedScore(cmUser, cityKey);

            Map<String, Object> dataMap = new HashMap<>();
            dataMap.put("credits", resultCredits);
            dataMap.put("continuousSignCount", cmUser.getContinuousSignCount());
            dataMap.put("createTime", new Date());
            resultMap.put("data", dataMap);
            resultMap.put("result", ReturnAppResult.APP_SUCCESS.getResultCode());
            resultMap.put("msg", "获取成功！");
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", ReturnAppResult.APP_FAIL.getResultCode());
            resultMap.put("msg", "获取信息失败!");
        }
        return JSONObject.fromObject(resultMap).toString();
    }

    @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

    }

}
