package com.tofly.ghrq_route.common.ui.activity;

import android.Manifest;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.AppCompatSpinner;
import androidx.appcompat.widget.Toolbar;

import com.gaoyuan.weixinrecord.utils.PermissionHelper;
import com.mgq.base.utils.check.CheckUtil;
import com.mgq.base.utils.customview.CircleImageView;
import com.mgq.base.utils.progressdialog.ProgressManager;
import com.tofly.ghrq_route.R;
import com.tofly.ghrq_route.base.BaseApp;
import com.tofly.ghrq_route.base.ui.BaseUi;
import com.tofly.ghrq_route.common.ui.dialog.InputDialog;
import com.tofly.ghrq_route.module.user.controller.UserCallBack;
import com.tofly.ghrq_route.module.user.controller.UserController;
import com.tofly.ghrq_route.module.user.domain.CompanyBean;
import com.tofly.ghrq_route.module.user.domain.CompanyUserBean;
import com.tofly.ghrq_route.module.user.domain.DeviceBean;
import com.tofly.ghrq_route.module.user.domain.RegisterInfoBean;
import com.tofly.ghrq_route.common.util.app.AppUtil;

import java.util.ArrayList;
import java.util.List;

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

/**
 * Created by Amu on 2017/6/30.
 */

public class UiRegisterAccount extends BaseUi {
    @BindView(R.id.main_toolbar)
    Toolbar mainToolbar;
    @BindView(R.id.face_parent)
    ImageView faceParent;
    @BindView(R.id.face)
    CircleImageView face;
    @BindView(R.id.text_device_name)
    TextView textDeviceName;
    @BindView(R.id.image_edit_name)
    ImageView imageEditName;
    @BindView(R.id.text_device_brand)
    TextView textDeviceBrand;
    @BindView(R.id.text_device_model)
    TextView textDeviceModel;
    @BindView(R.id.text_android_version)
    TextView textAndroidVersion;
    @BindView(R.id.text_imei)
    TextView textImei;
    @BindView(R.id.radio_group_imei)
    RadioGroup radioGroupImei;
    @BindView(R.id.check_imei1)
    RadioButton radioButtonImei1;
    @BindView(R.id.check_imei2)
    RadioButton radioButtonImei2;
    @BindView(R.id.layout_company_spinner)
    LinearLayout layoutCompanySelect;
    @BindView(R.id.spinner_pick_company)
    AppCompatSpinner spinnerPickCompany;
    @BindView(R.id.text_company_name)
    TextView textCompanyName;
/*    @BindView(R.id.swich_is_standby)
    SwitchCompat swichIsStandby;*/
    @BindView(R.id.layout_standby)
    RelativeLayout layoutStandBy;
    @BindView(R.id.text_is_standby)
    TextView textIsStandby;
    @BindView(R.id.layout_bind_user)
    RelativeLayout layoutBindUser;
    @BindView(R.id.layout_user_spinner)
    LinearLayout layoutUserSelect;
    @BindView(R.id.spinner_pick_user)
    AppCompatSpinner spinnerPickUser;
    @BindView(R.id.text_user_name)
    TextView  textUserName;
    @BindView(R.id.text_origin_account)
    TextView textOriginAccount;
/*  @BindView(R.id.edit_origin_account)
    EditText editOriginAccount;
    @BindView(R.id.layout_account_input)
    RelativeLayout layoutAccountInput; */
    @BindView(R.id.btn_register_account)
    Button btnRegisterAccount;
    @BindView(R.id.layout_device_name)
    RelativeLayout layoutDeviceName;
    @BindView(R.id.edit_device_name)
    EditText editDeviceName;
    @BindView(R.id.text_name_confirm)
    TextView textNameConfirm;
    @BindView(R.id.layout_input_name)
    RelativeLayout layoutInputName;

    private PermissionHelper permissionHelper;

    private boolean mIMEIValid = false;

    private DeviceBean mDeviceInfo = null;

    private UserController userController;

    private List<CompanyBean> mCompanyList = new ArrayList<>();

    private int mCompanyState = 0;

    private List<CompanyUserBean> mCompanyUserList;

    private int mCompanyUserState = 0;

