package com.ihaoin.hooloo.device.view;

import android.app.Presentation;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Display;
import android.widget.GridView;
import android.widget.ImageView;

import androidx.annotation.NonNull;

import com.bumptech.glide.Glide;
import com.fasterxml.jackson.core.type.TypeReference;
import com.ihaoin.hooloo.device.HLApplication;
import com.ihaoin.hooloo.device.R;
import com.ihaoin.hooloo.device.adapter.OrderAdapter;
import com.ihaoin.hooloo.device.component.NetworkHandler;
import com.ihaoin.hooloo.device.component.PushMessageReceiver;
import com.ihaoin.hooloo.device.config.Base;
import com.ihaoin.hooloo.device.data.MainData;
import com.ihaoin.hooloo.device.data.enums.ImageState;
import com.ihaoin.hooloo.device.data.enums.OrderState;
import com.ihaoin.hooloo.device.data.vo.Order;
import com.ihaoin.hooloo.device.data.vo.OrderPkg;
import com.ihaoin.hooloo.device.network.HttpUtil;
import com.ihaoin.hooloo.device.util.CollectionUtils;
import com.ihaoin.hooloo.device.util.JsonUtils;
import com.ihaoin.hooloo.device.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class MenuPresentation extends Presentation {

    private List<OrderPkg> pkgs;
    private LoadOrdersHandler loadOrdersHandler;
    private OrderStateChangeHandler orderStateChangeHandler;

    private List<Order> cookingOrders;
    private List<Order> waitingOrders;
    private List<Order> completedOrders;

    private ImageView imgLeft;
    private ImageView imgRight;
    private GridView gridCooking;
    private GridView gridWaiting;
    private GridView gridCompleted;
    private OrderAdapter cookingAdapter;
    private OrderAdapter waitingAdapter;
    private OrderAdapter completedAdapter;

    public MenuPresentation(Context outerContext, Display display) {
        super(outerContext, display);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_menu);

        initViews();
        loadDatas();
    }


    private void initViews() {
        imgLeft = findViewById(R.id.img_left);
        imgRight = findViewById(R.id.img_right);
        gridCooking = findViewById(R.id.grid_cooking);
        gridWaiting = findViewById(R.id.grid_waiting);
        gridCompleted = findViewById(R.id.grid_completed);

        cookingAdapter = new OrderAdapter(getContext());
        waitingAdapter = new OrderAdapter(getContext());
        completedAdapter = new OrderAdapter(getContext());

        gridCooking.setAdapter(cookingAdapter);
        gridWaiting.setAdapter(waitingAdapter);
        gridCompleted.setAdapter(completedAdapter);
    }

    private String getRightImage(String state) {
        MainData mainData = HLApplication.getMainData();
        if (mainData == null || mainData.getImages() == null) {
            return null;
        }
        if (CollectionUtils.isEmpty(mainData.getImages().getRight())) {
            return null;
        }
        return mainData.getImages().getRight().get(state);
    }

    private void showImages() {
        MainData mainData = HLApplication.getMainData();
        if (mainData == null || mainData.getImages() == null) {
            return;
        }
        if (!StringUtils.isEmpty(mainData.getImages().getLeft())) {
            Glide.with(getContext()).load(mainData.getImages().getLeft()).into(imgLeft);
        }

        if (mainData.getShopState().equals(0)) {
            Glide.with(getContext()).load(getRightImage(ImageState.CLOSED.getCode())).into(imgRight);
        } else if (!CollectionUtils.isEmpty(cookingOrders)) {
            Glide.with(getContext()).load(getRightImage(ImageState.COOKING.getCode())).into(imgRight);
        } else if (!CollectionUtils.isEmpty(completedOrders)) {
            Glide.with(getContext()).load(getRightImage(ImageState.COMPLETED.getCode())).into(imgRight);
        } else {
            Glide.with(getContext()).load(getRightImage(ImageState.NOT_COMPLETED.getCode())).into(imgRight);
        }
    }

    public void mainDataChanged() {
        showImages();
    }

    private void loadDatas() {
        loadOrdersHandler = new LoadOrdersHandler();
        HttpUtil.getOrders(loadOrdersHandler);
    }

    private void setDatas(String json) {
        try {
            pkgs = JsonUtils.getMapper().readValue(json, new TypeReference<List<OrderPkg>>() {
            });
            orderDataChanged();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void orderDataChanged() {
        cookingOrders = getOrders(OrderState.COOKING.getCode());
        waitingOrders = getOrders(OrderState.WAITING.getCode());
        completedOrders = getOrders(OrderState.COMPLETED.getCode());

        cookingAdapter.setOrders(cookingOrders);
        waitingAdapter.setOrders(waitingOrders);
        completedAdapter.setOrders(completedOrders);

        cookingAdapter.notifyDataSetChanged();
        waitingAdapter.notifyDataSetChanged();
        completedAdapter.notifyDataSetChanged();

        showImages();
        regsitOrderChangeListener();
    }

    private void regsitOrderChangeListener() {
        orderStateChangeHandler = new OrderStateChangeHandler();
        PushMessageReceiver.subscribe(Base.PUSH_ACTION_ORDER_STATE_CHANGED, orderStateChangeHandler);
    }

    private List<Order> getOrders(Integer state) {
        if (CollectionUtils.isEmpty(pkgs)) {
            return null;
        }
        Map<Integer, OrderPkg> map = pkgs.stream().collect(Collectors.toMap(OrderPkg::getState, Function.identity()));
        if (CollectionUtils.isEmpty(map)) {
            return null;
        }
        OrderPkg pkg = map.get(state);
        if (pkg == null) {
            return null;
        }
        return pkg.getOrders();
    }

    class LoadOrdersHandler extends NetworkHandler {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what != 1) {
                return;
            }
            String body = "[{\"state\":1,\"desc\":\"制作中\",\"orders\":[{\"orderId\":1011,\"orderNo\":\"N20220220A19231\",\"orderNumber\":\"Mon101\"},{\"orderId\":1012,\"orderNo\":\"N20220220A19232\",\"orderNumber\":\"Mon102\"},{\"orderId\":1013,\"orderNo\":\"N20220220A19233\",\"orderNumber\":\"Mon103\"}]},{\"state\":2,\"desc\":\"待制作\",\"orders\":[{\"orderId\":1014,\"orderNo\":\"N20220220A19234\",\"orderNumber\":\"Mon104\"},{\"orderId\":1015,\"orderNo\":\"N20220220A19235\",\"orderNumber\":\"Mon105\"},{\"orderId\":1016,\"orderNo\":\"N20220220A19236\",\"orderNumber\":\"Mon106\"},{\"orderId\":1017,\"orderNo\":\"N20220220A19237\",\"orderNumber\":\"Mon107\"},{\"orderId\":1018,\"orderNo\":\"N20220220A19238\",\"orderNumber\":\"Mon108\"}]},{\"state\":3,\"desc\":\"可取餐\",\"orders\":[{\"orderId\":1019,\"orderNo\":\"N20220220A19239\",\"orderNumber\":\"Mon109\"},{\"orderId\":1001,\"orderNo\":\"N20220220A19221\",\"orderNumber\":\"Mon121\"},{\"orderId\":1002,\"orderNo\":\"N20220220A19222\",\"orderNumber\":\"Mon122\"},{\"orderId\":1003,\"orderNo\":\"N20220220A19223\",\"orderNumber\":\"Mon123\"},{\"orderId\":1004,\"orderNo\":\"N20220220A19224\",\"orderNumber\":\"Mon124\"},{\"orderId\":1005,\"orderNo\":\"N20220220A19241\",\"orderNumber\":\"Mon141\"},{\"orderId\":1006,\"orderNo\":\"N20220220A19251\",\"orderNumber\":\"Mon151\"}]}]";
//            setDatas(msg.obj.toString());
            setDatas(body);
        }
    }

    class OrderStateChangeHandler extends Handler {
        @Override
        public void handleMessage(@NonNull Message msg) {
            try {
                super.handleMessage(msg);
                if (msg.obj == null) {
                    return;
                }
                String msgBody = msg.obj.toString();
                if (StringUtils.isEmpty(msgBody)) {
                    return;
                }

                Order order = JsonUtils.getMapper().readValue(msgBody, Order.class);
                if (order == null || order.getState() == null || order.getOrderId() == null || order.getOrderId() <= 0
                        || StringUtils.isEmpty(order.getOrderNo()) || StringUtils.isEmpty(order.getOrderNumber())) {
                    return;
                }

                if (CollectionUtils.isEmpty(pkgs)) {
                    OrderState state = OrderState.get(order.getState());
                    if (state == null) {
                        return;
                    }
                    pkgs = new ArrayList<>();

                    List<Order> orders = new ArrayList<>();
                    orders.add(order);
                    OrderPkg pkg = new OrderPkg();
                    pkg.setState(order.getState());
                    pkg.setOrders(orders);
                    pkgs.add(pkg);
                } else {
                    // 删除订单
                    pkgs.forEach(pkg -> {
                        if (CollectionUtils.isEmpty(pkg.getOrders())) {
                            return;
                        }
                        pkg.getOrders().remove(order);
                    });

                    OrderState state = OrderState.get(order.getState());
                    if (state == null) {
                        return;
                    }
                    // 添加新订单状态
                    pkgs.forEach(pkg -> {
                        if (!pkg.getState().equals(order.getState())) {
                            return;
                        }
                        List<Order> orders = pkg.getOrders();
                        if (CollectionUtils.isEmpty(orders)) {
                            orders = new ArrayList<>();
                        }
                        orders.add(order);
                        pkg.setOrders(orders);
                    });
                }

                orderDataChanged();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
