package com.gingersoft.gsa.cloud.table.mvp.ui.widget;

import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatCheckBox;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.gingersoft.gsa.cloud.base.utils.LanguageUtils;
import com.gingersoft.gsa.cloud.base.utils.other.SPUtils;
import com.gingersoft.gsa.cloud.base.utils.time.TimeUtils;
import com.gingersoft.gsa.cloud.table.R;
import com.gingersoft.gsa.cloud.table.mvp.model.bean.FoodSummary;
import com.gingersoft.gsa.cloud.table.mvp.model.constant.SkyOrderConstant;
import com.gingersoft.gsa.cloud.table.mvp.model.utils.MathUtils;
import com.gingersoft.gsa.cloud.table.mvp.ui.adapter.FoodSummaryAdapter;
import com.gingersoft.gsa.cloud.ui.recylcler.Indicator.PagerGridLayoutManager;
import com.gingersoft.gsa.cloud.ui.recylcler.Indicator.PagerGridSnapHelper;
import com.gingersoft.gsa.cloud.ui.widget.dialog.BaseRetryDialog;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.flexbox.JustifyContent;
import com.jess.arms.utils.ArmsUtils;
import com.qmuiteam.qmui.QMUILog;
import com.qmuiteam.qmui.alpha.QMUIAlphaTextView;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.QMUIEmptyView;
import com.qmuiteam.qmui.widget.popup.QMUIPopup;
import com.qmuiteam.qmui.widget.popup.QMUIPopups;
import com.rengwuxian.materialedittext.MaterialEditText;

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

/**
 * @author : bin
 * @create date: 2020-10-31
 * @update date: 2020-10-31
 * @description:
 */
public class SkyOrderDialog extends BaseRetryDialog implements View.OnClickListener, PagerGridLayoutManager.PageListener {

    private static final String TAG = "SkyOrderDialog";
    private TextView tv_table_name;
    private AppCompatCheckBox cb_title;
    private TextView tvMealHours;
    private TextView tvMealMinute;
    private LinearLayout ll_food_group;
    private LinearLayout ll_food_group_point;
    private RecyclerView rvSummary;
    private MaterialEditText edValue;
    private QMUIAlphaTextView btnAdd10;
    private QMUIAlphaTextView btn7;
    private QMUIAlphaTextView btn8;
    private QMUIAlphaTextView btn9;
    private QMUIAlphaTextView btn4;
    private QMUIAlphaTextView btn5;
    private QMUIAlphaTextView btn6;
    private QMUIAlphaTextView btn1;
    private QMUIAlphaTextView btn2;
    private QMUIAlphaTextView btn3;
    private QMUIAlphaTextView btn0;
    private QMUIAlphaTextView btnClear;
    private QMUIAlphaTextView btnDelte;
    private QMUIAlphaTextView btnSure;
    private QMUIEmptyView mEmptyView;
    private ProgressBar progress;

    private Activity mContext;

    // 动画时长
    private final static int mAnimationDuration = 300;
    // 持有 ContentView，为了做动画
    private View mContentView;
    private boolean mIsAnimating = false;

    private QMUIPopup mTimePopup;

    private FoodSummaryAdapter mFoodSummaryAdapter;
    private List<FoodSummary> mFoodSummaryList = new ArrayList<>();

    /**
     * 交台時間
     */
    private List<Integer> mMealHours = new ArrayList<>();
    private List<Integer> mMealMinute = new ArrayList<>();

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

    /**
     * 餐種分頁相關
     */
    private ImageView[] ivPoints;
    private int mSummaryRow = 2;
    private int mSummaryCol = 3;
    private int mSummaryPageMax = mSummaryRow * mSummaryCol;
    private int mSummaryTotalPage;

    private FoodSummary mFoodSummary;

    public SkyOrderDialog(Activity context) {
        super(context, R.style.QMUI_BottomSheet);
        this.mContext = context;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //noinspection ConstantConditions
        getWindow().getDecorView().setPadding(0, 0, 0, 0);

        // 在底部，宽度撑满
        WindowManager.LayoutParams params = getWindow().getAttributes();
        params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        params.gravity = Gravity.BOTTOM | Gravity.CENTER;

        int screenWidth = QMUIDisplayHelper.getScreenWidth(getContext());
        int screenHeight = QMUIDisplayHelper.getScreenHeight(getContext());
        params.width = screenWidth < screenHeight ? screenWidth : screenHeight;
        getWindow().setAttributes(params);
        setCanceledOnTouchOutside(true);
    }

