package com.qs.mp.admin.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.qs.mp.admin.domain.Coupon;
import com.qs.mp.admin.domain.CouponPkg;
import com.qs.mp.admin.domain.CouponPkgItem;
import com.qs.mp.admin.domain.Ticket;
import com.qs.mp.admin.domain.param.CouponPkgItemParam;
import com.qs.mp.admin.domain.param.CouponPkgParam;
import com.qs.mp.admin.domain.vo.CouponPkgItemVO;
import com.qs.mp.admin.domain.vo.CouponPkgVO;
import com.qs.mp.admin.mapper.CouponPkgMapper;
import com.qs.mp.admin.service.ICouponPkgItemService;
import com.qs.mp.admin.service.ICouponPkgService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qs.mp.admin.service.ICouponService;
import com.qs.mp.channel.domain.Channel;
import com.qs.mp.channel.service.IChannelService;
import com.qs.mp.common.constant.Constants;
import com.qs.mp.common.enums.CouponPkgStatusEnum;
import com.qs.mp.common.enums.CouponUseAreaEnum;
import com.qs.mp.common.enums.UserCouponStatusEnum;
import com.qs.mp.common.exception.ServiceException;
import com.qs.mp.common.utils.DateUtils;
import com.qs.mp.common.utils.LogUtil;
import com.qs.mp.system.service.id.BizIdGenerator;
import com.qs.mp.user.domain.UserCoupon;
import com.qs.mp.user.domain.UserCouponChannel;
import com.qs.mp.user.domain.UserTicketOrder;
import com.qs.mp.user.domain.UserTicketOrderItem;
import com.qs.mp.user.service.IUserCouponChannelService;
import com.qs.mp.user.service.IUserCouponService;
import com.qs.mp.user.service.IUserTicketOrderItemService;
import com.qs.mp.user.service.IUserTicketOrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 券包表 服务实现类
 * </p>
 *
 * @author quanshu
 * @since 2022-04-29
 */
@Service
public class CouponPkgServiceImpl extends ServiceImpl<CouponPkgMapper, CouponPkg> implements ICouponPkgService {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ICouponPkgItemService couponPkgItemService;


    @Autowired
    private ICouponService couponService;

    @Override
    @Transactional(rollbackFor = Exception.class)

    public void distributeByMarketing(Long userId, String couponPkgId) {
        List<CouponPkgItem> couponPkgItems = couponPkgItemService.list(new LambdaQueryWrapper<CouponPkgItem>().eq(CouponPkgItem::getCouponPkgId, couponPkgId));

        if (CollectionUtils.isEmpty(couponPkgItems)) {
            throw new ServiceException("券包下优惠券不存在");
        }
        for (CouponPkgItem couponPkgItem : couponPkgItems) {
            for (int i = 0; i < couponPkgItem.getCouponNum(); i++) {
                couponService.distributeByMarketing(userId, couponPkgItem.getCouponId().toString());
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void distribute(Ticket ticket, Long userId, String couponPkgId) {
        List<CouponPkgItem> couponPkgItems = couponPkgItemService.list(new LambdaQueryWrapper<CouponPkgItem>().eq(CouponPkgItem::getCouponPkgId, couponPkgId));

        if (CollectionUtils.isEmpty(couponPkgItems)) {
            throw new ServiceException("券包下优惠券不存在");
        }
        for (CouponPkgItem couponPkgItem : couponPkgItems) {
            for (int i = 0; i < couponPkgItem.getCouponNum(); i++) {
                couponService.distribute(ticket, userId, couponPkgItem.getCouponId().toString());
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Long id) {

        // 删除券包明细
        couponPkgItemService.remove(new LambdaQueryWrapper<CouponPkgItem>().eq(CouponPkgItem::getCouponPkgId, id));

        // 删除券包
        this.removeById(id);

        return true;
    }

    @Override
    public CouponPkgVO detail(Long id) {
        CouponPkgVO couponPkgVO = new CouponPkgVO();

        // 封装券包信息
        CouponPkg couponPkg = this.getById(id);
        if (Objects.isNull(couponPkg)) {
            throw new ServiceException("券包不存在");
        }
        BeanUtils.copyProperties(couponPkg, couponPkgVO);

        // 封装券包明细信息
        List<CouponPkgItemVO> list = couponPkgItemService.listDetailByCouponPkgId(id);
        couponPkgVO.setCouponPkgItemVOList(list);

        return couponPkgVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateCouponPkg(CouponPkgParam couponPkgParam) {

        if (Objects.isNull(couponPkgParam.getId()) || couponPkgParam.getId() == 0) {
            throw new ServiceException("券包ID不正确");
        }

        CouponPkg couponPkg = this.getById(couponPkgParam.getId());
        if (Objects.isNull(couponPkg)) {
            throw new ServiceException("券包不存在");
        }

        if (!CouponPkgStatusEnum.PUT_INIT.getValue().equals(couponPkg.getStatus())) {
            throw new ServiceException("券包只有待上架才可编辑");
        }


        List<CouponPkgItemParam> couponPkgItemList = couponPkgParam.getCouponPkgItemList();
        if (CollectionUtils.isEmpty(couponPkgItemList)) {
            throw new ServiceException("券包明细不能为空");
        }

        // 清除券包明细
        couponPkgItemService.remove(new LambdaQueryWrapper<CouponPkgItem>()
                .eq(CouponPkgItem::getCouponPkgId, couponPkgParam.getId()));

        // 更新券包
        couponPkg = new CouponPkg();
        BeanUtils.copyProperties(couponPkgParam, couponPkg);
        couponPkg.setPicUrl(Constants.COUPON_PIC);
        this.updateById(couponPkg);

        // 创建券包明细
        List<CouponPkgItem> params = new ArrayList<>();
        for (CouponPkgItemParam couponPkgItemParam : couponPkgItemList) {
            CouponPkgItem param = new CouponPkgItem();
            param.setCouponPkgId(couponPkg.getId());
            param.setCouponId(couponPkgItemParam.getCouponId());
            param.setCouponNum(couponPkgItemParam.getCouponNum());
            params.add(param);
        }
        couponPkgItemService.saveBatch(params);

        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean create(CouponPkgParam couponPkgParam) {

        List<CouponPkgItemParam> couponPkgItemList = couponPkgParam.getCouponPkgItemList();
        if (CollectionUtils.isEmpty(couponPkgItemList)) {
            throw new ServiceException("券包明细不能为空");
        }

        CouponPkg couponPkg = new CouponPkg();
        BeanUtils.copyProperties(couponPkgParam, couponPkg);
        couponPkg.setPicUrl(Constants.COUPON_PIC);
        this.save(couponPkg);

        List<CouponPkgItem> params = new ArrayList<>();
        for (CouponPkgItemParam couponPkgItemParam : couponPkgItemList) {
            CouponPkgItem param = new CouponPkgItem();
            param.setCouponPkgId(couponPkg.getId());
            param.setCouponId(couponPkgItemParam.getCouponId());
            param.setCouponNum(couponPkgItemParam.getCouponNum());
            params.add(param);
        }
        couponPkgItemService.saveBatch(params);

        return true;
    }
}
