package com.fs.app.controller.course;

import cn.hutool.core.date.DateTime;
import com.fs.app.annotation.UserOperationLog;
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.course.mapper.FsCourseSopLogsMapper;
import com.fs.course.mapper.FsCourseWatchLogMapper;
import com.fs.his.domain.FsUser;
import com.fs.his.enums.FsUserOperationEnum;
import com.fs.his.service.IFsUserService;
import com.fs.his.utils.ConfigUtil;
import com.fs.qw.mapper.QwExternalContactMapper;
import com.fs.sop.params.QwSopSettingTimeParam;
import com.fs.system.mapper.SysConfigMapper;
import com.fs.wx.mp.WxEeventType;
import com.fs.wx.mp.WxMessageType;
import com.fs.wx.mp.WxServiceMsgDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Synchronized;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
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 me.chanjar.weixin.mp.api.WxMpUserService;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Api("看课服务号授权登录接口")
@RestController
@RequestMapping("/app/wx/mp")
public class CourseMpLoginController {
  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;


  @ApiOperation("课程短链公众号登录")
  @PostMapping("/loginByMp")
  @Transactional
  @UserOperationLog(operationType = FsUserOperationEnum.H5LOGIN)
  public R loginByMp( @RequestBody FsUserLoginByMpParam param) {

    if (StringUtils.isBlank(param.getCode())) {
      return R.error("code不存在");
    }
    try{
      WxOAuth2AccessToken wxMpOAuth2AccessToken = wxMpService.getOAuth2Service().getAccessToken(param.getCode());
      WxOAuth2UserInfo wxMpUser = wxMpService.getOAuth2Service().getUserInfo(wxMpOAuth2AccessToken, null);
      if(StringUtils.isBlank(wxMpUser.getUnionId())){
        return R.error("请使用微信扫码登录");
      }
      FsUser user=userService.selectFsUserByUnionid(wxMpUser.getUnionId());
      if(user!=null){
        FsUser userMap=new FsUser();
        userMap.setUserId(user.getUserId());
        userMap.setNickName(wxMpUser.getNickname());
        userMap.setAvatar(wxMpUser.getHeadImgUrl());
        userMap.setMpOpenId(wxMpUser.getOpenid());
        userMap.setUpdateTime(new DateTime());
        userService.updateFsUser(userMap);
      }
      else{
        //写入
        user=new FsUser();
        user.setNickName(wxMpUser.getNickname());
        user.setAvatar(wxMpUser.getHeadImgUrl());
        user.setStatus(1);
        user.setSex(wxMpUser.getSex());
        user.setMpOpenId(wxMpUser.getOpenid());
        user.setUnionId(wxMpUser.getUnionId());
        user.setCreateTime(new Date());
        userService.insertFsUser(user);
      }
      System.out.println("user:id:"+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);
      logger.info("zyp \n 【点播公众号登录】：{}",user.getUserId());
      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());
      }
    }

  }

}
