package com.sybotan.android.demo.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Rect;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.view.TimePickerView;
import com.framework.mvvm.model.db.entity.Infos;
import com.framework.mvvm.model.db.entity.Options;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sybotan.android.demo.R;

import cn.sagacloud.android.cadengine.types.Photos;

import com.sybotan.android.demo.retrofit.Constant;
import com.sybotan.android.demo.tools.CommonUtils;
import com.sybotan.android.demo.view.CommonNumberControl;
import com.sybotan.android.demo.view.ListItemView;
import com.sybotan.android.demo.view.SelectListPopupWindow;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

/**
 * Created by lihao.
 * Date: 2021/9/26
 */
public class StaticInfoAdapter extends BaseRecyclerViewAdapter<Infos> {
    /**
     * text|textarea|radio|checkbox|picker|setpper|switch|date|photo|file
     */
    public HashMap<String, Object> hashMap = new HashMap<>();
    public ArrayList<String> valueList = new ArrayList<>();
    public static final int TEXT = 1;
    public static final int INT = 2;
    public static final int DOUBLE = 3;
    public static final int ENUM = 4;
    public static final int DATE = 5;
    public static final int MTEXT = 6;
    public static final int PICTURE = 7;

    private TimePickerView pvTime;
    private AddPic addPic;

    public StaticInfoAdapter(Context context, List<Infos> beans) {
        super(context, beans);
    }

    @Override
    protected int getItemLayoutId(int viewType) {
        switch (viewType) {
            case TEXT:
                return R.layout.view_text;
            case INT:
                return R.layout.view_int;
            case DOUBLE:
                return R.layout.view_double;
            case ENUM:
                return R.layout.view_enum;
            case DATE:
                return R.layout.view_date;
            case MTEXT:
                return R.layout.view_mtext;
            case PICTURE:
                return R.layout.view_picture;


        }
        return 0;
    }

