package com.unis.crk.basic.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.MD5;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.unis.crk.basic.entity.OrgInfo;
import com.unis.crk.basic.entity.UserInfo;
import com.unis.crk.basic.entity.UserOperationlog;
import com.unis.crk.basic.entity.UserRole;
import com.unis.crk.basic.mapper.UserInfoMapper;
import com.unis.crk.basic.mapper.UserRoleMapper;
import com.unis.crk.basic.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.unis.crk.basic.entity.vo.UserAndRoleInfo;
import com.unis.crk.basic.entity.vo.UserInfoVo;
import com.unis.crk.basic.util.TokenUtil;
import com.unis.crk.enums.LogConstant;
import com.unis.crk.utils.ResultUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 用户信息表 服务实现类
 * </p>
 *
 * @author ghh
 * @since 2021-09-26
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements IUserInfoService {
    @Resource
    private UserInfoMapper UserInfoMapper;
    @Resource
    private UserRoleMapper userRoleMapper;
    @Autowired
    private IUserRoleService userRoleService;
    @Autowired
    private IUserOperationlogService userOperationlogService;
    @Autowired
    private IRoleInfoService roleInfoService;
    @Autowired
    private IOrgInfoService orgInfoService;

    @Override
    public List<Map<Object, Object>> queryAuditUser(Map<Object, Object> map) {
        return UserInfoMapper.queryAuditUser(map);
    }

    @Override
    public boolean validUsername(String userId, String username) {

        QueryWrapper<UserInfo> basicQueryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotBlank(userId)){
            basicQueryWrapper.eq("user_id",userId);
        }
        if(username!=null){
            basicQueryWrapper.eq("username",username);
        }
        List<UserInfo> userInfos = UserInfoMapper.selectList(basicQueryWrapper);
        if (userInfos.size() > 0) {
            return true;
        }
        return false;
    }

    @Override
    public String queryPhoneByusername(String username) {
        QueryWrapper<UserInfo> basicQueryWrapper = new QueryWrapper<>();

        basicQueryWrapper.eq("username",username);
        UserInfo userInfo = UserInfoMapper.selectOne(basicQueryWrapper);
        return userInfo.getMobile();
    }

    @Override
    public String validPhone(String phoneNumber, String userId) {
        QueryWrapper<UserInfo> basicQueryWrapper = new QueryWrapper<>();
        basicQueryWrapper.eq("mobile",phoneNumber);
        UserInfo userInfo = UserInfoMapper.selectOne(basicQueryWrapper);
        if(userInfo !=null ){

            return userInfo.getUsername();
        }
        return "";
    }

    @Override
    public boolean validPassword(String resPassword, String oldPassword) {
        oldPassword = SecureUtil.md5(oldPassword);
        return resPassword.equals(oldPassword);
    }

    @Override
    public void resetPassword(String userId, String userPwd) {
        userPwd = SecureUtil.md5(userPwd);
        UpdateWrapper<UserInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("user_id",userId);
        updateWrapper.set("password",userPwd);
        UserInfoMapper.update(null, updateWrapper);
    }

    @Override
    public List<UserInfo> findAllUserByOrgId(String orgId) {
        QueryWrapper<UserInfo> basicQueryWrapper = new QueryWrapper<>();
        basicQueryWrapper.eq("org_id",orgId);
        List<UserInfo> userInfos = UserInfoMapper.selectList(basicQueryWrapper);
        return userInfos;
    }

    @Override
    public  IPage<Map<String, Object>> queryAllByOrgClass(Page<UserInfo> objectPage, QueryWrapper<UserInfo> userInfoQueryWrapper) {
        IPage<Map<String, Object>> mapIPage = UserInfoMapper.queryAllByOrgClass(objectPage, userInfoQueryWrapper);
        return mapIPage;
    }




    @Override
    public UserInfoVo selectUserInfoVoById(String userId) {
        HashMap hashMap = new HashMap();
        hashMap.put("userid",userId);
        List<UserInfoVo> userInfoVos = UserInfoMapper.selectUserInfoVoById(hashMap);
        if(userInfoVos !=null && userInfoVos.size()>0){
            return  userInfoVos.get(0) ;
        }
        return null;
    }

    @Override
    public IPage<Map<String, Object>> queryAll(Page<UserAndRoleInfo> p, QueryWrapper<UserAndRoleInfo> userAndRoleInfoQueryWrapper) {


        return  UserInfoMapper.queryAll(p,userAndRoleInfoQueryWrapper);
    }

    @Value("${nd.client-id}")
    private String clientId;

    @Value("${nd.client-secret}")
    private String clientSecret;

    @Value("${nd.url}")
    private String ndUrl;

    /**
     * 单点登录
     *
     * @param code
     * @return
     */
    @Override
    public JSONObject ssoLogin(String code) {
        JSONObject returnJson = new JSONObject();
        returnJson.set("success",false);
//        String client_id = "0fd6311f-5d4c-4c2c-99bc-0eaf7f73623d";
//          String url = "http://10.106.101.55:7080/uc/service/idp/sso/oidc/endpoint/token/"+client_id;
    //ip地址与clientId需要做成配置文件
//        String client_id = "06008a7b-8dd3-417c-a2e1-956ba3fe8c16";
        String client_id = clientId.trim();
        String url = "http://"+ndUrl.trim()+"/uc/service/idp/sso/oAuth2/endpoint/token/"+client_id;
        System.out.println(url+"----"+clientSecret);
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("code", code);
        paramMap.put("client_id", client_id);
        paramMap.put("client_secret", clientSecret.trim());
        paramMap.put("grant_type", "authorization_code");
        paramMap.put("redirect_uri", "-1");
        String result1 = HttpRequest.post(url)
                .header(Header.CONTENT_TYPE, "application/x-www-form-urlencoded")//头信息，多个头信息多次调用此方法即可
                .form(paramMap)//表单内容
                .timeout(20000)//超时，毫秒
                .execute().body();
        System.out.println(result1);
        if (JSONUtil.isJson(result1)){
            JSONObject token = JSONUtil.parseObj(result1);
            if (token.get("error") != null){
                returnJson.set("message","获取token失败!");
                return returnJson;
            }
            String token_type = token.getStr("token_type");
            String access_token = token.getStr("access_token");
            //得到用户相关信息
            url = "http://"+ndUrl+"/uc/service/idp/sso/oAuth2/endpoint/userInfo/"+client_id;
            String result2 = HttpRequest.get(url)
                    .header("Authorization", token_type+" "+access_token)//头信息，多个头信息多次调用此方法即可
                    .timeout(20000)//超时，毫秒
                    .execute().body();
            System.out.println(result2);
            if (JSONUtil.isJson(result2) ){
                JSONObject user = JSONUtil.parseObj(result2);
                if (user.get("loginName") != null){
                    String userName = user.getStr("loginName");
                    //进入登录业务
                    System.out.println(userName);
                    returnJson = loginByuserName(userName);
                }
            }
        }
        return returnJson;
    }

    /**
     * 从用户中心下载用户相关信息
     *
     * @param jsonObject
     * @return
     */
    @Override
    public JSONObject downSsoUserInfos(JSONObject jsonObject) {
        JSONObject returnJSON = new JSONObject();
        returnJSON.set("success",false);
        //得到返回数据
        JSONObject data = jsonObject.getJSONObject("data");
        //得到登录用户名
        String username = data.getOrDefault("loginName","").toString();
        //分组
        String groupPath = data.getOrDefault("groupPath","").toString();
        //使用最后三个字母org_code进行查询
        String orgCode = groupPath.substring(groupPath.length()-3).toUpperCase();
        OrgInfo supreOrg = orgInfoService.getById("00"); //顶级单位
        String orgId = "00";
        if (orgCode.equals(supreOrg.getOrgCode())){ //表示市级
            orgId = "00";
        }else{
            QueryWrapper<OrgInfo> orgInfoQueryWrapper = new QueryWrapper<>();
            orgInfoQueryWrapper.eq("org_code",orgCode);
            orgInfoQueryWrapper.last("limit 1");
            OrgInfo orgInfo = orgInfoService.getOne(orgInfoQueryWrapper,false);
            if (orgInfo == null){
                returnJSON.set("message",groupPath+"对应的单位不存在");
                return  returnJSON;
            }
            orgId = orgInfo.getOrgId().toString();
        }
        //生成单位信息
        //查询用户是否存在
        String userId = StringUtils.replace(data.getOrDefault("userId","").toString(),"-","");
        QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();
        userInfoQueryWrapper.eq("username",data.getOrDefault("loginName","").toString());
        userInfoQueryWrapper.eq("org_id",orgId);
     //   userInfoQueryWrapper.eq("user_id",userId);
        userInfoQueryWrapper.last("limit 1");
        UserInfo userInfo = super.getOne(userInfoQueryWrapper,false);
        if (userInfo == null){
            userInfo = new UserInfo();
        }
        //去掉-
        userInfo.setUserId(userId);
        userInfo.setOrgId(orgId);
        userInfo.setUsername(data.getStr("loginName",""));
        userInfo.setRealName(data.getStr("personalName",""));
        userInfo.setCreateTime(data.getDate("createTime",new Date()));
//        userInfo.setUpdatetime(data.getDate("updateTime",new Date()));
        userInfo.setPassword(SecureUtil.md5("123456")); //使用默认密码,数据中心不传密码过来
        userInfo.setUserAlias(data.getOrDefault("personalName","").toString());
        userInfo.setDelFlag(data.getBool("enabled",true)?1:2); //1使用,2删除
        userInfo.setEmail(data.getStr("email",""));
        JSONArray mobiles = data.getJSONArray("mobiles");
        if (mobiles.size()>0){
            userInfo.setMobile(mobiles.getStr(0,""));
        }
        if (!super.saveOrUpdate(userInfo)){
            returnJSON.set("message","保存对象失败");
            return  returnJSON;
        }
        returnJSON.set("success",true);
        returnJSON.set("message","保存成功");
        return  returnJSON;
    }

    @Override
    public JSONObject ddmLogin(String code) {
        JSONObject returnJson = new JSONObject();
        returnJson.set("success",false);
        if(StringUtils.isBlank(code)){
            return returnJson;
        }
        String username = code;
        returnJson = loginByuserName(code);
        return returnJson;
    }

    private JSONObject loginByuserName(String userName){
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("success",false);
        QueryWrapper<UserInfo> userInfoQuery = new QueryWrapper();
        userInfoQuery.eq("username",userName);
        List<UserInfo> userInfou =super.list(userInfoQuery);

        if(userInfou == null  || userInfou.size()<1){
            jsonObject.set("message","用户名错误");
            return jsonObject;
        }
        String token=null;
        HashMap hashMap1 = new HashMap();
        HashMap hashMap = new HashMap();
        hashMap.put("username",userName);
        hashMap.put("userId",userInfou.get(0).getUserId());
        hashMap.put("password",userInfou.get(0).getPassword());


        List<UserInfoVo> userInfoVos = UserInfoMapper.selectUserInfoVo(hashMap);

        if ( userInfoVos!=null && userInfoVos.size()>0) {
            UserInfoVo userInfoVo = userInfoVos.get(0);
            QueryWrapper<UserRole> userRoleQueryWrapper = new QueryWrapper<>();
            userRoleQueryWrapper.eq("user_id",userInfoVo.getUserId());
            List<UserRole> userRoles = userRoleMapper.selectList(userRoleQueryWrapper);
            List<String> roleNames = new ArrayList<>();
            List<String> roleIds = new ArrayList<>();
            for (UserRole userRole : userRoles) {
                roleIds.add(userRole.getRoleId());
                roleNames.add(roleInfoService.getById(userRole.getRoleId()).getRoleName());
            }
            userInfoVo.setRoleIds(roleIds);
            userInfoVo.setRoleNames(roleNames);
            token= TokenUtil.sign(userInfoVo);
            hashMap1.put("userInfo", userInfoVo);
            hashMap1.put("token", token);
            jsonObject.set("token",token);
            UserOperationlog userOperationlog = new UserOperationlog();
            userOperationlog.setUserId(Integer.parseInt(userInfoVo.getUserId()));
            userOperationlog.setOperationTime(new Date());
            userOperationlog.setUotId(LogConstant.LOGIN);
            userOperationlog.setParameterValue("登录");
            userOperationlogService.save(userOperationlog);
        }
        jsonObject.set("success",true);
        jsonObject.set("map",hashMap1);
        return jsonObject;
    }

}
