package com.fxy.login;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.fxy.BuildConfig;
import com.fxy.common.VersionUpgrades;
import com.elvishew.xlog.XLog;
import com.jaredrummler.materialspinner.MaterialSpinner;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.fxy.baselibrary.base.BaseActivity;
import com.fxy.baselibrary.language.other.CommSharedUtil;
import com.fxy.baselibrary.util.AnimShakeUtil;
import com.fxy.baselibrary.util.CircularAnim;
import com.fxy.baselibrary.util.JsonUtil;
import com.fxy.baselibrary.util.StringUtils;
import com.fxy.R;
import com.fxy.base.ServiceSettingActivity;
import com.fxy.base.SetLanguageActivity;
import com.fxy.bean.ActionBean;
import com.fxy.constant.BaseConfig;
import com.fxy.constant.SPCache;
import com.fxy.login.bean.UserBean;
import com.fxy.main.MainActivity;
import com.fxy.net.MyDialogCallback;
import com.fxy.net.Urls;

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

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 系统登录界面
 * @data 2020-01-05
 * @author James.Jiang
 */
public class LoginActivity extends BaseActivity {
    private Context mContext = this;

    @BindView(R.id.ll_page_content)
    LinearLayout llPageContent;
    /**
     * 账号
     */
    @BindView(R.id.log_et_name)
    EditText mLogEtName;
    /**
     * 密码
     */
    @BindView(R.id.log_et_pwd)
    EditText mLogEtPwd;


    /**
     * 服务设置/语言等容器
     */
    @BindView(R.id.ll_app_setting)
    LinearLayout ll_app_setting;

    //默认选中
    private Integer selectIndex= 0;
    // 定义仓库列表
    private List<Map<String, String>> warehouseMapList = new ArrayList<>();
    //仓库名称
    private  List<String> warehouseNameList = new ArrayList<String>();

    private String client_code = "";
    private String service_type = "";

    @Override
    public int getContentViewResId() {
        return R.layout.activity_login;
    }

    @Override
    public boolean showToolBar() {
        return false;
    }

    @Override
    public boolean openEventBus() {
        return false;
    }

