package com.fs.app.controller;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.fs.app.annotation.Login;
import com.fs.app.param.LoginParam;
import com.fs.app.utils.JwtUtils;
import com.fs.app.vo.CompanyRoleVO;
import com.fs.app.vo.UserListVO;
import com.fs.app.vo.UserPostVO;
import com.fs.app.vo.UserVO;
import com.fs.common.annotation.RepeatSubmit;
import com.fs.common.config.FSConfig;
import com.fs.common.core.domain.R;
import com.fs.common.core.redis.RedisCache;
import com.fs.common.exception.ServiceException;
import com.fs.common.exception.base.BaseException;
import com.fs.common.utils.PatternUtils;
import com.fs.common.utils.PinYinUtil;
import com.fs.common.utils.StringUtils;
import com.fs.common.utils.bean.BeanUtils;
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.param.EditPwdParam;
import com.fs.company.param.EditUserInfoParam;
import com.fs.company.param.EditUserQrCodeParam;
import com.fs.company.service.*;
import com.fs.company.vo.CompanyUserAppVO;
import com.fs.company.vo.CompanyUserVO;
import com.fs.core.security.SecurityUtils;
import com.fs.course.service.IFsCourseRedPacketLogService;
import com.fs.his.service.IFsUserService;
import com.fs.wx.miniapp.config.WxMaProperties;
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 lombok.extern.slf4j.Slf4j;
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 java.math.BigDecimal;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.fs.common.constant.Constants.PAGE_SIZE;

@Slf4j
@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 IFsUserService fsUserService;
    @Autowired
    private IFsCourseRedPacketLogService courseRedPacketLogService;

    @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("登录异常");
//		}
//	}

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

        // 密码校验
        if (!PatternUtils.checkPassword(param.getPassword())) {
            return R.error("密码格式不正确,需包含字母、数字和特殊字符,长度为 8-20位");
        }

        try {

            //判断用户基本规则
            CompanyUser companyUser = userService.selectUserByUserName(param.getAccount());
            if (companyUser == null) {
                return R.error("工号不存在");
            }
            if (companyUser.getStatus().equals("1")) {
                return R.error("用户已禁用");
            }
            if (!SecurityUtils.matchesPassword(param.getPassword(), companyUser.getPassword())) {
                return R.error("密码错误");
            }
            if (companyUser.getIsAudit() == 0) {
                return R.error("用户未审核");
            }

            Company company = companyService.selectCompanyById(companyUser.getCompanyId());
            if (company == null || company.getStatus() == 0 || company.getIsDel() == 1) {
                throw new BaseException("此用户所属公司不存在或已停用");
            }

            if (StringUtils.isNotEmpty(company.getCourseMiniAppId()) && !company.getCourseMiniAppId().equals(param.getAppid())){
                return R.error("登录用户不属于该小程序");
            }

            // 公司名称
            companyUser.setCompanyName(company.getCompanyName());
            // 岗位
            companyUser.setPosts(postService.selectCompanyPostListByUserId(companyUser.getUserId()));

            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, 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("登录异常:"+e.getMessage());
        }
    }

