/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.biz.modular.couponrecord.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wechat.pay.java.service.cashcoupons.model.Coupon;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.biz.modular.couponconfig.entity.CouponConfig;
import vip.xiaonuo.biz.modular.couponconfig.service.CouponConfigService;
import vip.xiaonuo.biz.modular.rechargerecord.entity.BizRechargeRecord;
import vip.xiaonuo.biz.modular.rechargerecord.service.BizRechargeRecordService;
import vip.xiaonuo.biz.modular.user.entity.BizUser;
import vip.xiaonuo.biz.modular.user.service.BizUserService;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.biz.modular.couponrecord.entity.BizCouponRecord;
import vip.xiaonuo.biz.modular.couponrecord.mapper.BizCouponRecordMapper;
import vip.xiaonuo.biz.modular.couponrecord.param.BizCouponRecordAddParam;
import vip.xiaonuo.biz.modular.couponrecord.param.BizCouponRecordEditParam;
import vip.xiaonuo.biz.modular.couponrecord.param.BizCouponRecordIdParam;
import vip.xiaonuo.biz.modular.couponrecord.param.BizCouponRecordPageParam;
import vip.xiaonuo.biz.modular.couponrecord.service.BizCouponRecordService;
import vip.xiaonuo.common.util.CommonCouponGeneratorUtil;
import vip.xiaonuo.common.util.CommonCryptogramUtil;
import vip.xiaonuo.dev.api.DevConfigApi;

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

/**
 * 优惠券记录Service接口实现类
 *
 * @author wulei
 * @date  2025/02/06 17:38
 **/
@Service
public class BizCouponRecordServiceImpl extends ServiceImpl<BizCouponRecordMapper, BizCouponRecord> implements BizCouponRecordService {

    @Resource
    private BizRechargeRecordService bizRechargeRecordService;
    @Resource
    private CouponConfigService couponConfigService;

    @Resource
    private DevConfigApi devConfigApi;

    @Resource
    private BizCouponRecordService bizCouponRecordService;

    @Resource
    private BizUserService bizUserService;

    @Override
    public Page<BizCouponRecord> page(BizCouponRecordPageParam bizCouponRecordPageParam) {
        QueryWrapper<BizCouponRecord> queryWrapper = new QueryWrapper<BizCouponRecord>().checkSqlInjection();
        if(ObjectUtil.isNotEmpty(bizCouponRecordPageParam.getCouponNo())) {
            queryWrapper.like("bcr.coupon_no", bizCouponRecordPageParam.getCouponNo());
        }
        if(ObjectUtil.isNotEmpty(bizCouponRecordPageParam.getCouponStatus())) {
            queryWrapper.eq("bcr.coupon_status", bizCouponRecordPageParam.getCouponStatus());
        }
        if(ObjectUtil.isNotEmpty(bizCouponRecordPageParam.getBeginTime()) && ObjectUtil.isNotEmpty(bizCouponRecordPageParam.getEndTime())){
            queryWrapper.between("bcr.time",bizCouponRecordPageParam.getBeginTime()+" 00:00:00",bizCouponRecordPageParam.getEndTime()+" 23:59:59");
        }
        if(ObjectUtil.isNotEmpty(bizCouponRecordPageParam.getOrgId())){
            queryWrapper.eq("bcr.org_id",bizCouponRecordPageParam.getOrgId());
        }
        // 校验数据范围
        List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
        if (ObjectUtil.isEmpty(loginUserDataScope)) {
            queryWrapper.in("brr.user_id", StpLoginUserUtil.getLoginUser().getId());
        }
        queryWrapper.eq("bcr.delete_flag","NOT_DELETE");
        queryWrapper.orderByDesc("bcr.create_time");
        Page<BizCouponRecord> pageList = this.getBaseMapper().getPageList(CommonPageRequest.defaultPage(), queryWrapper);
        for(BizCouponRecord bizCouponRecord : pageList.getRecords()){
            if(ObjectUtil.isNotEmpty(bizCouponRecord.getPhone())){
                //电话号码解密
                bizCouponRecord.setPhone(CommonCryptogramUtil.doSm4CbcDecrypt(bizCouponRecord.getPhone()));
            }
        }
        return pageList;
    }

