package com.gingersoft.gsa.cloud.ui.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.gingersoft.gsa.cloud.base.utils.other.SPUtils;
import com.gingersoft.gsa.cloud.base.utils.time.TimeUtils;
import com.gingersoft.gsa.cloud.ui.R;
import com.gingersoft.gsa.cloud.ui.R2;
import com.gingersoft.gsa.cloud.ui.adapter.SkyorderMealKindAdapter;
import com.gingersoft.gsa.cloud.ui.bean.TagViewBean;
import com.gingersoft.gsa.cloud.ui.utils.MathUtils;
import com.gingersoft.gsa.cloud.ui.widget.RoundButton;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.ThirdViewUtil;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.QMUIWrapContentListView;
import com.qmuiteam.qmui.widget.popup.QMUIPopup;

import java.util.ArrayList;
import java.util.List;

import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;

/**
 * 作者：ELEGANT_BIN
 * 版本：1.6.0
 * 创建日期：2018/5/24
 * 修订历史：2018/5/24
 * 描述：打印QRCode
 */

public class PrintQRCodeDialog {

    private Activity mContext;
    private Dialog dialog;

    @BindView(R2.id.lLayout_bg)
    LinearLayout lLayout_bg;

    @BindView(R2.id.tv_table_name)
    TextView tv_table_name;
    @BindView(R2.id.btn_delivery_time)
    RoundButton btn_delivery_time;
    @BindView(R2.id.tv_hour)
    TextView tv_hour;
    @BindView(R2.id.tv_minute)
    TextView tv_minute;
    @BindView(R2.id.recycler_food_kind)
    RecyclerView recycler_food_kind;

    @BindView(R2.id.ed_value)
    EditText ed_value;
    @BindView(R2.id.btn_0)
    Button btn_0;
    @BindView(R2.id.btn_1)
    Button btn_1;
    @BindView(R2.id.btn_2)
    Button btn_2;
    @BindView(R2.id.btn_3)
    Button btn_3;
    @BindView(R2.id.btn_4)
    Button btn_4;
    @BindView(R2.id.btn_5)
    Button btn_5;
    @BindView(R2.id.btn_6)
    Button btn_6;
    @BindView(R2.id.btn_7)
    Button btn_7;
    @BindView(R2.id.btn_8)
    Button btn_8;
    @BindView(R2.id.btn_9)
    Button btn_9;
    @BindView(R2.id.btn_back)
    Button btn_back;
    @BindView(R2.id.btn_ten_plus)
    Button btn_ten_plus;

    private QMUIPopup mHoursPopup;
    private QMUIPopup mMinutePopup;

    private List<Integer> mDeliveryHours = new ArrayList<>();
    private List<Integer> mDeliveryMinute = new ArrayList<>();
    private List<TagViewBean> mSummarys = new ArrayList<>();

    private SkyorderMealKindAdapter skyorderMealKindAdapter;

    private int hourSelectPosition = -1;
    private int minuteSelectPosition = -1;
    private int summaryId = 2;
    private int[] chooseDeliveryTimes = new int[2];
    private String currentTimes[];

    //选中10+的次数
    private int currentTenPlus = 0;

    private final String checkStatusKey = "check_status";
    private final String deliveryTimeHourKey = "delivery_time_hour";
    private final String deliveryTimeMinuteKey = "delivery_time_minute";

    public PrintQRCodeDialog(Activity context) {
        this.mContext = context;
        initView();
    }

    private void initView() {
        // 获取Dialog布局
        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_print_qrcode, null);

        ThirdViewUtil.bindTarget(this, view);//绑定

        // 定义Dialog布局和参数
        dialog = new Dialog(mContext, R.style.AlertDialogStyle);
        dialog.setContentView(view);
        dialog.setCancelable(true);

        // 调整dialog背景大小
        lLayout_bg.setLayoutParams(
                new FrameLayout.LayoutParams((int) (ArmsUtils.getScreenWidth(mContext) * 0.95), ViewGroup.LayoutParams.WRAP_CONTENT));

