package com.steerinfo.util;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Bourne.Cao
 * 操作SSO工具类
 * @date 2022-01-08 11:47
 */
@Component
public class SSOUtil {

    // sso注册用户
    public HashMap ssoRegister(HashMap params) throws Exception {
        HashMap<String, String> map = new HashMap<>();

        String ssoUrl = Configuration.readConfigString("sso.url", "application");

        // *将司机注册sso账户*
        // 使用默认账号登录sso
        String accessToken = ssoDefaultLogin();

        // 如果拿不到默认账户token，报错
        if(!StringUtils.isEmpty(accessToken)){
            // 新增车辆SSO账号
            Map<String, String> userMap = new HashMap<>();
            //system.out.println(params.get("carNo"));
            userMap.put("userCode", params.get("carNo").toString());
            userMap.put("userName", params.get("carNo").toString());
            userMap.put("orgCode", "123456789");
            userMap.put("orgName", "测试机构");
            userMap.put("groupData", "506514577756917769");
            userMap.put("companyData", "713710108567277568");
            userMap.put("groupId", "506514577756917769");
            userMap.put("companyId", "713710108567277568");
            userMap.put("orgId", "925357747573231616");
            userMap.put("loginStatus", "1");
            String ssomsg2 = HttpsRequest.sendPost(ssoUrl + "/v1/sysusers/", userMap, accessToken);

            JSONObject jsonObject2 = JSONObject.parseObject(ssomsg2);

            if(jsonObject2.get("code").toString().equals("0")) {
                String tempData2 = jsonObject2.get("data").toString();
                JSONObject tempObject2 = JSONObject.parseObject(tempData2);

                // 修改用户密码，参数生成
                Map<String, String> pwdMap = new HashMap<>();
                pwdMap.put("userid", tempObject2.get("userId").toString());
                pwdMap.put("prepassword", "123456");
                pwdMap.put("newpassword", params.get("password").toString());
                pwdMap.put("againNewpassword", params.get("password").toString());

                // 修改用户密码
                String ssomsg3 = HttpsRequest.sendPost(ssoUrl + "/v1/sysusers/updpsw", pwdMap, accessToken);

                JSONObject jsonObject3 = JSONObject.parseObject(ssomsg3);

                if(!jsonObject3.get("code").toString().equals("0")) {
                    map.put("code", jsonObject3.get("code").toString());
                    map.put("msg", jsonObject3.get("resultMessage").toString());
                    ssoDeleter(tempObject2.get("userId").toString(),accessToken);
                }
                else {
                    // 返回sso返回的data
                    map.put("code", "0");
                    map.put("data", tempObject2.get("userId").toString());
                }
            }
            else {
                map.put("code", "1");
                map.put("msg", jsonObject2.get("resultMessage").toString());
            }
        }
        else {
            map.put("code", "1");
            map.put("msg", "没有SSO默认账户，请联系系统管理员");
        }

        return map;
    }

    /**
     * sso修改
     * @param id
     * @param params
     * @param accessToken
     * @return
     */
    public String ssoUpdate(String id, HashMap params, String accessToken) throws Exception {
        String msg = "";
        String ssoUrl = Configuration.readConfigString("sso.url", "application");

        // 不传token时，自行获取默认账户的token
        if(StringUtils.isEmpty(accessToken)){
            accessToken = ssoDefaultLogin();
        }

        // 修改用户密码
        String ssomsg3 = HttpsRequest.sendPost(ssoUrl + "/v1/sysusers/updateUser/"+id, params, accessToken);

        JSONObject jsonObject = JSONObject.parseObject(ssomsg3);

        if(!jsonObject.get("code").toString().equals("0")){
            msg = jsonObject.get("message").toString();
        }

        return msg;
    }

    /**
     *
     * @param id sso用户id
     * @param accessToken 可以为空
     * @return
     */
    public String ssoDeleter(String id, String accessToken) throws Exception {
        String ssoUrl = Configuration.readConfigString("sso.url", "application");

        // 不传token时，自行获取默认账户的token
        if(StringUtils.isEmpty(accessToken)){
            accessToken = ssoDefaultLogin();
        }

        String ssomsg4 = HttpsRequest.sendDelete(ssoUrl + "/v1/sysusers/"+id, accessToken);

        JSONObject jsonObject = JSONObject.parseObject(ssomsg4);

        return jsonObject.get("resultMessage").toString();
    }

    /**
     * sso默认账户登录，用于获取token
     * @return
     */
    public String ssoDefaultLogin() throws Exception {
        String ssoUrl = Configuration.readConfigString("sso.url", "application");
        String ssoPassword = Configuration.readConfigString("sso.password", "application");
        String ssoAppUser = Configuration.readConfigString("sso.appuser", "application");
        // 使用默认账号登录sso
        // 默认账户密码加密
        String shaPass = SHAUtil.shaEncode(ssoPassword);
        // 获取sso token
        // https://jgwzjl.jiugang.com/icore.icp.web/pass/auth/login   post请求， 参数类型content-type: application/x-www-form-urlencoded
        // loginName=admin&password=fb94871a1c3c7c38330a3a434a0ee28f0deea30b&app_code=web
        Map<String, String> loginMap = new HashMap<>();
        loginMap.put("loginName", ssoAppUser);
        loginMap.put("password", shaPass);


        String ssomsg1 = HttpsRequest.sendPost(ssoUrl + "/auth/login", loginMap);
        // ssomsg1转JSONObject
        JSONObject jsonObject1 = JSONObject.parseObject(ssomsg1);
        //如果成功，读取accessToken
        String accessToken = "";
        if(jsonObject1.get("code").toString().equals("0")){
            String tempData = jsonObject1.get("data").toString();
            JSONObject tempObject = JSONObject.parseObject(tempData);
            accessToken = tempObject.get("accessToken").toString();
        }
        return accessToken;
    }

