package com.phlx.wool.ui.cattle.activity;

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

import androidx.annotation.NonNull;
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.phlx.wool.Configs;
import com.phlx.wool.R;
import com.phlx.wool.data.VMFactory;
import com.phlx.wool.databinding.ActivityCattleMarkBinding;
import com.phlx.wool.ui.base.BaseActivity;
import com.phlx.wool.ui.cattle.vm.CattleMarkVM;
import com.phlx.wool.ui.main.MainActivity;
import com.phlx.wool.ui.slaughter.SlaughterEntryActivity;
import com.phlx.wool.ui.slaughter.vm.SlaughterEntryVM;
import com.phlx.wool.ui.villus.VillusBuyActivity;
import com.phlx.wool.util.BaseImageUtils;
import com.phlx.wool.util.ImagePicker;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.Date;

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

public class CattleMarkActivity extends BaseActivity<ActivityCattleMarkBinding, CattleMarkVM> {

    private ImagePicker markImagePicker;

    private TimePickerView pvTime;


    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_cattle_mark;
    }

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

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

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

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

        viewModel.initToolbar();

        initTimePicker();

        if (markImagePicker == null) {
            markImagePicker = new ImagePicker(CattleMarkActivity.this);
            markImagePicker.setOnImagePickerListener(new ImagePicker.OnImagePickerListener() {
                @Override
                public void onSuccess(String path) {
                    Bitmap bitmap = BaseImageUtils.decodeBitmap(path, CattleMarkActivity.this);
//                    Bitmap bitmap2 = BaseImageUtils.rotateBitmapByDegree(bitmap, BaseImageUtils.getBitmapDegree(path));
                    BaseImageUtils.saveBitmapToSDCard(bitmap, viewModel.getMarkImgUrl());
                    viewModel.entity.setMarkImgPath(viewModel.getMarkImgUrl());
                    Glide.with(CattleMarkActivity.this)
                            .load(viewModel.getMarkImgUrl())
                            .apply(
                                    new RequestOptions()
                                            .skipMemoryCache(true)
                                            .diskCacheStrategy(DiskCacheStrategy.NONE)
                                            .error(R.drawable.no_image)
                                            .fallback(R.drawable.no_image)
                            )
                            .into(binding.markPhotoView);
                }
            });
        }
    }

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


        viewModel.birthDay.observe(this, aBoolean -> {
            pvTime.show(binding.entryDayTv);
        });

        viewModel.ancestryOnClick.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                binding.superiorDivisionSp.setAdapter(viewModel.getAdapter(CattleMarkActivity.this));
            }
        });

        viewModel.markPhotoOnClick.observe(this, aBoolean -> {
            RxPermissions rxPermissions = new RxPermissions(CattleMarkActivity.this);
            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) {
                                markImagePicker.show(CattleMarkActivity.this);
                            } else {
                                ToastUtils.showShort("权限被拒绝");
                            }
                        }
                    });
        });

        viewModel.scanLabelOnClick.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {

                new MaterialDialog.Builder(CattleMarkActivity.this)
                        .title("耳标录入")
//                        .iconRes(R.drawable.ic_logo)
                        .content("通过拍子扫描低频耳标")
//                                .widgetColor(Color.BLUE)//输入框光标的颜色
                        .inputType(InputType.TYPE_CLASS_NUMBER)//可以输入的类型
                        //前2个一个是hint一个是预输入的文字
                        .input("", "", 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.setScanLabel(dialog.getInputEditText().getText().toString());
                            }
                        })
                        .show();

            }
        });
    }

    private void initTimePicker() {//Dialog 模式下，在底部弹出
        pvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                viewModel.setBirthDate(date);
            }
        })
                .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.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    Gravity.BOTTOM);

            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.BOTTOM);//改成Bottom,底部显示
                dialogWindow.setDimAmount(0.3f);
            }
        }
    }
}
