package com.sqx.modules.app.service.impl;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.map.MapProxy;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyun.tea.ValidateException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.common.exception.SqxException;
import com.sqx.common.utils.Constant;
import com.sqx.common.utils.PageUtils;
import com.sqx.modules.app.dao.UserDao;
import com.sqx.modules.app.dao.UserPrizeExchangeDao;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.entity.UserPrizeExchange;
import com.sqx.modules.app.service.UserPrizeExchangeService;
import com.sqx.modules.discSpinning.dao.DiscSpinningRecordDao;
import com.sqx.modules.discSpinning.entity.DiscSpinningRecord;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;

/**
 * @author tankaikai
 * @since 2024-12-20 18:10
 */
@Slf4j
@Service
public class UserPrizeExchangeServiceImpl extends ServiceImpl<UserPrizeExchangeDao, UserPrizeExchange> implements UserPrizeExchangeService {

    @Resource
    private DiscSpinningRecordDao discSpinningRecordDao;

    @Resource
    private UserDao userDao;

    @Override
    public PageUtils page(Map<String, Object> params) {
        MapProxy proxy = MapProxy.create(params);
        Long discSpinningRecordId = proxy.getLong("discSpinningRecordId");
        Long userId = proxy.getLong("userId");
        String userName = proxy.getStr("userName");
        String prizeName = proxy.getStr("prizeName");
        Integer status = proxy.getInt("status");
        String phone = proxy.getStr("phone");
        String remark = proxy.getStr("remark");
        String beginDate = proxy.getStr("beginDate");
        String endDate = proxy.getStr("endDate");
        LambdaQueryWrapper<UserPrizeExchange> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(discSpinningRecordId != null, UserPrizeExchange::getDiscSpinningRecordId, discSpinningRecordId);
        wrapper.eq(userId != null, UserPrizeExchange::getUserId, userId);
        wrapper.like(StrUtil.isNotEmpty(userName), UserPrizeExchange::getUserName, userName);
        wrapper.like(StrUtil.isNotEmpty(prizeName), UserPrizeExchange::getPrizeName, prizeName);
        wrapper.eq(status != null, UserPrizeExchange::getStatus, status);
        wrapper.like(StrUtil.isNotEmpty(phone), UserPrizeExchange::getPhone, phone);
        wrapper.like(StrUtil.isNotEmpty(remark), UserPrizeExchange::getRemark, remark);
        if (StrUtil.isNotEmpty(beginDate)) {
            wrapper.apply("create_time >= str_to_date({0}, '%Y-%m-%d %H:%i:%s')", beginDate + " 00:00:00");
        }
        if (StrUtil.isNotEmpty(endDate)) {
            wrapper.apply("create_time <= str_to_date({0}, '%Y-%m-%d %H:%i:%s')", endDate + " 23:59:59");
        }
        wrapper.orderByDesc(UserPrizeExchange::getId);
        long pageNum = proxy.getLong(Constant.PAGE, 1L);
        long pageSize = proxy.getLong(Constant.LIMIT, 10L);
        IPage<UserPrizeExchange> page = this.page(new Page<>(pageNum, pageSize), wrapper);
        return new PageUtils(page);
    }

    @Override
    public void exchange(Long currentUserId, UserPrizeExchange dto) {
        if (dto.getDiscSpinningRecordId() == null) {
            throw new SqxException("中奖记录ID不能为空");
        }
        if (StrUtil.isBlank(dto.getPhone())) {
            throw new SqxException("用户手机号码不能为空");
        }
        try {
            Validator.isMobile(dto.getPhone());
        } catch (ValidateException e) {
            throw new SqxException("用户手机号码不合法");
        }
        DiscSpinningRecord record = discSpinningRecordDao.selectById(dto.getDiscSpinningRecordId());
        if (record == null) {
            throw new SqxException("中奖记录不存在");
        }
        if (record.getUserId() == null) {
            throw new SqxException("中奖用户数据不完整");
        }
        if (currentUserId == null) {
            throw new SqxException("未获取当前登录用户id");
        }
        Long userId = record.getUserId();
        if (!currentUserId.equals(userId)) {
            throw new SqxException("兑奖用户和获奖用户不一致");
        }
        UserEntity user = userDao.selectById(record.getUserId());
        if (user == null) {
            throw new SqxException("兑奖用户不存在");
        }
        if (ArrayUtil.contains(new int[]{1, 2}, record.getType())) {
            throw new SqxException("仅限兑换实物、会员卡等奖项");
        }
        Integer count = baseMapper.selectCount(Wrappers.<UserPrizeExchange>lambdaQuery()
                .eq(UserPrizeExchange::getDiscSpinningRecordId, record.getId())
        );
        if (count != null && count > 0) {
            throw new SqxException("奖品已兑换，请勿重复操作");
        }
        dto.setPrizeName(record.getName());
        dto.setUserId(record.getUserId());
        dto.setUserName(user.getUserName());
        dto.setStatus(0);
        dto.setCreateTime(new Date());
        baseMapper.insert(dto);
    }

    @Override
    public void deliver(UserPrizeExchange dto) {
        Long id = dto.getId();
        if (id == null) {
            throw new SqxException("兑奖id不能为空");
        }
        UserPrizeExchange entity = baseMapper.selectById(id);
        if (entity == null) {
            throw new SqxException("兑奖订单不存在");
        }
        entity.setStatus(1);
        if (StrUtil.isNotEmpty(dto.getAddress())) {
            entity.setAddress(dto.getAddress());
        }
        if (StrUtil.isNotEmpty(dto.getRemark())) {
            entity.setRemark(dto.getRemark());
        }
        entity.setUpdateTime(new Date());
        baseMapper.updateById(entity);
    }
}