    /**
     * sso登录
     * @param params
     * @param accessToken
     * @return
     */
    public HashMap ssoLogin(HashMap params, String accessToken) throws Exception {
        String ssoUrl = Configuration.readConfigString("sso.url", "application");

        HashMap<String, String> map = new HashMap<>();

        // 不传token时，自行获取默认账户的token
        if(StringUtils.isEmpty(accessToken)){
            accessToken = ssoDefaultLogin();
        }

        // sso登录
        // 密码加密
        String shaPass = SHAUtil.shaEncode(params.get("password").toString());

        Map<String, String> loginMap = new HashMap<>();
        loginMap.put("loginName", params.get("carNo").toString());
        loginMap.put("password", shaPass);

        String ssomsg1 = HttpsRequest.sendPost(ssoUrl + "/auth/login", loginMap);
        // ssomsg1转JSONObject
        JSONObject jsonObject1 = JSONObject.parseObject(ssomsg1);

        if(jsonObject1.get("code").toString().equals("0")) {
            // 返回sso返回的data
            map.put("code", "0");
            map.put("data", jsonObject1.get("data").toString());
        }
        else{
            map.put("code", "1");
            map.put("msg", jsonObject1.get("message").toString());
        }

        return map;
    }

    /**
     * sso修改
     * @param params
     * @return
     */
    public HashMap ssoChangePwd(HashMap params) throws Exception {
        String ssoUrl = Configuration.readConfigString("sso.url", "application");

        HashMap<String, String> map = new HashMap<>();

        // sso登录
        // 密码加密
        String shaPass = SHAUtil.shaEncode(params.get("oldpassword").toString());

        Map<String, String> loginMap = new HashMap<>();
        loginMap.put("loginName", params.get("carNo").toString());
        loginMap.put("password", shaPass);

        String ssomsg1 = HttpsRequest.sendPost(ssoUrl + "/auth/login", loginMap);
        // ssomsg1转JSONObject
        JSONObject jsonObject1 = JSONObject.parseObject(ssomsg1);
        //如果成功，读取accessToken
        String accessToken = "";
        if(jsonObject1.get("code").toString().equals("0")) {
            String tempData1 = jsonObject1.get("data").toString();
            JSONObject tempObject1 = JSONObject.parseObject(tempData1);
            accessToken = tempObject1.get("accessToken").toString();

            // 读取用户信息
            JSONObject tempObject2 = JSONObject.parseObject(tempObject1.get("user").toString());
            // 修改用户密码，参数生成
            Map<String, String> pwdMap = new HashMap<>();
            pwdMap.put("userid", tempObject2.get("userId").toString());
            pwdMap.put("prepassword", params.get("oldpassword").toString());
            pwdMap.put("newpassword", params.get("newpassword").toString());
            pwdMap.put("againNewpassword", params.get("newpassword").toString());

            // 修改用户密码
            String ssomsg3 = HttpsRequest.sendPost(ssoUrl + "/v1/sysusers/updpsw", pwdMap, accessToken);

            JSONObject jsonObject3 = JSONObject.parseObject(ssomsg3);

            if(jsonObject3.get("code").toString().equals("0")) {
                map.put("code", "0");
            }
            else {
                map.put("code", "1");
                map.put("msg", jsonObject1.get("message").toString());
            }
        }
        else{
            map.put("code", "1");
            map.put("msg", jsonObject1.get("message").toString());
        }

        return map;
    }

    /**
     * sso重置密码
     * @param id
     * @return
     */
    public String ssoResetPwd(String id, String password, String accessToken) throws Exception {
        String msg = "";
        String ssoUrl = Configuration.readConfigString("sso.url", "application");

        // 不传token时，自行获取默认账户的token
        if(StringUtils.isEmpty(accessToken)){
            accessToken = ssoDefaultLogin();
        }

        Map<String, String> map = new HashMap<>();
        map.put("password", password);

        String ssomsg4 = HttpsRequest.sendPut(ssoUrl + "/v1/sysusers/resetPassword/"+id, map, accessToken);

        JSONObject jsonObject2 = JSONObject.parseObject(ssomsg4);

        if(jsonObject2.get("code").toString().equals("0")) {
            // 将用户状态置为启用
            // 参数生成
            HashMap<String, String> pwdMap = new HashMap<>();
            pwdMap.put("loginStatus", "1");
            pwdMap.put("leave", "");
            ssoUpdate(id, pwdMap, accessToken);
        }
        else {
            msg = jsonObject2.get("resultMessage").toString();
        }

        return msg;
    }

//    /**
//     * sso重置密码
//     * @param carNo
//     * @return
//     */
//    public HashMap ssoSelect(String carNo) throws Exception {
//
//        String ssoUrl = Configuration.readConfigString("sso.url", "application");
//
//        String accessToken = ssoDefaultLogin();
//
//        String ssomsg = HttpsRequest.sendPut(ssoUrl + "/v1/sysusers/getUsersByOrgCode/?userCode="+carNo+"&pageNum=1&pageSize=20", null, accessToken);
//
//        JSONObject jsonObject = JSONObject.parseObject(ssomsg);
//
//        HashMap<String, String> map = new HashMap<>();
//        map.put("code", "0");
//        map.put("data", jsonObject.get("data").toString());
//
//        return map;
//    }
}
