package com.yyrh.ui.fragment;

import android.app.Activity;
import android.app.Fragment;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.yyrh.constant.SDKSettings;
import com.yyrh.networking.NetRequestApi;
import com.yyrh.sdk.SDKEntry;
import com.yyrh.sdk.YyrhSdkManager;
import com.yyrh.sdk.callback.LoginCallback;
import com.yyrh.ui.userlist.DatabaseHelper;
import com.yyrh.ui.userlist.QjUserListAdapter;
import com.yyrh.ui.userlist.User;
import com.yyrh.utils.ResourceUtil;
import com.yyrh.utils.TosUtil;
import com.yyrh.utils.Utils;
import com.yyrh.utils.YYLog;

import java.util.ArrayList;

import static com.yyrh.constant.Constants.CLICK_INTERVAL;

public class UserAccountLoginFragment extends BaseFragment {

    private EditText reg_account_edit,reg_pwd_edit;
    private ImageView down_btn,iv_show_pwd;
    private ImageButton close_btn;
    private Button reg_compete_btn;
    private TextView tv_fofget_pwd;
    private boolean isShowPwd = false;
    DatabaseHelper dbHelper;

    private QjUserListAdapter adapter;
    private ListView account_listview;


    private ImageView showListView;

    private boolean isShowList = false;

    private TextView list_text;

    private long clickLoginTime = 0L;

    private String login_token;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(ResourceUtil.getLayoutId(getActivity(),"hnyy_account_login"), container, false);
        view.setClickable(true);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        reg_account_edit = view.findViewById(ResourceUtil.getId(getActivity(),"reg_account_edit"));
        reg_pwd_edit= view.findViewById(ResourceUtil.getId(getActivity(),"reg_pwd_edit"));

        down_btn = view.findViewById(ResourceUtil.getId(getActivity(),"down_btn"));
        down_btn.setOnClickListener(this);

        iv_show_pwd = view.findViewById(ResourceUtil.getId(getActivity(),"iv_show_pwd"));
        iv_show_pwd.setOnClickListener(this);


        list_text  = view.findViewById(ResourceUtil.getId(getActivity(), "list_text"));

        account_listview  =  view.findViewById(ResourceUtil.getId(getActivity(), "account_listview"));


        showListView = view.findViewById(ResourceUtil.getId(getActivity(), "down_btn"));
        showListView.setOnClickListener(this);

        reg_compete_btn = view.findViewById(ResourceUtil.getId(getActivity(),"reg_compete_btn"));
        reg_compete_btn.setOnClickListener(this);

        tv_fofget_pwd = view.findViewById(ResourceUtil.getId(getActivity(),"tv_fofget_pwd"));
        tv_fofget_pwd.setOnClickListener(this);

