package com.fs.app.controller;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.fs.app.annotation.Login;
import com.fs.app.param.EditPwdParam;
import com.fs.app.param.EditUserInfoParam;
import com.fs.app.param.EditUserQrCodeParam;
import com.fs.app.param.LoginParam;
import com.fs.app.utils.JwtUtils;
import com.fs.app.vo.UserListVO;
import com.fs.app.vo.UserVO;
import com.fs.common.annotation.RepeatSubmit;
import com.fs.common.config.FSConfig;
import com.fs.common.constant.Constants;
import com.fs.common.core.domain.R;
import com.fs.common.core.redis.RedisCache;
import com.fs.common.exception.BaseException;
import com.fs.common.exception.CustomException;
import com.fs.common.utils.PinYinUtil;

import com.fs.common.utils.ServletUtils;
import com.fs.common.utils.StringUtils;
import com.fs.common.utils.http.HttpUtils;
import com.fs.company.domain.Company;
import com.fs.company.domain.CompanyUser;
import com.fs.company.domain.CompanyUserCard;
import com.fs.company.param.CompanyUserCardQueryParam;
import com.fs.company.service.*;
import com.fs.company.vo.CompanyUserVO;
import com.fs.core.security.SecurityUtils;
import com.fs.crm.param.CrmDelEventParam;
import com.fs.crm.param.CrmEventListQueryParam;
import com.fs.crm.vo.CrmEventListQueryVO;
import com.fs.store.vo.FsStoreCouponIssueVO;
import com.fs.wx.miniapp.config.WxMaProperties;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import static com.fs.common.constant.Constants.PAGE_SIZE;

@Api("个人中心")
@RestController
@RequestMapping(value="/app/user")
public class UserController extends  AppBaseController {

	@Autowired
	private FSConfig fsConfig;
	@Autowired
    JwtUtils jwtUtils;
	@Autowired
	ICompanyUserService userService;
	@Autowired
	ICompanyPostService postService;
	@Autowired
	ICompanyMenuService menuService;
	@Autowired
	private ICompanyService companyService;
	@Autowired
	RedisCache redisCache;
	@Autowired
	ICompanyUserService companyUserService;

	@Autowired
	ICompanyUserCardService companyUserCardService;

	@Autowired
	private WxMaProperties properties;
	private String aifabuAppId="7b471be905ab17e00f3b858c6710dd117601d008";

	@PostMapping("/loginByPwd")
	@ApiOperation("密码登录")
	public R loginByPwd(@Validated @RequestBody LoginParam param){
		try {

			CompanyUser companyUser=userService.selectUserByUserName(param.getUserName());
			if(companyUser==null){
				return R.error("工号不存在");
			}
			if(companyUser.getStatus().equals("1")){
				return R.error("用户已禁用");
			}
			if (!SecurityUtils.matchesPassword(param.getPassword(), companyUser.getPassword())) {
				return R.error("密码错误");
			}
			Company company=companyService.selectCompanyById(companyUser.getCompanyId()) ;
			if(company==null||company.getStatus()==0||company.getIsDel()==1){
				throw new BaseException("此用户所属公司不存在或已停用");
			}
			if(StringUtils.isNotEmpty(param.getJpushId())){
				companyUser.setJpushId(param.getJpushId());
				userService.updateUserProfile(companyUser);
			}
			//生成token
			String token = jwtUtils.generateToken(companyUser.getUserId());
			//调用REDIS生成用户的TOKEN

			//redisCache.setCacheObject("token:"+companyUser.getUserId(),token,2592000, TimeUnit.SECONDS);
			//redisCache.setCacheObject("companyId:"+companyUser.getUserId(),companyUser.getCompanyId(),2592000, TimeUnit.SECONDS);

			redisCache.setCacheObject("token:"+companyUser.getUserId(),token,604800, TimeUnit.SECONDS);
			redisCache.setCacheObject("companyId:"+companyUser.getUserId(),companyUser.getCompanyId(),604800, TimeUnit.SECONDS);

			//获取权限
			Set<String> perms = new HashSet<String>();
			// 管理员拥有所有权限
			if (companyUser.isAdmin())
			{
				perms.add("*:*:*");
			}
			else
			{
				perms.addAll(menuService.selectMenuPermsByUserId(companyUser.getUserId()));
			}

			//redisCache.setCacheObject("perms:"+companyUser.getUserId(), JSONUtil.toJsonStr(perms),2592000, TimeUnit.SECONDS);
			redisCache.setCacheObject("perms:"+companyUser.getUserId(), JSONUtil.toJsonStr(perms),604800, TimeUnit.SECONDS);

			Map<String ,Object> result=new HashMap<>();
			result.put("token",token);
			result.put("user",companyUser);
			result.put("perms",perms);
			return R.ok("登录成功").put("data",result);
		} catch (Exception e) {
			return R.error("登录异常");
		}
	}