    @Override
    public void setContentView(int layoutResID) {
        mContentView = LayoutInflater.from(getContext()).inflate(layoutResID, null);
        super.setContentView(mContentView);
    }

    @Override
    public void setContentView(@NonNull View view, ViewGroup.LayoutParams params) {
        mContentView = view;
        super.setContentView(view, params);
    }

    public View getContentView() {
        return mContentView;
    }

    @Override
    public void setContentView(@NonNull View view) {
        mContentView = view;
        super.setContentView(view);
    }

    /**
     * BottomSheet升起动画
     */
    private void animateUp() {
        if (mContentView == null) {
            return;
        }
        TranslateAnimation translate = new TranslateAnimation(
                Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f,
                Animation.RELATIVE_TO_SELF, 1f, Animation.RELATIVE_TO_SELF, 0f
        );
        AlphaAnimation alpha = new AlphaAnimation(0, 1);
        AnimationSet set = new AnimationSet(true);
        set.addAnimation(translate);
        set.addAnimation(alpha);
        set.setInterpolator(new DecelerateInterpolator());
        set.setDuration(mAnimationDuration);
        set.setFillAfter(true);

        set.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                if (dialogAnimationListener != null) {
                    dialogAnimationListener.showAnimEnd();
                }
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        mContentView.startAnimation(set);
    }

    /**
     * BottomSheet降下动画
     */
    private void animateDown() {
        if (mContentView == null) {
            return;
        }
        TranslateAnimation translate = new TranslateAnimation(
                Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0f,
                Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 1f
        );
        AlphaAnimation alpha = new AlphaAnimation(1, 0);
        AnimationSet set = new AnimationSet(true);
        set.addAnimation(translate);
        set.addAnimation(alpha);
        set.setInterpolator(new DecelerateInterpolator());
        set.setDuration(mAnimationDuration);
        set.setFillAfter(true);
        set.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                mIsAnimating = true;
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                mIsAnimating = false;
                /**
                 * Bugfix： Attempting to destroy the window while drawing!
                 */
                mContentView.post(new Runnable() {
                    @Override
                    public void run() {
                        // java.lang.IllegalArgumentException: View=com.android.internal.policy.PhoneWindow$DecorView{22dbf5b V.E...... R......D 0,0-1080,1083} not attached to window manager
                        // 在dismiss的时候可能已经detach了，简单try-catch一下
                        try {
                            SkyOrderDialog.super.dismiss();
                        } catch (Exception e) {
                            QMUILog.w(TAG, "dismiss error\n" + Log.getStackTraceString(e));
                        }
                    }
                });
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        mContentView.startAnimation(set);
    }

    @Override
    public void show() {
        super.show();
        animateUp();
    }

    @Override
    public void dismiss() {
        if (mIsAnimating) {
            return;
        }
        animateDown();
    }