        ed_value.setTextSize(ArmsUtils.dip2px(mContext, 12));
        ed_value.setHintTextColor(ArmsUtils.getColor(mContext, R.color.theme_hint_color));
        ed_value.setHint("請輸入人數");
        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                //恢复刷新餐台数据标志
//                GSAApplication.isRefreshData = true;
                cancelRecycler();
            }
        });
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                //恢复刷新餐台数据标志
//                GSAApplication.isRefreshData = true;
                cancelRecycler();
            }
        });
    }

    private void cancelRecycler() {
        if (mDeliveryHours != null) {
            mDeliveryHours.clear();
            mDeliveryHours = null;
        }
        if (mDeliveryMinute != null) {
            mDeliveryMinute.clear();
            mDeliveryMinute = null;
        }
        if (mSummarys != null) {
            mSummarys.clear();
            mSummarys = null;
        }
        chooseDeliveryTimes = null;
        skyorderMealKindAdapter = null;
    }

    public PrintQRCodeDialog builder() {
        initDeliveryHourTime();
        initDeliveryTimeClickListener();
        initDeliveryTimePopup();
        initSummaryAdapter();
        initSummaryDefaultSelect();
        initSummaryRecycleView();
        return this;
    }

    public void initDeliveryHourTime() {

        long currentTimeMillis = System.currentTimeMillis();
        //设置交檯时间（时）当前时间往后六小时
        currentTimes = TimeUtils.getStringByFormat(currentTimeMillis, TimeUtils.dateFormatHM).split(":");
        int currentHour = Integer.parseInt(currentTimes[0]);
        for (int i = currentHour; i < currentHour + 7; i++) {
            mDeliveryHours.add(i);
        }

        boolean isCheckLockedDeliveryTime = (boolean) SPUtils.get(mContext, checkStatusKey, false);

        if (isCheckLockedDeliveryTime) {
            Drawable drawable = mContext.getResources().getDrawable(R.drawable.qrcode_time_lock);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            btn_delivery_time.setCompoundDrawables(null, null, drawable, null);
            //交檯时间已锁定
            setLockedDeliveryTime();
        } else {
            //交檯时间未锁定，给一个默认选中时间
            setDefaultDeliveryTime();
        }

    }

    private void setLockedDeliveryTime() {
        String lockedHour = (String) SPUtils.get(mContext, deliveryTimeHourKey, "0");
        String lockedMinute = (String) SPUtils.get(mContext, deliveryTimeMinuteKey, "0");
        if (!TextUtils.isEmpty(lockedHour)) {
            chooseDeliveryTimes[0] = Integer.parseInt(lockedHour);
        }
        if (!TextUtils.isEmpty(lockedMinute)) {
            chooseDeliveryTimes[1] = Integer.parseInt(lockedMinute);
        }
        for (int i = 0; i < mDeliveryHours.size(); i++) {
            if (chooseDeliveryTimes.length > 0 && chooseDeliveryTimes[0] == mDeliveryHours.get(i)) {
                //找到当前选择的小时数下标
                hourSelectPosition = i;
                break;
            }
        }

        for (int j = 0; j < mDeliveryMinute.size(); j++) {
            if (chooseDeliveryTimes.length > 1 && chooseDeliveryTimes[1] == mDeliveryMinute.get(j)) {
                //找到当前选择的分钟数下标
                minuteSelectPosition = j;
                break;
            }
        }

    }

    private void setDefaultDeliveryTime() {
        /**
         * 设置默认小时数
         */
        long currentTimeMillis = System.currentTimeMillis();
        //设置默认交台时间为当前时间往后推多少分钟（可配置）
        long defaultDeliveryLater = currentTimeMillis;// + (GSAApplication.androidSetting.getQR_DeliveryLaterDefault() * 60 * 1000)
        String defaultDeliveryLaterTimes[] = TimeUtils.getStringByFormat(defaultDeliveryLater, TimeUtils.dateFormatHM).split(":");
        for (int i = 0; i < mDeliveryHours.size(); i++) {
            int hour = mDeliveryHours.get(i);
            if (hour == Integer.parseInt(defaultDeliveryLaterTimes[0])) {
                //设置默认交檯小时数
                chooseDeliveryTimes[0] = Integer.parseInt(defaultDeliveryLaterTimes[0]);
                hourSelectPosition = i;
                break;
            }
        }
        if (hourSelectPosition == -1) {
            //未设置默认交檯时，默认选中下一个小时
            chooseDeliveryTimes[0] = mDeliveryHours.get(1);
            hourSelectPosition = 1;
        }

        /**
         * 设置默认分钟数
         */
        //获取当前分钟
        int currentMinute = Integer.parseInt(currentTimes[1]);
        //找回与当前分钟数相近的整数
        int needNum = MathUtils.findRecentNum(mDeliveryMinute, currentMinute);
        //设置默认分钟数
        chooseDeliveryTimes[1] = needNum;
        for (int i = 0; i < mDeliveryMinute.size(); i++) {
            if (mDeliveryMinute.get(i) == chooseDeliveryTimes[1]) {
                minuteSelectPosition = i;
            }
        }
    }

    private void initDeliveryTimeClickListener() {
        btn_delivery_time.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                boolean isCheckLockedDeliveryTime = !(boolean) SPUtils.get(mContext, checkStatusKey, false);
                if (isCheckLockedDeliveryTime) {
                    SPUtils.put(mContext, deliveryTimeHourKey, String.valueOf(chooseDeliveryTimes[0]));
                    SPUtils.put(mContext, deliveryTimeMinuteKey, String.valueOf(chooseDeliveryTimes[1]));

                    Drawable drawable = mContext.getResources().getDrawable(R.drawable.qrcode_time_lock);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    btn_delivery_time.setCompoundDrawables(null, null, drawable, null);
                } else {
                    SPUtils.put(mContext, deliveryTimeHourKey, "");
                    SPUtils.put(mContext, deliveryTimeMinuteKey, "");
                    btn_delivery_time.setCompoundDrawables(null, null, null, null);
                }

                SPUtils.put(mContext, checkStatusKey, isCheckLockedDeliveryTime);
            }
        });
    }

    private void initDeliveryTimePopup() {

        if (hourSelectPosition != -1 && mDeliveryHours.size() > hourSelectPosition) {
            tv_hour.setText(mDeliveryHours.get(hourSelectPosition) + "");
        }

        if (minuteSelectPosition != -1 && mDeliveryMinute.size() > minuteSelectPosition) {
            tv_minute.setText(mDeliveryMinute.get(minuteSelectPosition) + "");
        }

        if (mHoursPopup == null) {
            mHoursPopup = initPopup(mDeliveryHours, (parent, view, position, id) -> {
                mHoursPopup.dismiss();
                chooseDeliveryTimes[0] = mDeliveryHours.get(position);
                tv_hour.setText(mDeliveryHours.get(position) + "");
                boolean isCheckLockedDeliveryTime = (boolean) SPUtils.get(mContext, checkStatusKey, false);
                if (isCheckLockedDeliveryTime) {
                    SPUtils.put(mContext, deliveryTimeHourKey, String.valueOf(chooseDeliveryTimes[0]));
                }
            });
            mHoursPopup.offsetYIfBottom(10);

//            mHoursPopup.setPopupTopBottomMinMargin(10);
//            mHoursPopup.setPositionOffsetYWhenBottom(10);
        }

        if (mMinutePopup == null) {
            mMinutePopup = initPopup(mDeliveryMinute, (parent, view, position, id) -> {
                mMinutePopup.dismiss();

                chooseDeliveryTimes[1] = mDeliveryMinute.get(position);
                tv_minute.setText(mDeliveryMinute.get(position) + "");

                boolean isCheckLockedDeliveryTime = (boolean) SPUtils.get(mContext, checkStatusKey, false);
                if (isCheckLockedDeliveryTime) {
                    SPUtils.put(mContext, deliveryTimeMinuteKey, String.valueOf(chooseDeliveryTimes[1]));
                }
            });
        }
    }

    private QMUIPopup initPopup(List<Integer> mDelivery, AdapterView.OnItemClickListener onItemClickListener) {
        int mHeight = QMUIDisplayHelper.dp2px(mContext, 200);
        int mWidth = QMUIDisplayHelper.dp2px(mContext, 150);
        ArrayAdapter hoursAdapter = new ArrayAdapter<>(mContext, R.layout.spinner_item_select, mDelivery);
        QMUIPopup popup = new QMUIPopup(mContext, mWidth, mHeight);

        ListView listView = new QMUIWrapContentListView(mContext, mHeight);
        FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        listView.setLayoutParams(lp);
        listView.setAdapter(hoursAdapter);
        listView.setVerticalScrollBarEnabled(false);
        listView.setOnItemClickListener(onItemClickListener);
        listView.setDivider(null);
        popup.view(listView);
        return popup;
    }


    private void initSummaryAdapter() {
        if (skyorderMealKindAdapter == null) {
            //当餐台有多种餐种时才显示 选择餐种
            skyorderMealKindAdapter = new SkyorderMealKindAdapter(mContext, mSummarys);
//            if (mSummarys.size() >= GSAApplication.androidSetting.getQR_SummaryIndexDefault()) {
//                //設置，默認選中餐種
//                skyorderMealKindAdapter.setDefaultCheckedIndex(GSAApplication.androidSetting.getQR_SummaryIndexDefault());
//            }
            recycler_food_kind.setAdapter(skyorderMealKindAdapter);
            skyorderMealKindAdapter.setOnClickCheckedListener(tagViewBean -> summaryId = tagViewBean.getId());
        }
    }

    private void initSummaryDefaultSelect() {
        if (mSummarys.size() > 0) {
            if (mSummarys.size() == 1) {
                //只有一种餐种 直接选中
                summaryId = mSummarys.get(0).getId();
            } else {
//                if (mSummarys.size() >= GSAApplication.androidSetting.getQR_SummaryIndexDefault()) {
//                    后台设置默认选中餐种的餐种在，可选数量范围内
//                    summaryId = mSummarys.get(GSAApplication.androidSetting.getQR_SummaryIndexDefault()).getId();
//                } else {
                //后台设置默认选中餐种不在可选数量范围内 ，默认选中第一个
                summaryId = mSummarys.get(0).getId();
//                }
            }
        }
    }

    @OnClick({R2.id.tv_hour, R2.id.tv_minute, R2.id.btn_0, R2.id.btn_1, R2.id.btn_2, R2.id.btn_3, R2.id.btn_4, R2.id.btn_5, R2.id.btn_6, R2.id.btn_7, R2.id.btn_8
            , R2.id.btn_9, R2.id.btn_back, R2.id.btn_ten_plus})
    public void onClick(View v) {
        if (v.getId() == R.id.tv_hour) {
            mHoursPopup.animStyle(QMUIPopup.ANIM_GROW_FROM_CENTER);
            mHoursPopup.preferredDirection(QMUIPopup.DIRECTION_BOTTOM);
            mHoursPopup.show(v);
        } else if (v.getId() == R.id.tv_minute) {
            mMinutePopup.animStyle(QMUIPopup.ANIM_GROW_FROM_CENTER);
            mMinutePopup.preferredDirection(QMUIPopup.DIRECTION_BOTTOM);
            mMinutePopup.show(v);
        } else if (v.getId() == R.id.btn_0 | v.getId() == R.id.btn_1 | v.getId() == R.id.btn_2 |
                v.getId() == R.id.btn_3 | v.getId() == R.id.btn_4 | v.getId() == R.id.btn_5 |
                v.getId() == R.id.btn_6 | v.getId() == R.id.btn_7 | v.getId() == R.id.btn_8 |
                v.getId() == R.id.btn_9) {
            int i = Integer.parseInt(v.getTag().toString());

            String values = String.valueOf(i);

            if (currentTenPlus > 0) {
                //有选择十整位
                values = currentTenPlus + values;
            }
            if (values.length() > 0 && Integer.parseInt(values) > 99) {
                values = "99";
                ed_value.setText(values);
            } else {
                ed_value.setText(values);
            }
            if (!TextUtils.isEmpty(getInputNumber())) {
                comfirm();
                cancel();
            }
        } else if (v.getId() == R.id.btn_back) {
            cancel();
        } else if (v.getId() == R.id.btn_ten_plus) {
            currentTenPlus++;
            ed_value.setText(String.valueOf(currentTenPlus));
        }
    }

    private void comfirm() {
        if (TextUtils.isEmpty(getInputNumber())) {
            ArmsUtils.makeText(mContext, "請輸入人數");
            return;
        }

        int person = Integer.parseInt(getInputNumber());
        String endTime = chooseDeliveryTimes[0] + ":" + chooseDeliveryTimes[1];

        if (TextUtils.isEmpty(endTime)) {
            ArmsUtils.makeText(mContext, "請選擇交檯時間");
            return;
        }

        if (summaryId == -1) {
            ArmsUtils.makeText(mContext, "請選擇餐種");
            return;
        }

        if (onComfirmListener != null) {
            onComfirmListener.onComfirm(person, formatEndTime(endTime), summaryId);
        }
        cancel();
    }

    public void initSummaryRecycleView() {
        GridLayoutManager manager = new GridLayoutManager(mContext, 4, LinearLayoutManager.VERTICAL, false);
        ArmsUtils.configRecyclerView(recycler_food_kind, manager);
        recycler_food_kind.setLayoutManager(manager);
        recycler_food_kind.setItemAnimator(new DefaultItemAnimator());
    }

    private String formatEndTime(String endTime) {
        String day = TimeUtils.getStringByFormat(System.currentTimeMillis(), TimeUtils.dateFormatYMD);
        return day + " " + endTime + ":00";
    }

    public PrintQRCodeDialog setCancelable(boolean cancelable) {
        dialog.setCancelable(cancelable);
        return this;
    }

    public void setMinute(List<Integer> mMinute) {
        this.mDeliveryMinute.addAll(mMinute);
    }

    public String getInputNumber() {
        return ed_value.getText().toString().trim();
    }

    public void setTableName(String name) {
        tv_table_name.setText(name);
    }

    public void show() {
        dialog.show();
        //先停止刷新餐台数据，避免卡顿
//        GSAApplication.isRefreshData = false;
    }

    public void cancel() {
        dialog.dismiss();
    }

    private OnComfirmListener onComfirmListener;

    public void setComfirmListener(OnComfirmListener onComfirmListener) {
        this.onComfirmListener = onComfirmListener;
    }

    public interface OnComfirmListener {
        void onComfirm(int person, String endTime, int summaryId);
    }

}
