package com.bofeng.service;

import com.baomidou.mybatisplus.toolkit.IdWorker;
import com.bofeng.dao.UserOpenMapper;
import com.bofeng.entity.ParseCurrentOpenId;
import com.bofeng.entity.UserOpen;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.yvan.springmvc.HttpParameterParser;
import com.yvan.springmvc.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

@Service
@Transactional(readOnly = true)
@Slf4j
public class HomeService {

    @Autowired
    private UserService userService;
    @Autowired
    private UserOpenMapper userOpenMapper;

    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public UserOpen getUserOpen() {
        ParseCurrentOpenId wxToken = userService.currentWxUser();
        WxMpUser wxMpUser = wxToken.getWxMpUser();
        UserOpen user = userOpenMapper.selectByOpenId(wxMpUser.getOpenId());
        if (user == null) {
            // 账户没有注册,需要注册
            UserOpen userOpen = new UserOpen();
            userOpen.setUserId(IdWorker.getId());
            userOpen.setOpenId(wxMpUser.getOpenId());
            userOpen.setNickName(wxMpUser.getNickname());
            userOpen.setSexDesc(wxMpUser.getSexDesc());
            userOpen.setSex(wxMpUser.getSex());
            userOpen.setCity(wxMpUser.getCity());
            userOpen.setProvince(wxMpUser.getProvince());
            userOpen.setCountry(wxMpUser.getCountry());
            userOpen.setHeadImgUrl(wxMpUser.getHeadImgUrl());
            userOpen.setBeActive("Y");
            userOpenMapper.insert(userOpen);
            return userOpen;
        }
        if (!user.getNickName().equals(wxMpUser.getNickname())) {
            user.setOpenId(wxMpUser.getOpenId());
            user.setNickName(wxMpUser.getNickname());
            user.setSexDesc(wxMpUser.getSexDesc());
            user.setSex(wxMpUser.getSex());
            user.setCity(wxMpUser.getCity());
            user.setProvince(wxMpUser.getProvince());
            user.setCountry(wxMpUser.getCountry());
            user.setHeadImgUrl(wxMpUser.getHeadImgUrl());
            userOpenMapper.updateById(user);
        }
        return user;
    }
}