    public SkyOrderDialog build() {
        View contentView = buildViews();
        setContentView(contentView, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int) (QMUIDisplayHelper.getScreenHeight(mContext) * 0.8)));

        initRvSummaryAdapter();
        initCheckBoxListener();
        initMealTimeClickListener();

        addMealHours();
        return this;
    }

    private View buildViews() {
        View view = View.inflate(mContext, getContentViewLayoutId(), null);

        tv_table_name = view.findViewById(R.id.tv_table_name);
        cb_title = view.findViewById(R.id.cb_title);
        tvMealHours = view.findViewById(R.id.tv_meal_hours);
        tvMealMinute = view.findViewById(R.id.tv_meal_minute);
        ll_food_group = view.findViewById(R.id.ll_food_group);
        ll_food_group_point = view.findViewById(R.id.ll_food_group_point);
        rvSummary = view.findViewById(R.id.rv_summary);
        btn0 = view.findViewById(R.id.btn_0);
        btn1 = view.findViewById(R.id.btn_1);
        btn2 = view.findViewById(R.id.btn_2);
        btn3 = view.findViewById(R.id.btn_3);
        btn4 = view.findViewById(R.id.btn_4);
        btn5 = view.findViewById(R.id.btn_5);
        btn6 = view.findViewById(R.id.btn_6);
        btn7 = view.findViewById(R.id.btn_7);
        btn8 = view.findViewById(R.id.btn_8);
        btn9 = view.findViewById(R.id.btn_9);
        btnAdd10 = view.findViewById(R.id.btn_add10);
        btnClear = view.findViewById(R.id.btn_clear);
        btnDelte = view.findViewById(R.id.btn_delete);
        btnSure = view.findViewById(R.id.btn_sure);
        edValue = view.findViewById(R.id.ed_value);
        progress = view.findViewById(R.id.progress);
        mEmptyView = view.findViewById(R.id.emptyView);

        btn0.setOnClickListener(this);
        btn1.setOnClickListener(this);
        btn2.setOnClickListener(this);
        btn3.setOnClickListener(this);
        btn4.setOnClickListener(this);
        btn5.setOnClickListener(this);
        btn6.setOnClickListener(this);
        btn7.setOnClickListener(this);
        btn8.setOnClickListener(this);
        btn9.setOnClickListener(this);
        btnAdd10.setOnClickListener(this);
        btnClear.setOnClickListener(this);
        btnDelte.setOnClickListener(this);
        btnSure.setOnClickListener(this);
        return view;
    }

    private void initCheckBoxListener() {
        cb_title.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                SPUtils.put(SkyOrderConstant.check_status, isChecked);
                saveMealTime(isChecked);
            }
        });
    }

    private void initMealTimeClickListener() {
        tvMealHours.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showSelectTimePopup(tvMealHours, mMealHours);
            }
        });
        tvMealMinute.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showSelectTimePopup(tvMealMinute, mMealMinute);
            }
        });
    }

    /**
     * 初始化默認就餐時間
     *
     * @param foodSummary
     */
    public void initMealTime(FoodSummary foodSummary) {
        boolean lockedCheckState = (boolean) SPUtils.get(SkyOrderConstant.check_status, false);
        if (lockedCheckState) {
            String lockedHour = (String) SPUtils.get(SkyOrderConstant.delivery_time_hour, "");
            String lockedMinute = (String) SPUtils.get(SkyOrderConstant.delivery_time_minute, "");
            if (TextUtils.isEmpty(lockedHour) || TextUtils.isEmpty(lockedMinute)) {
                SPUtils.put(SkyOrderConstant.check_status, false);
                setDefaultMealTime(foodSummary);
            } else {
                setLockedMealTime(lockedHour, lockedMinute);
            }
        } else {
            setDefaultMealTime(foodSummary);
        }
        if (hourSelectPosition != -1) {
            tvMealHours.setText(String.valueOf(chooseMealTimes[0]));
        }
        if (minuteSelectPosition != -1) {
            if (chooseMealTimes[1] == 0) {
                tvMealMinute.setText(chooseMealTimes[1] + "0");
            } else {
                tvMealMinute.setText(String.valueOf(chooseMealTimes[1]));
            }
        }
        cb_title.setChecked(lockedCheckState);
    }

    /**
     * 設置已鎖定的交檯时间
     *
     * @param lockedHour
     * @param lockedMinute
     */
    private void setLockedMealTime(String lockedHour, String lockedMinute) {
        if (!TextUtils.isEmpty(lockedHour)) {
            chooseMealTimes[0] = Integer.parseInt(lockedHour);
        }
        if (!TextUtils.isEmpty(lockedMinute)) {
            chooseMealTimes[1] = Integer.parseInt(lockedMinute);
        }
        for (int i = 0; i < mMealHours.size(); i++) {
            if (chooseMealTimes.length > 0 && chooseMealTimes[0] == mMealHours.get(i)) {
                //找到当前选择的小时数下标
                hourSelectPosition = i;
                break;
            }
        }
        for (int j = 0; j < mMealMinute.size(); j++) {
            if (chooseMealTimes.length > 1 && chooseMealTimes[1] == mMealMinute.get(j)) {
                //找到当前选择的分钟数下标
                minuteSelectPosition = j;
                break;
            }
        }
    }

    /**
     * 交檯时间未锁定，给一个默认选中时间
     *
     * @param foodSummary
     */
    private void setDefaultMealTime(FoodSummary foodSummary) {
        /**
         * 设置默认小时数
         */
        long currentTimeMillis = System.currentTimeMillis();
        //设置默认交台时间为当前时间往后推多少分钟（可配置）
        long defaultMealLater = currentTimeMillis + (foodSummary.getDiningTime() * 60 * 1000);
        String defaultMealLaterTimes[] = TimeUtils.getStringByFormat(defaultMealLater, TimeUtils.DATE_FORMAT_DATE_HM).split(":");
        for (int i = 0; i < mMealHours.size(); i++) {
            int hour = mMealHours.get(i);
            if (hour == Integer.parseInt(defaultMealLaterTimes[0])) {
                //设置默认交檯小时数
                chooseMealTimes[0] = Integer.parseInt(defaultMealLaterTimes[0]);
                hourSelectPosition = i;
                break;
            }
        }
        if (hourSelectPosition == -1) {
            //未设置默认交檯时，默认选中下一个小时
            chooseMealTimes[0] = mMealHours.get(1);
            hourSelectPosition = 1;
        }

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

    /**
     * 更新餐種數據
     *
     * @param foodSummaryList
     */
    public void updateFoodSummaryList(List<FoodSummary> foodSummaryList) {
        if (mFoodSummaryList.size() == 0) {
            //設置默認選中的餐種
            setCurrentFoodSummary(getDefalutFoodSummary(foodSummaryList));
        } else {
            mFoodSummaryList.clear();
        }

        //总的页数向上取整
        mSummaryTotalPage = (int) Math.ceil(foodSummaryList.size() * 1.0 / mSummaryPageMax);
        setLayoutPagePoint(foodSummaryList, mSummaryTotalPage);

        mFoodSummaryList.addAll(foodSummaryList);
        mFoodSummaryAdapter.notifyDataSetChanged();
    }

    /**
     * 設置用餐時段
     */
    private void setCurrentFoodSummary(FoodSummary foodSummary) {
        if (foodSummary == null) {
            return;
        }
        mFoodSummary = foodSummary;
        initMealTime(foodSummary);
        updateSelectState(foodSummary);
    }

    /**
     * 添加用餐小時數
     */
    private void addMealHours() {
        if (mMealHours.size() > 0) {
            mMealHours.clear();
        }
        long currentTimeMillis = System.currentTimeMillis();
        //设置交檯时间（时）当前时间往后六小时
        currentTimes = TimeUtils.getStringByFormat(currentTimeMillis, TimeUtils.DATE_FORMAT_DATE_HM).split(":");
        int currentHour = Integer.parseInt(currentTimes[0]);
        for (int i = currentHour; i < currentHour + 7; i++) {
            mMealHours.add(i);
        }
    }

    /**
     * 添加用餐分鐘數
     */
    public void addMealMinutes(List<Integer> mealMinute) {
        if (mealMinute == null) {
            return;
        }
        if (mMealMinute.size() > 0) {
            mMealMinute.clear();
        }
        mMealMinute.addAll(mealMinute);
    }

    /**
     * 更新餐種選中狀態
     *
     * @param foodSummary
     */
    private void updateSelectState(FoodSummary foodSummary) {
        if (mFoodSummaryList != null) {
            initSelectedStatus(mFoodSummaryList);
        }
        foodSummary.setSelected(true);
        mFoodSummaryAdapter.notifyDataSetChanged();
    }

    /**
     * 獲取默認選中的餐種
     *
     * @param foodSummaryList
     * @return
     */
    private FoodSummary getDefalutFoodSummary(List<FoodSummary> foodSummaryList) {
        for (FoodSummary foodSummary : foodSummaryList) {
            if (foodSummary.isDefault()) {
                return foodSummary;
            }
        }
        return foodSummaryList.get(0);
    }

    /**
     * 初始化默認選中
     *
     * @param foodSummaryList
     */
    private void initSelectedStatus(List<FoodSummary> foodSummaryList) {
        for (FoodSummary foodSummary : foodSummaryList) {
            foodSummary.setSelected(false);
        }
    }

    private void saveMealTime(boolean isChecked) {
        if (isChecked) {
            SPUtils.put(SkyOrderConstant.delivery_time_hour, String.valueOf(chooseMealTimes[0]));
            if (chooseMealTimes[1] == 0) {
                SPUtils.put(SkyOrderConstant.delivery_time_minute, chooseMealTimes[1] + "0");
            } else {
                SPUtils.put(SkyOrderConstant.delivery_time_minute, String.valueOf(chooseMealTimes[1]));
            }
        } else {
            SPUtils.put(SkyOrderConstant.delivery_time_hour, "");
            SPUtils.put(SkyOrderConstant.delivery_time_minute, "");
        }
        SPUtils.put(SkyOrderConstant.check_status, isChecked);
    }

    private void initRvSummaryAdapter() {
        mFoodSummaryAdapter = new FoodSummaryAdapter(mFoodSummaryList);
        rvSummary.setAdapter(mFoodSummaryAdapter);
        mFoodSummaryAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                setCurrentFoodSummary(mFoodSummaryList.get(position));
            }
        });

        PagerGridLayoutManager layoutManager = new PagerGridLayoutManager(mSummaryRow, mSummaryCol, PagerGridLayoutManager.HORIZONTAL);
        // 水平分页布局管理器
        layoutManager.setPageListener(this);
        //设置页面变化监听器
        rvSummary.setLayoutManager(layoutManager);

        // 设置滚动辅助工具
        PagerGridSnapHelper pageSnapHelper = new PagerGridSnapHelper();
        pageSnapHelper.attachToRecyclerView(rvSummary);
    }

    /**
     * 設置餐種分頁碼
     *
     * @param list
     * @param totalPage
     */
    private void setLayoutPagePoint(List<?> list, int totalPage) {
        ivPoints = new ImageView[totalPage];
        for (int i = 0; i < totalPage; i++) {
            //循坏加入点点图片组
            ivPoints[i] = new ImageView(mContext);
            if (i == 0) {
                ivPoints[i].setImageResource(R.drawable.base_recycler_bottom_radius5_focuese);
            } else {
                ivPoints[i].setImageResource(R.drawable.base_recycler_bottom_radius5_unfocused);
            }
            ivPoints[i].setPadding(10, 0, 0, 0);
            ll_food_group_point.addView(ivPoints[i]);
        }
        if (list.size() > mSummaryPageMax) {
            ll_food_group_point.setVisibility(View.VISIBLE);
        } else {
            ll_food_group_point.setVisibility(View.GONE);
        }
    }

    private FlexboxLayoutManager createLayoutManager() {
        FlexboxLayoutManager flexboxLayoutManager = new FlexboxLayoutManager(mContext);
        //flexDirection 属性决定主轴的方向（即项目的排列方向）。类似 LinearLayout 的 vertical 和 horizontal。
        flexboxLayoutManager.setFlexDirection(FlexDirection.ROW);//主轴为水平方向，起点在左端。
        //flexWrap 默认情况下 Flex 跟 LinearLayout 一样，都是不带换行排列的，但是flexWrap属性可以支持换行排列。
        flexboxLayoutManager.setFlexWrap(FlexWrap.WRAP);//按正常方向换行
        //justifyContent 属性定义了项目在主轴上的对齐方式。
        flexboxLayoutManager.setJustifyContent(JustifyContent.FLEX_START);//交叉轴的起点对齐。
        return flexboxLayoutManager;
    }

    private void showSelectTimePopup(TextView textView, List<Integer> text) {
        List<Map<String, Object>> lists = new ArrayList<>();
        for (int i = 0; i < text.size(); i++) {
            Map<String, Object> map = new HashMap<>();
            if (text.get(i) == 0) {
                map.put("text", text.get(i) + "0");
            } else {
                map.put("text", String.valueOf(text.get(i)));
            }
            lists.add(map);
        }
        SimpleAdapter adapter = new SimpleAdapter(mContext, lists, R.layout.table_item_skyorder_meal_lenght
                , new String[]{"text"}
                , new int[]{R.id.tv_name});
        mTimePopup = QMUIPopups.listPopup(mContext, QMUIDisplayHelper.getScreenWidth(mContext) / 3, QMUIDisplayHelper.getScreenHeight(mContext), adapter, new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                int viewId = textView.getId();
                if (viewId == R.id.tv_meal_hours) {
                    chooseMealTimes[0] = mMealHours.get(position);
                } else if (viewId == R.id.tv_meal_minute) {
                    chooseMealTimes[1] = mMealMinute.get(position);
                }

                boolean lockedCheckState = (boolean) SPUtils.get(SkyOrderConstant.check_status, false);
                saveMealTime(lockedCheckState);

                textView.setText(lists.get(position).get("text").toString());

                mTimePopup.dismiss();
            }
        }).show(textView);
    }

    public void setTvTableName(String tableName) {
        tv_table_name.setText(tableName);
    }

    public void showEmptyView(boolean isSuccess, int size, Throwable t) {
        showEmptyView(isSuccess, size, t, mEmptyView, rvSummary);
    }

    public void setProgressVisibility(boolean show) {
        progress.setVisibility(show ? View.VISIBLE : View.INVISIBLE);
    }

    private String getInputPeopleNum() {
        return edValue.getText().toString();
    }

    protected int getContentViewLayoutId() {
        return R.layout.table_dialog_skyorder;
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();

        if (id == R.id.btn_1 || id == R.id.btn_2 || id == R.id.btn_3 || id == R.id.btn_4 || id == R.id.btn_5 ||
                id == R.id.btn_6 || id == R.id.btn_7 || id == R.id.btn_8 || id == R.id.btn_9 || id == R.id.btn_add10 || id == R.id.btn_0 ||
                id == R.id.btn_clear || id == R.id.btn_delete || id == R.id.btn_sure) {

            String value = edValue.getText().toString();

            int i = Integer.parseInt(v.getTag().toString());
            switch (i) {
                case 0:
                case 1:
                case 2:
                case 3:
                case 4:
                case 5:
                case 6:
                case 7:
                case 8:
                case 9:
                    edValue.setText(String.valueOf(i));
                    break;
                case 99: //+10
                    if (!TextUtils.isEmpty(value)) {
                        edValue.setText(String.valueOf(Integer.parseInt(value) + 10));
                    } else {
                        edValue.setText(String.valueOf(i));
                    }
                    break;
                case 98: //×
                    if (!TextUtils.isEmpty(value)) {
                        edValue.setText("");
                    }
                    break;
                case 97:  //√
                    if (callbackListener != null && printCondtion()) {
                        int person = Integer.parseInt(getInputPeopleNum());
                        String endTime = TimeUtils.getCurrentDate(TimeUtils.DATE_FORMAT_DATE) + " " + chooseMealTimes[0] + ":" + chooseMealTimes[1] + ":00";
                        callbackListener.onPrint(mFoodSummary, person, endTime);
                    }
                    break;
                case 58: //clear
                    if (!TextUtils.isEmpty(value)) {
                        edValue.setText("");
                    }
                    break;
                default:
                    break;
            }
        }
    }

    private boolean printCondtion() {
        if (TextUtils.isEmpty(getInputPeopleNum())) {
            ArmsUtils.makeText(mContext, LanguageUtils.get_language_system(mContext, "input.number", "請輸入人數"));
            return false;
        }
        String endTime = chooseMealTimes[0] + ":" + chooseMealTimes[1];
        if (TextUtils.isEmpty(endTime)) {
            ArmsUtils.makeText(mContext, LanguageUtils.get_language_system(mContext, "please.choose.time.delivery", "請選擇交檯時間"));
            return false;
        }
        if (mFoodSummary == null) {
            ArmsUtils.makeText(mContext, LanguageUtils.get_language_system(mContext, "please.choose.meal", "請選擇餐種"));
            return false;
        }
        return true;
    }

    private OnCallbackListener callbackListener;

    public void setCallbackListener(OnCallbackListener callbackListener) {
        this.callbackListener = callbackListener;
    }

    @Override
    public void onPageSizeChanged(int pageSize) {

    }

    @Override
    public void onPageSelect(int pageIndex) {
        if (ivPoints == null) {
            return;
        }
        for (int i = 0; i < mSummaryTotalPage; i++) {
            if (i == pageIndex) {
                ivPoints[i].setImageResource(R.drawable.base_recycler_bottom_radius5_focuese);
            } else {
                ivPoints[i].setImageResource(R.drawable.base_recycler_bottom_radius5_unfocused);
            }
            ivPoints[i].setPadding(10, 0, 0, 0);
        }
    }

    public interface OnCallbackListener {
        void onPrint(FoodSummary foodSummary, int person, String endTime);
    }
}
