package com.live.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.live.client.OkHttpClient;
import com.live.enums.Terminal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.Assert;

import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Properties;
import java.util.concurrent.TimeUnit;


/**
 * 公共登录工具类
 */
public class CommonLogin {
    JsonAndFile fileHandle;
    OkHttpClient okHttpClient;
    // 组装请求
    IdentityHashMap<String, String> params;
    HashMap<String, String> headers;
    String url;
    Properties prop;
    JSONObject body;
    String xmTtoken = "";
    Logger logger = LoggerFactory.getLogger(com.live.utils.CommonLogin.class);

    /**
     * @param env           登录环境
     * @param loginUser     登录user
     * @param loginTerminal 登录端位
     */
    public void login(String env, String loginUser, String loginTerminal) {
        headers = new HashMap<String, String>();
        params = new IdentityHashMap<String, String>();
        okHttpClient = new OkHttpClient();
        prop = CommUtil.getconfig();


        String parameters = JsonAndFile.readTxtFile(System.getProperty("user.dir") + "/src/main/resources/parameter.json");
        JSONObject object = JSON.parseObject(parameters).getJSONObject(loginUser); //获取name在parameter.json文件中的信息
        Assert.assertNotNull(object, "找不到用户登录信息，请检查parameter.json 文件是否已有保存登录账号信息！");
        if (!object.isEmpty()) {
            JSONObject account = object.getJSONObject(env);
            String accountNo = account.getString("accountNo");
            String uid = account.getString("uid");
            String userType = account.getString("userType");
            String host = prop.getProperty(env);
            CommonLoginInfo loginInfoMap = (CommonLoginInfo) SpringContextUtil.getBean("commonLoginInfoMap");


            if (Terminal.B.equals(loginTerminal)) {
                // 设置请求头
                headers.put("Content-type", "application/json;charset=utf-8");

                String certificate = account.get("certificate").toString();
                String instId = account.getString("instId");
                String aid = account.getString("aid");
                String tid = account.getString("tid");

                url = host + "/business/anon/b/login?p=w&v=v5.0.0&userType=B&aid=" + aid;
//                B端登录URL
                logger.info("B端登录URL==>>"+url);
                String data = "{\"accountNo\":\"" + accountNo + "\",\"certificate\":\"" + certificate + "\",\"appTerm\":\"PC\",\"loginType\":\"PHONE_PWD\"}";

                okHttpClient.doPostRequest(url, data, headers);
//                try {
//                    TimeUnit.SECONDS.sleep(16);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
                body = okHttpClient.getBodyInJSON();
//               校验是否登录成功
//                Assert.assertEquals(body.getString("success"), "true",
//                        env + "环境" + loginTerminal + "端:" + loginUser + "登陆失败:"+body.getString("message"));
                if (body.getString("success").equals("true")){
                    // 获取token
                    xmTtoken = body.getJSONObject("result").get("xmToken").toString();
                    //                上面写法会导致参数传空
                    CommonRequestParameters loginIofo = new CommonRequestParameters();
                    loginIofo.setAid(aid)
                            .setUid(uid).setTid(tid).setUserType("B").setP("PC").setXmversion("5.0").setB("552595").setSaasV("5.0")
                            .setVn("5.4.3")
                            .setDeviceVersion("13.4.1")
                            .setV("5.4.3")
                            .setToken(xmTtoken)
                            .setTid(tid)
                            .setInstId(instId)
                            .setAccountNo(accountNo);

                    loginInfoMap.add(loginUser, loginIofo);

                }else {
                    logger.warn(env + "环境" + loginTerminal + "端:" + loginUser + "登陆失败:"+body.getString("message"));
                }
//                Assert.assertNotNull(xmTtoken, env + "环境" + loginTerminal + "端:" + loginUser + "登陆失败！");
                // 设置登录信息
//                CommonRequestParameters  loginIofo = new CommonRequestParameters().setAid(aid)

            } else if (Terminal.M.equals(loginTerminal)) {
                url = host + "/api-m/m/login/authCode";
                logger.info("M端登录URL==>>"+url);
                String deptpath = account.getString("deptpath");

                IdentityHashMap<String, String> param = new IdentityHashMap<>();
                param.put("phone", accountNo);
                param.put("code", "000000");

                okHttpClient.doPostForForm(url, param, headers);
                body = okHttpClient.getBodyInJSON();
                // 获取token
//                Assert.assertNotNull(body, env + "环境" + loginTerminal + "端:" + loginUser + "登陆失败！");
//                xmTtoken = body.getJSONObject("data").get("token").toString();
//                Assert.assertNotNull(xmTtoken, env + "环境" + loginTerminal + "端:" + loginUser + "登陆失败！");
                if (body.getString("success").equals("true")){
                    // 获取token
                    xmTtoken = body.getJSONObject("result").get("xmToken").toString();
                    // 设置登录信息
                    CommonRequestParameters loginIofo = new CommonRequestParameters().setDeptpath(deptpath)
                            .setUid(uid).setUserType(userType)
                            .setToken(xmTtoken)
                            .setU(accountNo)
                            .setAccountNo(accountNo);
                    ;
                    loginInfoMap.add(loginUser, loginIofo);
                }else {
                    logger.warn(env + "环境" + loginTerminal + "端:" + loginUser + "登陆失败:"+body.getString("message"));
                }
            } else if (Terminal.C.equals(loginTerminal)) {

                headers.remove("User-Agent");
                headers.remove("Cookie");
                headers.remove("Accept");
                headers.remove("Connection");

                String appId = account.get("appId").toString();
                String token = account.get("xmtoken").toString();
                String openId = account.get("openId").toString();
                String p = account.getString("p");

                headers.put("accept", "application/json");
                headers.put("appId", appId);
                headers.put("openId", openId);
                headers.put("xmtoken", token);
                headers.put("p", p);

                // 执行获取验证码
                headers.put("content-type", "application/json; charset=UTF-8");
                url = host + "/horn/anon/horn/msgAuthCode";
                logger.info("执行获取验证码登录URL==>>"+url);

                String data = "{\n" +
                        "  \"serverType\": \"BIND_PHONE\",\n" +
                        "  \"phone\": " + accountNo + "\n" +
                        "}";
                okHttpClient.doPostRequest(url, data, headers);

                // 执行验证码登录

                url = host + "/account/public/account/bindPhone";
                logger.info("执行验证码登录URL==>>"+url);

                data = "{\n" +
                        "  \"authCode\": \"0000\",\n" +
                        "  \"phone\": " + accountNo + "\n" +
                        "}";
                okHttpClient.doPostRequest(url, data, headers);

                body = okHttpClient.getBodyInJSON();
                // 获取token
//                Assert.assertNotNull(body, env + "环境" + loginTerminal + "端:" + loginUser + "登陆失败！");
//                String id = body.getJSONObject("result").getString("id");
//                Assert.assertNotNull(id, env + "环境" + loginTerminal + "端:" + loginUser + "登陆失败！");
                if (body.getString("success").equals("true")){
                    // 获取token
                    String id = body.getJSONObject("result").getString("id");
                    // 设置登录信息
                    CommonRequestParameters loginIofo = new CommonRequestParameters()
                            .setUid(id).setUserType(userType)
                            .setToken(token)
                            .setP(p)
                            .setAccountNo(accountNo)
                            .setOpenId(openId)
                            .setWechatAppId(appId);
                    loginInfoMap.add(loginUser, loginIofo);
                }else {
                    logger.warn(env + "环境" + loginTerminal + "端:" + loginUser + "登陆失败:"+body.getString("message"));
                }


            } else if (Terminal.minApp.equals(loginTerminal)) {

                String appId = account.getString("appId");
                String openId = account.getString("openId");
                String verifyCode = account.getString("verifyCode");

                params.put("phone", accountNo);
                params.put("verifyCode", verifyCode);
                params.put("xcxOpenId", openId);
                params.put("appId", appId);
                params.put("serverType", "HOMEWORK_LOGIN");

                url = host + "/api-h/c/login/xcx/homework/loginVersionTwo";
                logger.info("minApp登录URL==>>"+url);

                okHttpClient.doPostForForm(url, params, headers);
                body = okHttpClient.getBodyInJSON();
//
//                Assert.assertNotNull(body, env + "环境" + loginTerminal + "端:" + loginUser + "登陆失败！");
//                // 获取token
//                String token = body.getJSONObject("data").getString("token");
//                Assert.assertNotNull(token, env + "环境" + loginTerminal + "端:" + loginUser + "登陆失败！");
                if (body.getString("success").equals("true")){
                    // 获取token
                    xmTtoken = body.getJSONObject("result").get("xmToken").toString();
                    String userId = body.getJSONObject("data").getString("userId");
                    // 设置登录信息
                    CommonRequestParameters loginIofo = new CommonRequestParameters()
                            .setUid(userId).setUserType(loginTerminal)
                            .setToken(xmTtoken)
                            .setP("xcx")
                            .setAccountNo(accountNo)
                            .setOpenId(openId)
                            .setWechatAppId(appId);
                    loginInfoMap.add(loginUser, loginIofo);
                }else {
                    logger.warn(env + "环境" + loginTerminal + "端:" + loginUser + "登陆失败:"+body.getString("message"));
                }


            } else if (Terminal.APP_C.equals(loginTerminal)) {
                //app 每课学堂，手动滑动滑块， 可以 账户 + 0000 登录成功，不需要传openId等，跟C端有区别

//                headers.put("accept", "application/json");
                // 执行获取验证码
                headers.put("content-type", "application/json; charset=UTF-8");
                url = host + "/horn/anon/horn/msgAuthCode";
                logger.info("执行获取验证码登录URL==>>" + url);

                String data = "{\n" +
                        "  \"serverType\": \"C_LOGIN\",\n" +
                        "  \"phone\": " + accountNo + "\n" +
                        "}";
                okHttpClient.doPostRequest(url, data, headers);


                JSONObject loginInfo = new JSONObject();
                loginInfo.put("accountNo", accountNo);
//                loginInfo.put("certificate", account.get("certificate").toString());
                loginInfo.put("certificate", 0000);
                loginInfo.put("loginType", "PHONE_AUTH_CODE");
                loginInfo.put("appTerm", "IOS");
                loginInfo.put("userType", "C");
                url = host + "/zeus/anon/account/login";
                logger.info("APP_C登录URL==>>"+url);

                okHttpClient.doPostRequest(url, loginInfo.toJSONString(), headers);
                body = okHttpClient.getBodyInJSON();
//
//                Assert.assertNotNull(body, env + "环境" + loginTerminal + "端:" + loginUser + "登陆失败！");
//                // 获取token
//                String token = body.getJSONObject("result").getString("xmToken");
//                Assert.assertNotNull(token, env + "环境" + loginTerminal + "端:" + loginUser + "登陆失败！");
//                String userId = body.getJSONObject("result").getString("userId");
                if (body.getString("success").equals("true")){
                    // 获取token
                    String xmTtoken = body.getJSONObject("result").get("xmToken").toString();
                    String userId = body.getJSONObject("result").getString("userId");
                    String usertype = body.getJSONObject("result").getString("userType");

                    // 设置登录信息
                    CommonRequestParameters loginIofo = new CommonRequestParameters()
                            .setUid(userId).setUserType(loginTerminal)
                            .setToken(xmTtoken)
                            .setUserType(usertype)
                            .setAccountNo(accountNo);
                    loginInfoMap.add(loginUser, loginIofo);

                }else {
                    logger.warn(env + "环境" + loginTerminal + "端:" + loginUser + "登陆失败:"+body.getString("message"));
                }
            }
        } else {
            logger.warn("账号信息不存在！");

        }
    }


}
