package com.hzya.frame.sysnew.login.impl;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.request.OapiV2UserGetRequest;
import com.dingtalk.api.request.OapiV2UserGetuserinfoRequest;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.dingtalk.api.response.OapiV2UserGetResponse;
import com.dingtalk.api.response.OapiV2UserGetuserinfoResponse;
import com.hzya.frame.sysnew.application.dao.ISysApplicationDao;
import com.hzya.frame.sysnew.application.entity.SysApplicationEntity;
import com.hzya.frame.sysnew.login.ILoginService;
import com.hzya.frame.sysnew.organ.dao.ISysOrganDao;
import com.hzya.frame.sysnew.organ.entity.SysOrganEntity;
import com.hzya.frame.sysnew.person.dao.ISysPersonDao;
import com.hzya.frame.sysnew.person.entity.SysPersonEntity;
import com.hzya.frame.sysnew.popedomInterface.entity.SysPopedomInterfaceEntity;
import com.hzya.frame.sysnew.popedomInterface.service.impl.InterfaceCache;
import com.hzya.frame.sysnew.sysInterface.entity.SysInterfaceEntity;
import com.hzya.frame.sysnew.user.dao.ISysUserDao;
import com.hzya.frame.sysnew.user.entity.SysUserEntity;
import com.hzya.frame.sysnew.userCompany.dao.ISysUserCompanyDao;
import com.hzya.frame.sysnew.userCompany.entity.SysUserCompanyEntity;
import com.hzya.frame.sysnew.userRoles.entity.SysUserRolesEntity;
import com.hzya.frame.util.AESUtil;
import com.hzya.frame.web.entity.BaseResult;
import com.hzya.frame.web.entity.JsonResultEntity;
import com.hzya.frame.web.exception.BaseSystemException;
import org.checkerframework.checker.units.qual.C;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;


/**
 * @Description 登录
 * @Author xiangerlin
 * @Date 2022/12/20 16:09
 **/
@Service(value = "loginService")
public class LoginServiceImpl implements ILoginService {
    private final Logger logger = LoggerFactory.getLogger(LoginServiceImpl.class);

