package cn.iocoder.yudao.module.custom.service.impl;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.custom.entity.CustomerBalanceChange;
import cn.iocoder.yudao.module.custom.entity.CustomerCoupon;
import cn.iocoder.yudao.module.custom.mapper.CustomerCouponMapper;
import cn.iocoder.yudao.module.custom.service.CustomerBalanceChangeService;
import cn.iocoder.yudao.module.custom.service.CustomerCouponService;
import cn.iocoder.yudao.module.custom.vo.CustomerCouponPageReqVO;
import cn.iocoder.yudao.module.custom.vo.CustomerCouponRespVO;
import cn.iocoder.yudao.module.custom.vo.CustomerCouponSaveReqVO;
import cn.iocoder.yudao.module.member.entity.MemberCoupon;
import cn.iocoder.yudao.module.member.service.MemberCouponService;
import cn.iocoder.yudao.module.order.entity.RepairOrderInfo;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import static cn.iocoder.yudao.common.BaseConstants.*;

/**
 * 用户卡券 Service 实现类
 *
 * @author pqz
 */
@Service
@Validated
public class CustomerCouponServiceImpl extends ServiceImpl<CustomerCouponMapper, CustomerCoupon> implements CustomerCouponService {

    @Resource
    private CustomerCouponMapper customerCouponMapper;
    @Resource
    private CustomerBalanceChangeService changeService;
    @Resource
    private MemberCouponService couponService;



    /**
     * 卡券核销
     *
     * @param saveReqVO CustomerCouponSaveReqVO实体
     * @author PQZ
     * @date 15:37 2024/9/23
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void couponVerification(CustomerCouponSaveReqVO saveReqVO) {
        CustomerCoupon customerCoupon = getById(saveReqVO.getId());
        //核销后剩余
        BigDecimal newBalance = customerCoupon.getBalance().subtract(customerCoupon.getUnitPrice());
        customerCoupon.setBalance(newBalance);
        if (newBalance.compareTo(BigDecimal.ZERO) == 0) {
            customerCoupon.setIsValid(GENERAL_NO);
        }
        //保存核销后的卡券
        saveOrUpdate(customerCoupon);
        //保存核销记录
        changeService.saveChange(saveReqVO.getCusId(),
                saveReqVO.getUserId(),
                saveReqVO.getCouponId(),
                BALANCE_CHANGE_TYPE_KQHX,
                BALANCE_CHANGE_MAIN_KQ,
                saveReqVO.getOutRule(),
                saveReqVO.getUnitPrice(),
                newBalance,
                "核销" + saveReqVO.getCouponName() + saveReqVO.getUnitPrice() + "次/元，核销后剩余" + newBalance + "次/元"
        );
    }

    /**
     * 开卡有礼回调
     *
     * @param orderInfo RepairOrderInfo
     * @author PQZ
     * @date 21:50 2024/9/24
     **/
    @Override
    public void couponCallBack(RepairOrderInfo orderInfo) {
        List<String> ids = new ArrayList<>();
        ids.add(orderInfo.getGoodsId());
        //查询选中卡片信息
        List<MemberCoupon> couponList = couponService.listByIds(ids, true);
        List<CustomerCoupon> customerCouponList = transCoupon(orderInfo.getActiveId(), orderInfo.getCusId(), orderInfo.getUserId(),  couponList);
        List<CustomerBalanceChange> changeList = changeService.transChange(orderInfo.getCusId(), orderInfo.getUserId(), orderInfo.getGoodsTitle(), couponList);
        saveBatch(customerCouponList);
        changeService.saveBatch(changeList);
    }

    /**
     * 卡券实体转换
     *
     * @param couponList MemberCoupon集合
     * @return java.util.List<cn.iocoder.yudao.module.custom.entity.CustomerCoupon>
     * @author PQZ
     * @date 11:01 2024/9/21
     **/
    @Override
    public List<CustomerCoupon> transCoupon(String activeId, String cusId, Long userId, List<MemberCoupon> couponList) {
        List<CustomerCoupon> transList = new ArrayList<>();
        couponList.forEach(item -> {
            CustomerCoupon coupon = new CustomerCoupon();
            coupon.setCusId(cusId);
            coupon.setUserId(userId);
            coupon.setActiveId(activeId);
            coupon.setCouponId(item.getId());
            coupon.setAmount(item.getAmount());
            coupon.setBalance(item.getAmount());
            coupon.setUnitPrice(item.getUnitPrice());
            coupon.setOutRule(item.getOutRule());
            coupon.setIsValid(GENERAL_YES);
            transList.add(coupon);
        });
        return transList;
    }

    @Override
    public void deleteCustomerCoupon(String id) {
        // 删除
        customerCouponMapper.deleteById(id);
    }


    /**
     * 获取用户卡券信息及卡券变动信息
     *
     * @param id 用户卡券id
     * @return cn.iocoder.yudao.module.custom.vo.CustomerCouponRespVO
     * @author PQZ
     * @date 22:51 2024/9/20
     **/
    @Override
    public CustomerCouponRespVO getCustomerCoupon(String id) {
        CustomerCoupon coupon = getById(id);
        CustomerCouponRespVO result = BeanUtils.toBean(coupon, CustomerCouponRespVO.class);
        List<CustomerBalanceChange> changeList = changeService.getCouponChange(coupon.getCusId(), coupon.getCouponId());
        result.setChangeList(changeList);
        return result;
    }

    /**
     * 根据用户id获取卡券信息
     *
     * @param cusId 用户id
     * @return java.util.List<cn.iocoder.yudao.module.custom.vo.CustomerCouponRespVO>
     * @author PQZ
     * @date 20:43 2024/9/20
     **/
    @Override
    public List<CustomerCouponRespVO> listByCusId(String cusId) {
        return customerCouponMapper.listByCusId(cusId);
    }

}