package com.fs.store.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.fs.common.exception.CustomException;
import com.fs.common.utils.DateUtils;
import com.fs.common.utils.StringUtils;
import com.fs.store.config.StoreSignConfig;
import com.fs.store.domain.FsUser;
import com.fs.store.domain.FsUserIntegralLogs;
import com.fs.store.enums.BillDetailEnum;
import com.fs.store.mapper.FsUserIntegralLogsMapper;
import com.fs.store.mapper.FsUserMapper;
import com.fs.store.param.FsUserSignQueryParam;
import com.fs.store.service.IFsUserBillService;
import com.fs.system.service.ISysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.fs.store.mapper.FsUserSignMapper;
import com.fs.store.domain.FsUserSign;
import com.fs.store.service.IFsUserSignService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 签到记录Service业务层处理
 *
 * @author fs
 * @date 2022-03-15
 */
@Service
public class FsUserSignServiceImpl implements IFsUserSignService
{
    @Autowired
    private FsUserSignMapper fsUserSignMapper;
    @Autowired
    private FsUserMapper userMapper;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private IFsUserBillService billService;
    @Autowired
    private FsUserIntegralLogsMapper integralLogsMapper;
    /**
     * 查询签到记录
     *
     * @param int 签到记录ID
     * @return 签到记录
     */
    @Override
    public FsUserSign selectFsUserSignById(Long id)
    {
        return fsUserSignMapper.selectFsUserSignById(id);
    }

    /**
     * 查询签到记录列表
     *
     * @param fsUserSign 签到记录
     * @return 签到记录
     */
    @Override
    public List<FsUserSign> selectFsUserSignList(FsUserSign fsUserSign)
    {
        return fsUserSignMapper.selectFsUserSignList(fsUserSign);
    }

    /**
     * 新增签到记录
     *
     * @param fsUserSign 签到记录
     * @return 结果
     */
    @Override
    public int insertFsUserSign(FsUserSign fsUserSign)
    {
        fsUserSign.setCreateTime(DateUtils.getNowDate());
        return fsUserSignMapper.insertFsUserSign(fsUserSign);
    }

    /**
     * 修改签到记录
     *
     * @param fsUserSign 签到记录
     * @return 结果
     */
    @Override
    public int updateFsUserSign(FsUserSign fsUserSign)
    {
        fsUserSign.setUpdateTime(DateUtils.getNowDate());
        return fsUserSignMapper.updateFsUserSign(fsUserSign);
    }

    /**
     * 批量删除签到记录
     *
     * @param ints 需要删除的签到记录ID
     * @return 结果
     */
    @Override
    public int deleteFsUserSignByIds(Long[] ids)
    {
        return fsUserSignMapper.deleteFsUserSignByIds(ids);
    }

    /**
     * 删除签到记录信息
     *
     * @param int 签到记录ID
     * @return 结果
     */
    @Override
    public int deleteFsUserSignById(Long id)
    {
        return fsUserSignMapper.deleteFsUserSignById(id);
    }

    @Override
    @Transactional
    public Long sign(FsUser user) {
        String json=configService.selectConfigByKey("store.sign");
        if(StringUtils.isEmpty(json)) {
            throw new CustomException("请先配置签到天数");
        }
        JSONArray jsonArray= JSONUtil.parseArray(json);
        List<StoreSignConfig> signs=jsonArray.toList(StoreSignConfig.class);
        boolean isDaySign = this.getToDayIsSign(user.getUserId());
        if(isDaySign) {
            throw new CustomException("已签到");
        }
        Long signNumber = 0l; //积分
        Long userSignNum = user.getSignNum(); //签到次数
        if(getYesterDayIsSign(user.getUserId())){
            if(user.getSignNum() > (signs.size() - 1)){
                userSignNum = 0l;
            }
        }else{
            userSignNum = 0l;
        }
        int index = 0;
        for (StoreSignConfig config : signs) {
            if(index == userSignNum){
                signNumber = config.getSignNum();
                break;
            }
            index++;
        }
        userSignNum += 1;


        FsUserSign userSign = new FsUserSign();
        userSign.setUserId(user.getUserId());
        String title = "签到奖励";
        if(userSignNum == signs.size()){
            title = "连续签到奖励";
        }
        userSign.setTitle(title);
        userSign.setNumber(signNumber);
        userSign.setCreateTime(new Date());
        userSign.setBalance(user.getIntegral().longValue());
        fsUserSignMapper.insertFsUserSign(userSign);

        FsUserIntegralLogs logs = new FsUserIntegralLogs();
        logs.setIntegral(BigDecimal.valueOf(signNumber));
        logs.setUserId(user.getUserId());
        logs.setBalance(NumberUtil.add(user.getIntegral(),signNumber));
        logs.setLogType(1);
        logs.setBusinessId(userSign.getId().toString());
        logs.setCreateTime(new Date());
        integralLogsMapper.insertFsUserIntegralLogs(logs);
        //用户积分增加
        FsUser userMap =new  FsUser();
        userMap.setIntegral(NumberUtil.add(user.getIntegral(),signNumber));
        userMap.setUserId(user.getUserId());
        userMap.setSignNum(userSignNum);

        Integer res =userMapper.updateFsUser(userMap);
        if(res==0) {
            throw new CustomException("签到失败");
        }
        //插入流水
//        billService.addBill(user.getUserId(),BillDetailEnum.CATEGORY_2.getValue(),1,BillDetailEnum.TYPE_7.getDesc(),signNumber.doubleValue(),user.getIntegral().doubleValue(),title,"",0l);
        return signNumber;
    }

    @Override
    public List<FsUserSign> selectFsUserSignListQuery(FsUserSignQueryParam param) {
        return fsUserSignMapper.selectFsUserSignListQuery(param);
    }

    @Override
    public Long getSign(FsUser user) {
        String json=configService.selectConfigByKey("store.sign");
        if(StringUtils.isEmpty(json)) {
            throw new CustomException("请先配置签到天数");
        }
        JSONArray jsonArray= JSONUtil.parseArray(json);
        List<StoreSignConfig> signs=jsonArray.toList(StoreSignConfig.class);
        boolean isDaySign = this.getToDayIsSign(user.getUserId());
        Long userSignNum = user.getSignNum(); //签到次数
        if(getYesterDayIsSign(user.getUserId())){
            if(user.getSignNum() > (signs.size() - 1)){
                if(isDaySign) {
                    return user.getSignNum();
                }
                else{
                    userSignNum = 0l;
                }
            }
        }else{
            if(isDaySign) {
                return user.getSignNum();
            }
            else{
                userSignNum = 0l;
            }

        }
        return userSignNum;
    }

    @Override
    public Boolean isDaySign(FsUser user) {
        boolean isDaySign = this.getToDayIsSign(user.getUserId());
        return isDaySign;
    }




    /**
     * 获取用户今天是否签到
     * @param userId uid
     * @return boolean true=YES false=NO
     */
    private boolean getToDayIsSign(Long userId) {
        Date today = DateUtil.beginOfDay(new Date());
        int count=fsUserSignMapper.getToDayIsSign(userId);
        if(count > 0) {
            return true;
        }
        return false;
    }

    /**
     * 获取用户昨天是否签到
     * @param userId userId
     * @return boolean
     */
    private boolean getYesterDayIsSign(Long userId) {

        int count=fsUserSignMapper.getYesterDayIsSign(userId);
        if(count > 0) {
            return true;
        }
        return false;
    }
}