    @Resource
    private ISysUserDao sysUserDao;
    @Resource
    private ISysPersonDao sysPersonDao;
    @Resource
    private ISysOrganDao sysOrganDao;
    @Value("${zt.url}")
    private String url ;
    @Resource
    private ISysApplicationDao sysApplicationDao;
    @Resource
    private InterfaceCache interfaceCache;
    /**
     * 登录
     *
     * @param jsonObject
     * @return
     * @throws Exception
     */
    @Override
    public JsonResultEntity doLogin(JSONObject jsonObject) throws Exception {
        SysUserEntity entity = getData("jsonStr", jsonObject, SysUserEntity.class);
        if (entity == null) {
            return BaseResult.getFailureMessageEntity("请输入用户名或密码");
        }
        if (entity.getPassword() == null || "".equals(entity.getPassword())) {
            return BaseResult.getFailureMessageEntity("请输入用户名或密码");
        }
        if (entity.getLoginCode() == null || "".equals(entity.getLoginCode())) {
            return BaseResult.getFailureMessageEntity("请输入用户名或密码");
        }
        entity.setPassword(AESUtil.encrypt(entity.getLoginCode() + "-" + entity.getPassword()));
        SysUserEntity sysUserEntity = new SysUserEntity();
        sysUserEntity.setLoginCode(entity.getLoginCode());
        sysUserEntity.setPassword(entity.getPassword());
        sysUserEntity = sysUserDao.queryOne(sysUserEntity);
        if (sysUserEntity == null || sysUserEntity.getId() == null || "".equals(sysUserEntity.getId())) {
            return BaseResult.getFailureMessageEntity("用户名或密码错误");
        }
        if (sysUserEntity.getState() == null || !"0".equals(sysUserEntity.getState())) {
            return BaseResult.getFailureMessageEntity("当前用户已停用，请先启用");
        }
        if(sysUserEntity.getPersonId() != null &&!"".equals(sysUserEntity.getPersonId())){
            SysPersonEntity sysPersonEntity = sysPersonDao.get(sysUserEntity.getPersonId());
            if(sysPersonEntity != null && sysPersonEntity.getPersonName()!= null){
                sysUserEntity.setPersonName(sysPersonEntity.getPersonName());
            }
        }
        //校验当前登陆人是否有权限
        //boolean flag = false;
        //SysInterfaceEntity sysInterfaceEntity = (SysInterfaceEntity) interfaceCache.get("6","beanNameloginServiceinterfacNamedoLogin");
        //if(sysInterfaceEntity == null || sysInterfaceEntity.getId() == null){
        //    return BaseResult.getFailureMessageEntity("用户无访问权限，请联系管理员");
        //}
        ////查询用户权限
        //if(!flag){
        //    SysPopedomInterfaceEntity userPopedomInterfaceEntity = (SysPopedomInterfaceEntity) interfaceCache.get("4","userId"+sysUserEntity.getId()+"interfaceId"+sysInterfaceEntity.getId());
        //    if(userPopedomInterfaceEntity != null && userPopedomInterfaceEntity.getId() != null ){
        //        flag = true;
        //    }
        //}
        ////查询用户角色的权限
        //if(!flag){
        //    List<SysUserRolesEntity> userRoleMap = (List<SysUserRolesEntity>) interfaceCache.get("3",null);
        //    if(userRoleMap != null && userRoleMap.size() > 0){
        //        for (SysUserRolesEntity sysUserRolesEntity : userRoleMap) {
        //            if(sysUserRolesEntity.getUserId().equals(sysUserEntity.getId())){
        //                SysPopedomInterfaceEntity sysPopedomInterfaceEntity = (SysPopedomInterfaceEntity) interfaceCache.get("5","roleId"+sysUserRolesEntity.getRoleId()+"interfaceId"+sysInterfaceEntity.getId());
        //                if(sysPopedomInterfaceEntity != null && sysPopedomInterfaceEntity.getId() != null ){
        //                    flag = true;
        //                    break;
        //                }
        //            }
        //        }
        //    }
        //}
        //if(!flag){
        //    return BaseResult.getFailureMessageEntity("用户无访问权限，请联系管理员");
        //}
        //登录
        StpUtil.login(sysUserEntity.getId());
        //修改ddid或者修改微信id
        if((entity.getDdUserId() != null && !"".equals(entity.getDdUserId()))
                || (entity.getWxUserId() != null && !"".equals(entity.getWxUserId())) ){
            sysUserEntity.setDdUserId(entity.getDdUserId());
            sysUserEntity.setWxUserId(entity.getWxUserId());
            sysUserDao.update(sysUserEntity);
        }

        //获取token
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        String token = tokenInfo.getTokenValue();
        //获取公司
        SysOrganEntity sysOrganEntity = new SysOrganEntity();
        sysOrganEntity.setUserId(sysUserEntity.getId());
        List<SysOrganEntity> sysOrganEntities = sysOrganDao.queryUserCompany(sysOrganEntity);
        //返回值
        JSONObject res = new JSONObject();
        res.put("zt-token", token);
        res.put("userInfo", sysUserEntity);
        res.put("company", sysOrganEntities);


        //切换数据源查询
        return BaseResult.getSuccessMessageEntity("登录成功", res);
    }

