package com.fs.app.controller;

import cn.hutool.core.date.DateTime;
import com.fs.app.param.FsUserLoginByMpParam;
import com.fs.app.utils.JwtUtils;
import com.fs.common.core.domain.R;
import com.fs.common.core.redis.RedisCache;
import com.fs.company.domain.Company;
import com.fs.company.domain.CompanyUser;
import com.fs.company.service.ICompanyService;
import com.fs.company.service.ICompanyUserService;
import com.fs.course.mapper.FsCourseSopLogsMapper;
import com.fs.course.mapper.FsCourseWatchLogMapper;
import com.fs.qw.mapper.QwExternalContactMapper;
import com.fs.store.domain.FsUser;
import com.fs.store.service.IFsUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Synchronized;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.menu.WxMenu;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpMenuService;
import me.chanjar.weixin.mp.api.WxMpService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Api("会员-h5-微信相关接口")
@RestController
@RequestMapping("/app/wx/h5/mp")
@Slf4j
public class WxH5MpController {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private WxMpService wxMpService;

    @Autowired
    private IFsUserService userService;

    @Autowired
    JwtUtils jwtUtils;
    @Autowired
    RedisCache redisCache;

    @Autowired
    FsCourseWatchLogMapper fsCourseWatchLogMapper;
    @Autowired
    QwExternalContactMapper qwExternalContactMapper;
    @Autowired
    ICompanyService companyService;
    @Autowired
    ICompanyUserService companyUserService;


    @ApiOperation("课程分享链接公众号登录")
    @PostMapping("/loginByMp")
    public R loginByMp(@Valid @RequestBody FsUserLoginByMpParam param) throws WxErrorException {
//        try {
            //获取微信用户信息
            WxOAuth2AccessToken wxMpOAuth2AccessToken = wxMpService.getOAuth2Service().getAccessToken(param.getCode());
            WxOAuth2UserInfo wxMpUser = wxMpService.getOAuth2Service().getUserInfo(wxMpOAuth2AccessToken, null);
            //1、特殊（需求设计：需要根据公司是否开启黑名单来设置会员初始化的状态）
            Company company = null;
            if(param.getCompanyId() != null){
                company = companyService.selectCompanyById(param.getCompanyId());
            }
            // 根据销售后台设置的  是否需要单独注册会员 来判断是否需要设置销售的值
            CompanyUser companyUser = companyUserService.selectCompanyUserById(param.getCompanyUserId());

            FsUser user;
            if(StringUtils.isNotEmpty(wxMpUser.getUnionId())) {
                user = userService.selectFsUserByUnionId(wxMpUser.getUnionId());
            } else {
                user = userService.selectFsUserByMpOpenId(wxMpUser.getOpenid());
            }
            if (user != null) {
                //修改
                FsUser userMap = new FsUser();
                userMap.setUserId(user.getUserId());
                userMap.setMpOpenId(wxMpUser.getOpenid());
                userMap.setUnionId(wxMpUser.getUnionId());
                userMap.setUpdateTime(new DateTime());
                userMap.setAvatar(wxMpUser.getHeadImgUrl());
                userMap.setNickname(wxMpUser.getNickname());
                userService.updateFsUser(userMap);
            } else {
                //新增
                user = new FsUser();
                user.setNickname(wxMpUser.getNickname());
                user.setAvatar(wxMpUser.getHeadImgUrl());
                user.setStatus((company != null ? company.getFsUserIsDefaultBlack() : 0) == 1 ? 0 : 1);
                user.setMpOpenId(wxMpUser.getOpenid());
                user.setUnionId(wxMpUser.getUnionId());
                user.setCreateTime(new Date());
                if(companyUser.getIsNeedRegisterMember() != 1){
                    user.setCompanyId(param.getCompanyId());
                    user.setCompanyUserId(param.getCompanyUserId());
                }
                userService.insertFsUser(user);
            }
            log.error("用户信息user: {}, 用户id: {}", user, user.getUserId());
            String token = jwtUtils.generateToken(user.getUserId());
            redisCache.setCacheObject("token:" + user.getUserId(), token, 604800, TimeUnit.SECONDS);
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            map.put("user", user);
            return R.ok(map);
//        } catch (WxErrorException e) {
//            if (e.getError().getErrorCode() == 40163) {
//                return R.error(40163, e.getError().getErrorMsg());
//            } else {
//                return R.error("授权失败," + e.getMessage());
//            }
//        }

    }


}
