package com.fs.company.controller.company;

import com.alibaba.fastjson.JSONObject;
import com.fs.common.constant.Constants;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.redis.RedisCache;
import com.fs.common.exception.ServiceException;
import com.fs.common.exception.user.CaptchaException;
import com.fs.common.exception.user.CaptchaExpireException;
import com.fs.common.exception.user.UserPasswordNotMatchException;
import com.fs.common.utils.MessageUtils;
import com.fs.common.utils.PatternUtils;
import com.fs.common.utils.ServletUtils;
import com.fs.company.domain.CompanyMenu;
import com.fs.company.domain.CompanyUser;
import com.fs.company.service.ICompanyMenuService;
import com.fs.framework.manager.AsyncManager;
import com.fs.framework.manager.factory.AsyncFactory;
import com.fs.framework.security.LoginBody;
import com.fs.framework.security.LoginUser;
import com.fs.framework.service.CompanyLoginService;
import com.fs.framework.service.CompanyPermissionService;
import com.fs.framework.service.TokenService;
import com.fs.system.domain.SysConfig;
import com.fs.system.service.ISysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 登录验证
 *

 */
@RestController
@Slf4j
public class CompanyLoginController
{
    @Autowired
    private CompanyLoginService loginService;

    @Autowired
    private ICompanyMenuService menuService;

    @Autowired
    private CompanyPermissionService permissionService;

    @Autowired
    private TokenService tokenService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private ISysConfigService configService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        if (!PatternUtils.checkPassword(loginBody.getPassword())) {
            return AjaxResult.error("密码格式不正确,需包含字母、数字和特殊字符,长度为 8-20 位");
        }

        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }


    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        CompanyUser user = loginUser.getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);


        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        // 用户信息
        CompanyUser user = loginUser.getUser();
        List<CompanyMenu> menus = menuService.selectMenuTreeByUserId(user.getUserId(), loginUser.getUser().isAdmin());
        return AjaxResult.success(menuService.buildMenus(menus));
    }


    /**
     * 根据系统配置去查询是否需要首次登录，并开启校验
     * @return
     */
    @GetMapping("getFirstLogin")
    public AjaxResult getFirstLogin()
    {
        SysConfig config = configService.selectConfigByConfigKey("his.login");
        if(config != null && config.getConfigValue() != null){
            String configValue = config.getConfigValue();
            JSONObject jsonObject = JSONObject.parseObject(configValue);
            Boolean disabled = jsonObject.getBoolean("disabled");
            if(disabled){
                LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
                Long userId = redisCache.getCacheObject("newCompanyUser:" + loginUser.getUser().getCompanyId() + ":" + loginUser.getUser().getUserName());
                if (loginUser.getUser().getUserId().equals(userId)) {
                    return AjaxResult.success(true);
                }
            }
        }
        return AjaxResult.success(false);
    }

    @PostMapping("/checkIsNeedCheck")
    public boolean checkIsNeedCheck(@RequestBody LoginBody loginBody)
    {
//        return false;
        return loginService.checkIsNeedCheck(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(), loginBody.getUuid());
    }

    @PostMapping("/getWechatQrCode")
    public AjaxResult getWechatQrCode(@RequestBody Map<String,String> params) throws Exception {
        Map<String,String> qr = loginService.getWechatQrCode(params.get("username"));
        return AjaxResult.success(qr);
    }

    @GetMapping("/checkWechatScan")
    public AjaxResult checkWechatScan(@RequestParam String ticket) {
        //log.info("触发轮询");
        String token = loginService.checkWechatScan(ticket);
        Map<String, String> stringStringMap = Collections.singletonMap(Constants.TOKEN, token);
        if (token != null){
            return AjaxResult.success(Constants.TOKEN, token);
        }
        return AjaxResult.success("waiting");
    }

    @GetMapping("/callback")
    public String wechatCallback(@RequestParam String code, @RequestParam String state) {
        try {
            log.info("触发回调");
            loginService.handleCallback(code, state);
            return "success"; // 微信要求返回内容，显示给用户即可
        } catch (Exception e) {
            return "error";
        }
    }


}

