package com.fs.app.controller.store;

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.course.mapper.FsCourseSopLogsMapper;
import com.fs.course.mapper.FsCourseWatchLogMapper;
import com.fs.hisStore.service.IFsUserScrmService;
import com.fs.qw.mapper.QwExternalContactMapper;
import com.fs.hisStore.domain.FsUserScrm;
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.web.bind.annotation.*;

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



@RestController
@RequestMapping("/store/app/wx/mp")
public class WxMpScrmController {
    Logger logger= LoggerFactory.getLogger(getClass());
    @Autowired
    private WxMpService wxMpService;
    private static final String MP_TOKEN = "U2qmxEbsp0PJFoLRvUDvIjVi9XPzuVc2";

    private static final String EncodingAESKey = "P3HE7Gd1PJVQqCLoOMop5uYfjx9LwfY53rnC3VUuLZS";

    @Autowired
    private IFsUserScrmService userService;

    @Autowired
    JwtUtils jwtUtils;
    @Autowired
    RedisCache redisCache;

    @Autowired
    FsCourseWatchLogMapper fsCourseWatchLogMapper;
    @Autowired
    QwExternalContactMapper qwExternalContactMapper;
    @Autowired
    private FsCourseSopLogsMapper courseSopLogsMapper;



    @GetMapping
    public String checkWxToken(
            @RequestParam("signature") String signature,
            @RequestParam("timestamp") String timestamp,
            @RequestParam("nonce") String nonce,
            @RequestParam("echostr") String echostr) {
      logger.info("数据回调URLServer-微信调用dataGet请求");
      boolean check = wxMpService.checkSignature(timestamp,nonce,signature);
      logger.info("验证结果：{}",check);
      if (check){
        return echostr;
      }
      return "error";
    }

    @PostMapping("/createMenu")
    public R createMenu(@RequestBody WxMenu wxMenu) throws WxErrorException{
      WxMpMenuService wxMpMenuService = wxMpService.getMenuService();
      try{
        wxMpMenuService.menuCreate(wxMenu);
        return R.ok("创建成功");
      }catch (WxErrorException e){
        logger.error(e.getMessage());
        return R.error("创建失败");
      }
    }

    @ApiOperation("课程短链公众号登录")
    @PostMapping("/loginByMp")
    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);
        WxMpUserService wxMpUserService = wxMpService.getUserService();
        WxMpUser userInfo = wxMpUserService.userInfo(wxMpUser.getOpenid());
  //      if (!userInfo.getSubscribe()){
  //        return R.error("请关注公众号进行登录");
  //      }
        FsUserScrm user=userService.selectFsUserByUnionid(wxMpUser.getUnionId());
        if(user!=null){

          FsUserScrm userMap=new FsUserScrm();
          userMap.setUserId(user.getUserId());
          userMap.setMpOpenId(wxMpUser.getOpenid());
          userMap.setUpdateTime(new DateTime());
          userMap.setNickname(wxMpUser.getNickname());
          userService.updateFsUser(userMap);
        }
        else{
          //写入
          user=new FsUserScrm();
  //        user.setPhone(code);
          user.setNickname(wxMpUser.getNickname());
          user.setAvatar(wxMpUser.getHeadImgUrl());
          user.setStatus(1);
          user.setMpOpenId(wxMpUser.getOpenid());
          user.setUnionId(wxMpUser.getUnionId());
          // 新用户 - 添加 appId
          if (StringUtils.isNotEmpty(param.getAppId())) {
            user.setAppId(param.getAppId());
          }
          user.setCreateTime(new Date());
          userService.insertFsUser(user);
        }
        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());
        }
      }

    }

    @GetMapping("/getWxConfig")
    @Synchronized
    public R getWxConfig(@RequestParam String url) throws WxErrorException {
        try {
            String sLink = URLDecoder.decode(url, "UTF-8");
            final WxJsapiSignature jsapiSignature = wxMpService.createJsapiSignature(sLink);
            return R.ok().put("data", jsapiSignature);
        } catch (UnsupportedEncodingException e) {
            // URL解码异常
            return R.error(e.getMessage());
        }

    }

}
