package com.phlx.anchorcollect.ui.fragment;

import android.Manifest;
import android.app.Dialog;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
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.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
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.App;
import com.phlx.anchorcollect.Configs;
import com.phlx.anchorcollect.R;
import com.phlx.anchorcollect.data.VMFactory;
import com.phlx.anchorcollect.databinding.FragmentWeightmanBinding;
import com.phlx.anchorcollect.entity.DictEntity;
import com.phlx.anchorcollect.entity.GenTableColumn;
import com.phlx.anchorcollect.entity.WeightManEntity;
import com.phlx.anchorcollect.event.EventTag;
import com.phlx.anchorcollect.ui.fragment.vm.WeightManVM;
import com.phlx.anchorcollect.ui.info.CattleActivity;
import com.phlx.anchorcollect.util.DictUtils;
import com.phlx.anchorcollect.util.ImagePicker;
import com.phlx.anchorcollect.util.TextUtil;
import com.phlx.anchorcollect.widget.SpaceItemDecoration;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
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 WeightManFragment extends BaseFragment<FragmentWeightmanBinding, WeightManVM> {

    private TimePickerView pvTime;

    private ImagePicker mImagePicker;

    private MaterialDialog showEpcDialog;

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

    private WeightManFragment() {
    }

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


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

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

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

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

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

        viewModel.initGen();

        //修改重量数字字体
        binding.tvWeight.setTypeface(Configs.typeface);
        binding.tvWeighLast.setTypeface(Configs.typeface);
        binding.tvWeighAdg.setTypeface(Configs.typeface);
        binding.tvWeighBwg.setTypeface(Configs.typeface);

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

        initTimePicker();
    }

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

        if (!hidden) {
            viewModel.addInventoryListener();
            viewModel.initDataForUnid(Configs.tempUnid);
            Configs.currentEvent = EventTag.EVENT_WEIGHT_DATA_WEIGHT;
        } else {
            viewModel.removeInventoryListener();
            Configs.currentEvent = "";
            App.getInstance().getLinkage().stopInventory();
            viewModel.isScan = false;
        }
    }

    @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.onTagClickEvent.observe(getActivity(), new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                //设置字体大小
                TextInfo textInfo = new TextInfo();
                textInfo.setFontSize(10);

                InputDialog.show("耳标号", "", "确定", "取消")
                        .setCancelable(false)
                        .setInputInfo(new InputInfo().setTextInfo(textInfo))
                        .setTitleTextInfo(textInfo)
                        .setOkTextInfo(textInfo)
                        .setCancelTextInfo(textInfo)
                        .setMaxWidth(600)
                        .setInputHintText("请输入可视化耳标号").setOkButton(new OnInputDialogButtonClickListener<InputDialog>() {
                    @Override
                    public boolean onClick(InputDialog baseDialog, View v, String inputStr) {
                        viewModel.tag.set(inputStr);
                        viewModel.initDataForTag(inputStr);
                        return false;
                    }
                });

            }
        });

        viewModel.onCattleClickEvent.observe(getActivity(), new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                //TODO 修改验证方式
                if (TextUtil.isSpace(viewModel.tag.get())) {
                    ToastUtils.showShort("请先输入可视耳标号");
                } else {
                    Bundle bundle = new Bundle();
                    bundle.putString("Tag", viewModel.tag.get());
                    startActivity(CattleActivity.class, bundle);
                }

            }
        });

        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();


                File[] files;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    files = getContext().getExternalFilesDirs(Environment.MEDIA_MOUNTED);
                    for (File file : files) {
                        Log.e("main", file.getPath());
                    }
                }
                Glide.with(getContext())
                        .load(viewModel.imgUrl)
                        .apply(
                                new RequestOptions()
                                        .skipMemoryCache(true)
                                        .diskCacheStrategy(DiskCacheStrategy.NONE)
                                        .error(R.drawable.no_image)
                                        .fallback(R.drawable.no_image)
                        )
                        .into(binding.ivCattlePhoto);
                binding.rvCollect.getAdapter().notifyDataSetChanged();
            }
        });

        viewModel.onCoverRecordEvent.observe(this, new Observer<WeightManEntity>() {
            @Override
            public void onChanged(WeightManEntity weightManEntity) {

                new MaterialDialog.Builder(getActivity()).title("系统提示").content(weightManEntity.getWTime() + "已有称重记录，是否覆盖").positiveText("确定").negativeText("取消").onAny(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        if (which == DialogAction.POSITIVE) {
                            viewModel.saveWeightMan(weightManEntity);
                        }
                    }
                }).show();

            }
        });

        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();
            }
        });

        viewModel.onShowEpcListEvent.observe(getActivity(), new Observer<List<String>>() {
            @Override
            public void onChanged(List<String> stringList) {

                if (showEpcDialog != null) {
                    if (showEpcDialog.isShowing()) {//弹窗前先给上一次的取消了
                        showEpcDialog.dismiss();
                    }
                    showEpcDialog = null;
                }
                showEpcDialog = new MaterialDialog.Builder(getActivity())
                        .title("请选择耳标")
//                .positiveText("确认")
//                .negativeText("取消")
                        .items(stringList)
                        .itemsCallback(new MaterialDialog.ListCallback() {
                            @Override
                            public void onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
//                                String epcStr = text.toString().substring(text.toString().indexOf("----") + 4);
                                viewModel.initDataForRfid(text.toString());
                            }
                        })
                        .show();
            }
        });
    }


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

        new MaterialDialog.Builder(getActivity())
                .title(uiParamEntity.getColumnComment())
//                .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;
        }
        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;
                            }
                        }
                        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.card0);
    }

    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);
            }
        }
    }

}