        adapter = new QjUserListAdapter(getActivity(),getData());
        account_listview.setAdapter(adapter);
        account_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                reg_account_edit.setText(adapter.list.get(position).uname);
                reg_pwd_edit.setText(adapter.list.get(position).pwd);
                login_token  = adapter.list.get(position).login_token;
                hideListView();
            }
        });

        close_btn = view.findViewById(ResourceUtil.getId(getActivity(),"close_btn"));
        close_btn.setOnClickListener(this);

        SharedPreferences sp = getActivity().getSharedPreferences("yyrh", Activity.MODE_PRIVATE);
        reg_account_edit.setText(sp.getString("username", ""));
        reg_pwd_edit.setText(sp.getString("password", ""));
        reg_pwd_edit.setTransformationMethod(PasswordTransformationMethod.getInstance());

    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        int id = v.getId();
        if (id == ResourceUtil.getId(getActivity(), "reg_compete_btn")){
            if (System.currentTimeMillis() - clickLoginTime < CLICK_INTERVAL) {
                YYLog.i("调用登录接口太频繁，拦截此次操作");
                return;
            }
            clickLoginTime = System.currentTimeMillis();
            startLogin(reg_account_edit.getText().toString(), reg_pwd_edit.getText().toString());

        }else if(id == ResourceUtil.getId(getActivity(), "down_btn")){
            /*	显示缓存账号	*/
            if (!isShowList) {
                showListView.setImageResource(ResourceUtil.getMipmapId(getActivity(), "hnyy_arrow_select"));
                showListView();
            } else {

                showListView.setImageResource(ResourceUtil.getMipmapId(getActivity(), "hnyy_arrow_normal"));
                hideListView();
            }
        }else if(id == ResourceUtil.getId(getActivity(), "iv_show_pwd")){

            if (!isShowPwd) {
                isShowPwd = true;
                reg_pwd_edit.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                iv_show_pwd.setImageResource(ResourceUtil.getMipmapId(getActivity(), "hnyy_open_eye"));
            } else {
                isShowPwd = false;
                reg_pwd_edit.setTransformationMethod(PasswordTransformationMethod.getInstance());
                iv_show_pwd.setImageResource(ResourceUtil.getMipmapId(getActivity(), "hnyy_close_eye"));
            }

        }else if(id == ResourceUtil.getId(getActivity(), "btn_account_login")){

            Fragment accountLoginFragment = FragmentUtils.getSdkFragment(getActivity(),FragmentUtils.SDK_LOGIN_TAG);
            replaceFragmentToActivity(getFragmentManager(),accountLoginFragment,ResourceUtil.getId(getActivity(),"hnyy_content"));

        }else if(id == ResourceUtil.getId(getActivity(), "close_btn")){
            Fragment accountLoginFragment = FragmentUtils.getSdkFragment(getActivity(),FragmentUtils.SDK_PHONE_REGISTER_TAG);
            replaceFragmentToActivity(getFragmentManager(),accountLoginFragment,ResourceUtil.getId(getActivity(),"hnyy_content"));

        }else if(id == ResourceUtil.getId(getActivity(), "tv_fofget_pwd")){


            Fragment accountLoginFragment = FragmentUtils.getSdkFragment(getActivity(),FragmentUtils.SDK_RETRIEVE_PWD_TAG);
            replaceFragmentToActivity(getFragmentManager(),accountLoginFragment,ResourceUtil.getId(getActivity(),"hnyy_content"));

        }


    }


    private void startLogin(final String account, final String pwd) {
        if (Utils.judgeStrNull(account)){
            new TosUtil(getActivity(),TosUtil.TOAST_ERROR, getString(ResourceUtil.getStringId(getActivity(), "hnyy_band_need_account"))).show();

            return;
        }
        if (Utils.judgeStrNull(pwd)){
            new TosUtil(getActivity(),TosUtil.TOAST_ERROR, getString(ResourceUtil.getStringId(getActivity(), "hnyy_band_need_pwd"))).show();

            return;
        }

        if(account.length()<6)
        {
            new TosUtil(getActivity(),TosUtil.TOAST_ERROR, getString(ResourceUtil.getStringId(getActivity(), "hnyy_account_limit_6"))).show();

            return;
        }
        if(pwd.length()<6)
        {
            new TosUtil(getActivity(),TosUtil.TOAST_ERROR, getString(ResourceUtil.getStringId(getActivity(), "hnyy_pwd_limit_6"))).show();

            return;
        }

        NetRequestApi.loginWithYy(true,getActivity(), account, pwd,"", new LoginCallback() {
            @Override
            public void onLoginSuccess(String token) {


                getActivity().finish();

                YyrhSdkManager.defaultManager().saveUserLoginInfo(SDKEntry.getSdkInstance().gameAct,account,pwd, SDKSettings.loginData.login_token,token);

            }

            @Override
            public void onLoginFailed(String msg) {
                new TosUtil(getActivity(),TosUtil.TOAST_ERROR, msg).show();

                SDKEntry.getSdkInstance().sdkCallback.onLoginFailed(msg);

            }

            @Override
            public void onLoginError(String msg) {
                new TosUtil(getActivity(),TosUtil.TOAST_ERROR, msg).show();
            }
        });

    }



    @Override
    public void onDestroy() {
        super.onDestroy();

    }

    private ArrayList<User> getData() {
        ArrayList<User> userList = new ArrayList<User>();
        dbHelper = new DatabaseHelper(getActivity());
        SQLiteDatabase db = null;
        db = dbHelper.getReadableDatabase();
        String qurey_sql = "select name,pwd,login_token from user order by time desc";
        Cursor cursor = db.rawQuery(qurey_sql, null);
        while (cursor.moveToNext()) {
            User user = new User();
            user.uname = cursor.getString(0);
            user.pwd = cursor.getString(1);
            user.login_token = cursor.getString(2);
            userList.add(user);
        }
        cursor.close();
        db.close();
        return userList;
    }

    private void showListView() {
        if (adapter.list.size() == 0) {
            list_text.setVisibility(View.VISIBLE);
        } else {
            account_listview.setVisibility(View.VISIBLE);
            list_text.setVisibility(View.GONE);

        }
        isShowList = true;


    }

    private void hideListView() {
        account_listview.setVisibility(View.GONE);
        list_text.setVisibility(View.GONE);
        isShowList = false;

        showListView.setImageResource(ResourceUtil.getMipmapId(getActivity(), "hnyy_arrow_normal"));
    }
}
