package com.ylx.massage.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ylx.massage.domain.TWxUser;
import com.ylx.massage.domain.dto.QueryWxUserDTO;
import com.ylx.massage.domain.vo.TWxUserVo;
import com.ylx.massage.mapper.TWxUserMapper;
import com.ylx.massage.service.TWxUserService;
import com.ylx.shopingfundsdetail.service.ShoppingFundsDetailService;
import com.ylx.shoppingfunds.domain.dto.MyShoppingFundsUpdateDto;
import com.ylx.shoppingfunds.domain.vo.MyShoppingFundsQueryVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;


/**
 * 服务实现类
 */
@Service
public class TWxUserServiceImpl extends ServiceImpl<TWxUserMapper, TWxUser> implements TWxUserService {
    @Resource(name = "shoppingFundsDetailService")
    private ShoppingFundsDetailService shoppingFundsDetailService;
    @Override
    public TWxUser getByOpenId(String openId) {
        LambdaQueryWrapper<TWxUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TWxUser::getcOpenid,openId);
        return getOne(wrapper);
    }

    @Override
    public TWxUser getByPhone(String phone) {
        LambdaQueryWrapper<TWxUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TWxUser::getcPhone, phone);
        return getOne(wrapper);
    }

    @Override
    public Page<TWxUserVo> getUserList(Page<TWxUserVo> page, QueryWxUserDTO queryWxUserDTO) {
        if (queryWxUserDTO == null) {
            queryWxUserDTO = new QueryWxUserDTO();
        }
        if(StringUtils.isNotBlank(queryWxUserDTO.getStartTime())){
            //开始时间添加00:00:00
            queryWxUserDTO.setStartTime(queryWxUserDTO.getStartTime()+" 00:00:00");
        }
        if(StringUtils.isNotBlank(queryWxUserDTO.getEndTime())){
            //结束时间添加23:59:59
            queryWxUserDTO.setEndTime(queryWxUserDTO.getEndTime()+" 23:59:59");
        }
        return baseMapper.selectTWxUserList(page, queryWxUserDTO);
    }

    @Override
    public boolean bindPhone(String openId, String phone) {
        TWxUser user = getByOpenId(openId);
        if (user == null) {
            return false;
        }
        user.setcPhone(phone);
        return updateById(user);
    }

    @Override
    public TWxUser phoneLogin(String phone) {
        // 根据手机号查询用户
        TWxUser user = getByPhone(phone);
        // 如果用户不存在，则创建新用户
        if (user == null) {
            user = new TWxUser();
            user.setcPhone(phone);
            // 设置默认角色为普通用户
            user.setRole(0);
            //设置默认头像
            user.setcIcon("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
            //设置默认昵称
            user.setcNickName("用户"+phone.substring(7,11));
            save(user);
        }
        return user;
    }

    /**
     * 查询我的购物金余额
     * @param userId
     * @return
     */
    @Override
    public MyShoppingFundsQueryVo queryMyShoppingFunds(String userId) {
        TWxUser user = this.getById(userId);
        if (ObjectUtil.isNull(user)) {
            throw new IllegalArgumentException("参数有误，用户不存在");
        }
        MyShoppingFundsQueryVo myShoppingFundsVo = new MyShoppingFundsQueryVo();
        myShoppingFundsVo.setWxUserId(user.getId());
        myShoppingFundsVo.setDBalance(user.getdBalance());
        return myShoppingFundsVo;
    }

    /**
     * 更新我的购物金余额
     * @param userId
     * @param amount
     * @param expenseType
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateMyShoppingFunds(String userId, BigDecimal amount, Integer expenseType) {
        TWxUser user = this.getById(userId);
        if (ObjectUtil.isNull(user)){
            throw new IllegalArgumentException("参数有误，用户不存在");
        }
        //表示购卡
        if(expenseType.equals(0)){
            user.setdBalance(user.getdBalance().add(amount));
        }else if(expenseType.equals(1)){
            //表示消费购物金
            if(user.getdBalance().compareTo(amount)<0) {
                throw new IllegalArgumentException("参数有误，余额不足");
            }
            user.setdBalance(user.getdBalance().subtract(amount));
        }
        this.updateById(user);
    }
}
