package com.mq.mylibrary.base;

import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;

import com.mq.mylibrary.ChannelTool;
import com.mq.mylibrary.R;
import com.mq.mylibrary.db.car.CarDao;
import com.mq.mylibrary.db.grain_type.GrainTypeDao;
import com.mq.mylibrary.db.load_info.LoadInfoDao;
import com.mq.mylibrary.db.sotre.StoreDao;
import com.mq.mylibrary.db.team_group.TeamGroupDao;
import com.mq.mylibrary.db.user.UserDao;
import com.mq.mylibrary.db.user.UserEntity;
import com.mq.mylibrary.tool.ETTool;
import com.mq.mylibrary.tool.FileTool;
import com.mq.mylibrary.tool.LogTool;
import com.mq.mylibrary.tool.SPTool;
import com.mq.mylibrary.tool.StringTool;
import com.mq.mylibrary.tool.ToastTool;

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

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

/**
 * 创建人 mQ
 * 创建时间 2019/8/7 0007 11:12
 * 文件名称 BaseLoginActivity
 * 说明:
 **/
public abstract class BaseLoginActivity extends BaseActivity {


    /**
     * 设置功能标题
     */
    public abstract String setTitle();

    /**
     * 登录成功 进行下一步操作
     */
    public abstract void loginSuccess(UserEntity userEntity);

    public ImageView mIvLogo;
    public EditText mEtUsername;
    public EditText mEtPassword;
    public TextView mTvTitle;
    public Button mBtLogin;
    public Button mBtInit;
    public Button mBtReset;
    public RadioButton mRBNfc;
    public RadioButton mRBM10a;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
        setLogoForChannel();
        mTvTitle.setText(setTitle());

