package com.efounder.chat.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.efounder.chat.R;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.http.JFCommonRequestManager;
import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.utils.Constants;
import com.efounder.http.EFHttpRequest;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.util.AppContext;
import com.efounder.util.ToastUtil;
import com.efounder.utils.ResStringUtil;
import com.utilcode.util.LogUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.net.URLEncoder;
import java.util.HashMap;

import static com.efounder.frame.utils.Constants.CHAT_USER_ID;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_ADDRESS;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_HTTP_TYPE;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_PATH;
import static com.efounder.frame.utils.Constants.KEY_SETTING_DEFAULT_SERVER_PORT;


/**
 * Created by Tian Yu on 2016/9/12.
 */
public class LoginThirdWebActivity extends BaseActivity implements View.OnClickListener {


    private User user;
    private ImageView iv_avatar;
    private TextView tv_nickname;
    private TextView tv_text;
    private String json = "";
    private ImageView ivBack;
    private TextView tvTitle;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_loginweb);
        initview();
        initData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void initData() {
        json = getIntent().getStringExtra("result");
        if (json != null) {
            try {
                JSONObject jsonObject = new JSONObject(json);
//            webname=jsonObject.getString("websitename");
                //urlstring = jsonObject.getString("url");
            } catch (JSONException e) {
                Toast.makeText(LoginThirdWebActivity.this, R.string.wrchatview_qr_code_fail, Toast.LENGTH_SHORT).show();
                LoginThirdWebActivity.this.finish();
            }
        }

        user = WeChatDBManager.getInstance().getOneUserById(Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID)));
        String avatar = user.getAvatar();
        //设置头像
        showUserAvatar(avatar);
        tv_nickname.setText(user.getNickName().toString());
        tv_text.setText(R.string.wrchatview_request_login);
        tvTitle.setText(R.string.wrchatview_scan_code_login);
    }


    private void initview() {
        iv_avatar = (ImageView) findViewById(R.id.iv_avatar);
        tv_nickname = (TextView) findViewById(R.id.tv_nickname);
        tv_text = (TextView) findViewById(R.id.tv_text);
        ivBack = (ImageView) findViewById(R.id.iv_back);
        tvTitle = (TextView) findViewById(R.id.tv_title);

        Button btn_accept = (Button) findViewById(R.id.btn_accept);
        Button btn_cancle = (Button) findViewById(R.id.btn_cancle);

        btn_accept.setOnClickListener(this);
        btn_cancle.setOnClickListener(this);

        ImageView iv_back = (ImageView) findViewById(R.id.iv_back);
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LoginThirdWebActivity.this.finish();
            }
        });


    }

    /**
     * 显示用户头像
     */
    private void showUserAvatar(String url) {
        LXGlideImageLoader.getInstance().showRoundUserAvatar(LoginThirdWebActivity.this, iv_avatar,
                url, LXGlideImageLoader.DEFATLT_AVATAR_RADIUS_12);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.btn_accept) {
            startLogin();
        } else if (id == R.id.btn_cancle) {
            LoginThirdWebActivity.this.finish();
        }
    }

    private void startLogin() {
        showLoading(ResStringUtil.getString(R.string.wrchatview_requesting_login));
        try {
            JSONObject jsonObject = new JSONObject(json);
            String type = jsonObject.getString("type");
            if (type.equals("opLogin")) {
                //判断type是否为星际通讯的扫码登录
                openPlanetLogin(json);
            } else if (type.equals("qrlogin")) {
                //中建，财务共享扫码登陆
                if (EnvironmentVariable.getProperty(Constants.KEY_SETTING_APPID).equals("OSPMobileCSCES")) {
                    zjLogin(json);
                } else if (EnvironmentVariable.getProperty(Constants.KEY_SETTING_APPID).equals("ZSYGXOSPMobile") ||
                        EnvironmentVariable.getProperty(Constants.KEY_SETTING_APPID).equals("ZSYGXOSPMobileYS")) {
                    gxLogin(json);
                }
            } else {
                weiXinAndShanDaLogin(json);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 共享扫码登陆
     *
     * @param json
     */
    private void gxLogin(String json) {
        try {
            JSONObject jsonObject = new JSONObject(json);
            String type = jsonObject.getString("type");
            String qrcode = jsonObject.getString("qrcode");

            JSONObject param = new JSONObject();
            JSONObject paramRoot = new JSONObject();
            JSONObject RequestParam = new JSONObject();
            paramRoot.put("type", "login");
            paramRoot.put("username", EnvironmentVariable.getUserName());
            paramRoot.put("qrcode", qrcode);
            param.put("paramRoot", paramRoot);
            RequestParam.put("Param", param);

//            String requestUrl = "http://124.127.206.3:2012/OSPPortal/rest/qrlogin/login";
            String requestUrl = EnvironmentVariable.getProperty("SARestfulUrl") + "/OpenAPIService/SAQRLoginService?RequestParam=";
            LogUtils.d(requestUrl + param.toString());
            JFCommonRequestManager.getInstance(AppContext.getInstance())
                    //.requestPostByAsyncWithRequsetBody(TAG, "http://192.168.248.41:8081/ImageUpload/UploadImage",
                    .requestPostByAsyncWithJSON(TAG, requestUrl, RequestParam.toString(), new JFCommonRequestManager.ReqCallBack<String>() {
                        @Override
                        public void onReqSuccess(String result) {
                            try {
                                net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(result);
                                if (jsonObject.optString("ErrorCode").equals("0")) {
                                    loginSuccess();
                                } else {
                                    loginFailed();
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                loginFailed();
                            }
                        }

                        @Override
                        public void onReqFailed(String errorMsg) {
                            loginFailed();
                        }
                    });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 中建扫码登陆
     */
    private void zjLogin(String jsonString) {
        try {
            JSONObject jsonObject = new JSONObject(jsonString);
            String type = jsonObject.getString("type");
            String qrcode = jsonObject.getString("qrcode");

            JSONObject param = new JSONObject();
            param.put("username", EnvironmentVariable.getUserName());
            param.put("qrcode", qrcode);

//            String requestUrl = "http://124.127.206.3:2012/OSPPortal/rest/qrlogin/login";
            String requestUrl = EnvironmentVariable.getProperty("WebLoginUrl") + "/rest/qrlogin/login";
            LogUtils.d(requestUrl + param.toString());
            JFCommonRequestManager.getInstance(AppContext.getInstance())
                    //.requestPostByAsyncWithRequsetBody(TAG, "http://192.168.248.41:8081/ImageUpload/UploadImage",
                    .requestPostByAsyncWithJSON(TAG, requestUrl, param.toString(), new JFCommonRequestManager.ReqCallBack<String>() {
                        @Override
                        public void onReqSuccess(String result) {
                            try {
                                net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(result);
                                if (jsonObject.optString("code").equals("0")) {
                                    loginSuccess();
                                } else {
                                    loginFailed();
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                loginFailed();
                            }
                        }

                        @Override
                        public void onReqFailed(String errorMsg) {
                            loginFailed();
                        }
                    });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 山大扫码登录
     *
     * @param jsonString
     */
    private void weiXinAndShanDaLogin(String jsonString) {
        try {
            JSONObject jsonObject = new JSONObject(jsonString);

            String type = jsonObject.getString("type");
            String authId = jsonObject.getString("authId");
            String url = jsonObject.getString("url");
            String userId = EnvironmentVariable.getUserName();
            User user = WeChatDBManager.getInstance().
                    getOneUserById(Integer.valueOf(EnvironmentVariable.getProperty(Constants.CHAT_USER_ID)));
            String userName = user.getNickName();
            HashMap<String, String> map = new HashMap<>();
            map.put("url", url);
            map.put("authId", authId);
            map.put("type", type);
            map.put("userId", userId);
            if (userId.length() >= 25) {
                map.put("idSrc ", "WX");
            } else {
                map.put("idSrc", "SD");
            }
            map.put("extraInfo", URLEncoder.encode(EnvironmentVariable.getProperty("extraInfo", ""), "utf-8"));
            map.put("userName", URLEncoder.encode(userName, "utf-8"));
            String baseURL = EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_HTTP_TYPE) + "://" + EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_ADDRESS) + ":"
                    + EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_PORT) + "/"
                    + EnvironmentVariable.getProperty(KEY_SETTING_DEFAULT_SERVER_PATH) + "/ThirdLoginServlet";
            EFHttpRequest httpRequest = new EFHttpRequest(TAG);
            httpRequest.setHttpRequestListener(new EFHttpRequest.HttpRequestListener() {
                @Override
                public void onRequestSuccess(int arg0, String arg1) {
                    loginSuccess();


                }

                // HTTP请求失败；
                @Override
                public void onRequestFail(int arg0, String arg1) {
                    loginFailed();
                }
            });

            httpRequest.httpPost(baseURL, map);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 星际通讯扫码登录
     */
    private void openPlanetLogin(final String jsonString) {

        try {
            final JSONObject jsonObject = new JSONObject(jsonString);
            String client_id = jsonObject.getString("client_id");
            String code = jsonObject.getString("code");
            final HashMap<String, String> map = new HashMap<>();

            map.put("access_token", EnvironmentVariable.getProperty("tc_access_token"));
            map.put("code", code);
            map.put("client_id", client_id);

            String baseUrl = EnvironmentVariable.getProperty("TalkChainUrl") + "/tcserver";
            JFCommonRequestManager.getInstance().requestGetByAsyn(TAG, baseUrl + "/oauth/authorizeCode", map,
                    new JFCommonRequestManager.ReqCodeCallBack<String>() {
                        @Override
                        public void onReqFailed(int errorCode, String errorMsg) {
                            loginFailed();
                        }

                        @Override
                        public void onReqSuccess(String result) {
                            if (result == null || "".equals(result)) {
                                loginFailed();
                                return;
                            }
                            net.sf.json.JSONObject jsonObject1 = net.sf.json.JSONObject.fromObject(result);
                            if (jsonObject1.getString("result").equals("success")) {
                                loginSuccess();
                            } else {
                                loginFailed();
                            }
                        }

                        @Override
                        public void onReqFailed(String errorMsg) {
                        }
                    });

        } catch (Exception e) {
            e.printStackTrace();
            loginFailed();
        }
    }

    /**
     * 登录成功提示
     */
    private void loginSuccess() {
        if (isDestroyed()) {
            return;
        }
        dismissLoading();
        Toast.makeText(LoginThirdWebActivity.this, R.string.wrchatview_login_success, Toast.LENGTH_SHORT).show();
        Class<?> clazz = null;
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        try {
            clazz = loader.loadClass(getResources().getString(R.string.from_group_backto_first));
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        if (clazz != null) {

            Intent intent = new Intent(LoginThirdWebActivity.this, clazz);
            //启动BaseActivity
            startActivity(intent);
        } else {
            finish();
        }
    }

    /**
     * 登录失败提示
     */
    private void loginFailed() {
        if (isDestroyed()) {
            return;
        }
        dismissLoading();
        ToastUtil.showToast(LoginThirdWebActivity.this, R.string.wrchatview_login_fail);
    }


}
