package com.xiaomai.utils;

import com.alibaba.fastjson.JSONObject;
import com.xiaomai.client.OkHttpClient;
import com.xiaomai.enums.Terminal;
import com.xiaomai.jdbc.dao.DataDao;
import com.xiaomai.jdbc.entity.UserInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.test.context.ContextConfiguration;
import org.testng.Assert;

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


/**
 * 公共登录工具类
 */
@ContextConfiguration(locations = {"classpath:/spring-core.xml", "classpath:/applicationContext.xml"})
public class CommonLogin {
    JsonAndFile fileHandle;
    OkHttpClient okHttpClient;
    // 组装请求
    IdentityHashMap<String, String> params;
    HashMap<String, String> headers;
    String url;
    Properties prop;
    JSONObject body;
    String token = "";
    Logger logger = LoggerFactory.getLogger(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();


        DataDao dataDao = (DataDao) SpringContextUtil.getBean("dataDao");
        UserInfo userInfo = dataDao.getUserInfo(loginUser, env);
        Assert.assertNotNull(userInfo, "找不到用户登录信息, 姓名" + loginUser + "; 环境:" + env + "，请检查是否已有保存登录账号信息。");
        if (null != userInfo) {
            String accountNo = userInfo.getAccount_no();
            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");
                headers.put("xm-request-source", "xmTest");
                headers.put("User-Agent", "XMSport/1.0 (com.jiejing.sport; build:1; iOS 15.8.1) Alamofire/5.8.0");
                String tenant = userInfo.getTenant();
                String adminId = userInfo.getAdminId();
                String brandId = userInfo.getBrandId();
                String studioId = userInfo.getStudioId();
                String user = userInfo.getUser();
                url = host + "/polar/anon/login/loginAdmin?version=1.0&sfb=0.0&build=1&deviceType=ios&sft=20.0&sfl=0.0&sfr=0.0";
//                B端登录URL
                logger.info("B端登录URL==>>" + url);
                String data = "{\"accountNo\":\"" + accountNo + "\",\"certificate\":\"0000\",\"loginTerm\":\"FITNESS_ADMIN_APP\",\"loginMode\":\"PHONE_AUTH_CODE\",\"serverType\": \"B_LOGIN\"}";
                // 发起登录请求
                okHttpClient.doPostRequest(url, data, headers);
                body = okHttpClient.getBodyInJSON();

                // 获取token
                Assert.assertNotNull(body, env + "环境" + loginTerminal + "端:" + loginUser + "登陆失败！");
                token = body.getJSONObject("result").get("authToken").toString();
                Assert.assertNotNull(token, env + "环境" + loginTerminal + "端:" + loginUser + "登陆失败！");

                CommonRequestParameters loginInfo = new CommonRequestParameters();
                user = body.getJSONObject("result").get("userId").toString();
                loginInfo.setDomain("FITNESS_ADMIN")
                        .setTenant(tenant)
                        .setToken(token)
                        .setUser(user)
                        .setAdminId(adminId)
                        .setAccountNo(accountNo)
                        .setBrandId(brandId)
                        .setStudioId(studioId);
                loginInfoMap.add(loginUser,loginInfo);

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

                String appId = userInfo.getApp_id();
                String openId = userInfo.getOpen_id();
                String brandId = userInfo.getBrandId();
                String studioId = userInfo.getStudioId();
                String token = userInfo.getXm_token();
                String user = userInfo.getUser();
                headers.put("xm-request-source", "xmTest");

                CommonRequestParameters loginIofo = new CommonRequestParameters()
                        .setUser(user)
                        .setDomain("FITNESS_MEMBER")
                        .setToken(token)
                        .setAccountNo(accountNo)
                        .setOpenId(openId)
                        .setToken(token)
                        .setWechatAppId(appId)
                        .setBrandId(brandId)
                        .setStudioId(studioId);
                loginInfoMap.add(loginUser, loginIofo);
            }  else {
                logger.warn(env + "环境" + loginTerminal + "端:" + loginUser + "登陆失败:" + body.getString("message"));
            }
        } else {
            logger.warn("账号信息不存在！");

        }
    }


}
