package com.gxwebsoft.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.shop.entity.Order;
import com.gxwebsoft.shop.mapper.UsersMapper;
import com.gxwebsoft.shop.service.UsersService;
import com.gxwebsoft.shop.entity.Users;
import com.gxwebsoft.shop.param.UsersParam;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

/**
 * Service实现
 *
 * @author 科技小王子
 * @since 2024-07-12 01:10:04
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements UsersService {

    @Override
    public PageResult<Users> pageRel(UsersParam param) {
        PageParam<Users, UsersParam> page = new PageParam<>(param);
        page.setDefaultOrder("sort_number asc, create_time desc");
        List<Users> list = baseMapper.selectPageRel(page, param);
        return new PageResult<>(list, page.getTotal());
    }

    @Override
    public List<Users> listRel(UsersParam param) {
        List<Users> list = baseMapper.selectListRel(param);
        // 排序
        PageParam<Users, UsersParam> page = new PageParam<>();
        page.setDefaultOrder("sort_number asc, create_time desc");
        return page.sortRecords(list);
    }

    @Override
    public Users getByIdRel(Integer id) {
        UsersParam param = new UsersParam();
        param.setId(id);
        return param.getOne(baseMapper.selectListRel(param));
    }

    @Override
    public void addIntegral(Order order) {
      final Users users = getOne(new LambdaUpdateWrapper<Users>().eq(Users::getPhone, order.getPhone()).last("limit 1"));
      final BigDecimal old = users.getIntegral();
      final BigDecimal news = users.getIntegral().add(order.getPayPrice());
      users.setIntegral(news);
      updateById(users);
      // 记录明细
//      final IntegralLog integralLog = new IntegralLog();
//      integralLog.setOrderNum(order.getOrderNo());
//      integralLog.setOid(order.getOrderId());
//      integralLog.setSiteName(order.getMerchantName());
//      integralLog.setUsername(order.getRealName());
//      integralLog.setPhone(users.getPhone());
//      integralLog.setIntegral(order.getPayPrice());
//      integralLog.setOldMoney(old);
//      integralLog.setNewMoney(news);
//      integralLog.setCreateTime(DateUtil.currentSeconds());
//      integralLog.setInfo("消费获取积分");
//      if (order.getType().equals(1)) {
//        integralLog.setInfo("预订场地获得积分");
//      }
//      integralLogService.save(integralLog);
    }

  @Override
  public Users getByPhone(String phone) {
    return getOne(new LambdaUpdateWrapper<Users>().eq(Users::getPhone,phone).last("limit 1"));
  }

}