        initData();

    }

    private void initView() {
        mIvLogo = (ImageView) findViewById(R.id.iv_logo);
        mEtUsername = (EditText) findViewById(R.id.et_username);
        mEtPassword = (EditText) findViewById(R.id.et_password);
        mTvTitle = (TextView) findViewById(R.id.tv_title);
        mEtPassword.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_GO ||
                        (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    mBtLogin.callOnClick();
                }
                return false;
            }
        });
        mBtLogin = (Button) findViewById(R.id.bt_login);
        mBtLogin.setOnClickListener(mOnClickListener);

        mBtInit = (Button) findViewById(R.id.bt_init);
        mBtInit.setOnClickListener(mOnClickListener);

        mBtReset = (Button) findViewById(R.id.bt_reset);
        mBtReset.setOnClickListener(mOnClickListener);

        String name = (String) SPTool.get(BaseConstant.LOGIN_NAME, "");
        mEtUsername.setText(name);

        mRBNfc = (RadioButton) findViewById(R.id.rb_nfc);
        mRBM10a = (RadioButton) findViewById(R.id.rb_m10a);
        String rwType = (String) SPTool.get(BaseConstant.READ_WRITE_TYPE, "");
        if (rwType.equals(BaseConstant.R_W_NFC)) {
            mRBNfc.setChecked(true);
        } else if (rwType.equals(BaseConstant.R_W_M10A)) {
            mRBM10a.setChecked(true);
        }
    }

    private View.OnClickListener mOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int id = v.getId();
            if (id == R.id.bt_login) {
                login();
            } else if (id == R.id.bt_init) {
                initData();
            } else if (id == R.id.bt_reset) {
                mEtUsername.setText("");
                mEtPassword.setText("");
            }
        }
    };

    private void login() {
        String username = ETTool.getData(mEtUsername);
        if (StringTool.isEmpty(username)) {
            ToastTool.showLong("用户名不能为空");
            return;
        }
        String password = ETTool.getData(mEtPassword);
        if (StringTool.isEmpty(password)) {
            ToastTool.showLong("密码不能为空");
            return;
        }

        UserEntity user = UserDao.get().checkUser(BaseApp.getDBHelper(), username, password);
        if (user == null) {
            ToastTool.showLong("用户名或密码错误，请重试！");
            return;
        }

        String rbType = null;
        if (mRBNfc.isChecked()) rbType = BaseConstant.R_W_NFC;
        if (mRBM10a.isChecked()) {
            rbType = BaseConstant.R_W_M10A;
            try {
                FileOutputStream fout = new FileOutputStream("/sys/class/gpio/gpio898/direction");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                ToastTool.showLong("当前设备不支持M10A读写,请选择其他读写卡方式");
                return;
            }
        }
        if (rbType == null) {
            ToastTool.showLong("请选择读写卡方式");
            return;
        }


        SPTool.save(BaseConstant.LOGIN_NAME, username);
        SPTool.save(BaseConstant.REAL_NAME, user.getReal_name());
        SPTool.save(BaseConstant.READ_WRITE_TYPE, rbType);
        ToastTool.showLong("登录成功");
        loginSuccess(user);
    }


    @SuppressLint("StaticFieldLeak")
    public void initData() {
        showPd();
        new AsyncTask<Void, Void, String>() {

            @Override
            protected String doInBackground(Void... voids) {
                // 判断SD卡是否存在
                if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    LogTool.d("SD卡不存在，无法读取数据: " + Environment.getExternalStorageState());
                    return "SD卡不存在，无法读取数据";
                }
                String result = FileTool.getFileContent("JSON.txt");
                if (StringTool.isEmpty(result)) {
                    LogTool.d("没有初始化文件，请检查！");
                    return "没有初始化文件，请检查！";
                }
                StringBuilder log = new StringBuilder();

                try {
                    JSONObject object = new JSONObject(result);
                    //清空并插入
                    UserDao.get().deleltAll(BaseApp.getDBHelper());
                    boolean userFlg = UserDao.get()
                            .insertByJSONArray(BaseApp.getDBHelper(), object.optJSONArray("user"));
                    if (!userFlg) {
                        log.append("初始化用户信息失败！").append("\n");
                    }

                    //清空并插入
                    StoreDao.get().deleltAll(BaseApp.getDBHelper());
                    boolean storeFlg = StoreDao.get()
                            .insertByJSONArray(BaseApp.getDBHelper(), object.optJSONArray("cfhw"));
                    if (!storeFlg) {
                        log.append("初始化仓房信息失败！").append("\n");
                    }

                    //清空并插入
                    TeamGroupDao.get().deleltAll(BaseApp.getDBHelper());
                    boolean teamGroupFlg = TeamGroupDao.get()
                            .insertByJSONArray(BaseApp.getDBHelper(), object.optJSONArray("zyz"));
                    if (!teamGroupFlg) {
                        log.append("初始化作业队组信息失败！").append("\n");
                    }

                    //清空并插入
                    CarDao.get().deleltAll(BaseApp.getDBHelper());
                    boolean carFlg = CarDao.get()
                            .insertByJSONArray(BaseApp.getDBHelper(), object.optJSONArray("wlcl"));
                    if (!carFlg) {
                        log.append("初始化车辆信息失败！").append("\n");
                    }

                    //清空并插入
                    GrainTypeDao.get().deleltAll(BaseApp.getDBHelper());
                    boolean grainTypeFlg = GrainTypeDao.get()
                            .insertByJSONArray(BaseApp.getDBHelper(), object.optJSONArray("lypz"));
                    if (!grainTypeFlg) {
                        log.append("初始化粮油品种信息失败！").append("\n");
                    }

                    //清空并插入
                    LoadInfoDao.get().deleltAll(BaseApp.getDBHelper());
                    boolean loadInfoFlg = LoadInfoDao.get()
                            .insertByJSONArray(BaseApp.getDBHelper(), object.optJSONArray("qczc"));
                    if (!loadInfoFlg) {
                        log.append("初始化火车卸车信息失败！").append("\n");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    log.append("初始化失败！").append("\n");
                }
                log.append("初始化成功！");
                return log.toString();
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                cancelPd();
                if (StringTool.notEmpty(s))
                    ToastTool.showLong(s);
            }
        }.execute();

    }

    /**
     * 设置logo
     */
    public void setLogo(int resId) {
        mIvLogo.setImageResource(resId);
    }

    /**
     * 通过渠道更改LOGO
     */
    private void setLogoForChannel() {
        String channel = BaseApp.mChannelName;
        switch (channel) {
            case ChannelTool.C_YUN_NAN:
                setLogo(R.drawable.ic_logo_yunnan);
                break;
//            case ChannelTool.C_PU_ER:
//                setLogo(R.drawable.ic_logo_yunnan);
//                break;
            case ChannelTool.C_SHAN_XI:
                setLogo(R.drawable.ic_logo_shanxi);
                break;
            case ChannelTool.C_TIAN_JIN:
                setLogo(R.drawable.ic_logo_tianjin);
                break;
            default:
                setLogo(R.drawable.ic_logo);
                break;
        }
    }

}
