package com.efounder.chat.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.efounder.chat.R;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.utils.ResStringUtil;

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

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

import static com.efounder.frame.utils.Constants.CHAT_USER_ID;

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

    private User user;
//    private DisplayImageOptions options;
    private ImageView iv_avatar;
//    private ImageLoader imageLoader;
    private TextView tv_nickname;
    private TextView tv_text;
    private String webname="内控（测试）";
    private String urlstring="";
    private String json="";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_loginweb);

        json=getIntent().getStringExtra("result");

        iv_avatar= (ImageView) findViewById(R.id.iv_avatar);
        tv_nickname= (TextView) findViewById(R.id.tv_nickname);
        tv_text= (TextView) findViewById(R.id.tv_text);
        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) {
                LoginWebActivity.this.finish();
            }
        });

        initview();
    }


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

        user = WeChatDBManager.getInstance().getOneUserById(Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID)));

//        initImageLoader();
        String avatar=user.getAvatar();
        //设置头像
        showUserAvatar(avatar);

        tv_nickname.setText(user.getNickName().toString());
//        tv_text.setText("请求登录"+webname+"，请确认是否本人操作");
        tv_text.setText(R.string.wrchatview_request_login);
    }

    /**
     * 显示用户头像
     */
    private void showUserAvatar(String url) {
            Glide.with(this)
                    .load(url)
                    .apply(new RequestOptions().centerCrop()
                            .dontAnimate()
                            .placeholder(R.drawable.default_useravatar)
                            .error(R.drawable.default_useravatar))
                    .thumbnail(0.5f)
                    //  .override(size/4*3, size/4*3)
                    .into(iv_avatar);
//            imageLoader.displayImage(url, iv_avatar, options);

    }

    /**
     * 异步加载头像
     */
    public void initImageLoader() {
//        // 初始化异步加载图片的类
//        imageLoader = ImageLoader.getInstance();
//        // 设置异步加载图片的配置信息
//        options = ImageUtil.getImageLoaderOptions(R.drawable.default_useravatar);

    }

    @Override
    public void onClick(View v) {
        int id=v.getId();
        if(id==R.id.btn_accept){
            urlstring=urlstring+"&UserName="+user.getName();
            login();
        }
        else if(id==R.id.btn_cancle){
            LoginWebActivity.this.finish();
        }
    }

    private void login()
    {
        new AsyncTask<String, Integer, String>() {
            private ProgressDialog dialog;
            @Override
            protected void onPreExecute() {
                dialog = new ProgressDialog(LoginWebActivity.this);
                dialog.setMessage(ResStringUtil.getString(R.string.wrchatview_logining));
                dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                dialog.show();
                super.onPreExecute();
            }

            @Override
            protected String doInBackground(String... params) {
                int code=0;
                try {
                    System.out.println("url="+urlstring);
                    URL url=new URL(urlstring);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setConnectTimeout(3*1000);
                    conn.setRequestMethod("GET");
                    code=conn.getResponseCode();
                    if(code==200){
                        return "success";
                    }else{
                        return "fail";
                    }
                } catch (ProtocolException e) {
                    e.printStackTrace();
                    return "fail";
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                    return "fail";
                } catch (IOException e) {
                    e.printStackTrace();
                    return "fail";
                }
            }

            @Override
            protected void onPostExecute(String result) {
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
                if (result.equals("success")) {
                    Toast.makeText(LoginWebActivity.this,R.string.wrchatview_login_success,Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(LoginWebActivity.this,R.string.wrchatview_login_fail+result,Toast.LENGTH_SHORT).show();
                }
                LoginWebActivity.this.finish();
            }
        }.execute();
    }


    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle data = msg.getData();
            String val = data.getString("value");

            if (val.equals("200")) {
                Toast.makeText(LoginWebActivity.this,R.string.wrchatview_login_success,Toast.LENGTH_SHORT).show();
            }else{
                Toast.makeText(LoginWebActivity.this,R.string.wrchatview_login_fail+val,Toast.LENGTH_SHORT).show();
            }
            LoginWebActivity.this.finish();
        }
    };
}
