package com.xxfc.platform.activity.biz;

import com.alibaba.fastjson.JSONArray;
import com.github.wxiaoqi.security.admin.feign.dto.AppUserDTO;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.xxfc.platform.activity.entity.IntegralRule;
import com.xxfc.platform.activity.entity.IntegralSignRecord;
import com.xxfc.platform.activity.entity.IntegralUserRecord;
import com.xxfc.platform.activity.mapper.IntegralSignRecordMapper;
import com.xxfc.platform.activity.user.UserInfoBiz;
import com.xxfc.platform.activity.util.IntegralToolsUtils;
import com.xxfc.platform.activity.vo.IntegralRuleDto;
import com.xxfc.platform.activity.vo.IntegralUserRecordDto;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class IntegralSignRecordBiz extends BaseBiz<IntegralSignRecordMapper, IntegralSignRecord> {

    @Autowired
    UserInfoBiz userInfoBiz;
    @Autowired
    IntegralRuleBiz integralRuleBiz;
    @Autowired
    IntegralUserTotalBiz integralUserTotalBiz;
    @Autowired
    IntegralUserRecordBiz integralUserRecordBiz;

    /**
     * 签到
     * @return
     */
    public ObjectRestResponse add(String code) {
        AppUserDTO appUserDTO = userInfoBiz.getUserInfo();
        if (appUserDTO == null) {
            return ObjectRestResponse.createFailedResult(508, "token is null or invalid");
        }
        if(StringUtils.isBlank(code)) {
            return ObjectRestResponse.createDefaultFail();
        }
        List<IntegralSignRecord> integralSignRecordList = mapper.selectByUserId(appUserDTO.getUserid());
        //第一次签到 默认连续１
        if(integralSignRecordList == null || integralSignRecordList.size() <= 0) {
            IntegralSignRecord integralSignRecord = new IntegralSignRecord();
            IntegralRuleDto integralRule = new IntegralRuleDto();
            integralRule.setCode(code);
            ObjectRestResponse<IntegralRule> objectRestResponse = integralRuleBiz.getOne(integralRule);
            if(objectRestResponse.getData() != null) {
                integralSignRecord.setUserId(appUserDTO.getUserid());
                integralSignRecord.setIsdel(false);
                integralSignRecord.setSignDays(1);
                integralSignRecord.setStartTime(new Date().getTime());
                integralSignRecord.setLastTime(new Date().getTime());
                mapper.insertSelective(integralSignRecord);
                IntegralRule oldValue = objectRestResponse.getData();
                addPoint(oldValue,integralSignRecord, appUserDTO, 1);
            } else { //规则不存在
                return ObjectRestResponse.createFailedResult(1003,"签到规则不存在！");
            }
            //已经签到过
        } else {
            IntegralSignRecord integralSignRecord = integralSignRecordList.get(0);
            //判断最后签到的时间和当前时间是不是相差一天
            int day = IntegralToolsUtils.differentDaysByMillisecond(integralSignRecord.getLastTime(), new Date().getTime());
            IntegralRuleDto integralRule = new IntegralRuleDto();
            integralRule.setCode(code);
            ObjectRestResponse<IntegralRule> objectRestResponse = integralRuleBiz.getOne(integralRule);
            if(objectRestResponse.getData() != null) {
                   if(day == 1) {//第二天续签
                       //修改签到记录
                       integralSignRecord.setSignDays(integralSignRecord.getSignDays() + 1);
                       integralSignRecord.setLastTime(new Date().getTime());
                       mapper.updateByPrimaryKeySelective(integralSignRecord);
                       //添加积分记录
                       addPoint(objectRestResponse.getData(),integralSignRecord, appUserDTO, integralSignRecord.getSignDays());
                   } else if(day >1 ) {//断续签
                       //规则连续签到 断签需要重新签到
                       if(objectRestResponse.getData().getIsContinuity()) {
                           integralSignRecord.setIsdel(true);
                           mapper.updateByPrimaryKeySelective(integralSignRecord);
                           IntegralSignRecord newValue = new IntegralSignRecord();
                           newValue.setUserId(appUserDTO.getUserid());
                           newValue.setIsdel(false);
                           newValue.setSignDays(1);
                           newValue.setStartTime(new Date().getTime());
                           newValue.setLastTime(new Date().getTime());
                           mapper.insertSelective(newValue);
                           addPoint(objectRestResponse.getData(),newValue, appUserDTO, newValue.getSignDays());
                       //规则不连续签到
                       } else {
                           integralSignRecord.setSignDays(integralSignRecord.getSignDays() + 1);
                           integralSignRecord.setLastTime(new Date().getTime());
                           mapper.updateByPrimaryKeySelective(integralSignRecord);
                           addPoint(objectRestResponse.getData(),integralSignRecord, appUserDTO, integralSignRecord.getSignDays());
                       }
                   } else { //当天多次签到
                       boolean flag = getSignNumberBoolean(appUserDTO, objectRestResponse.getData());
                       if(!flag) {//可以继续签到
                           integralSignRecord.setLastTime(new Date().getTime());
                           mapper.updateByPrimaryKeySelective(integralSignRecord);
                           addPoint(objectRestResponse.getData(),integralSignRecord, appUserDTO, integralSignRecord.getSignDays());
                           return  ObjectRestResponse.succ(objectRestResponse.getData().getPoint());
                       }
                       return ObjectRestResponse.createFailedResult(1006,"今日已签到！");
                   }
            } else {
                return ObjectRestResponse.createFailedResult(1003,"签到规则不存在！");
            }
    }
            return ObjectRestResponse.succ();
    }

    /**
     * 添加积分记录
     * @param integralRule
     * @param integralSignRecord
     * @param appUserDTO
     */
    public void addPoint(IntegralRule integralRule, IntegralSignRecord integralSignRecord, AppUserDTO appUserDTO, Integer day) {
        //获取的积分
        Integer point = 0;
        //获取其他规则积分
        Integer otherRulePoint = getOtherRulePoint(point, integralRule.getOtherRule(), integralSignRecord.getSignDays());
        if (day < integralRule.getFinishDay()) { //不符合积分天数规则
            point = IntegralToolsUtils.getMax(otherRulePoint, integralRule.getPoint(), 0);
        } else {//符合积分规则天数
            point = IntegralToolsUtils.getMax(otherRulePoint, integralRule.getPoint(), integralRule.getFinishPoint());
        }
        //添加积分记录
        List<IntegralSignRecord> integralSignRecords = mapper.selectByUserId(appUserDTO.getUserid());
        IntegralUserRecordDto integralUserRecord = new IntegralUserRecordDto();
        integralUserRecord.setUserId(appUserDTO.getUserid());
        integralUserRecord.setType(0);
        integralUserRecord.setChannelId(integralSignRecords.get(0).getId().toString());
        integralUserRecord.setIntegralRuleCode(integralRule.getCode());
        integralUserRecord.setPoint(point);
        integralUserRecordBiz.add(integralUserRecord);
}
    /**
     * 获取其他规则的积分
     * @return
     */
    public Integer getOtherRulePoint(Integer point, String  otherRule, Integer day){
        JSONArray jsonArray = JSONArray.parseArray(otherRule);
        if(jsonArray != null) { //其他规则积分
            for(int i = 0; i < jsonArray.size(); i++ ) {
                if(jsonArray.getJSONObject(i).getInteger("day") == day) {
                    point = jsonArray.getJSONObject(i).getInteger("integeral");
                }
            }
        }
        return point;
    }


    //判断签到次数是否超过规则
    public boolean getSignNumberBoolean(AppUserDTO appUserDTO, IntegralRule integralRule) {
        IntegralUserRecordDto integralUserRecordDto = new IntegralUserRecordDto();
        integralUserRecordDto.setUserId(appUserDTO.getUserid());
        integralUserRecordDto.setIntegralRuleCode(integralRule.getCode());
        switch (integralRule.getPeriod()) {
            case 0 : //日
                return getBoolean(IntegralToolsUtils.getDayStart(), IntegralToolsUtils.getDayStart() + 24 * 60 * 60 * 1000 - 1, integralUserRecordDto, integralRule);
            case 1:  //周
                return getBoolean(IntegralToolsUtils.weekFirstDay(0, -5), IntegralToolsUtils.weekFirstDay(0, 1) + 24 * 60 * 60 * 1000 - 1, integralUserRecordDto, integralRule);
            case 4:  //季度
                return getBoolean(IntegralToolsUtils.parseDate(IntegralToolsUtils.getCurrQuarter(IntegralToolsUtils.getQuarter())[0]), IntegralToolsUtils.parseDate(IntegralToolsUtils.getCurrQuarter(IntegralToolsUtils.getQuarter())[1]) + 24 * 60 * 60 * 1000 - 1, integralUserRecordDto, integralRule);
            case 3:  //月
                return getBoolean(IntegralToolsUtils.getMonthBegin(new Date()), IntegralToolsUtils.getMonthEnd(new Date()), integralUserRecordDto, integralRule);
            case 5:  //年
                return getBoolean(IntegralToolsUtils.getFirstDayOfYear(new Date()), IntegralToolsUtils.getLastDayOfYear(new Date()), integralUserRecordDto, integralRule);
            default:
                return false;
        }
    }


    public boolean getBoolean(Long startTime, Long endTime, IntegralUserRecordDto integralUserRecordDto, IntegralRule integralRule) {
        integralUserRecordDto.setStartTime(startTime);
        integralUserRecordDto.setEndTime(endTime);
        ObjectRestResponse<List<IntegralUserRecord>> restResponse = integralUserRecordBiz.getByUserAndTime(integralUserRecordDto);
        if(restResponse.getData() != null) {
            if(restResponse.getData().size() >= integralRule.getNumber()) {//签到数已经达标
                return true;
            } else { //未达标
                return false;
            }
        }
        return false;
    }


    public static void main(String[] args) {
            System.out.println(IntegralToolsUtils.getFirstDayOfYear(new Date()));
        System.out.println(IntegralToolsUtils.getLastDayOfYear(new Date()));
    }

}
