package cn.pluss.platform.userIntegral.impl;

import cn.pluss.platform.entity.*;
import cn.pluss.platform.enums.UserRoleEnum;
import cn.pluss.platform.mapper.MercOrderDetailMapper;
import cn.pluss.platform.mapper.MerchantStoreMapper;
import cn.pluss.platform.mapper.UserAppMapper;
import cn.pluss.platform.mapper.UserIntegralMapper;
import cn.pluss.platform.merchantOrder.MerchantOrderService;
import cn.pluss.platform.userIntegral.UserIntegralService;
import cn.pluss.platform.util.StringUtil;
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 lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户积分详情表 服务实现类
 * </p>
 *
 * @author crystal
 * @since 2022-05-17
 */
@Service
@Slf4j
public class UserIntegralServiceImpl extends ServiceImpl<UserIntegralMapper, UserIntegral> implements UserIntegralService {

    @Resource
    private UserAppMapper userAppMapper;

    @Resource
    private MerchantStoreMapper merchantStoreMapper;

    @Resource
    private MercOrderDetailMapper mercOrderDetailMapper;

    @Setter(onMethod_ = {@Autowired,@Lazy})
    private MerchantOrderService merchantOrderService;

    /**
     * BST积分条件 交易笔数2000比
     * @date: 2022/2/14 11:00
     */
    private final int BST_INTEGRAL_TRANS_NUM = 2000;


    private final BigDecimal BST_LI_BAO_AMT2 = BigDecimal.valueOf(169);
    /**
     * BST积分条件 交易金额50000
     * @date: 2022/2/14 11:00
     */
    private final double BST_INTEGRAL_TRANS_AMOUNT = 50000d;
    /**
     * 保存用户积分操作
     * @param orderNumber 订单号
     * @param orderAmt 订单金额
     * @param userId 用户ID
     * @param type 积分类型1：交易积分 2：机具积分 3：其他积分
     * @param source 订单来源 1：交易 2：云音箱 3：扫码王
     * @param integral 积分数值
     */
    @Override
    public void saveUserIntegral(String orderNumber,BigDecimal orderAmt, Long userId, String type,String source, BigDecimal integral) {
        UserIntegral userIntegral = new UserIntegral(orderNumber,orderAmt,userId,type,source,integral);
        this.save(userIntegral);
    }

    @Override
    public void bstOrderIntegralReward(MerchantOrder order) {
        log.info("【倍斯特】积分返操作开始，订单号:{}",order.getOrderNumber());
        try {
            String merchantCode = order.getMerchantCode();
            if(StringUtil.isEmpty(merchantCode)){
                return;
            }
            UserApp userApp = userAppMapper.selectByMerchantCode(merchantCode);
            if(userApp == null || !UserRoleEnum.ZY_BST.getCode().equals(userApp.getRoleCode())){
                return;
            }
            MerchantStore store = merchantStoreMapper.getStoreByMerchantCode(merchantCode);
            if(store == null || !"1".equals(store.getIsMarket())){
                return;
            }
            QueryWrapper<MercOrderDetail> queryDeviceWrapper = new QueryWrapper<MercOrderDetail>()
                    .eq("userId",userApp.getUserId()).in("status","01","05","06").eq("code","libao");
            List<MercOrderDetail> list = mercOrderDetailMapper.selectList(queryDeviceWrapper);
            if(list.isEmpty()){
                return;
            }
            QueryWrapper<UserIntegral> queryWrapper = new QueryWrapper<UserIntegral>()
                    .eq("userId",userApp.getUserId()).eq("type","2").eq("source","2");
            List<UserIntegral> lists = baseMapper.selectList(queryWrapper);
            if(!lists.isEmpty()){
                return;
            }
            QueryWrapper<MerchantOrder> orderQuery = new QueryWrapper<MerchantOrder>()
                    .eq("merchantCode",userApp.getMerchantCode())
                    .eq("status","1").select("count(1) as transNum,IFNULL(SUM(consumeFee),0) as transAmt");
            Map<String, Object> map = merchantOrderService.getMap(orderQuery);
            if(map == null || map.size() == 0){
                return;
            }
            long transNum = (long)map.get("transNum");
            double transAmt = (double) map.get("transAmt");
            log.info("【倍斯特】积分返操作成功，订单号:{},交易笔数：{}，交易总额：{}",order.getOrderNumber(),transNum,transAmt);
            if(transNum >= BST_INTEGRAL_TRANS_NUM || transAmt >= BST_INTEGRAL_TRANS_AMOUNT){
                this.saveUserIntegral(null,null,userApp.getUserId(),"2","2",BST_LI_BAO_AMT2);
                log.info("【倍斯特】积分返操作成功，订单号:{},用户ID：{}，积分数值：{}",order.getOrderNumber(),userApp.getUserId(),BST_LI_BAO_AMT2);
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error("【倍斯特】积分返异常,异常信息:{}",e.getMessage());
        }
    }

    /**
     * 查询积分余额
     * @param userId
     * @param date
     * @param auditDate
     * @return
     */
    @Override
    public BigDecimal getCountIntegral(Serializable userId, String date, String auditDate) {
        return baseMapper.getCountIntegral(userId,date,null);
    }

    /**
     * 查询积分余额
     * @param userId
     * @return
     */
    @Override
    public BigDecimal getCountIntegral(Serializable userId) {
        return baseMapper.getCountIntegral(userId);
    }

    /**
     * 分页查询
     * @param page
     * @param query
     * @return
     */
    @Override
    public Page<UserIntegral> pageInfo(Page<UserIntegral> page, UserIntegral query) {
        return baseMapper.pageInfo(page,query);
    }

    @Override
    public UserIntegral getByOrderNumber(String orderNumber) {
        return baseMapper.getByOrderNumber(orderNumber);
    }
}