    /****
     * 移动端登录地址
     * @content:
     * @author 👻👻👻👻👻👻👻👻 gjh
     * @date  2024-09-14 11:14
     * @param
     * @return com.hzya.frame.web.entity.JsonResultEntity
     **/
    @Override
    public JsonResultEntity appDoLogin(JSONObject jsonObject) {
        //移动端类型
        JSONObject entity = getData("jsonStr", jsonObject, JSONObject.class);
        logger.error(entity.toString());
        //boolean f = true;
        //if(f){
        //    return BaseResult.getFailureMessageEntity("cuowu",entity);
        //}
        //DD,weChat
        String appType = entity.getString("appType");
        String appId = entity.getString("appId");
        String apiCode = entity.getString("apiCode");
        String userApiCode = entity.getString("userApiCode");
        SysUserEntity userEntity = new SysUserEntity();
        switch (appType){
            case "DD":
                String code = entity.getString("code");//授权码
                String requestType = entity.getString("UserAgent");// pc端还是移动端
                JSONObject  bodyParams = new JSONObject();
                bodyParams.put("code",code);
                String result = HttpRequest.post(url).
                        header("appId",appId).
                        header("apiCode",userApiCode).
                        header("publicKey","ZJYAWb7lhAUTYqekPkU+uHJv1/ObJxb7dT7sD8HPRDGAgyhCe7eDIk+3zDUT+v578prj").
                        header("secretKey","fviZnLBsQUAGF8w8FSOdJi7XlIm/XAZclMxRagDLfTyJFlvnIBF3w66Hrpfzs8cYj3JzOP8MtA1LSGvL+2BWG8c/o7DKi92S4mr3zcGearA=").
                        body(bodyParams.toJSONString()).
                        execute().
                        body();
                JSONObject resultJson = JSONObject.parseObject(result);
                boolean flag  = resultJson.getBoolean("flag");
                if(!flag){
                    return BaseResult.getFailureMessageEntity("请求错误:"+resultJson.getString("msg"));
                }
                String userid  = resultJson.getJSONObject("attribute").getJSONObject("result").getString("userid");
                if(StrUtil.isEmpty(userid)){
                    return BaseResult.getFailureMessageEntity("认证失败！获取钉钉userid错误","1006");
                }
                userEntity.setDdUserId( userid);
                userEntity = sysUserDao.queryOne(userEntity);
                if(null == userEntity ){
                    JSONObject object = new JSONObject();
                    object.put("userid",userid);
                    return BaseResult.getFailureMessageEntity("认证失败！当前用户未绑定钉钉","1005",object);
                }
                break;
            case "weChat":
                String authCode = entity.getString("code");//授权码
                JSONObject  params = new JSONObject();
                params.put("code",authCode);
                params.put("corpid",entity.getString("corpid"));
                params.put("corpsecret",entity.getString("corpsecret"));
                params.put("access_token",entity.getString("access_token"));
                String res = HttpRequest.post(url).
                        header("appId",appId).
                        header("apiCode",userApiCode).
                        header("publicKey","ZJYAWb7lhAUTYqekPkU+uHJv1/ObJxb7dT7sD8HPRDGAgyhCe7eDIk+3zDUT+v578prj").
                        header("secretKey","fviZnLBsQUAGF8w8FSOdJi7XlIm/XAZclMxRagDLfTyJFlvnIBF3w66Hrpfzs8cYj3JzOP8MtA1LSGvL+2BWG8c/o7DKi92S4mr3zcGearA=").
                        body(params.toJSONString()).
                        execute().
                        body();
                JSONObject resJsonObject =   JSONObject.parseObject(res);
                JSONObject attribute = resJsonObject.getJSONObject("attribute");
                String attributeCode = attribute.getString("code");
                String attributeMsg = attribute.getString("msg");
                if(!"200".equals(attributeCode)){
                    return BaseResult.getFailureMessageEntity("请求错误:"+attributeMsg);
                }
                String weComUserid  = attribute.getString("data");
                userEntity.setWxUserId(weComUserid);
                userEntity = sysUserDao.queryOne(userEntity);
                if(null == userEntity ){
                    JSONObject object = new JSONObject();
                    object.put("userid",weComUserid);
                    return BaseResult.getFailureMessageEntity("认证失败！当前用户未绑定企业微信","1005",object);
                }
                break;
            default:
                return BaseResult.getFailureMessageEntity("错误的App类型:"+appType+" 支持的app类型有：DD,weChat");

        }
        //登录
        StpUtil.login(userEntity.getId());
        //获取token
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        String token = tokenInfo.getTokenValue();
        //获取公司
        SysOrganEntity sysOrganEntity = new SysOrganEntity();
        sysOrganEntity.setUserId(userEntity.getId());
        List<SysOrganEntity> sysOrganEntities = sysOrganDao.queryUserCompany(sysOrganEntity);
        //返回值
        JSONObject res = new JSONObject();
        res.put("token", token);
        res.put("userInfo", userEntity);
        res.put("company", sysOrganEntities);
        //切换数据源查询

        return BaseResult.getSuccessMessageEntity("登录成功", res);

        //校验当前登陆人是否有权限
        //boolean flag = false;
        //SysInterfaceEntity sysInterfaceEntity = (SysInterfaceEntity) interfaceCache.get("6","beanNameloginServiceinterfacNamedoLogin");
        //if(sysInterfaceEntity == null || sysInterfaceEntity.getId() == null){
        //    return BaseResult.getFailureMessageEntity("用户无访问权限，请联系管理员");
        //}
        ////查询用户权限
        //if(!flag){
        //    SysPopedomInterfaceEntity userPopedomInterfaceEntity = (SysPopedomInterfaceEntity) interfaceCache.get("4","userId"+sysUserEntity.getId()+"interfaceId"+sysInterfaceEntity.getId());
        //    if(userPopedomInterfaceEntity != null && userPopedomInterfaceEntity.getId() != null ){
        //        flag = true;
        //    }
        //}
        ////查询用户角色的权限
        //if(!flag){
        //    List<SysUserRolesEntity> userRoleMap = (List<SysUserRolesEntity>) interfaceCache.get("3",null);
        //    if(userRoleMap != null && userRoleMap.size() > 0){
        //        for (SysUserRolesEntity sysUserRolesEntity : userRoleMap) {
        //            if(sysUserRolesEntity.getUserId().equals(sysUserEntity.getId())){
        //                SysPopedomInterfaceEntity sysPopedomInterfaceEntity = (SysPopedomInterfaceEntity) interfaceCache.get("5","roleId"+sysUserRolesEntity.getRoleId()+"interfaceId"+sysInterfaceEntity.getId());
        //                if(sysPopedomInterfaceEntity != null && sysPopedomInterfaceEntity.getId() != null ){
        //                    flag = true;
        //                    break;
        //                }
        //            }
        //        }
        //    }
        //}
        //if(!flag){
        //    return BaseResult.getFailureMessageEntity("用户无访问权限，请联系管理员");
        //}

    }