    private ArrayAdapter<String> mUserNameApdater;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.ui_register_account);
        ButterKnife.bind(this);

        initView();
        initData();
        initListener();
    }

    private void initView() {
        textOriginAccount.setFocusableInTouchMode(true);
    }

    private void initData() {
        permissionHelper = new PermissionHelper(this);
        String imei = BaseApp.getInstance().getDevieImei();
        if (imei == null || imei.isEmpty()) {
            getDeviceImei();
        } else {
            textImei.setText(imei);
            getRegisterInfo(imei);
        }

        String buildBrand = Build.BRAND;
        textDeviceBrand.setText(buildBrand);

        String buildModel = Build.MODEL;
        textDeviceModel.setText(buildModel);

        String buildVersion = Build.VERSION.RELEASE;
        textAndroidVersion.setText(buildVersion);

        String buildName = Build.PRODUCT;
        textDeviceName.setText(buildName);
    }

    private void getDeviceImei() {
        String phoneStatePermission = Manifest.permission.READ_PHONE_STATE;
        permissionHelper.requestPermissions("请授予[读取电话状态]权限，否则无法获取本机IMEI号码",
                new PermissionHelper.PermissionListener() {
                    @Override
                    public void doAfterGrand(String... permission) {
//                        BaseApp.getInstance().getIMEIData();
                        String imei = BaseApp.getInstance().getDevieImei();
                        textImei.setText(imei);
                        getRegisterInfo(imei);
                    }

                    @Override
                    public void doAfterDenied(String... permission) {
                        String errstr = "授权失败,无法获取本机IMEI号码";
                        toast(errstr);
                    }
                }, phoneStatePermission);
    }

    private void initListener() {
        textImei.setOnClickListener(view -> showIMEIInputDialog());
    }

    private void getCompanyList(){
        if (userController == null)
            userController = new UserController(this);
        userController.getCompanyList(new UserCallBack(){
            @Override
            public void onGetCompanyList(boolean isSuccess, int errorCode, String errMsg, List<CompanyBean> companyList) {
                super.onGetCompanyList(isSuccess, errorCode, errMsg, companyList);
                if (isSuccess){
                    mCompanyList.clear();
                    for (CompanyBean companyBean : companyList){
                        if (companyBean != null && !companyBean.getCompanyid().isEmpty())
                            mCompanyList.add(companyBean);
                    }
                    setCompanyList(mCompanyList);
                }else {
                    String err = BaseApp.formatErrorMessage(errorCode, errMsg);
                    toast(err);
                }
            }
        });
    }

    private void setCompanyList(List<CompanyBean> companyList){
        List<String> companyNameList = new ArrayList<>();
        for (CompanyBean companyBean : companyList) {
            companyNameList.add(companyBean.getCompany_name());
        }
        ArrayAdapter<String> adapterDevType = new ArrayAdapter<>(UiRegisterAccount.this, R.layout.my_simple_spinner_item, companyNameList);
        adapterDevType.setDropDownViewResource(R.layout.danger_report_spinner_item);
        spinnerPickCompany.setAdapter(adapterDevType);
    }

    private void getCompanyUserList(String companyid){
        if (companyid != null && !companyid.isEmpty()){
            if (userController == null)
                userController = new UserController(this);
            String strUploading = getString(R.string.updating_data);
            ProgressManager.getInstance().showProgress(this, null, strUploading, false);
            userController.getCompanyUserList(companyid, new UserCallBack(){
                @Override
                public void onGetCompanyUserList(boolean isSuccess, int errorCode, String errMsg, List<CompanyUserBean> userList) {
                    super.onGetCompanyUserList(isSuccess, errorCode, errMsg, userList);
                    ProgressManager.getInstance().cancelProgress();
                    if (isSuccess){
                        mCompanyUserList = userList;
                        setCompanyUserList(userList);
                    }else {
                        mCompanyUserList = null;
                        if (mUserNameApdater != null){
                            mUserNameApdater.clear();
                        }
                        String err = BaseApp.formatErrorMessage(errorCode, errMsg);
                        toast(err);
                    }
                }
            });
        }
    }

    private void setCompanyUserList(List<CompanyUserBean> userList){
        List<String> userNameList = new ArrayList<>();
        for (CompanyUserBean userBean : userList) {
            String userName = userBean.getName();
            if (userName != null)
                userNameList.add(userBean.getName());
        }
        mUserNameApdater = new ArrayAdapter<>(UiRegisterAccount.this, R.layout.my_simple_spinner_item, userNameList);
        mUserNameApdater.setDropDownViewResource(R.layout.danger_report_spinner_item);
        spinnerPickUser.setAdapter(mUserNameApdater);
    }

    private void getRegisterInfo(String imei){
        if (imei != null && !imei.isEmpty()){
            mIMEIValid = true;
            if (userController == null)
                userController = new UserController(this);
            String strUploading = getString(R.string.updating_data);
            ProgressManager.getInstance().showProgress(this, null, strUploading, false);
            userController.getRegisterDeviceInfo(imei, new UserCallBack(){
                @Override
                public void onGetRegisterDeviceInfo(boolean isSuccess, int errorCode, String errMsg, RegisterInfoBean infoBean) {
                    super.onGetRegisterDeviceInfo(isSuccess, errorCode, errMsg, infoBean);
                    ProgressManager.getInstance().cancelProgress();
                    if (isSuccess){
                        if (infoBean != null){
                            int state = infoBean.getState();
                            if (state == RegisterInfoBean.DEIVCE_STATE_REGISTERED){
                                onDeviceRegistered(infoBean);
                            }else {
                                getCompanyList();
                            }
                        }
                    }else {
                        String err = BaseApp.formatErrorMessage(errorCode, errMsg);
                        toast(err);
                        getCompanyList();
                    }
                }
            });
        }else {
            mIMEIValid = false;
            textImei.setText(R.string.get_imei_error);
            textImei.setTextColor(getResources().getColor(R.color.colorAccent));
        }
    }

    private void showIMEIInputDialog(){
        String title = "手动输入IMEI号码";
        String hint = "请输入IMEI:";
        InputDialog inputDialog = new InputDialog(this, title, "", hint);
        inputDialog.setClicklistener(new InputDialog.ClickListenerInterface() {
            @Override
            public void doOk(String content) {
                if (CheckUtil.isIMEINum(content)) {
                    textImei.setText(content);
                    textImei.setTextColor(getResources().getColor(R.color.gray));
                    BaseApp.getInstance().setImei(content);
                    toast("设置成功");
                    reload();
                }else {
                    toast("输入的IMEI格式无效");
                }
            }

            @Override
            public void doCancel() {

            }
        });
        inputDialog.show();
    }

    private void onDeviceRegistered(RegisterInfoBean registerInfoBean){
        if (registerInfoBean != null){
            String companyName = registerInfoBean.getCompany_name();
            String userName = registerInfoBean.getName();
            boolean isStandBy = registerInfoBean.getType() == 1;
            layoutCompanySelect.setVisibility(View.GONE);
            textCompanyName.setVisibility(View.VISIBLE);
            if (companyName != null && !companyName.isEmpty())
                textCompanyName.setText(companyName);
            if (!isStandBy){
                layoutStandBy.setVisibility(View.GONE);
                layoutUserSelect.setVisibility(View.GONE);
                textUserName.setVisibility(View.VISIBLE);
                textUserName.setText(userName);
            }else {
                layoutStandBy.setVisibility(View.VISIBLE);
                textIsStandby.setText(R.string.yes);
                layoutBindUser.setVisibility(View.GONE);
            }
            btnRegisterAccount.setText(R.string.registered);
            btnRegisterAccount.setEnabled(false);
        }
    }

    @OnItemSelected({R.id.spinner_pick_company, R.id.spinner_pick_user})
    public void onItemSelected(AdapterView<?> parent, int position){
        switch (parent.getId()){
            case R.id.spinner_pick_company:{
                mCompanyState = position;
                if (mCompanyList != null && position < mCompanyList.size()){
                    CompanyBean companyBean = mCompanyList.get(position);
                    if (companyBean != null){
                        getCompanyUserList(companyBean.getCompanyid());
                    }
                }
            }
            break;
            case R.id.spinner_pick_user:{
                mCompanyUserState = position;
            }
            break;
        }
    }

    @OnClick({R.id.image_edit_name, R.id.text_name_confirm, R.id.btn_register_account})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.image_edit_name:{
                onImageEditNameClicked();
            }
            break;
            case R.id.text_name_confirm:{
                onBtnNameConfirmClicked();
            }
            break;
            case R.id.btn_register_account:{
                if (layoutInputName.getVisibility() == View.VISIBLE){
                    onBtnNameConfirmClicked();
                }
                //editOriginAccount.clearFocus();
                boolean isValid = checkValid();
                if (isValid){
                    registerAccount();
                }
            }
            break;
        }
    }

    private void onImageEditNameClicked(){
        layoutDeviceName.setVisibility(View.GONE);
        layoutInputName.setVisibility(View.VISIBLE);
        String strDeviceName = textDeviceName.getText().toString();
        if (!strDeviceName.isEmpty()){
            editDeviceName.setText(strDeviceName);
        }
    }

    private void onBtnNameConfirmClicked(){
        layoutDeviceName.setVisibility(View.VISIBLE);
        layoutInputName.setVisibility(View.GONE);
        String strDeviceName = editDeviceName.getText().toString();
        if (strDeviceName.isEmpty()){
            strDeviceName = textDeviceName.getText().toString();
        }

        textDeviceName.setText(strDeviceName);
    }

    /*@OnCheckedChanged({R.id.swich_is_standby})
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        int id = buttonView.getId();
        switch (id) {
            case R.id.swich_is_standby: {
                mIsStandBy = isChecked;
                *//*editOriginAccount.setEnabled(isChecked);
                layoutAccountInput.setVisibility(isChecked ? View.VISIBLE : View.GONE);*//*
            }
            break;
        }
    }*/

    private boolean checkValid(){
        if (!mIMEIValid){
            toast("未获取到设备的IMEI号码，无法进行注册");
            return false;
        }

        /*if (mIsStandBy){
            String loginid = editOriginAccount.getText().toString();
            if (loginid == null || loginid.isEmpty()){
                toast("请输入原来账号的登录名");
                return false;
            }
        }*/

        String deviceName = textDeviceName.getText().toString();
        if (deviceName.isEmpty()){
            toast("请输入设备名称");
            return false;
        }

        if (mCompanyList == null || mCompanyList.size() == 0 || mCompanyState < 0){
            toast("无法获取公司信息");
            return false;
        }

        if (mCompanyUserList == null || mCompanyUserList.size() == 0 || mCompanyUserState < 0){
            toast("请选择绑定的用户");
            return false;
        }

        collectDeviceInfo();

        return true;
    }

    private void collectDeviceInfo(){
        mDeviceInfo = new DeviceBean();

        String imei = textImei.getText().toString();
        mDeviceInfo.setImei(imei);

        String padName = textDeviceName.getText().toString();
        mDeviceInfo.setPadname(padName);

        String buildBrand = Build.BRAND;
        mDeviceInfo.setBrand(buildBrand);

        String buildModel = Build.MODEL;
        mDeviceInfo.setModel(buildModel);

        String buildVersion = Build.VERSION.RELEASE;
        mDeviceInfo.setAndroidVersion(buildVersion);

        String appVersion = AppUtil.getLocalVersionName(this);
        mDeviceInfo.setAppversion(appVersion);
    }

    private void registerAccount(){
        if (mDeviceInfo != null){
            /*String loginid = null;
            if (mIsStandBy){
                loginid = editOriginAccount.getText().toString();
            }*/
            if (userController == null)
                userController = new UserController(this);
            String strUploading = getString(R.string.uploading_data);
            CompanyBean companyBean = mCompanyList.get(mCompanyState);
            CompanyUserBean userBean = mCompanyUserList.get(mCompanyUserState);
            ProgressManager.getInstance().showProgress(this, null, strUploading, false);
            boolean mIsStandBy = false;
            userController.registerAccount(mDeviceInfo, mIsStandBy, companyBean, userBean, new UserCallBack(){
                @Override
                public void onRegisterAccount(boolean isSuccess, int errorCode, String errMsg) {
                    super.onRegisterAccount(isSuccess, errorCode, errMsg);
                    ProgressManager.getInstance().cancelProgress();
                    if (isSuccess){
                        showFinishedDialog();
                    }else {
                        toast(errMsg);
                    }
                }
            });
        }
    }

    private void showFinishedDialog() {
        String message = "申请成功后请与管理员取得联系，获取账号密码";
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(message);
        builder.setPositiveButton(android.R.string.ok, (dialog, which) -> {
            btnRegisterAccount.setEnabled(false);
            btnRegisterAccount.setText("已注册");
        });
        builder.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
