package com.zhilin.patrol.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.model.GlideUrl;
import com.zhilin.patrol.R;
import com.zhilin.patrol.bean.HomeEntity;
import com.zhilin.patrol.bean.LoginEntity;
import com.zhilin.patrol.bean.LoginEntityNull;
import com.zhilin.patrol.http.HttpUrl;
import com.zhilin.patrol.tool.CheckPermissionUtils;
import com.zhilin.patrol.tool.CodeUtils;
import com.zhilin.patrol.tool.DialogUtil;
import com.zhilin.patrol.tool.EncryptUtil;
import com.zhilin.patrol.tool.IpUtils;
import com.zhilin.patrol.tool.JsonUtils;
import com.zhilin.patrol.tool.SPUtil;
import com.zhilin.patrol.tool.Utils;
import com.zhilin.patrol.views.CustomProgressDialog;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.BitmapCallback;
import com.zhy.http.okhttp.callback.Callback;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import static com.zhilin.patrol.http.HttpUrl.IMAGEPNG_GET;

/**
 * 登录界面
 */
public class LoginActivity extends BaseActivity {

    String TAG="LoginActivity";
    @BindView(R.id.et_account)
    EditText mAccountEt;//账号
    @BindView(R.id.et_pwd)
    EditText mPwdEt;//密码
    @BindView(R.id.image)
    ImageView imageVe;
    @BindView(R.id.btn_login)
    Button mLoginBtn;
    @BindView(R.id.et_code)
    EditText mCodeEt;//账号

    private CustomProgressDialog mProgressDialog;
    private LoginEntity.InfoListBean.UserInfoBean mUserInfo;
    private HomeEntity.InfoListBean homeInfo;
    private CodeUtils codeUtils;
    private String PHPSESSID;
    public static final int GET_DATA_SUCCESS = 1;
    public static final int NETWORK_ERROR = 2;
    public static final int SERVER_ERROR = 3;
    String[] mPermissions = {
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isContainNavi(false);
        setContentView(R.layout.activity_login);

        LoginEntity.InfoListBean infoList = (LoginEntity.InfoListBean) SPUtil.getShareObject(LoginActivity.this, SPUtil.SP_COMMON_CONFIG, "infoList");
        if (infoList!=null){//登录过直接去主页
            toMain(infoList);
            return;
        }
        ButterKnife.bind(this);
        mProgressDialog = new CustomProgressDialog(this);
        checkPermissions();
        requestImg();
    }

    @TargetApi(Build.VERSION_CODES.M)
    private void checkPermissions() {
        mPermissions = CheckPermissionUtils.getNeededPermission(this, mPermissions);
        if (mPermissions.length > 0) {
            requestPermissions(mPermissions, 999);
        }
        if (mPermissions.length == 0) {
            //申请过一次这里的permissions.length就为0 了  直接启动程序
        }

    }

    @OnClick({R.id.btn_login,R.id.image})
    public void onClick(View view) {
        if (view.getId() == R.id.btn_login) {//登录
            String accountText = mAccountEt.getText().toString().trim();
            String pwdText = mPwdEt.getText().toString().trim();
            String codeText = mCodeEt.getText().toString().trim();
            if (isEmpt(accountText, "请输入账号")) return;
            if (isEmpt(pwdText, "请输入密码")) return;
            if (isEmpt(codeText, "请输入验证码")) return;
            String ipAddress = IpUtils.getIpAddress(this);
            Log.i(TAG,"ipAddress地址");
            Log.i(TAG,ipAddress);

            try {
                String pwdByMd5 = EncryptUtil.encodeByMd5(pwdText);
                Log.i("PASSWORD",pwdByMd5);
                postLogin(accountText, ipAddress, pwdByMd5,codeText);

            } catch (Exception e) {
                Utils.showToast(this, "md5加密失败");
            }
        }
        if(view.getId()==R.id.image){
            requestImg();
        }
    }
    /**
     * 特殊的自动管理Cookies
     */
   /* private class CookiesManager implements CookieJar {

        //保存每个url的cookie
        private HashMap<okhttp3.HttpUrl, List<Cookie>> cookieStore = new HashMap<okhttp3.HttpUrl, List<Cookie>>();

        //上一个请求url
        private okhttp3.HttpUrl url;

        @Override
        public void saveFromResponse(okhttp3.HttpUrl httpUrl, List<Cookie> list) {
            //保存链接的cookie
            cookieStore.put(httpUrl, list);
            //保存上一次的url，供给下一次cookie的提取。
            url = httpUrl;
        }

        @Override
        public List<Cookie> loadForRequest(okhttp3.HttpUrl httpUrl) {

            //加载上一个链接的cookie
            List<Cookie> cookies = cookieStore.get(url);
            return cookies != null ? cookies : new ArrayList<Cookie>();

        }

    }*/