    @Override
    protected void getBundleExtras(Bundle extras) {

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 200 && resultCode == 200)//之前提到的两个标志，在这里显示出了作用
        {

        }
    }

    @Override
    public boolean isPlayMusic() {
        return true;
    }


    /**
     * 初始化界面组件
     */
    @Override
    protected void initView() {
        ButterKnife.bind(this);
        try {
            //检查文件读写 权限
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
                ActivityCompat.requestPermissions(this, new String[]{ Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            }
        }catch (Exception e){
            XLog.e("获取读写权限出错："+e.getMessage());
        }

        // 生产环境不显示服务设置


        // 登录未过期则直接跳转到主面板
        if (StringUtils.isNotEmpty(SPCache.getInstance(LoginActivity.this).getToken())) {
            intent2Page(LoginActivity.this, MainActivity.class, true);
            return;
        }
        iniData();

        new Thread() {
            @Override
            public void run() {
                (new VersionUpgrades(mContext)).checkUpgrades();
            }
        }.start();

    }

    private void iniData(){
        // 记住用户名
        String userAccountStr = SPCache.getInstance(LoginActivity.this).getAccountName();
        if (StringUtils.isNotEmpty(userAccountStr)) {
            mLogEtName.setText(userAccountStr);
        }
        initService();
    }

    /**
     * 初始化服务端
     */
    private void initService(){
        String serviceAddress = Urls.getServiceAddress(mContext);
        if (serviceAddress==null || serviceAddress.isEmpty()){
            //修改默认连接是oss
            SPCache spCache = SPCache.getInstance(mContext);
            spCache.setResourceHost(BuildConfig.OSS_HOST);
            spCache.setResourceType(BuildConfig.RESOURCE_TYPE);
            spCache.setResourcePrefix(BuildConfig.RESOURCE_PREFIX);

            new AlertDialog.Builder(this)
                    .setTitle(R.string.dl_hint)
                    .setMessage("请先服务设置")
                    .setCancelable(false)
                    .setNegativeButton(R.string.str_submit, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            Bundle bundle = new Bundle();
                            //startActivity(new Intent(LoginActivity.this, ServiceSettingActivity.class));
                            intentPageResult(LoginActivity.this,ServiceSettingActivity.class, bundle,200);
                        }
                    }).show();
        }


    }



    /**
     * 判断登录必录项
     * @return
     */
    private boolean isCanLogin() {
        String userAccountStr = mLogEtName.getText().toString().trim();
        if (StringUtils.isEmpty(userAccountStr)) {
            AnimShakeUtil.shake(mLogEtName);
            return false;
        }
        String pwdStr = mLogEtPwd.getText().toString().trim();
        if (StringUtils.isEmpty(pwdStr)) {
            AnimShakeUtil.shake(mLogEtPwd);
            return false;
        }
        return true;
    }

    /**
     * 登录系统
     */
    private void login(final String username, final String password) {
        HashMap<String, Object> params = new HashMap<>();
        params.put("username", username);
        params.put("password", password);
        JSONObject jsonObject = new JSONObject(params);
        OkGo.<String>post(Urls.getServiceAddress(this)+ Urls.LOGIN ).upJson(jsonObject)
                .execute(new MyDialogCallback(this, false, true) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            ActionBean bean = JsonUtil.getObject(response.body(), ActionBean.class);
                            if (bean.code == 1) {
                                if (StringUtils.isNotEmpty(bean.data)) {
                                    UserBean mUserBean = JsonUtil.getObject(bean.data, UserBean.class);

                                    SPCache spCache = SPCache.getInstance(LoginActivity.this);

                                    //保存资源类型已经
                                    spCache.setResourceHost(mUserBean.resource_domain);
                                    spCache.setResourceType(mUserBean.resource_type);
                                    spCache.setResourcePrefix(mUserBean.resource_prefix);
                                    spCache.setResourceRegion(mUserBean.resource_region);
                                    spCache.setResourceBucket(mUserBean.resource_bucket);


                                    spCache.setToken(mUserBean.user_token);
                                    spCache.setWeightUnit(mUserBean.weight_unit);
                                    //spCache.setAvatarUrl(Urls.HEAD_IMAGE);

                                    spCache.setBusinessType(mUserBean.business_type);

                                }
                                if (getIntent().getIntExtra("type", 0) == 1) {
                                    finish();
                                } else {
                                    CircularAnim.fullActivity(LoginActivity.this, llPageContent)
                                            .colorOrImageRes(R.color.md_orange_STO)
                                            .go(new CircularAnim.OnAnimationEndListener() {
                                                @Override
                                                public void onAnimationEnd() {
                                                    startActivity(new Intent(LoginActivity.this, MainActivity.class));

                                                }
                                            });
                                }
                            } else {
                                mLogEtName.requestFocus();
                                showWarningToast(bean.msg);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            XLog.e(e.getMessage());
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        showWarningToast("登录异常,请检查服务是否可用");
                    }


                });

    }


    /**
     * 绑定事件:登录确认、语言选择、服务设置等
     * @param view
     */
    @OnClick({R.id.log_btn_chose_language,R.id.log_btn_setting, R.id.log_btn_login})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.log_btn_chose_language:
                startActivity(new Intent(LoginActivity.this, SetLanguageActivity.class));
                break;
            case R.id.log_btn_setting:

                Bundle bundle = new Bundle();
                //startActivity(new Intent(LoginActivity.this, ServiceSettingActivity.class));
                intentPageResult(this,ServiceSettingActivity.class, bundle,200);
                break;
            case R.id.log_btn_login:

                if (isCanLogin()) {
                    login(mLogEtName.getText().toString().trim(),mLogEtPwd.getText().toString().trim());
//                    ConfirmDialog.Builder builder = new ConfirmDialog.Builder(this);
//                    builder.setView(captchaView);
//                    if(capchatDialog != null){
//                        capchatDialog.show();
//                    }else{
//                        capchatDialog = builder.create();
//                        capchatDialog.show();
//                    }
                }
                break;

        }
    }
}