package com.phlx.anchorcollect.ui.fragment;

import android.Manifest;
import android.app.Dialog;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectChangeListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.phlx.anchorcollect.R;
import com.phlx.anchorcollect.data.VMFactory;
import com.phlx.anchorcollect.databinding.FragmentPerformanceBinding;
import com.phlx.anchorcollect.entity.DictEntity;
import com.phlx.anchorcollect.entity.GenTableColumn;
import com.phlx.anchorcollect.rfid.ModuleManager;
import com.phlx.anchorcollect.ui.fragment.vm.BasicsCollectVM;
import com.phlx.anchorcollect.ui.fragment.vm.PerformanceVM;
import com.phlx.anchorcollect.util.DictUtils;
import com.phlx.anchorcollect.util.ImagePicker;
import com.phlx.anchorcollect.widget.SpaceItemDecoration;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import io.reactivex.functions.Consumer;
import me.goldze.mvvmhabit.base.BaseFragment;
import me.goldze.mvvmhabit.utils.ToastUtils;
import me.tatarka.bindingcollectionadapter2.BR;

public class PerformanceFragment extends BaseFragment<FragmentPerformanceBinding, PerformanceVM> {

    private TimePickerView pvTime;

    private ImagePicker mImagePicker;

    private static class SingletonClassInstance {
        private static final PerformanceFragment instance = new PerformanceFragment();
    }

    private PerformanceFragment() {
    }

    public static PerformanceFragment getInstance() {
        return PerformanceFragment.SingletonClassInstance.instance;
    }

    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_performance;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public void initParam() {
        super.initParam();
    }

    @Override
    public PerformanceVM initViewModel() {
        VMFactory factory = VMFactory.getInstance(getActivity().getApplication());
        return ViewModelProviders.of(this, factory).get(PerformanceVM.class);
    }

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

        viewModel.initGen();

        binding.rvCollect.addItemDecoration(new SpaceItemDecoration(10));