	/**
	 * 获取用户信息
	 * @param request
	 * @return
	 */
	@Login
	@ApiOperation("获取用户信息")
	@GetMapping("/getUserInfo")
	public R getUserInfo(HttpServletRequest request){
		try {
			CompanyUser companyUser=userService.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("检测是否登录")
	@GetMapping("/checkLogin")
	public R checkLogin(HttpServletRequest request){
		return R.ok("认证成功");
	}


	@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);
		user.setCompanyId(getCompanyId());
		user.setIsDel(0);
		List<CompanyUserVO> list = userService.selectMyUserList(user);
		List<UserVO> users=new ArrayList<>();
		for(CompanyUserVO u:list){
			UserVO vo=new UserVO();
			vo.setDeptName(u.getDept().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);
	}

	@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=userService.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("操作异常");
		}
	}

	@Login
	@ApiOperation("修改密码")
	@PostMapping("/setPwd")
	public R setPwd(HttpServletRequest request,@RequestBody EditPwdParam param){
		try {

			CompanyUser user=userService.selectCompanyUserById(Long.parseLong(getUserId()));
			if (!SecurityUtils.matchesPassword(param.getOldPassword(), user.getPassword()))
			{
				return R.error("旧密码错误");
			}
			if (SecurityUtils.matchesPassword(param.getOldPassword(), param.getPassword()))
			{
				return R.error("新密码不能与旧密码相同");
			}
			if (userService.resetUserPwd(user.getUserName(), SecurityUtils.encryptPassword(param.getPassword())) > 0)
			{
				return R.ok("密码修改成功");
			}
			else{
				return R.error("密码修改失败");
			}
		} catch (Exception e) {

			return R.error("操作异常"+e.getMessage());
		}
	}
	/**
	 * 修改头像
	 * @param request
	 * @param headImg
	 * @return
	 */
	@Login
	@ApiOperation("修改头像")
	@PostMapping("/setHeadImg")
	public R setHeadImg(HttpServletRequest request,
						@ApiParam(required=true,name="headImg",value="用户头像")@RequestParam(value="headImg",required=false)String headImg){
		try {
			CompanyUser user=userService.selectCompanyUserById(Long.parseLong(getUserId()));
			if(user==null){
				return R.error("用户不存在");
			}
			if(user.getStatus().equals("1")){
				return R.error("用户已禁用");
			}
			CompanyUser map=new CompanyUser();
			map.setUserId(user.getUserId());
			if(userService.updateUserAvatar(user.getUserName(),headImg)>0){
				return R.ok("修改成功");
			} else {
				return R.error("修改失败");
			}
		} catch (Exception e) {

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

	/**
	 * 修改用户信息
	 * @return
	 */
	@Login
	@ApiOperation("修改用户信息")
	@PostMapping("/setUserInfo")
	public R setUserInfo(HttpServletRequest request,@RequestBody EditUserInfoParam param){
		try {

			CompanyUser user=userService.selectCompanyUserById(Long.parseLong(getUserId()));
			if(user==null){
				return R.error("用户不存在");
			}
			if(user.getStatus().equals("1")){
				return R.error("用户已禁用");
			}
			user.setAvatar(param.getHeadImg());
			if(!Validator.isMobile(param.getMobile())){
				return R.error("手机号不正确");
			}
			if(!Validator.isEmail(param.getEmail())){
				return R.error("邮箱格式不正确");
			}
			user.setPhonenumber(param.getMobile());
			user.setEmail(param.getEmail());
			user.setSex(param.getSex());
			if(userService.updateUserProfile(user)>0){
				return R.ok("修改成功");
			} else {
				return R.error("修改失败");
			}

		} catch (Exception e) {

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

	@Login
	@ApiOperation("修改二维码")
	@PostMapping("/editQrCode")
	@RepeatSubmit
	public R editQrCode(HttpServletRequest request,@RequestBody EditUserQrCodeParam param){
		try {
			CompanyUser user=userService.selectCompanyUserById(Long.parseLong(getUserId()));
			if(user==null){
				return R.error("用户不存在");
			}
			if(user.getStatus().equals("1")){
				return R.error("用户已禁用");
			}
			  //个人微信
			  CompanyUserCard companyUserCard=null;
			  if(param.getCardId()==null){   //添加名片
					companyUserCard=new CompanyUserCard();
					companyUserCard.setUserId(Long.parseLong(getUserId()));
					companyUserCard.setCompanyId(getCompanyId());
					companyUserCard.setTitle(param.getTitle());
					companyUserCard.setCreateTime(new Date());
					companyUserCard.setType((long)param.getType());
					companyUserCard.setImageUrl(param.getQrCodeWeixin());
					int rows=companyUserCardService.insertCompanyUserCard(companyUserCard);
					if(rows>0){
						String shorUrl=this.getShortUrlAction(companyUserCard.getId(),param.getTitle());
						companyUserCard.setShortUrl(shorUrl);
						if(companyUserCardService.updateUserCardShortUrlById(companyUserCard.getId(),shorUrl)>0){
							return R.ok("修改成功");
						}
					}
					return R.error("修改失败");
				}
			  else{
					companyUserCard=companyUserCardService.selectCompanyUserCardById(param.getCardId());
					companyUserCard.setImageUrl(param.getQrCodeWeixin());
					companyUserCard.setUpdateTime(new Date());
					if(companyUserCardService.updateCompanyUserCard(companyUserCard)>0){
						return R.ok("修改成功");
					}else{
						return R.error("修改失败");
					}
			  }

		} catch (Exception e) {
			return R.error("操作异常"+e.getMessage());
		}
	}

	@Login
	@ApiOperation("获取我的名片列表")
	@GetMapping("/getMyCardList")
	public R getMyCardList(CompanyUserCardQueryParam param)
	{
		PageHelper.startPage(param.getPage(), PAGE_SIZE);
		param.setCompanyId(getCompanyId());
		param.setCompanyUserId(Long.parseLong(getUserId()));
		List<CompanyUserCard> list = companyUserCardService.selectMyCardListQuery(param);
		PageInfo<CompanyUserCard> listPageInfo=new PageInfo<>(list);
		return R.ok().put("data",listPageInfo);
	}


	@Login
	@ApiOperation("删除名片")
	@PostMapping("/delMyCard")
	public R delMyCard(@RequestParam("cardId") Long cardId)
	{
		try {
			CompanyUserCard companyUserCard=companyUserCardService.selectCompanyUserCardById(cardId);
			String shortUrl=companyUserCard.getShortUrl();
			String[] chainArr=shortUrl.split(".cn/");
			String chain="";
			if(chainArr.length==2){
				chain=chainArr[1];
			}
			if(StringUtils.isNotEmpty(chain)){
				JSONObject jsonObject = new JSONObject();
				jsonObject.put("apikey",aifabuAppId);
				String[] chains=new String[1];
				chains[0]=chain;
				jsonObject.put("chains","["+chain+"]");
				String paramStr=jsonObject.toJSONString();
				String postUrl="https://openapi.aifabu.com/v1/chain/delChain?apikey="+aifabuAppId+"&chains="+"["+chain+"]";
				String postStr = HttpUtils.doPost(postUrl,paramStr);
				JSONObject obj = JSONObject.parseObject(postStr);
//				Integer code= obj.getInteger("code");
//				if(code==1){
//
//				}
			}
			if(companyUserCardService.deleteCompanyUserCardById(cardId)>0){
				return R.ok("操作成功");
			}
			else{
				return R.error("操作失败");
			}
		} catch (Exception e){
			return R.error("操作异常"+e.getMessage());
		}
	}


	@ApiOperation("查询微信urlScheme")
	@GetMapping("/getAppletScheme")
	public R getAppletScheme(@RequestParam(value = "cardId") Long cardId)
	{
		try {
			String appId= properties.getConfigs().get(0).getAppid();
			String secret= properties.getConfigs().get(0).getSecret();
			String rspStr = HttpUtils.sendGet("https://api.weixin.qq.com/cgi-bin/token", "grant_type=client_credential&"+"appid=" + appId + "&secret="+secret);
			JSONObject obj = JSONObject.parseObject(rspStr);
			String access_token = obj.getString("access_token");
			JSONObject jsonObject = new JSONObject();
			JSONObject jump_wxaObj=new JSONObject();
			jump_wxaObj.put("path", "/pages_company/card");
			jump_wxaObj.put("query", "id="+cardId);
			jsonObject.put("jump_wxa",jump_wxaObj);
			jsonObject.put("is_expire",false);
			String paramStr=jsonObject.toJSONString();
			String postStr = HttpUtils.doPost("https://api.weixin.qq.com/wxa/generatescheme?access_token="+access_token,paramStr);
			obj = JSONObject.parseObject(postStr);
			//response.addHeader("Access-Control-Allow-Origin", "*");
			return R.ok().put("result",obj);
		}
		catch (Exception e) {
			return R.error("操作失败");
		}
	}


	private String getShortUrlAction(Long cardId,String title){
		try {

			JSONObject jsonObject = new JSONObject();
			jsonObject.put("apikey",aifabuAppId);
			String url="http://company.yjf.runtzh.com/wx.html?id="+cardId;
			jsonObject.put("target_url",url);
			jsonObject.put("group_id",308195);
			if(StringUtils.isNotEmpty(title)){
				jsonObject.put("chain_title",title);
			}
			String paramStr=jsonObject.toJSONString();
			String postStr = HttpUtils.doPost("https://openapi.aifabu.com/v1/chain/createChain",paramStr);
			JSONObject obj = JSONObject.parseObject(postStr);
			Integer code= obj.getInteger("code");
			String shortUrl="";
			if(code==1){
				JSONObject result = obj.getJSONObject("result");
				shortUrl=result.getString("render_url");
			}
			return shortUrl;
		}
		catch (Exception e) {
			return "";
		}
	}

	@Login
	@ApiOperation("获取短链接")
	@GetMapping("/getShortUrl")
	public R getShortUrl(@RequestParam(value = "url") String url,@RequestParam(value = "title") String title)
	{

		try {
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("apikey",aifabuAppId);
			jsonObject.put("target_url",url);
			jsonObject.put("group_id",308195);
			if(StringUtils.isNotEmpty(title)){
				jsonObject.put("chain_title",title);
			}
			String paramStr=jsonObject.toJSONString();
			String postStr = HttpUtils.doPost("https://openapi.aifabu.com/v1/chain/createChain",paramStr);
			JSONObject obj = JSONObject.parseObject(postStr);
			return R.ok().put("data",obj);
		}
		catch (Exception e) {
			return R.error("操作失败");
		}
	}

	@GetMapping("/getUserList")
	public R getUserList() {
		CompanyUser companyUser=companyUserService.selectCompanyUserById(Long.parseLong(getUserId()));
		CompanyUser map=new CompanyUser();
		map.setCompanyId(companyUser.getCompanyId());
		List<CompanyUser> list = companyUserService.selectCompanyUserList(map);
		return  R.ok().put("data",list);
	}

}