    @Override
    protected void onBindDataToView(ViewHolder holder, Infos info) {
        if (TextUtils.isEmpty(info.getInputType())) {
            if (!CommonUtils.IsNull(info.getOptions())) {
                ListItemView enumItemView = holder.getView(R.id.view_enum);
                String unit = "";
                if (!TextUtils.isEmpty(info.getUnit())) {
                    unit = "(" + info.getUnit() + ")";
                }
                enumItemView.setTvLeft(info.getLabel() + unit);
                enumItemView.setTvRight("请选择");

                if (!valueList.contains(info.getCode())) {
                    if (hashMap != null && hashMap.get(info.getCode()) != null) {
                        ArrayList<Options> value = new Gson().fromJson((String) hashMap.get(info.getCode()), new TypeToken<List<Options>>() {
                        }.getType());
                        StringBuilder sb = new StringBuilder();
                        for (int i = 0; i < value.size(); i++) {
                            sb.append(value.get(i).getTxt()).append("、");
                        }
                        enumItemView.setTvRight(sb.toString());
                    }
                }
                valueList.add(info.getCode());

                enumItemView.getView(R.id.tv_right).setOnClickListener(v -> {
                    SelectListPopupWindow popupWindow = new SelectListPopupWindow(mContext);
                    popupWindow.setList(info.getOptions(), Constant.TYPE1);
                    popupWindow.setOnCommit(new SelectListPopupWindow.Commit() {
                        @Override
                        public void onCommit(ArrayList<Integer> list) {
                            ArrayList<Options> arrayList = new ArrayList<>();
                            StringBuilder sb = new StringBuilder();
                            for (int i = 0; i < list.size(); i++) {
                                sb.append(info.getOptions().get(list.get(i)).getTxt()).append("、");
                                arrayList.add(info.getOptions().get(list.get(i)));
                            }
                            hashMap.put(info.getCode(), new Gson().toJson(arrayList));
                            enumItemView.setTvRight(sb.toString());
                        }
                    });
                    popupWindow.showAtLocation(enumItemView, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                });
            } else {
                String unit = "";
                if (!TextUtils.isEmpty(info.getUnit())) {
                    unit = "(" + info.getUnit() + ")";
                }
                holder.setText(R.id.mtextTitle, info.getLabel() + unit);
                EditText mtextContent2 = holder.getView(R.id.mtextContent);
                initEditTextTouch(mtextContent2, info);
            }
            return;
        }
        String unit = "";
        if (!TextUtils.isEmpty(info.getUnit())) {
            unit = "(" + info.getUnit() + ")";
        }
        switch (info.getInputType()) {
            case "text":
                ListItemView textItemView = holder.getView(R.id.view_text);
                textItemView.setTvLeft(info.getLabel() + unit);
                EditText etRight = textItemView.findViewById(R.id.et_right);
                initEditTextTouch(etRight, info);
                break;
            case "textarea":
                holder.setText(R.id.mtextTitle, info.getLabel() + unit);
                EditText mtextContent = holder.getView(R.id.mtextContent);
                initEditTextTouch(mtextContent, info);
                break;
            case "radio":
            case "picker":
                ListItemView enumItemView = holder.getView(R.id.view_enum);
                enumItemView.setTvLeft(info.getLabel() + unit);
                enumItemView.setTvRight("请选择");

                if (!valueList.contains(info.getCode())) {
                    if (hashMap != null && hashMap.get(info.getCode()) != null) {
                        ArrayList<Options> value = new Gson().fromJson((String) hashMap.get(info.getCode()), new TypeToken<List<Options>>() {
                        }.getType());
                        StringBuilder sb = new StringBuilder();
                        for (int i = 0; i < value.size(); i++) {
                            sb.append(value.get(i).getTxt()).append("、");
                        }
                        enumItemView.setTvRight(sb.toString());
                    }
                }
                valueList.add(info.getCode());

                enumItemView.getView(R.id.tv_right).setOnClickListener(v -> {
                    SelectListPopupWindow popupWindow = new SelectListPopupWindow(mContext);
                    popupWindow.setList(info.getOptions(), Constant.TYPE1);
                    popupWindow.setOnCommit(new SelectListPopupWindow.Commit() {
                        @Override
                        public void onCommit(ArrayList<Integer> list) {
                            ArrayList<Options> arrayList = new ArrayList<>();
                            StringBuilder sb = new StringBuilder();
                            for (int i = 0; i < list.size(); i++) {
                                sb.append(info.getOptions().get(list.get(i)).getTxt()).append("、");
                                arrayList.add(info.getOptions().get(list.get(i)));
                            }
                            hashMap.put(info.getCode(), new Gson().toJson(arrayList));
                            enumItemView.setTvRight(sb.toString());
                        }
                    });
                    popupWindow.showAtLocation(enumItemView, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                });
                break;
            case "setpper":
//                return INT;
                ListItemView intItemView = holder.getView(R.id.view_int);
                intItemView.setTvLeft(info.getLabel() + unit);
                CommonNumberControl numberControl = (CommonNumberControl) intItemView.getView(R.id.et_right);
                initEditTextTouch(numberControl.getEditText(), info);
                break;
            case "photo":
                List<Photos> beans = new ArrayList<>();
                Photos photo = new Photos();
                photo.itemType = 1;
                beans.add(photo);

                if (!valueList.contains(info.getCode())) {
                    if (hashMap != null && hashMap.get(info.getCode()) != null) {
                        ArrayList<Photos> value = new Gson().fromJson((String) hashMap.get(info.getCode()), new TypeToken<List<Photos>>() {
                        }.getType());
                        ArrayList<Photos> photos = value;
                        beans.addAll(photos);
                    }
                }
                valueList.add(info.getCode());

                PictureAdapter pictureAdapter = new PictureAdapter(mContext, beans, "", false, holder.getCurrentPosition(), 85);
                pictureAdapter.setOnPicAdd(new PictureAdapter.PicAdd() {
                    @Override
                    public void onPicAdd() {
                        if (addPic != null) {
                            addPic.onAddPic(info);
                        }
                    }
                });
                RecyclerView recycler = holder.getView(R.id.viewRecycler);
                recycler.setLayoutManager(new GridLayoutManager(mContext, 3));
                recycler.setAdapter(pictureAdapter);
//                return PICTURE;
                break;
            case "date":
//                return DATE;
                ListItemView listItemView = holder.getView(R.id.view_date);
                listItemView.setTvLeft(info.getLabel() + unit);
                listItemView.getView(R.id.tv_right).setOnClickListener(v -> {
                    pvTime.show(true);
                });
                initTimePicker();
                break;
            default:
                if (!CommonUtils.IsNull(info.getOptions())) {
//                    return ENUM;
                    ListItemView enumItemView2 = holder.getView(R.id.view_enum);
                    enumItemView2.setTvLeft(info.getLabel() + unit);
                    enumItemView2.setTvRight("请选择");

                    if (!valueList.contains(info.getCode())) {
                        if (hashMap != null && hashMap.get(info.getCode()) != null) {
                            ArrayList<Options> value = new Gson().fromJson((String) hashMap.get(info.getCode()), new TypeToken<List<Options>>() {
                            }.getType());
                            StringBuilder sb = new StringBuilder();
                            for (int i = 0; i < value.size(); i++) {
                                sb.append(value.get(i).getTxt()).append("、");
                            }
                            enumItemView2.setTvRight(sb.toString());
                        }
                    }
                    valueList.add(info.getCode());

                    enumItemView2.getView(R.id.tv_right).setOnClickListener(v -> {
                        SelectListPopupWindow popupWindow = new SelectListPopupWindow(mContext);
                        popupWindow.setList(info.getOptions(), Constant.TYPE1);
                        popupWindow.setOnCommit(new SelectListPopupWindow.Commit() {
                            @Override
                            public void onCommit(ArrayList<Integer> list) {
                                ArrayList<Options> arrayList = new ArrayList<>();
                                StringBuilder sb = new StringBuilder();
                                for (int i = 0; i < list.size(); i++) {
                                    sb.append(info.getOptions().get(list.get(i)).getTxt()).append("、");
                                    arrayList.add(info.getOptions().get(list.get(i)));
                                }
                                hashMap.put(info.getCode(), new Gson().toJson(arrayList));
                                enumItemView2.setTvRight(sb.toString());
                            }
                        });
                        popupWindow.setTitle(false, "");
                        popupWindow.showAtLocation(enumItemView2, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
                    });
                } else {
//                    return MTEXT;
                    holder.setText(R.id.mtextTitle, info.getLabel() + unit);
                    EditText mtextContent2 = holder.getView(R.id.mtextContent);
                    initEditTextTouch(mtextContent2, info);
                }
                break;

        }

//        switch (o.hashCode()) {
//            case TEXT:
//
//                break;
//            case INT:
//
//                break;
//            case DOUBLE:
//                ListItemView doubleItemView = holder.getView(R.id.view_double);
//                break;
//            case ENUM:
//
//                break;
//            case DATE:
//
//                break;
//            case MTEXT:
//
//                break;
//            case PICTURE:
//
//                break;
//        }
    }

    @SuppressLint("ClickableViewAccessibility")
    private void initEditTextTouch(EditText editText, Infos info) {
//        editText.setOnTouchListener((v, event) -> {
//            if (MotionEvent.ACTION_DOWN == event.getAction()) {
//                v.getParent().requestDisallowInterceptTouchEvent(true);
//            } else if (MotionEvent.ACTION_UP == event.getAction()) {
//                v.getParent().requestDisallowInterceptTouchEvent(false);
//            }
//            return false;
//        });
        TextWatcher textWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                hashMap.put(info.getCode(), s.toString());
            }
        };
        if (editText.getTag() instanceof TextWatcher) {
            editText.removeTextChangedListener((TextWatcher) editText.getTag());
        }
        if (!valueList.contains(info.getCode())) {
            if (hashMap != null && hashMap.get(info.getCode()) != null) {
                editText.setText((String) hashMap.get(info.getCode()));
            }
        }
        valueList.add(info.getCode());
        editText.addTextChangedListener(textWatcher);
        editText.setTag(textWatcher);

        editText.getViewTreeObserver().addOnGlobalLayoutListener(
                () -> {
                    Rect r = new Rect();
                    editText.getWindowVisibleDisplayFrame(r);
                    int screenHeight = editText.getRootView()
                            .getHeight();
                    int heightDifference = screenHeight - (r.bottom);
                    if (heightDifference > 200) {
                        //软键盘显示
                        editText.setFocusable(true);
                    } else {
                        //软键盘隐藏
                        editText.clearFocus();

                    }
                });
        editText.setOnClickListener(v -> {
            editText.setFocusable(true);
            editText.setFocusableInTouchMode(true);
            editText.requestFocus();
            editText.findFocus();
            InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(editText, InputMethodManager.SHOW_FORCED);// 显示输入法
        });
    }

    @Override
    public int getItemViewType(int position) {
        if (TextUtils.isEmpty(mBeans.get(position).getInputType())) {
            if (!CommonUtils.IsNull(mBeans.get(position).getOptions())) {
                return ENUM;
            } else {
                return MTEXT;
            }
        }
        switch (mBeans.get(position).getInputType()) {
            case "text":
                return TEXT;
            case "textarea":
                return MTEXT;
            case "radio":
            case "picker":
                return ENUM;
            case "setpper":
                return INT;
            case "photo":
                return PICTURE;
            case "date":
                return DATE;
            default:
                if (!CommonUtils.IsNull(mBeans.get(position).getOptions())) {
                    return ENUM;
                }
                return MTEXT;
        }
    }

    public void initTimePicker() {
        Calendar currentDate = Calendar.getInstance();
        Calendar endDate = Calendar.getInstance();
        endDate.set(3000, 12, 31);
        //初始化时间选择器
        pvTime = new TimePickerBuilder(mContext, (date, v) -> {//选中事件回调
            long timeBegin = 0;
            long timeEnd = 0;
        }).setLayoutRes(R.layout.pickerview_custom_time, v -> {
            Button btnSubmit = v.findViewById(R.id.btnSubmit);
            Button btnCancel = v.findViewById(R.id.btnCancel);
            //确定
            btnSubmit.setOnClickListener(v1 -> {
                pvTime.returnData();
                pvTime.dismiss();
            });
            //取消
            btnCancel.setOnClickListener(v2 -> {
                pvTime.dismiss();
            });
        }).setType(new boolean[]{true, true, true, false, false, false})
                .setLabel("年", "月", "日", "", "", "") //设置空字符串以隐藏单位提示   hide label
                .setDividerColor(Color.DKGRAY)
                .setContentTextSize(20)
                .setDate(currentDate)
                .setRangDate(currentDate, endDate)
//                .setDecorView((ViewGroup) findViewById(R.id.root))//非dialog模式下,设置ViewGroup,
                // pickerView将会添加到这个ViewGroup中
                .setBackgroundId(0xb0000000)
                .setOutSideCancelable(false)
                .build();
        pvTime.setKeyBackCancelable(false);//系统返回键监听屏蔽掉
    }

    public interface AddPic {
        void onAddPic(Infos info);
    }

    public void setOnAddPic(AddPic addPic) {
        this.addPic = addPic;
    }

}
