package com.cyksj.service.advertisement.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.mapper.advertisement.AdvertisementUserMapper;
import com.cyksj.model.dto.MiniProgramSession;
import com.cyksj.model.dto.UserWhoami;
import com.cyksj.model.entity.AdvertisementUser;
import com.cyksj.service.advertisement.AdvertisementUserService;
import com.cyksj.service.wechat.WeChatService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.Optional;

/**
 * @author chan
 * @date 2023/5/16 11:05 AM
 */
@RequiredArgsConstructor
@Service
public class AdvertisementUserServiceImpl extends ServiceImpl<AdvertisementUserMapper, AdvertisementUser> implements AdvertisementUserService {

    private final WeChatService weChatService;

    @Override
    public AdvertisementUser wxlogin(String code, String appId) throws Exception{
        MiniProgramSession session = weChatService.code2Session(appId,code);
        if(StringUtils.isBlank(session.getOpenid())){
            throw BusinessRuntimeException.getInstance("获取用户信息异常.");
        }
        // 根据unionId 判断用户是否存在
        String openid = session.getOpenid();

        // 查询用户是否存在
        LambdaQueryWrapper<AdvertisementUser> userLambdaQueryWrapper = new QueryWrapper<AdvertisementUser>().lambda();
        userLambdaQueryWrapper.eq(AdvertisementUser::getOpenId, openid);

        AdvertisementUser user = Optional.ofNullable(
                        getOne(userLambdaQueryWrapper))
                .orElseGet(() -> new AdvertisementUser()
                        .setOpenId(openid));

        this.saveOrUpdate(user);
        user = getById(user.getId());

        return user;
    }

    @Override
    public UserWhoami whoami(Long userId) {
        AdvertisementUser user = this.getById(userId);
        Assert.notNull(user,"业务处理失败,请联系客服");
        UserWhoami userWhoami = new UserWhoami();

        BeanUtil.copyProperties(user, userWhoami);

        return userWhoami;
    }
}
