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.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.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
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.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.widget.dialog.BaseRetryDialog;
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 {

    private static final String TAG = "SkyOrderDialog";
    AppCompatCheckBox cb_title;
    TextView tvStartTime;
    TextView tvEndTime;
    RecyclerView rvSummary;
    MaterialEditText edValue;
    QMUIAlphaTextView btnAdd10;
    QMUIAlphaTextView btn7;
    QMUIAlphaTextView btn8;
    QMUIAlphaTextView btn9;
    QMUIAlphaTextView btn4;
    QMUIAlphaTextView btn5;
    QMUIAlphaTextView btn6;
    QMUIAlphaTextView btn1;
    QMUIAlphaTextView btn2;
    QMUIAlphaTextView btn3;
    QMUIAlphaTextView btn0;
    QMUIAlphaTextView btnClear;
    QMUIAlphaTextView btnDelte;
    QMUIAlphaTextView btnSure;
    QMUIEmptyView mEmptyView;
    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> mDeliveryHours = new ArrayList<>();
    private List<Integer> mDeliveryMinute = new ArrayList<>();

    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;


    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);
        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.75)));

        initRvSummaryAdapter();
        initCheckBoxListener();
        initDeliveryTimeClickListener();
        return this;
    }

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

        cb_title = view.findViewById(R.id.cb_title);
        tvStartTime = view.findViewById(R.id.tv_start_time);
        tvEndTime = view.findViewById(R.id.tv_end_time);
        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) {
                if (callbackListener != null) {
                    callbackListener.lockState(isChecked);
                }
                SPUtils.put(SkyOrderConstant.check_status, isChecked);
            }
        });

    }

    private void initDeliveryTimeClickListener() {
        String[] startTextList = new String[]{
                "10",
                "11",
                "12",
                "14",
                "15",
                "16",
        };
        String[] endTextList = new String[]{
                "10",
                "20",
                "30",
                "40",
                "50",
                "55",
        };
        tvStartTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showSelectTimePopup(tvStartTime, startTextList);
            }
        });
        tvEndTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showSelectTimePopup(tvEndTime, endTextList);
            }
        });
    }

    public void initDeliveryHourTime(FoodSummary foodSummary) {

        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++) {
            mDeliveryHours.add(i);
        }

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

        if (lockedCheckState) {
            //交檯时间已锁定
            setLockedDeliveryTime();
        } else {
            //交檯时间未锁定，给一个默认选中时间
//            setDefaultDeliveryTime(foodSummary);
        }
    }

    private void setLockedDeliveryTime() {
        String lockedHour = (String) SPUtils.get(SkyOrderConstant.delivery_time_hour, "");
        String lockedMinute = (String) SPUtils.get(SkyOrderConstant.delivery_time_minute, "");
        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(FoodSummary foodSummary) {
        /**
         * 设置默认小时数
         */
        long currentTimeMillis = System.currentTimeMillis();
        //设置默认交台时间为当前时间往后推多少分钟（可配置）
        long defaultDeliveryLater = currentTimeMillis + (foodSummary.getMealLength() * 60 * 1000);
        String defaultDeliveryLaterTimes[] = TimeUtils.getStringByFormat(defaultDeliveryLater, TimeUtils.DATE_FORMAT_DATE_HM).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;
            }
        }
    }

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

    /**
     * 設置用餐時段
     */
    private void setFoodSummaryTime(FoodSummary foodSummary) {
        if (foodSummary == null) {
            return;
        }
        if (mFoodSummaryList != null) {
            initSelectedStatus(mFoodSummaryList);
        }
        initDeliveryHourTime(foodSummary);

        foodSummary.setSelected(true);
        mFoodSummaryAdapter.notifyDataSetChanged();
    }


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

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


    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) {
                setFoodSummaryTime(mFoodSummaryList.get(position));
            }
        });
        RecyclerView.LayoutManager layoutManager = createLayoutManager();
        rvSummary.setLayoutManager(layoutManager);
    }

    private RecyclerView.LayoutManager createLayoutManager() {
        return new GridLayoutManager(mContext, 4, LinearLayoutManager.VERTICAL, false) {
            @Override
            public RecyclerView.LayoutParams generateDefaultLayoutParams() {
                return new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            }
        };
    }

    private void showSelectTimePopup(TextView textView, String[] text) {
        List<Map<String, Object>> lists = new ArrayList<>();
        for (int i = 0; i < text.length; i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("text", text[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) {

                boolean lockedCheckState = (boolean) SPUtils.get(SkyOrderConstant.check_status, false);
                if (lockedCheckState) {
                    SPUtils.put(SkyOrderConstant.delivery_time_hour, String.valueOf(chooseDeliveryTimes[0]));
                    SPUtils.put(SkyOrderConstant.delivery_time_minute, String.valueOf(chooseDeliveryTimes[1]));
                } else {
                    SPUtils.put(SkyOrderConstant.delivery_time_hour, "");
                    SPUtils.put(SkyOrderConstant.delivery_time_minute, "");
                }
                SPUtils.put(SkyOrderConstant.check_status, lockedCheckState);

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

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

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

    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:
                    if (!TextUtils.isEmpty(value)) {
                        edValue.setText(value + i);
                    } else {
                        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) {
                        callbackListener.onPrint();
                    }
                    break;
                case 58: //clear
                    if (!TextUtils.isEmpty(value)) {
                        edValue.setText("");
                    }
                    break;
                default:
                    break;
            }
        }
    }

    private OnCallbackListener callbackListener;

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

    public interface OnCallbackListener {
        void lockState(boolean state);

        void onPrint();
    }
}
