package com.zhongzheng.modules.activity.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import com.zhongzheng.common.utils.DateUtils;
import com.zhongzheng.modules.activity.service.IActivityConfigurationService;
import com.zhongzheng.modules.activity.vo.ActivityConfigurationVo;
import com.zhongzheng.modules.order.bo.CouponAddBo;
import com.zhongzheng.modules.order.service.ICouponService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.Page;
import com.zhongzheng.modules.activity.bo.ActivityConfigurationUseAddBo;
import com.zhongzheng.modules.activity.bo.ActivityConfigurationUseQueryBo;
import com.zhongzheng.modules.activity.bo.ActivityConfigurationUseEditBo;
import com.zhongzheng.modules.activity.domain.ActivityConfigurationUse;
import com.zhongzheng.modules.activity.mapper.ActivityConfigurationUseMapper;
import com.zhongzheng.modules.activity.vo.ActivityConfigurationUseVo;
import com.zhongzheng.modules.activity.service.IActivityConfigurationUseService;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author change
 * @date 2021-06-15
 */
@Service
public class ActivityConfigurationUseServiceImpl extends ServiceImpl<ActivityConfigurationUseMapper, ActivityConfigurationUse> implements IActivityConfigurationUseService {

    @Autowired
    private IActivityConfigurationService activityConfigurationService;

    @Autowired
    private ICouponService couponService;

    @Override
    public ActivityConfigurationUseVo queryById(Long userId){
        ActivityConfigurationUse db = this.baseMapper.selectById(userId);
        return BeanUtil.toBean(db, ActivityConfigurationUseVo.class);
    }

    @Override
    public List<ActivityConfigurationUseVo> queryList(ActivityConfigurationUseQueryBo bo) {
        LambdaQueryWrapper<ActivityConfigurationUse> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getActivityType() != null, ActivityConfigurationUse::getActivityType, bo.getActivityType());
        lqw.eq(bo.getUse() != null, ActivityConfigurationUse::getUse, bo.getUse());
        return entity2Vo(this.list(lqw));
    }

    /**
    * 实体类转化成视图对象
    *
    * @param collection 实体类集合
    * @return
    */
    private List<ActivityConfigurationUseVo> entity2Vo(Collection<ActivityConfigurationUse> collection) {
        List<ActivityConfigurationUseVo> voList = collection.stream()
                .map(any -> BeanUtil.toBean(any, ActivityConfigurationUseVo.class))
                .collect(Collectors.toList());
        if (collection instanceof Page) {
            Page<ActivityConfigurationUse> page = (Page<ActivityConfigurationUse>)collection;
            Page<ActivityConfigurationUseVo> pageVo = new Page<>();
            BeanUtil.copyProperties(page,pageVo);
            pageVo.addAll(voList);
            voList = pageVo;
        }
        return voList;
    }

    @Override
    public Boolean insertByAddBo(ActivityConfigurationUseAddBo bo) {
        ActivityConfigurationUse add = BeanUtil.toBean(bo, ActivityConfigurationUse.class);
        validEntityBeforeSave(add);
        return this.save(add);
    }

    @Override
    public Boolean updateByEditBo(ActivityConfigurationUseEditBo bo) {
        ActivityConfigurationUse update = BeanUtil.toBean(bo, ActivityConfigurationUse.class);
        validEntityBeforeSave(update);
        return this.updateById(update);
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(ActivityConfigurationUse entity){
        //TODO 做一些数据校验,如唯一约束
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return this.removeByIds(ids);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean receive(ActivityConfigurationUseAddBo bo) {
        //判断用户是否领取过活动
        if (baseMapper.queryByUse(bo) > 0){
            throw new IllegalArgumentException("已领取活动，请勿重复领取");
        }
        if (bo.getConfigurationId() == null){
            throw new IllegalArgumentException("活动ID为空");
        }
        //未领取过领取活动
        bo.setCreateTime(DateUtils.getNowTime());
        ActivityConfigurationVo activityConfigurationVo = activityConfigurationService.queryById(bo.getConfigurationId());
        bo.setActivityType(Convert.toInt(activityConfigurationVo.getActivityType()));
        switch (bo.getActivityType()){
            case 3:
            case 4:
            case 2:
            case 5:
                bo.setUse(1);
                break;
            //向卡券表中生成优惠券或折扣券
            default:
                bo.setUse(0);
                CouponAddBo couponAddBo = new CouponAddBo();
                couponAddBo.setPrice(activityConfigurationVo.getPrice());
                couponAddBo.setEndTime(afterSixMonthDate(new Date(),activityConfigurationVo.getCouponEnd()));
                couponAddBo.setUserId(bo.getUserId());
                couponAddBo.setUserStatus(0);
                couponAddBo.setConfigurationId(bo.getConfigurationId());
                couponAddBo.setCouponType(Convert.toInt(activityConfigurationVo.getActivityType()));
                couponService.insertByAddBo(couponAddBo);
        }
        return this.insertByAddBo(bo);
    }

    @Override
    public Integer countConfig(Long id) {
        Integer num = baseMapper.countConfig(id);
        return num;
    }

    @Override
    public Integer queryByCount(Long userId) {
        ActivityConfigurationUseAddBo activityConfigurationUseAddBo = new ActivityConfigurationUseAddBo();
        activityConfigurationUseAddBo.setUserId(userId);
        return baseMapper.queryByUse(activityConfigurationUseAddBo);
    }

    public Long afterSixMonthDate(Date currentDate,Integer amount){
        Calendar c = Calendar.getInstance();
        c.setTime(currentDate);
        c.add(Calendar.MONTH, amount);
        Date m3 = c.getTime();
        return m3.getTime();
    }

}
