package com.tenlionsoft.baselib.core.widget.views;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.hjq.toast.ToastUtils;
import com.tenlionsoft.baselib.R;
import com.tenlionsoft.baselib.core.beans.DictionaryBean;
import com.tenlionsoft.baselib.core.beans.PersonSearchBean;
import com.tenlionsoft.baselib.core.retrofit_net.RetrofitManager;
import com.tenlionsoft.baselib.core.retrofit_net.api.BaseApiService;
import com.tenlionsoft.baselib.utils.ExceptionHandler;
import com.tenlionsoft.baselib.utils.LogUtils;
import com.tenlionsoft.baselib.utils.RegexUtils;
import com.tenlionsoft.baselib.utils.UIUtil;
import com.tenlionsoft.baselib.utils.UserLgUtils;

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

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;


/**
 * 作者 : Adam on 2018/7/23.
 * 邮箱 : itgaojian@163.com
 * 描述 : 从底部弹出的选择文件的dialog
 */
public class SearchPersonDialogView extends Dialog {

    private boolean iscancelable;
    private boolean isBackCancelable;
    private View view;
    private Context context;
    private int gravity;
    private OnChoseListener mListener;
    private boolean mIsShow;
    private boolean mIsShowOther;
    private EditText mEtCard;
    private LinearLayout mLlInfo;
    private TextView mTvName;
    private TextView mTvGender;
    private TextView mTvPhone;
    private TextView mTvHint;
    private Button mBtnConfirm;
    private PersonSearchBean data;
    private TextView mTvType;
    private List<DictionaryBean> mDictionaryBeanList = new ArrayList<>();
    private OptionsPickerView mCommunityTypePicker;

    private SearchPersonDialogView(Context context, boolean isCancelable, boolean isBackCancelable, int gravity, boolean isShow, boolean isShowOther) {
        super(context, R.style.Dialog_ChoseFile);
        this.context = context;
        this.gravity = gravity;
        this.iscancelable = isCancelable;
        this.isBackCancelable = isBackCancelable;
        this.mIsShow = isShow;
        this.mIsShowOther = isShowOther;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        view = LayoutInflater.from(context).inflate(R.layout.dialog_choose_input, null);
        setContentView(view);
        setCancelable(iscancelable);
        setCanceledOnTouchOutside(isBackCancelable);
        mEtCard = view.findViewById(R.id.et_card_number);
        mTvName = view.findViewById(R.id.tv_name);
        mTvGender = view.findViewById(R.id.tv_gender);
        mTvPhone = view.findViewById(R.id.tv_phone);
        mTvHint = view.findViewById(R.id.tv_hint);
        mLlInfo = view.findViewById(R.id.ll_info);
        mTvType = view.findViewById(R.id.tv_type);
        mLlInfo.setVisibility(View.GONE);
        mBtnConfirm = view.findViewById(R.id.btn_bind);
        initList();
        mTvType.setOnClickListener(v -> onShowType());
        mBtnConfirm.setOnClickListener(v -> choseType(6));
        view.findViewById(R.id.btn_search).setOnClickListener(v -> doSearchPerson());
        DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
        Window window = this.getWindow();
        window.setGravity(Gravity.CENTER);
        window.setWindowAnimations(R.style.Dialog_ChoseFile);
        WindowManager.LayoutParams params = window.getAttributes();
        params.width = (int) (displayMetrics.widthPixels * 0.9);
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(params);
        window.setBackgroundDrawable(new ColorDrawable());
    }

    private void initList() {
        DictionaryBean bean = new DictionaryBean();
        bean.setName("房主");
        bean.setId("房主");
        DictionaryBean bean1 = new DictionaryBean();
        bean.setName("租户");
        bean.setId("租户");
        mDictionaryBeanList.add(bean);
        mDictionaryBeanList.add(bean1);
    }