    private JSONObject getAccess_token(String appId,String apiCode) {
        String result = HttpRequest.post(url).
                header("appId",appId).
                header("apiCode",apiCode).
                header("publicKey","ZJYAWb7lhAUTYqekPkU+uHJv1/ObJxb7dT7sD8HPRDGAgyhCe7eDIk+3zDUT+v578prj").
                header("secretKey","fviZnLBsQUAGF8w8FSOdJi7XlIm/XAZclMxRagDLfTyJFlvnIBF3w66Hrpfzs8cYj3JzOP8MtA1LSGvL+2BWG8c/o7DKi92S4mr3zcGearA=").
                execute().
                body();
        JSONObject resultJson = JSONObject.parseObject(result);
        return resultJson;
    }


    protected <T> T getData(String key, JSONObject jsonObject, Class<T> clz) {
        if (checkStr(jsonObject.getString(key))) {
            return jsonObject.getJSONObject(key).toJavaObject(clz);
        }
        return null;
    }

    /**
     * @param str
     * @return void
     * @Author lvleigang
     * @Description 校验字符串
     * @Date 11:41 上午 2022/12/7
     **/
    protected Boolean checkStr(String str) {
        Boolean flag = true;
        if (str == null || "".equals(str)) {
            flag = false;
        }
        return flag;
    }
}
