package com.fs.app.controller;


import cn.hutool.core.date.DateTime;
import com.fs.app.annotation.Login;
import com.fs.app.param.LoginParam;
import com.fs.app.vo.UserListVO;
import com.fs.app.vo.UserVO;
import com.fs.chat.service.IChatRoleService;
import com.fs.common.core.domain.R;
import com.fs.common.core.redis.RedisCache;
import com.fs.common.utils.PinYinUtil;
import com.fs.common.utils.SecurityUtils;
import com.fs.common.utils.StringUtils;
import com.fs.company.domain.CompanyUser;
import com.fs.company.domain.CompanyWxAccount;
import com.fs.company.service.ICompanyPostService;
import com.fs.company.service.ICompanyUserService;
import com.fs.company.service.ICompanyWxAccountService;
import com.fs.company.vo.CompanyUserVO;
import com.fs.his.domain.FsUser;
import com.fs.his.service.IFsUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.WxMpUserService;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Api("用户接口")
@RestController
@AllArgsConstructor
@RequestMapping(value="/app/user")
public class UserController extends AppBaseController {
	private final ICompanyPostService postService;
	private final ICompanyUserService companyUserService;
	private final RedisCache redisCache;
	private final WxMpService wxMpService;
	private final IFsUserService userService;


	@ApiOperation("课程短链公众号登录")
	@PostMapping("/loginByMp")
	public R loginByMp( @RequestBody LoginParam param) {
//		if (org.apache.commons.lang3.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("请关注公众号进行登录");
//      }
			FsUser user=userService.selectFsUserByUnionid(param.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);
//			}
			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());
//			}
//		}

	}

	@ApiOperation("检测是否登录")
	@GetMapping("/checkLogin")
	public R checkLogin(){
		if(StringUtils.isEmpty(getUserId())){
			//未登录
			return R.error("未登录");
		}
		else{
			//登录
			String token = jwtUtils.generateToken(Long.parseLong(getUserId()));
			Map<String,Object> map=new HashMap<>();
			map.put("token",token);
			return R.ok("认证成功").put("userId",getUserId()).put("token",token);
		}
	}

	/**
	 * 获取用户信息
	 */
	@Login
	@ApiOperation("获取用户信息")
	@GetMapping("/getUserInfo")
	public R getUserInfo(){
		try {
			CompanyUser companyUser=companyUserService.selectCompanyUserById(Long.parseLong(getUserId()));
			List<String> postList=postService.selectPostNameListByUserId(Long.parseLong(getUserId()));
			if(companyUser==null){
				return R.error(40001,"用户不存在");
			}
			if(companyUser.getStatus().equals("1")){
				return R.error(40002,"用户已停用");
			}
			return R.ok().put("user",companyUser).put("post",postList);
		} catch (Exception e){

			return R.error("操作异常");
		}
	}
	@Login
	@ApiOperation("获取用户信息ByUserId")
	@GetMapping("/getUserInfoByUserId")
	public R getUserInfoByUserId(
			@ApiParam(required = true, name = "userId", value = "用户ID") @RequestParam(value = "userId", required = false) Long userId,
			HttpServletRequest request){
		try {
			CompanyUser user=companyUserService.selectCompanyUserById(userId);
			List<String> postList=postService.selectPostNameListByUserId(userId);
			if(user==null){
				return R.error(40001,"用户不存在");
			}
			if(user.getStatus().equals("1")){
				return R.error(40002,"用户已停用");
			}
			return R.ok().put("user",user).put("post",postList);
		} catch (Exception e){

			return R.error("操作异常");
		}
	}

}