//    /**
//     * 获取用户信息
//     *
//     * @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("/getCompanyUser")
    public R getCompanyUser() {
        try {
            CompanyUser companyUser = userService.selectCompanyUserById(Long.parseLong(getUserId()));
            if (companyUser == null) {
                return R.error(40001, "用户不存在");
            }
            if (companyUser.getStatus().equals("1")) {
                return R.error(40002, "用户已停用");
            }
            // 公司名称
            Company company = companyService.selectCompanyById(companyUser.getCompanyId());
            companyUser.setCompanyName(company.getCompanyName());
            // 岗位
            companyUser.setPosts(postService.selectCompanyPostListByUserId(companyUser.getUserId()));
            return R.ok().put("user", companyUser).put("balance", company.getMoney());
        } 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,
                         @RequestParam Integer isAudit) {
        log.debug("获取通讯录 searchKey:{}, isAudit: {}", searchKey, isAudit);
        CompanyUser user = new CompanyUser();
        user.setNickName(searchKey);
        user.setCompanyId(getCompanyId());
        user.setIsAudit(isAudit);
        user.setIsDel(0);
        List<CompanyUserVO> list = userService.selectMyUserList(user);
        List<UserVO> users = new ArrayList<>();
        for (CompanyUserVO u : list) {
            UserVO vo = new UserVO();
            if (Objects.nonNull(u.getDept())) {
                vo.setDeptId(u.getDept().getDeptId());
                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());
            if (Objects.nonNull(u.getCreateTime())) {
                vo.setRegisterTime(u.getCreateTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
            }
            vo.setStatus(u.getStatus());
            vo.setPhoneNumber(u.getPhonenumber());
            vo.setIsAudit(u.getIsAudit());

            // 岗位信息
            if (Objects.nonNull(u.getPosts())) {
                vo.setPost(u.getPosts().stream().map(p -> {
                    UserPostVO post = new UserPostVO();
                    post.setPostId(p.getPostId());
                    post.setPostName(p.getPostName());
                    return post;
                }).collect(Collectors.toList()));
            }

            // 角色信息
            if (Objects.nonNull(u.getRoles())) {
                vo.setRoles(u.getRoles().stream().map(r -> {
                    CompanyRoleVO role = new CompanyRoleVO();
                    role.setRoleId(r.getRoleId());
                    role.setRoleName(r.getRoleName());
                    return role;
                }).collect(Collectors.toList()));
            }

            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 {
            log.debug("获取用户信息ByUserId userId:{}", userId);
            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, "用户已停用");
            }


            // 查询用户会员数、今日新增用户数
            Map<String, Long> result = fsUserService.getUserVipCountByCompanyUserId(userId);
            // 红包数
            int redPackCount = courseRedPacketLogService.getCountByCompanyUserIdId(userId);
            // 新用户红包金额
            BigDecimal newVipRedPackAmount = courseRedPacketLogService.getNewVipRedPackAmountByCompanyUserIdId(userId);

            CompanyUserAppVO userVO = new CompanyUserAppVO();
            BeanUtils.copyProperties(user, userVO);

            userVO.setVipCount(result.getOrDefault("vipCount", 0L));
            userVO.setNewVipCount(result.getOrDefault("newVipCount", 0L));
            userVO.setRedPacketCount(redPackCount);
            userVO.setNewVipRedPackAmount(newVipRedPackAmount);

            return R.ok().put("user", userVO).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("操作异常");
        }
    }


    @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("用户已停用");
            }
            if (param == null) {
                return R.error("修改参数对象不能为空");
            }
            if (!Validator.isMobile(param.getMobile())) {
                return R.error("手机号不正确");
            }
            if (!Validator.isEmail(param.getEmail())) {
                return R.error("邮箱格式不正确");
            }
            user.setAvatar(param.getHeadImg());
            user.setPhonenumber(param.getMobile());
            user.setEmail(param.getEmail());
            user.setSex(param.getSex());
            user.setNickName(param.getNickName());
            user.setQrCodeWeixin(param.getQrCodeWeixin());
            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);
            if (companyUserCard == null) {
                return R.error("名片不存在");
            }
            // 校验名片归属，防止越权删除他人名片
            Long currentUserId = Long.parseLong(getUserId());
            if (companyUserCard.getUserId() == null || !companyUserCard.getUserId().equals(currentUserId)) {
                return R.error("无权删除他人名片");
            }
            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.sendPost(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.sendPost("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.sendPost("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.sendPost("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("操作失败");
        }
    }

    @Login
    @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);
    }

    @Login
    @ApiOperation("修改用户状态")
    @PostMapping("/changeUserState")
    public R changeUserState(@RequestParam Long userId) {
        log.debug("修改用户状态 userId :{}", userId);
        CompanyUser operator = companyUserService.selectCompanyUserById(Long.parseLong(getUserId()));
        if (Objects.isNull(operator) || !operator.isAdmin()) {
            return R.error("仅管理员可操作");
        }
        CompanyUser companyUser = companyUserService.selectCompanyUserById(userId);
        if (Objects.isNull(companyUser)) {
            throw new ServiceException("用户不存在");
        }
        // 仅允许操作同公司用户
        if (operator.getCompanyId() == null || !operator.getCompanyId().equals(companyUser.getCompanyId())) {
            return R.error("无权操作其他公司用户");
        }

        String state = "0".equals(companyUser.getStatus()) ? "1" : "0";
        companyUser.setStatus(state);
        companyUserService.updateCompanyUser(companyUser);
        return R.ok();
    }

    @Login
    @ApiOperation("批量审核用户")
    @PostMapping("/audit")
    public R auditUser(@RequestParam List<Long> userIds) {
        log.debug("批量审核用户 userIds :{}", userIds);
        if(ObjectUtil.isNotNull(userIds) && !userIds.isEmpty() && userIds.size() > 20){
            return R.error("审核用户一次性不能大于20人！");
        }

        CompanyUser companyUser = companyUserService.selectCompanyUserByUserId(Long.parseLong(getUserId()));
        if (ObjectUtil.isEmpty(companyUser)) {
            return R.error("当前操作用户不存在！");
        }else if (!companyUser.isAdmin()) {
            return R.error("没有权限");
        }

        companyUserService.auditUsers(userIds,companyUser.getCompanyId());
        return R.ok();
    }

}
