package com.fs.app.controller;


import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.fs.ai.service.IBaiduAIService;
import com.fs.ai.vo.BaiduAIMsgResultVO;
import com.fs.app.annotation.Login;
import com.fs.app.param.AICallChatParam;
import com.fs.app.param.EditChatMsgParam;
import com.fs.app.param.LoginParam;
import com.fs.app.vo.UserListVO;
import com.fs.app.vo.UserVO;
import com.fs.chat.config.WxConfig;
import com.fs.chat.domain.ChatMsg;
import com.fs.chat.domain.ChatMsgLogs;
import com.fs.chat.domain.ChatRole;
import com.fs.chat.domain.ChatSession;
import com.fs.chat.param.ChatMsgListAParam;
import com.fs.chat.service.IChatMsgLogsService;
import com.fs.chat.service.IChatMsgService;
import com.fs.chat.service.IChatRoleService;
import com.fs.chat.service.IChatSessionService;
import com.fs.chat.vo.ChatMsgListAVO;
import com.fs.common.annotation.Log;
import com.fs.common.core.domain.AjaxResult;
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.ServletUtils;
import com.fs.common.utils.StringUtils;
import com.fs.common.utils.sign.Md5Utils;
import com.fs.common.utils.spring.SpringUtils;
import com.fs.company.domain.CompanyUser;
import com.fs.company.service.ICompanyPostService;
import com.fs.company.service.ICompanyUserService;
import com.fs.company.vo.CompanyUserVO;
import com.fs.his.service.IFsUserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
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;

import static com.fs.common.constant.FsConstants.REDIS_CHAT_SESSION;


@RestController
@RequestMapping(value="/app/user")
public class UserController extends AppBaseController {
	@Autowired
	ICompanyPostService postService;
	@Autowired
	IChatRoleService chatRoleService;
	@Autowired
	ICompanyUserService companyUserService;

	@Autowired
	RedisCache redisCache;
	@PostMapping("/login")
	public R login(@RequestBody LoginParam param)
	{
		CompanyUser user=companyUserService.selectUserByUserName(param.getAccount());
		if(user==null){
			return R.error("帐号不存在");
		}
		if(!user.getStatus().equals("0")){
			return R.error("帐号已被禁用");
		}
		if(!SecurityUtils.matchesPassword(param.getPassword(),user.getPassword())){
			return R.error("密码不正确");
		}
		String token = jwtUtils.generateToken(user.getUserId());
//		redisCache.setCacheObject("doctorToken:"+user.getUserId(),token,604800, TimeUnit.SECONDS);
		redisCache.setCacheObject("AiChatToken:"+user.getUserId(),token,604800, TimeUnit.SECONDS);

		Map<String,Object> map=new HashMap<>();
		map.put("token",token);
		map.put("user",user);

		return R.ok().put("data",map);
	}


 	@Login
	@GetMapping("getCompanyUser")
	public R getCompanyUser()
	{
		CompanyUser user = companyUserService.selectCompanyUserById(Long.parseLong(getUserId()));
		return R.ok().put("data",user);
	}

	@ApiOperation("检测是否登录")
	@GetMapping("/checkLogin")
	public R checkLogin(HttpServletRequest request){
		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("/getAllUsers")
	public R getAllUsers(HttpServletRequest request, @ApiParam(required = false, name = "searchKey", value = "searchKey") @RequestParam(value = "searchKey", required = false) String searchKey){
		CompanyUser user=new CompanyUser();
		user.setNickName(searchKey);
		CompanyUser companyUser = companyUserService.selectCompanyUserById(Long.parseLong(getUserId()));
		user.setCompanyId(companyUser.getCompanyId());
		user.setIsDel(0);
		List<CompanyUserVO> list = companyUserService.selectMyUserList(user);
		List<UserVO> users=new ArrayList<>();
		for(CompanyUserVO u:list){
			UserVO vo=new UserVO();
			vo.setDeptName(u.getDeptName());
			vo.setFirstLetter(PinYinUtil.cn2py(u.getNickName().substring(0,1)));
			vo.setNickName(u.getNickName());
			vo.setUserId(u.getUserId());
			vo.setAvatar(u.getAvatar());
			users.add(vo);
		}
		Map<Object, List<UserVO>> res = users.parallelStream().collect(
				Collectors.groupingBy(
						item->{return Character.toUpperCase(item.getFirstLetter().charAt(0));},//根据首字母分组
						TreeMap::new,//有序map实现排序
						Collectors.toList()
				)
		);
		List<UserListVO> vos=res.entrySet().stream().map(e -> new UserListVO(e.getKey().toString(),e.getValue())).collect(Collectors.toList());
		return R.ok( ).put("users",vos);
	}

	/**
	 * 获取用户信息
	 * @param request
	 * @return
	 */
	@Login
	@ApiOperation("获取用户信息")
	@GetMapping("/getUserInfo")
	public R getUserInfo(HttpServletRequest request){
		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("操作异常");
		}
	}


}
