package com.qxgmat.service.inline;

import com.github.pagehelper.Page;
import com.nuliji.tools.AbstractService;
import com.nuliji.tools.exception.ParameterException;
import com.nuliji.tools.exception.SystemException;
import com.nuliji.tools.mybatis.Example;
import com.qxgmat.data.constants.enums.module.PayModule;
import com.qxgmat.data.dao.UserPayMapper;
import com.qxgmat.data.dao.entity.UserPay;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;

@Service
public class UserPayService extends AbstractService {
    private static final Logger logger = LoggerFactory.getLogger(UserPayService.class);

    @Resource
    private UserPayMapper userPayMapper;

    /**
     * 合并用户信息，将old转移至new
     * @param oldUserId
     * @param newUserId
     */
    public void mergeUser(Number oldUserId, Integer newUserId){
        Example example = new Example(UserPay.class);
        example.and(
                example.createCriteria().andEqualTo("userId", oldUserId)
        );
        update(userPayMapper, example, UserPay.builder().userId(newUserId).build());
    }

    /**
     * 获取未使用的购买信息：根据模块
     * @param userId
     * @param module
     * @return
     */
    public List<UserPay> listUnUse(Integer userId, PayModule module){
        Example example = new Example(UserPay.class);
        example.and(
                example.createCriteria()
                        .andEqualTo("userId", userId)
                        .andEqualTo("module", module.key)
                        .andEqualTo("isUse", 0)
        );
        return select(userPayMapper, example);
    }

    public UserPay add(UserPay pay){
        int result = insert(userPayMapper, pay);
        pay = one(userPayMapper, pay.getId());
        if(pay == null){
            throw new SystemException("支付添加失败");
        }
        return pay;
    }

    public UserPay edit(UserPay pay){
        UserPay in = one(userPayMapper, pay.getId());
        if(in == null){
            throw new ParameterException("支付记录不存在");
        }
        int result = update(userPayMapper, pay);
        return pay;
    }

    public boolean delete(Number id){
        UserPay in = one(userPayMapper, id);
        if(in == null){
            throw new ParameterException("支付记录不存在");
        }
        int result = delete(userPayMapper, id);
        return result > 0;
    }

    public UserPay get(Number id){
        UserPay in = one(userPayMapper, id);

        if(in == null){
            throw new ParameterException("支付记录不存在");
        }
        return in;
    }

    public Page<UserPay> select(int page, int pageSize){
        return select(userPayMapper, page, pageSize);
    }

    public List<UserPay> select(Collection ids){
        return select(userPayMapper, ids);
    }

}
