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.kongzue.dialogx.dialogs.InputDialog;
import com.kongzue.dialogx.interfaces.OnInputDialogButtonClickListener;
import com.kongzue.dialogx.util.InputInfo;
import com.kongzue.dialogx.util.TextInfo;
import com.phlx.anchorcollect.Configs;
import com.phlx.anchorcollect.R;
import com.phlx.anchorcollect.data.VMFactory;
import com.phlx.anchorcollect.databinding.FragmentMedicalRecordBinding;
import com.phlx.anchorcollect.entity.DictEntity;
import com.phlx.anchorcollect.entity.GenTableColumn;
import com.phlx.anchorcollect.ui.fragment.vm.MedicalRecordVM;
import com.phlx.anchorcollect.util.LoginInfoUtils;
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 MedicalRecordFragment extends BaseFragment<FragmentMedicalRecordBinding, MedicalRecordVM> {

    private TimePickerView pvTime;

    private ImagePicker mImagePicker;

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

    private MedicalRecordFragment() {
    }

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

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

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

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

    @Override
    public MedicalRecordVM initViewModel() {
        VMFactory factory = VMFactory.getInstance(getActivity().getApplication());
        return ViewModelProviders.of(this, factory).get(MedicalRecordVM.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(uiParamEntity.getColumnComment())
//                .positiveText("确认")
//                .negativeText("取消")
                .items(LoginInfoUtils.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 = LoginInfoUtils.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(LoginInfoUtils.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 = LoginInfoUtils.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;
        }
        int finalInputType = inputType;

        //判断下限制的长度
        int columnSize = 500;//不限制的设置成500
        int columnPointSize = -1;

        if (uiParamEntity.getColumnType().indexOf("(") > -1 && uiParamEntity.getColumnType().indexOf(")") > -1) {

            if (uiParamEntity.getColumnType().indexOf(",") > -1) {//有“,”说明是Duoble
                columnSize = Integer.parseInt(
                        uiParamEntity.getColumnType().substring(
                                uiParamEntity.getColumnType().indexOf("(") + 1, uiParamEntity.getColumnType().indexOf(",")
                        )
                ) + 1;
                columnPointSize = Integer.parseInt(
                        uiParamEntity.getColumnType().substring(
                                uiParamEntity.getColumnType().indexOf(",") + 1, uiParamEntity.getColumnType().indexOf(")")
                        )
                );
            } else {
                columnSize = Integer.parseInt(
                        uiParamEntity.getColumnType().substring(
                                uiParamEntity.getColumnType().indexOf("(") + 1, uiParamEntity.getColumnType().indexOf(")")
                        )
                );
            }
        }

        int maxColumnSize = columnSize * 37;
        if (maxColumnSize < 600) {
            maxColumnSize = 600;
        }
        if (maxColumnSize > 1200) {
            maxColumnSize = 1200;
        }

        //设置字体大小
        TextInfo textInfo = new TextInfo();
        textInfo.setFontSize(10);

        int finalColumnSize = columnSize;
        int finalColumnPointSize = columnPointSize;
        InputDialog.show(uiParamEntity.getColumnComment(), "", "确定", "取消")
                .setCancelable(false)
                .setInputInfo(new InputInfo().setTextInfo(textInfo).setInputType(finalInputType).setMAX_LENGTH(columnSize))
                .setTitleTextInfo(textInfo)
                .setOkTextInfo(textInfo)
                .setCancelTextInfo(textInfo)
                .setMaxWidth(maxColumnSize)
                .setInputHintText("输入" + uiParamEntity.getColumnComment()).setOkButton(new OnInputDialogButtonClickListener<InputDialog>() {
                    @Override
                    public boolean onClick(InputDialog baseDialog, View v, String inputStr) {

                        if (uiParamEntity.getJavaType().equals("BigDecimal") || uiParamEntity.getJavaType().equals("Duoble")) {
                            if (!inputStr.matches(
                                    "^\\d{1," + (finalColumnSize - finalColumnPointSize - 1) + "}(\\.\\d{1," + (finalColumnPointSize<1?1:finalColumnPointSize) + "})?$"
                            )) {
                                ToastUtils.showShort("输入异常，整数最大" + (finalColumnSize - finalColumnPointSize - 1) + "位，小数最大" + finalColumnPointSize + "位");
                                return true;
                            }
                        } else if (uiParamEntity.getJavaType().equals("Integer")) {
                            if (!inputStr.matches("^[1-9][0-9]{0," + (finalColumnSize) + "}$")) {
                                ToastUtils.showShort("输入异常，整数最大" + (finalColumnSize) + "位");
                                return true;
                            }
                        }
                        viewModel.currentParamEntity.setShowName(inputStr);
                        viewModel.currentParamEntity.setContent(inputStr);
                        viewModel.currentParamEntity.notifyChange();
                        return false;

                    }
                });

        /** 原

         new MaterialDialog.Builder(getActivity())
         .title(uiParamEntity.getColumnComment())
         //                        .iconRes(R.drawable.ic_logo)
         .canceledOnTouchOutside(false)
         .content("请输入")
         //              .widgetColor(Color.BLUE)//输入框光标的颜色
         .inputType(inputType)//可以输入的类型
         .inputRangeRes(0, columnSize, android.R.color.black)
         //前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);
        String inputStr = dialog.getInputEditText().getText().toString();
        //                        if (finalInputType == InputType.TYPE_CLASS_TEXT && inputStr.length() > 10) {
        //                            dialog.getInputEditText().setText(inputStr.subSequence(0, 10));
        //                            ToastUtils.showShort("输入长度超长");
        //                        } else {
        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(R.style.picker_view_slide_anim);//修改动画样式
                dialogWindow.setGravity(Gravity.CENTER);//改成Bottom,底部显示
                dialogWindow.setDimAmount(0.3f);
            }
        }
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);

        if (this != null && !hidden) {
            viewModel.clearParamList();

            //说明是列表跳转的
            if (Configs.resumeId != null) {
                viewModel.isModify = true;
                viewModel.queryMedicalRecord();
            } else {
                //清除一下数据
                viewModel.isModify = false;
                binding.rvCollect.getAdapter().notifyDataSetChanged();
            }
            viewModel.rfid.set(Configs.tempRfid);
        } else {
            viewModel.rfid.set("");
        }
    }
}
