package com.gxwebsoft.shop.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.common.system.service.UserService;
import com.gxwebsoft.shop.entity.Order;
import com.gxwebsoft.shop.mapper.UserOauthMapper;
import com.gxwebsoft.shop.param.OrderParam;
import com.gxwebsoft.shop.service.UserOauthService;
import com.gxwebsoft.shop.entity.UserOauth;
import com.gxwebsoft.shop.param.UserOauthParam;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.PageResult;
import lombok.val;
import org.springframework.stereotype.Service;

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

/**
 * 第三方用户信息表Service实现
 *
 * @author 科技小王子
 * @since 2022-12-15 08:33:13
 */
@Service
public class UserOauthServiceImpl extends ServiceImpl<UserOauthMapper, UserOauth> implements UserOauthService {
    @Resource
    private UserService userService;
    @Resource
    private UserOauthService userOauthService;

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

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

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

    @Override
    public String getOauthIdByUserId(Integer userId, String platform) {
      UserOauthParam param = new UserOauthParam();
      param.setUserId(userId);
      param.setOauthType(platform);
      return param.getOne(baseMapper.selectListRel(param)).getOauthId();
    }

    @Override
    public User getByOauthId(String openid) {
      UserOauth userOauth = query().eq("oauth_id", openid).one();
      if(userOauth == null){
        return null;
      }
      // 查询用户
      User user = userService.getById(userOauth.getUserId());
      if(user == null){
        // 如果用户不存在，则清理第三方信息
        userOauth.setDeleted(1);
        userOauthService.save(userOauth);
      }
      return user;
    }

    @Override
    public UserOauth getByUnionId(UserOauthParam param) {
      UserOauth userOauth = param.getOne(baseMapper.getOne(param));
      System.out.println("userOauth0 = " + userOauth);
      if(userOauth == null){
        return null;
      }
      return userOauth;
    }
}