    /*
    * 获取图形验证码
    * */
    public void requestImg() {
//        URL url = new URL("http://39.106.14.189:8081/index.php/ApiMobi/getImgPng");
//        returnBitMap("http://39.106.14.189:8081/index.php/ApiMobi/getImgPng");
//        image.setImageURI(url);
        setImageURL(IMAGEPNG_GET);
        //初始化okhttp，
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case GET_DATA_SUCCESS:
                    Bitmap bitmap = (Bitmap) msg.obj;
                    imageVe.setImageBitmap(bitmap);
                    break;
                case NETWORK_ERROR:
                    Utils.showToast(LoginActivity.this, "网络连接失败");
                    break;
                case SERVER_ERROR:
                    Utils.showToast(LoginActivity.this, "服务器发生错误");
                    break;
            }
        }
    };
    //设置网络图片
    public void setImageURL(final String path) {
        //开启一个线程用于联网
        new Thread() {
            @Override
            public void run() {
                try {
                    //把传过来的路径转成URL
//                    URL url = new URL(path);
                    //获取连接

//               OkHttpUtils.post().url(path).build().execute(new BitmapCallback() {
//                        @Override
//                        public void onResponse(Bitmap bitmap, int i) {
//                            try {
//                                imageVe.setImageBitmap(bitmap);
//
//                            } catch (Exception e) {
//                            }
//                        }
//
//                        @Override
//                        public void onError(Call arg0, Exception arg1, int arg2) {
//                            // TODO Auto-generated method stub
//                        }
//                    });
                /*Response response = null;
                try {
                    response = OkHttpUtils.post()
                            .url(path)
                            .build().execute();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Headers responseHeaders = response.headers();
                int responseHeadersLength = responseHeaders.size();
                for (int i = 0; i < responseHeadersLength; i++){
                    String headerName = responseHeaders.name(i);
                    String headerValue = responseHeaders.get(headerName);
                    if(headerName.equals("Set-Cookie")){
                        PHPSESSID=headerValue;
                    }

                    System.out.print("TAG----------->Name:"+headerName+"------------>Value:"+headerValue+"\n");
                }*/
                Response response = OkHttpUtils.post()
                            .url(path)
                            .build().execute();
                if (response.isSuccessful()) {
                    byte[] jsonStr = response.body().bytes();
//                    Log.i("验证码图片=",jsonStr);
//                    InputStream inputStream = response.body().byteStream();
                    Bitmap img =  BitmapFactory.decodeByteArray(jsonStr,0,jsonStr.length);
//                    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                    Message msg = Message.obtain();
                    msg.obj = img;
                    msg.what = GET_DATA_SUCCESS;
                    handler.sendMessage(msg);
//                    inputStream.close();
                    Headers responseHeaders = response.headers();
                    int responseHeadersLength = responseHeaders.size();
                    for (int i = 0; i < responseHeadersLength; i++){
                        String headerName = responseHeaders.name(i);
                        String headerValue = responseHeaders.get(headerName);
                        if(headerName.equals("Set-Cookie")){
                            PHPSESSID=headerValue;
                        }
                        System.out.print("TAG----------->Name:"+headerName+"------------>Value:"+headerValue+"\n");
                    }
                    }else {
                         Utils.showToast(LoginActivity.this, "获取验证码失败");
                    }
/*
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    //使用GET方法访问网络
                    connection.setRequestMethod("GET");
                    //超时时间为10秒
                    connection.setConnectTimeout(10000);
                    //获取返回码
                    int code = connection.getResponseCode();
                    if (code == 200) {
                        InputStream inputStream = connection.getInputStream();
                        //使用工厂把网络的输入流生产Bitmap

                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                        //利用Message把图片发给Handler
                        Message msg = Message.obtain();
                        msg.obj = bitmap;
                        msg.what = GET_DATA_SUCCESS;
                        handler.sendMessage(msg);
                        inputStream.close();
                    } else {
                        //服务启发生错误
                        handler.sendEmptyMessage(SERVER_ERROR);
                    }*/
                } catch (IOException e) {
                    e.printStackTrace();
                    //网络连接错误
                    handler.sendEmptyMessage(NETWORK_ERROR);
                }
            }
        }.start();
    }
    /**
     * 提交登录
     *
     * @param accountText
     * @param ipAddress
     * @param pwdByMd5
     * @throws IOException
     */
    private void postLogin(String accountText, String ipAddress, String pwdByMd5,String codeText) throws IOException {
        mProgressDialog.showDialog("正在登录...");
        OkHttpUtils.post()
                .url(HttpUrl.LOGIN_URL)
                .addHeader("Cookie", PHPSESSID)
                .addParams("loginName", accountText)
                .addParams("loginPwd", pwdByMd5)
                .addParams("userIP", ipAddress)
                .addParams("tokenCode",codeText)
                .build().execute(new Callback<LoginEntity>() {
            @Override
            public LoginEntity parseNetworkResponse(Response response, int id) throws Exception {
                String jsonStr = response.body().string();
                Log.i(TAG,jsonStr+"jsonStr");

//                Log.i(TAG,JsonUtils.parseJson2Obj(jsonStr, LoginEntity.class).toString());
//                jsonStr.contains("userCode");
                LoginEntity loginEntity = new LoginEntity();

                if(jsonStr.contains("userCode")){//是否存在userCode
                    Log.i(TAG,"infolist不为空");
                    LoginEntity notnullEntity = (LoginEntity) JsonUtils.parseJson2Obj(jsonStr, LoginEntity.class);//序列化
                    loginEntity.setReturnCode((notnullEntity.getReturnCode()));
                    loginEntity.setReturnMsg(notnullEntity.getReturnMsg());
                    loginEntity.setInfoList(notnullEntity.getInfoList());

                }else{
                    Log.i(TAG,"infolist为空");
                    LoginEntityNull nullEntity=(LoginEntityNull) JsonUtils.parseJson2Obj(jsonStr,LoginEntityNull.class);//
                    loginEntity.setReturnCode(nullEntity.getReturnCode());
                    loginEntity.setReturnMsg(nullEntity.getReturnMsg());
                }
                return loginEntity;
            }

//            @Override
//            public LoginEntityNull parseNetworkResponse(Response response, int id) throws Exception {
//                String jsonStr = response.body().string();
//                Log.i(TAG,jsonStr);
//                if(jsonStr.contains("userCode")){
//                    return (LoginEntityNull) JsonUtils.parseJson2Obj(jsonStr, LoginEntityNull.class);
//                }else{
//                    return (LoginEntityNull) JsonUtils.parseJson2Obj(jsonStr, LoginEntityNull.class);//
//                }
//            }

            @Override
            public void onError(Call call, Exception e, int id) {
                mProgressDialog.dismiss();
                DialogUtil.showNetFailDialog(LoginActivity.this);
            }

            @Override
            public void onResponse(LoginEntity entity, int id) {
                mProgressDialog.dismiss();
                if (entity == null) {
                    Log.i(TAG,"entity=null");
                    DialogUtil.showErrDialog(LoginActivity.this, "返回信息为空");
                    return;
                }
                //!"1000".endsWith(entity.getReturnCode())
                if (!"1000".endsWith(entity.getReturnCode())) {
                    DialogUtil.showErrDialog(LoginActivity.this, entity.getReturnMsg());
                    Log.i(TAG,"entity.getreturncode"+entity.getReturnCode());
                    return;
                }
                LoginEntity.InfoListBean infoList = entity.getInfoList();
                Log.i(TAG,entity.getReturnCode());
                Log.i(TAG,"entity.getreturncode=1000");
//                LoginEntity.InfoListBean infoBean = null;
//                List<LoginEntity.InfoListBean> infoList = entity.getInfoList();
//                if(infoList.size() != 0){
//                    infoBean = infoList.get(0);
//                }
                SPUtil.savaToShared(LoginActivity.this, SPUtil.SP_COMMON_CONFIG, "infoList", infoList);
//                toMain(infoBean);

                toMain(infoList);

            }
        });

    }

    /**
     * 去主页
     * @param infoList
     */
    private void toMain(LoginEntity.InfoListBean infoList) {
        mUserInfo=infoList.getUserInfo();

        if(mUserInfo.getUserRole()==1||mUserInfo.getUserRole()==2){
            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
            intent.putExtra("infoList", infoList);
            startActivity(intent);
            finish();
        }

        if(mUserInfo.getUserRole()==3) {
            Intent intent = new Intent(LoginActivity.this, RectifyMainActivity.class);
//            intent.putExtra("userInfo", mUserInfo);
            intent.putExtra("infoList", infoList);
            startActivity(intent);
            finish();
        }
    }

    /**
     * 判断是否为空
     *
     * @param text
     * @param errText
     * @return
     */
    private boolean isEmpt(String text, String errText) {
        if (TextUtils.isEmpty(text)) {
            Utils.showToast(this, errText);
            return true;
        }
        return false;
    }
   /* @Override
    public void request() {
        String ipAddress = IpUtils.getIpAddress(this);
        PostFormBuilder formBuilder = OkHttpUtils.post();
        formBuilder.url(HttpUrl.MAIN_URL);
        formBuilder.addParams("userCode", mUserInfo.getUserCode());
        formBuilder.addParams("userRole", mUserInfo.getUserRole() + "");
        formBuilder.addParams("userIP", ipAddress);
        RequestCall call = formBuilder.build();
        call.execute(new Callback<TaskTypeEntity>() {
            @Override
            public TaskTypeEntity parseNetworkResponse(Response response, int id) throws Exception {
                String jsonStr = response.body().string();
                return (TaskTypeEntity) JsonUtils.parseJson2Obj(jsonStr, TaskTypeEntity.class);
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                DialogUtil.showNetFailDialog(LoginActivity.this);
            }

            @Override
            public void onResponse(TaskTypeEntity entity, int id) {
                if (entity == null) {
                    DialogUtil.showErrDialog(LoginActivity.this, "返回信息为空");
                    return;
                }
                homeInfo = entity.getInfoList();
                if (!"1000".endsWith(entity.getReturnCode())) {
                    DialogUtil.showErrDialog(LoginActivity.this, entity.getReturnMsg());
                    return;
                }

            }
        });
    }*/

}