    @Override
    public Page<BizCouponRecord> userPage(BizCouponRecordPageParam bizCouponRecordPageParam) {
        QueryWrapper<BizCouponRecord> queryWrapper = new QueryWrapper<BizCouponRecord>().checkSqlInjection();
        if(ObjectUtil.isNotEmpty(bizCouponRecordPageParam.getCouponNo())) {
            queryWrapper.like("bcr.coupon_no", bizCouponRecordPageParam.getCouponNo());
        }
        if(ObjectUtil.isNotEmpty(bizCouponRecordPageParam.getCouponStatus())) {
            queryWrapper.eq("bcr.coupon_status", bizCouponRecordPageParam.getCouponStatus());
        }
        if(ObjectUtil.isNotEmpty(bizCouponRecordPageParam.getBeginTime()) && ObjectUtil.isNotEmpty(bizCouponRecordPageParam.getEndTime())){
            queryWrapper.between("bcr.time",bizCouponRecordPageParam.getBeginTime()+" 00:00:00",bizCouponRecordPageParam.getEndTime()+" 23:59:59");
        }
        if(ObjectUtil.isNotEmpty(bizCouponRecordPageParam.getOrgId())){
            queryWrapper.eq("bcr.org_id",bizCouponRecordPageParam.getOrgId());
        }
        queryWrapper.in("brr.user_id", StpLoginUserUtil.getLoginUser().getId());
        queryWrapper.eq("bcr.delete_flag","NOT_DELETE");
        queryWrapper.orderByDesc("bcr.create_time");
        Page<BizCouponRecord> pageList = this.getBaseMapper().getPageList(CommonPageRequest.defaultPage(), queryWrapper);
        for(BizCouponRecord bizCouponRecord : pageList.getRecords()){
            if(ObjectUtil.isNotEmpty(bizCouponRecord.getPhone())){
                //电话号码解密
                bizCouponRecord.setPhone(CommonCryptogramUtil.doSm4CbcDecrypt(bizCouponRecord.getPhone()));
            }
        }
        return pageList;
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(BizCouponRecordAddParam bizCouponRecordAddParam) {
        BizCouponRecord bizCouponRecord = BeanUtil.toBean(bizCouponRecordAddParam, BizCouponRecord.class);
        this.save(bizCouponRecord);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(BizCouponRecordEditParam bizCouponRecordEditParam) {
        BizCouponRecord bizCouponRecord = this.queryEntity(bizCouponRecordEditParam.getId());
        BeanUtil.copyProperties(bizCouponRecordEditParam, bizCouponRecord);
        this.updateById(bizCouponRecord);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<BizCouponRecordIdParam> bizCouponRecordIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(bizCouponRecordIdParamList, BizCouponRecordIdParam::getId));
    }

    @Override
    public BizCouponRecord detail(BizCouponRecordIdParam bizCouponRecordIdParam) {
        return this.queryEntity(bizCouponRecordIdParam.getId());
    }

    @Override
    public BizCouponRecord queryEntity(String id) {
        BizCouponRecord bizCouponRecord = this.getById(id);
        if(ObjectUtil.isEmpty(bizCouponRecord)) {
            throw new CommonException("优惠券记录不存在，id值为：{}", id);
        }
        return bizCouponRecord;
    }

    @Override
    public BizCouponRecord queryByCode(BizCouponRecordPageParam bizCouponRecordPageParam) {
        BizCouponRecord bizCouponRecord = this.getOne(new QueryWrapper<BizCouponRecord>().lambda().
                eq(BizCouponRecord::getCouponNo, bizCouponRecordPageParam.getCouponNo()).
                eq(BizCouponRecord::getCouponStatus,"0").
                last("limit 1"));
        if(ObjectUtil.isNull(bizCouponRecord)){
            throw new CommonException("蛋糕券已核销！");
        }
        /*BizRechargeRecord rechargeRecord = bizRechargeRecordService.getById(bizCouponRecord.getRechargeRecordId());
        if(ObjectUtil.isNotNull(rechargeRecord)){
            bizCouponRecord.setCouponAmount(rechargeRecord.getCouponAmount());
        }*/
        CouponConfig couponConfig = couponConfigService.getById(bizCouponRecord.getCouponId());
        if(ObjectUtil.isNotNull(couponConfig)){
            bizCouponRecord.setCouponAmount(couponConfig.getCouponAmount());
            bizCouponRecord.setCouponType(couponConfig.getCouponType());
        }
        return bizCouponRecord;
    }

    @Override
    public BizCouponRecord getCouponNoList(BizCouponRecordPageParam bizCouponRecordPageParam) {
        QueryWrapper<BizCouponRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("brr.user_id",bizCouponRecordPageParam.getUserId());
        queryWrapper.eq("bcr.delete_flag","NOT_DELETE");
        queryWrapper.groupBy("brr.user_id");
        BizCouponRecord couponNoList = this.getBaseMapper().getCouponNoList(queryWrapper);
        return couponNoList;
    }

    @Override
    public List<BizCouponRecord> getList(BizCouponRecordPageParam bizCouponRecordPageParam) {
        QueryWrapper<BizCouponRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("brr.user_id",bizCouponRecordPageParam.getUserId());
        queryWrapper.eq("bcr.coupon_status","0");
        queryWrapper.eq("bcr.delete_flag","NOT_DELETE");
        List<BizCouponRecord> list = this.getBaseMapper().getList(queryWrapper);
        return list;
    }

    /***/
    @Override
    public void destroy(BizCouponRecordEditParam bizCouponRecordEditParam) {
        //获取优惠券信息
        BizCouponRecord bizCouponRecord = this.queryEntity(bizCouponRecordEditParam.getId());
        //判断该优惠券是否过期
        if(ObjectUtil.isNotEmpty(bizCouponRecordEditParam.getEndTime())){
            if(new Date().getTime() > bizCouponRecord.getEndTime().getTime()){
                throw new CommonException("优惠券已过期！");
            }
        }
        if(StringUtils.equals(bizCouponRecord.getCouponStatus(),"1")){
            throw new CommonException("优惠券已经核销过！");
        }
        //状态修改成已核销
        bizCouponRecord.setCouponStatus("1");
        //核销人
        bizCouponRecord.setDestroyUser(StpLoginUserUtil.getLoginUser().getId());
        //核销时间
        bizCouponRecord.setDestroyTime(new Date());
        //核销门店
        bizCouponRecord.setOrgId(StpLoginUserUtil.getLoginUser().getOrgId());
        this.updateById(bizCouponRecord);
    }

    @Transactional
    @Override
    public void giftCoupon(BizCouponRecordEditParam bizCouponRecordEditParam) {
        //管理员手动赠送蛋糕券
        //当前传参id是会员id
        CouponConfig couponConfig = couponConfigService.queryEntity(bizCouponRecordEditParam.getCouponId());
        for(int i=0;i<couponConfig.getCouponNum();i++){
            //添加充值记录
            String planId = devConfigApi.getValueByKey("SNOWY_GIFT_COUPON");
            BizRechargeRecord bizRechargeRecord = new BizRechargeRecord();
            bizRechargeRecord.setUserId(bizCouponRecordEditParam.getId());
            bizRechargeRecord.setRechargePlanId(planId);
            bizRechargeRecord.setPlanAccountBalance(new BigDecimal(0));
            if(ObjectUtil.isNotNull(couponConfig)){
                bizRechargeRecord.setRechargePlanDescribe("手动赠送蛋糕券"+couponConfig.getCouponAmount()+(couponConfig.getCouponType().equals("1")?"寸":"元")+"1个");
            }
            bizRechargeRecord.setRechargeAmount(new BigDecimal(0));
            bizRechargeRecord.setRechargeTime(new Date());
            bizRechargeRecord.setCouponNum(couponConfig.getCouponNum());
            bizRechargeRecord.setCouponAmount(couponConfig.getCouponAmount());
            // 本系统订单号
            String orderNumber = "BBT" + DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_MS_PATTERN) + RandomUtil.randomNumbers(3);
            bizRechargeRecord.setOrderNo(orderNumber);
            bizRechargeRecord.setIsPay("1");
            BizUser bizUser = bizUserService.getById(bizCouponRecordEditParam.getId());
            if(ObjectUtil.isNotNull(bizUser)){
                bizRechargeRecord.setOldAccountBalance(bizUser.getAccountBalance());
                bizRechargeRecord.setOldVoucherBalance(bizUser.getVoucherBalance());
                bizRechargeRecord.setNewAccountBalance(bizUser.getAccountBalance());
                bizRechargeRecord.setNewVoucherBalance(bizUser.getVoucherBalance());
            }
            bizRechargeRecordService.save(bizRechargeRecord);

            //添加蛋糕券记录
            BizCouponRecord bizCouponRecord = new BizCouponRecord();
            DateTime date = DateUtil.date();
            bizCouponRecord.setCouponNo(CommonCouponGeneratorUtil.generateCouponCode());
            bizCouponRecord.setTime(date);
            bizCouponRecord.setStartTime(date);
            bizCouponRecord.setEndTime(DateUtil.offset(date, DateField.YEAR,1));
            bizCouponRecord.setRechargePlanId(bizRechargeRecord.getRechargePlanId());
            bizCouponRecord.setRechargeRecordId(bizRechargeRecord.getId());
            bizCouponRecord.setCouponId(couponConfig.getId());
            bizCouponRecordService.save(bizCouponRecord);
        }


    }
}
