/*
 * 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.util.ObjectUtil;
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 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.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.CommonCryptogramUtil;

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 {

    @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());
        }
        // 校验数据范围
        List<String> loginUserDataScope = StpLoginUserUtil.getLoginUserDataScope();
        if (ObjectUtil.isEmpty(loginUserDataScope)) {
            queryWrapper.in("brr.user_id", StpLoginUserUtil.getLoginUser().getId());
        }
        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"));
        return bizCouponRecord;
    }

    /***/
    @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);
    }
}
