package com.starry.admin.modules.personnel.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.starry.admin.common.exception.CustomException;
import com.starry.admin.modules.custom.module.entity.PlayCustomUserInfoEntity;
import com.starry.admin.modules.order.module.constant.OrderConstant.BalanceOperationType;
import com.starry.admin.modules.order.module.entity.PlayOrderInfoEntity;
import com.starry.admin.modules.order.service.IPlayOrderInfoService;
import com.starry.admin.modules.personnel.mapper.PlayBalanceDetailsInfoMapper;
import com.starry.admin.modules.personnel.module.entity.PlayBalanceDetailsInfoEntity;
import com.starry.admin.modules.personnel.module.enums.BalanceDetailsUserType;
import com.starry.admin.modules.personnel.module.vo.PlayBalanceDetailsQueryVo;
import com.starry.admin.modules.personnel.module.vo.PlayBalanceDetailsReturnVo;
import com.starry.admin.modules.personnel.service.IPlayBalanceDetailsInfoService;
import com.starry.common.utils.IdUtils;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Arrays;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;

/**
 * 余额明细Service业务层处理
 *
 * @author admin
 * @since 2024-04-30
 */
@Service
public class PlayBalanceDetailsInfoServiceImpl
        extends
            ServiceImpl<PlayBalanceDetailsInfoMapper, PlayBalanceDetailsInfoEntity>
        implements
            IPlayBalanceDetailsInfoService {
    @Resource
    private PlayBalanceDetailsInfoMapper playBalanceDetailsInfoMapper;

    @Resource
    private IPlayOrderInfoService playOrderInfoService;

    /**
     * 查询余额明细
     *
     * @param id
     *            余额明细主键
     * @return 余额明细
     */
    @Override
    public PlayBalanceDetailsInfoEntity selectPlayBalanceDetailsInfoById(String id) {
        return this.baseMapper.selectById(id);
    }

    @Override
    public IPage<PlayBalanceDetailsReturnVo> selectByPage(PlayBalanceDetailsQueryVo vo) {
        MPJLambdaWrapper<PlayBalanceDetailsInfoEntity> lambdaQueryWrapper = new MPJLambdaWrapper<PlayBalanceDetailsInfoEntity>()
                // 查询主表全部字段
                .selectAll(PlayBalanceDetailsInfoEntity.class)
                // 查询顾客表
                .selectAs(PlayCustomUserInfoEntity::getId, "customId")
                .selectAs(PlayCustomUserInfoEntity::getNickname, "customNickname")
                .selectAs(PlayCustomUserInfoEntity::getAvatar, "customAvatar")
                // 查询订单表
                // .selectAs(PlayOrderInfoEntity::getId,
                // "orderId").selectAs(PlayOrderInfoEntity::getOrderNo,
                // "orderNo").selectAs(PlayOrderInfoEntity::getPayMethod,"payMethod")
                .selectAll(PlayOrderInfoEntity.class)
                .leftJoin(PlayOrderInfoEntity.class, PlayOrderInfoEntity::getId,
                        PlayBalanceDetailsInfoEntity::getOrderId)
                .leftJoin(PlayCustomUserInfoEntity.class, PlayCustomUserInfoEntity::getId,
                        PlayBalanceDetailsInfoEntity::getUserId);

        if (StrUtil.isNotBlank(vo.getPayMethod())) {
            lambdaQueryWrapper.eq(PlayOrderInfoEntity::getPayMethod, vo.getPayMethod());
        }
        if (StrUtil.isNotBlank(vo.getOperationType())) {
            lambdaQueryWrapper.eq(PlayBalanceDetailsInfoEntity::getOperationType, vo.getOperationType());
        }
        if (StrUtil.isNotBlank(vo.getUserType())) {
            lambdaQueryWrapper.eq(PlayBalanceDetailsInfoEntity::getUserType, vo.getUserType());
        }
        if (StrUtil.isNotBlank(vo.getNickname())) {
            lambdaQueryWrapper.like(PlayCustomUserInfoEntity::getNickname, vo.getNickname());
        }
        if (StrUtil.isNotBlank(vo.getUserId())) {
            lambdaQueryWrapper.like(PlayBalanceDetailsInfoEntity::getUserId, vo.getUserId());
        }

        if (!vo.getOperationTime().isEmpty()) {
            lambdaQueryWrapper.between(PlayBalanceDetailsInfoEntity::getOperationTime, vo.getOperationTime().get(0),
                    vo.getOperationTime().get(1));
        }
        lambdaQueryWrapper.orderByDesc(PlayBalanceDetailsInfoEntity::getOperationTime);
        return this.baseMapper.selectJoinPage(new Page<>(vo.getPageNum(), vo.getPageSize()),
                PlayBalanceDetailsReturnVo.class, lambdaQueryWrapper);

    }

    /**
     * 查询余额明细列表
     *
     * @param playBalanceDetailsInfo
     *            余额明细
     * @return 余额明细
     */
    @Override
    public IPage<PlayBalanceDetailsInfoEntity> selectPlayBalanceDetailsInfoByPage(
            PlayBalanceDetailsInfoEntity playBalanceDetailsInfo) {
        Page<PlayBalanceDetailsInfoEntity> page = new Page<>(1, 10);
        return this.baseMapper.selectPage(page, new LambdaQueryWrapper<>());
    }

    @Override
    public void insertBalanceDetailsInfo(String userType, String userId, BigDecimal balanceBeforeOperation,
            BigDecimal balanceAfterOperation, String operationType, String operationAction, BigDecimal balanceMoney,
            BigDecimal giftAmount, String orderId) {
        PlayOrderInfoEntity orderInfo = null;
        try {
            orderInfo = playOrderInfoService.selectOrderInfoById(orderId);
        } catch (CustomException ex) {
            orderInfo = null;
        }
        PlayBalanceDetailsInfoEntity entity = new PlayBalanceDetailsInfoEntity();
        entity.setId(IdUtils.getUuid());
        entity.setUserType(userType);
        entity.setUserId(userId);
        entity.setBalanceBeforeOperation(balanceBeforeOperation);
        entity.setBalanceAfterOperation(balanceAfterOperation);
        entity.setOperationType(operationType);
        entity.setBalanceMoney(balanceMoney);
        entity.setGiftAmount(giftAmount);
        entity.setPaymentAmount(orderInfo == null ? balanceMoney : orderInfo.getFinalAmount());
        entity.setOperationTime(LocalDateTime.now());
        entity.setOrderId(orderId);
        this.baseMapper.insert(entity);
    }

    /**
     * 新增余额明细
     *
     * @param playBalanceDetailsInfo
     *            余额明细
     * @return 结果
     */
    @Override
    public boolean create(PlayBalanceDetailsInfoEntity playBalanceDetailsInfo) {
        if (StrUtil.isBlankIfStr(playBalanceDetailsInfo.getId())) {
            playBalanceDetailsInfo.setId(IdUtils.getUuid());
        }
        return save(playBalanceDetailsInfo);
    }

    /**
     * 修改余额明细
     *
     * @param playBalanceDetailsInfo
     *            余额明细
     * @return 结果
     */
    @Override
    public boolean update(PlayBalanceDetailsInfoEntity playBalanceDetailsInfo) {
        return updateById(playBalanceDetailsInfo);
    }

    /**
     * 批量删除余额明细
     *
     * @param ids
     *            需要删除的余额明细主键
     * @return 结果
     */
    @Override
    public int deletePlayBalanceDetailsInfoByIds(String[] ids) {
        return playBalanceDetailsInfoMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除余额明细信息
     *
     * @param id
     *            余额明细主键
     * @return 结果
     */
    @Override
    public int deletePlayBalanceDetailsInfoById(String id) {
        return playBalanceDetailsInfoMapper.deleteById(id);
    }

    @Override
    public boolean existsCustomerConsumeRecord(String userId, String orderId) {
        return lambdaQuery()
                .eq(PlayBalanceDetailsInfoEntity::getUserType, BalanceDetailsUserType.CUSTOMER.getCode())
                .eq(PlayBalanceDetailsInfoEntity::getUserId, userId)
                .eq(PlayBalanceDetailsInfoEntity::getOrderId, orderId)
                .eq(PlayBalanceDetailsInfoEntity::getOperationType, BalanceOperationType.CONSUME.getCode())
                .last("limit 1")
                .one() != null;
    }
}