    private void onShowType() {
        if (mCommunityTypePicker == null) {
            mCommunityTypePicker = new OptionsPickerBuilder(context, (o1, o2, o3, v) -> {
                DictionaryBean bean = mDictionaryBeanList.get(o1);
                mTvType.setText(bean.getName());
            })
                    .setTitleText("请选择")
                    .isDialog(true)
                    .setCancelColor(Color.parseColor("#1189FF"))
                    .setSubmitColor(Color.parseColor("#1189FF"))
                    .setTitleColor(Color.parseColor("#1189FF"))
                    .build();
            LogUtils.e(mCommunityTypePicker + "===" + mDictionaryBeanList);
            mCommunityTypePicker.setPicker(mDictionaryBeanList);
        }
        mCommunityTypePicker.show();
    }

    private void doSearchPerson() {
        String card = mEtCard.getText().toString().trim();
        if (TextUtils.isEmpty(card) || !RegexUtils.isIDNumber(card)) {
            ToastUtils.show("请输入合法的身份证号码");
            return;
        }
        ProgressDialog dialog = UIUtil.initDialog(context, "搜索中...");
        dialog.show();
        RetrofitManager.getInstance()
                .create(BaseApiService.class)
                .doSearchPerson(card, UserLgUtils.getToken())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<PersonSearchBean>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull PersonSearchBean personSearchBean) {
                        dialog.dismiss();
                        if (!TextUtils.isEmpty(personSearchBean.getFullName())) {
                            data = personSearchBean;
                            mLlInfo.setVisibility(View.VISIBLE);
                            mTvHint.setVisibility(View.GONE);
                            mTvGender.setText("性别:" + data.getGenderDictionaryName());
                            mTvName.setText("姓名:" + data.getFullName());
                            mTvPhone.setText("联系方式:" + data.getTelephone());
                        } else {
                            mTvHint.setVisibility(View.VISIBLE);
                            mTvHint.setText("人口数据库中未找到该人员");
                            mLlInfo.setVisibility(View.GONE);
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        dialog.dismiss();
                        ExceptionHandler.handleException(e);
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    public void addOnChoseListener(OnChoseListener listener) {
        this.mListener = listener;
    }

    /**
     * 选择
     *
     * @param i
     */
    private void choseType(int i) {
        if (mListener != null) {
            switch (i) {
                case 1:
                    mListener.choseAlbum();
                    break;
                case 2:
                    mListener.choseFile();
                    break;
                case 3:
                    mListener.choseShoot();
                    break;
                case 4:
                    mListener.changePwd();
                    break;
                case 5:
                    mListener.loginOut();
                    break;
                case 6:
                    mListener.bindPerson(data.getFullName(), data.getGender(), data.getTelephone(), data.getIdCardNumber());
                    break;
            }
        }
//        this.dismiss();
    }

    public interface OnChoseListener {
        void choseFile();

        void choseAlbum();

        void choseShoot();

        void loginOut();

        void changePwd();

        void bindPerson(String name, String gender, String phone, String idCard);
    }

    public static class DialogBuilder {
        private Context mContext;
        private boolean isCancelable;
        private boolean mIsBackable;
        private int mGravity = Gravity.BOTTOM;
        private OnChoseListener mListener;
        private boolean mIsShowOther;

        public DialogBuilder(Context context) {
            this.mContext = context;
        }

        public DialogBuilder setIscancelable(boolean iscancelable) {
            this.isCancelable = iscancelable;
            return this;
        }

        public DialogBuilder setIsBackCancelable(boolean isBackCancelable) {
            this.mIsBackable = isBackCancelable;
            return this;
        }

        public DialogBuilder setShowLocation(int gravity) {
            this.mGravity = gravity;
            return this;
        }

        private boolean mIsShow;

        public DialogBuilder setIsShowFile(boolean isShowFile) {
            mIsShow = isShowFile;
            return this;
        }

        public DialogBuilder setIsShowOther(boolean isShow) {
            mIsShowOther = isShow;
            return this;
        }

        public SearchPersonDialogView build() {
            return new SearchPersonDialogView(this.mContext, this.isCancelable, this.mIsBackable, this.mGravity, mIsShow, mIsShowOther);
        }
    }
}