package top.continew.admin.business.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import top.continew.admin.business.mapper.ConsumptionHistoryMapper;
import top.continew.admin.business.model.entity.ConsumptionHistoryDO;
import top.continew.admin.business.model.query.ConsumptionHistoryQuery;
import top.continew.admin.business.model.req.ConsumptionHistoryAddReq;
import top.continew.admin.business.model.req.ConsumptionHistoryEditReq;
import top.continew.admin.business.model.req.ConsumptionReq;
import top.continew.admin.business.model.resp.ConsumptionHistoryResp;
import top.continew.admin.business.service.ConsumptionHistoryService;
import top.continew.admin.system.mapper.UserMapper;
import top.continew.admin.system.model.entity.UserDO;
import top.continew.admin.system.service.UserService;
import top.continew.starter.data.mp.service.impl.ServiceImpl;
import top.continew.starter.data.mp.util.QueryWrapperHelper;
import top.continew.starter.extension.crud.model.query.PageQuery;
import top.continew.starter.extension.crud.model.resp.PageResp;
import top.continew.starter.web.model.R;

import java.util.Collections;
import java.util.List;

/**
 * 用户充值消费历史记录业务实现
 *
 * @author jiay
 * @since 2025/extends7:51
 */
@Service
@RequiredArgsConstructor
public class ConsumptionHistoryServiceImpl extends ServiceImpl<ConsumptionHistoryMapper, ConsumptionHistoryDO> implements ConsumptionHistoryService {
    private final ConsumptionHistoryMapper consumptionHistoryMapper;
    private final UserMapper userMapper;
    private final UserService userService;

    @Override
    public List<ConsumptionHistoryResp> getConsumptionHistoryList(ConsumptionHistoryQuery query) {
        QueryWrapper queryWrapper = QueryWrapperHelper.build(query);
        List list = this.list(queryWrapper);

        if (CollectionUtil.isNotEmpty(list)) {
            return BeanUtil.copyToList(list, ConsumptionHistoryResp.class);
        }
        return Collections.emptyList();
    }

    @Override
    public boolean addConsumptionHistory(ConsumptionHistoryAddReq req) {
        //先校验userId
        String userId = req.getUserId();
        if (!StpUtil.isLogin(userId)) {
            StpUtil.login(userId);
        }

        userMapper.updateSysBeansById(Long.parseLong(userId), req.getChargePoints());

        ConsumptionHistoryDO entity = BeanUtil.copyProperties(req, ConsumptionHistoryDO.class);
        entity.setCreateUser(Long.parseLong(req.getUserId()));
        return consumptionHistoryMapper.insert(entity) > 0;
    }

    @Override
    public boolean editConsumptionHistory(ConsumptionHistoryEditReq req) {
        ConsumptionHistoryDO ConsumptionHistoryDO = BeanUtil.copyProperties(req, ConsumptionHistoryDO.class);
        return consumptionHistoryMapper.updateById(ConsumptionHistoryDO) > 0;

    }

    @Override
    public boolean deleteConsumptionHistory(Long id) {
        if (id != null) {
            return consumptionHistoryMapper.deleteById(id) > 0;
        }
        return false;
    }

    @Override
    public ConsumptionHistoryResp getConsumptionHistory(Long id) {
        ConsumptionHistoryDO ConsumptionHistoryDO = consumptionHistoryMapper.selectById(id);
        ConsumptionHistoryResp ConsumptionHistoryResp = new ConsumptionHistoryResp();
        if (ConsumptionHistoryDO != null) {
            ConsumptionHistoryResp = BeanUtil.copyProperties(ConsumptionHistoryDO, ConsumptionHistoryResp.class);
        }
        return ConsumptionHistoryResp;
    }

    @Override
    public PageResp<ConsumptionHistoryResp> getConsumptionHistoryPage(ConsumptionHistoryQuery query,
                                                                      PageQuery pageQuery) {
        QueryWrapper queryWrapper = QueryWrapperHelper.build(query);
        this.sort(queryWrapper, pageQuery.getSort());
        Page page = consumptionHistoryMapper.selectPage(new Page<>(pageQuery.getPage(), pageQuery
            .getSize()), queryWrapper);
        return PageResp.build(page);
    }

    /**
     * 设置排序
     *
     * @param queryWrapper 查询条件封装对象
     * @param sort         排序查询条件
     */
    private void sort(QueryWrapper queryWrapper, Sort sort) {
        if (sort == null || sort.isUnsorted()) {
            return;
        }
        for (Sort.Order order : sort) {
            String property = order.getProperty();
            queryWrapper.orderBy(true, order.isAscending(), CharSequenceUtil.toUnderlineCase(property));
        }
    }

    @Override
    public R checkBalance(ConsumptionReq req) {
        //先校验userId
        Long userId = req.getUserId();
        if (!StpUtil.isLogin(userId)) {
            StpUtil.login(userId);
        }
        UserDO user = userService.getById(req.getUserId());
        if (user.getSysBeans() < req.getChargePoints()) {
            return R.fail(R.fail().getCode(), "余额不足，请充值！");
        }
        return R.ok();
    }

}