        initTimePicker();
    }

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

        viewModel.onCardClickEvent.observe(getActivity(), new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                if (viewModel.currentParamEntity != null) {
                    switch (viewModel.currentParamEntity.getHtmlType()) {
                        case "checkbox":
                            showCheckboxDialog(viewModel.currentParamEntity);
                            break;
                        case "input":
                        case "textarea":
                            showInputDialog(viewModel.currentParamEntity);
                            break;
                        case "datetime":
                            showSelectDateDialog(viewModel.currentParamEntity);
                            break;
                        case "select":
                        case "radio":
                            showSpinnerDialog(viewModel.currentParamEntity);
                            break;
                        case "photo":
                            if (viewModel.tag.get().equals("")) {
                                ToastUtils.showShort("请先输入可视耳标号");
                            } else {
                                showPhotoDialog(viewModel.currentParamEntity);
                            }
                            break;
                    }

                }
            }
        });

        viewModel.onNotifyAllEvent.observe(getActivity(), new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                if (aBoolean)
                    viewModel.clearParamList();

                for (GenTableColumn gtc : viewModel.uiList) {
                    gtc.notifyChange();
                }
                viewModel.remarkParamEntity.notifyChange();
                binding.rvCollect.getAdapter().notifyDataSetChanged();
            }
        });

        viewModel.onShowDialogEvent.observe(getActivity(), new Observer<String>() {
            @Override
            public void onChanged(String s) {

                new MaterialDialog.Builder(getActivity()).title("系统提示").content(s).positiveText("确定").onAny(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        if (which == DialogAction.POSITIVE) {

                        }
                    }
                }).show();
            }
        });
    }



    //选择框
    private void showSpinnerDialog(GenTableColumn uiParamEntity) {

        new MaterialDialog.Builder(getActivity())
                .title("标题")
//                .positiveText("确认")
//                .negativeText("取消")
                .items(DictUtils.getDistNameList(uiParamEntity.getDictType()))
                .itemsCallback(new MaterialDialog.ListCallback() {
                    @Override
                    public void onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
                        Toast.makeText(getActivity(), which + ":" + text.toString(), Toast.LENGTH_SHORT).show();
                        viewModel.currentParamEntity.setShowName(text.toString());
                        List<DictEntity> distTypeList = DictUtils.getDistList(uiParamEntity.getDictType());
                        viewModel.currentParamEntity.setContent(distTypeList.get(which).getDictValue());
                        viewModel.currentParamEntity.notifyChange();
                    }
                })
                .show();
    }

    //多选框
    private void showCheckboxDialog(GenTableColumn uiParamEntity) {

        new MaterialDialog.Builder(getActivity()).title("系统信息").content("请选择!!!")
                .cancelable(false).canceledOnTouchOutside(false)
                .positiveText("确定")
                .items(DictUtils.getDistNameList(uiParamEntity.getDictType()))
                .itemsCallbackMultiChoice(null, new MaterialDialog.ListCallbackMultiChoice() {
                    @Override
                    public boolean onSelection(MaterialDialog dialog, Integer[] which, CharSequence[] text) {

                        String showName = "";
                        String content = "";
                        List<DictEntity> distTypeList = DictUtils.getDistList(uiParamEntity.getDictType());
                        if (which != null && which.length > 0) {
                            for (Integer i : which) {
                                showName += distTypeList.get(i).getDictLabel();
                                showName += ",";
                                content += distTypeList.get(i).getDictValue();
                                content += ",";
                            }

                        }
                        viewModel.currentParamEntity.setShowName(showName);
                        viewModel.currentParamEntity.setContent(content);
                        viewModel.currentParamEntity.notifyChange();

                        return true;
                    }
                }).show();
    }

    //输入框
    private void showInputDialog(GenTableColumn uiParamEntity) {

        int inputType = 0;
        if (uiParamEntity.getJavaType().equals("Long") || uiParamEntity.getJavaType().equals("Integer")) {
            inputType = InputType.TYPE_CLASS_NUMBER;
        } else if (uiParamEntity.getJavaType().equals("BigDecimal") || uiParamEntity.getJavaType().equals("Duoble")) {
            inputType = InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED;
            ;
        } else if (uiParamEntity.getJavaType().equals("String")) {
            inputType = InputType.TYPE_CLASS_TEXT;
        }

        new MaterialDialog.Builder(getActivity())
                .title(uiParamEntity.getColumnComment())
//                        .iconRes(R.drawable.ic_logo)
                .content("请输入")
//                                .widgetColor(Color.BLUE)//输入框光标的颜色
                .inputType(inputType)//可以输入的类型
                //前2个一个是hint一个是预输入的文字
                .input("输入" + uiParamEntity.getColumnComment(), uiParamEntity.getShowName(), new MaterialDialog.InputCallback() {

                    @Override
                    public void onInput(@NonNull MaterialDialog dialog, CharSequence input) {

                        Log.i("scan", "输入的是：" + input);
                    }
                })

                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
//                                    dialog.getActionButton(DialogAction.POSITIVE).setEnabled(false);
                        viewModel.currentParamEntity.setShowName(dialog.getInputEditText().getText().toString());
                        viewModel.currentParamEntity.setContent(dialog.getInputEditText().getText().toString());
                        viewModel.currentParamEntity.notifyChange();
                    }
                })
                .show();
    }

    //拍照
    private void showPhotoDialog(GenTableColumn uiParamEntity) {

        RxPermissions rxPermissions = new RxPermissions(getActivity());
        rxPermissions.request(Manifest.permission.CAMERA, Manifest.permission
                .READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            mImagePicker.show(getActivity());
                        } else {
                            ToastUtils.showShort("权限被拒绝");
                        }
                    }
                });
    }

    //时间选择
    private void showSelectDateDialog(GenTableColumn uiParamEntity) {
        pvTime.show(binding.card99);
    }

    private void initTimePicker() {//Dialog
        pvTime = new TimePickerBuilder(getActivity(), new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                viewModel.currentParamEntity.setContent(dateFormat.format(date));
                viewModel.currentParamEntity.setShowName(dateFormat.format(date));
                viewModel.currentParamEntity.notifyChange();
            }
        })
                .setTimeSelectChangeListener(new OnTimeSelectChangeListener() {
                    @Override
                    public void onTimeSelectChanged(Date date) {
                    }
                })
                .setType(new boolean[]{true, true, true, false, false, false})
                .isDialog(true) //默认设置false ，内部实现将DecorView 作为它的父控件。
                .addOnCancelClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Log.i("pvTime", "onCancelClickListener");
                    }
                })
                .setItemVisibleCount(5) //若设置偶数，实际值会加1（比如设置6，则最大可见条目为7）
                .setLineSpacingMultiplier(2.0f)
                .isAlphaGradient(true)
                .build();

        Dialog mDialog = pvTime.getDialog();
        if (mDialog != null) {

            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    Gravity.CENTER);

            params.leftMargin = 0;
            params.rightMargin = 0;
            pvTime.getDialogContainerLayout().setLayoutParams(params);

            Window dialogWindow = mDialog.getWindow();
            if (dialogWindow != null) {
                dialogWindow.setWindowAnimations(com.bigkoo.pickerview.R.style.picker_view_slide_anim);//修改动画样式
                dialogWindow.setGravity(Gravity.CENTER);//改成Bottom,底部显示
                dialogWindow.setDimAmount(0.3f);
            }
        }
    }
}
