package com.gingersoft.gsa.delivery_pick_mode.mvp.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.Group;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gingersoft.gsa.cloud.base.order.bean.BillOrderMoney;
import com.gingersoft.gsa.cloud.base.order.bean.OrderDetail;
import com.gingersoft.gsa.cloud.base.order.bean.mealManger.MyOrderManage;
import com.gingersoft.gsa.cloud.base.utils.other.TextUtil;
import com.gingersoft.gsa.cloud.base.utils.time.TimePickerUtils;
import com.gingersoft.gsa.cloud.base.utils.time.TimeUtils;
import com.gingersoft.gsa.cloud.print.bean.OrderDetails;
import com.gingersoft.gsa.cloud.ui.adapter.ListSelectAdapter;
import com.gingersoft.gsa.cloud.ui.widget.dialog.LoadingDialog;
import com.gingersoft.gsa.delivery_pick_mode.R;
import com.gingersoft.gsa.delivery_pick_mode.R2;
import com.gingersoft.gsa.delivery_pick_mode.data.model.bean.BillBean;
import com.gingersoft.gsa.delivery_pick_mode.di.component.DaggerSendOrderComponent;
import com.gingersoft.gsa.delivery_pick_mode.mvp.contract.SendOrderContract;
import com.gingersoft.gsa.delivery_pick_mode.mvp.model.MemberAddressInfoBean;
import com.gingersoft.gsa.delivery_pick_mode.mvp.presenter.SendOrderPresenter;
import com.gingersoft.gsa.delivery_pick_mode.ui.adapter.FoodListAdapter;
import com.gingersoft.gsa.delivery_pick_mode.ui.adapter.PayBillAdapter;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.qmuiteam.qmui.widget.popup.QMUIPopup;
import com.qmuiteam.qmui.widget.popup.QMUIPopups;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.jess.arms.utils.Preconditions.checkNotNull;

/**
 * @author admin
 */
public class SendOrderActivity extends BaseActivity<SendOrderPresenter> implements SendOrderContract.View, View.OnClickListener {


    @BindView(R2.id.send_order_top_bar)
    QMUITopBar sendOrderTopBar;
    @BindView(R2.id.rv_send_order_foods)
    RecyclerView rvSendOrderFoods;
    @BindView(R2.id.rv_send_order_bills)
    RecyclerView rvSendOrderBills;
    @BindView(R2.id.tv_send_order_name_text)
    TextView tvSendOrderNameText;
    @BindView(R2.id.ed_send_order_name)
    EditText edSendOrderName;
    @BindView(R2.id.iv_select_member_arrow)
    ImageView ivSelectMemberArrow;
    @BindView(R2.id.tv_send_order_phone_text)
    TextView tvSendOrderPhoneText;
    @BindView(R2.id.ed_send_order_phone)
    EditText edSendOrderPhone;
    @BindView(R2.id.tv_send_order_address_text)
    TextView tvSendOrderAddressText;
    @BindView(R2.id.ed_send_order_address)
    EditText edSendOrderAddress;
    @BindView(R2.id.iv_select_address_arrow)
    ImageView ivSelectAddressArrow;
    @BindView(R2.id.tv_send_order_distribution_mode_text)
    TextView tvSendOrderDistributionModeText;
    @BindView(R2.id.rg_send_order_distribution_mode)
    RadioGroup rgSendOrderDistributionMode;
    @BindView(R2.id.tv_send_order_pay_mode_text)
    TextView tvSendOrderPayModeText;
    @BindView(R2.id.rg_send_order_pay_mode)
    RadioGroup rgSendOrderPayMode;
    @BindView(R2.id.tv_send_order_delivery_time_text)
    TextView tvSendOrderDeliveryTimeText;
    @BindView(R2.id.tv_delivery_time_type)
    TextView tvDeliveryTimeType;
    @BindView(R2.id.iv_select_delivery_time)
    ImageView ivSelectDeliveryTime;
    @BindView(R2.id.tv_delivery_time_hour)
    TextView tvDeliveryTimeHour;
    @BindView(R2.id.tv_delivery_time_colon)
    TextView tvDeliveryTimeColon;
    @BindView(R2.id.tv_delivery_time_min)
    TextView tvDeliveryTimeMin;
    @BindView(R2.id.tv_continue_add_food)
    TextView tvContinueAddFood;
    @BindView(R2.id.tv_confirm_order)
    TextView tvConfirmOrder;
    @BindView(R2.id.layout_btn)
    LinearLayout layoutBtn;
    @BindView(R2.id.view_delivery_time_mode_line)
    View deliveryTimeLine;
    @BindView(R2.id.group_time)
    Group timeGroup;

    private final int SELECT_ADDRESS_REQUEST_CODE = 1001;
    private final int SELECT_ADDRESS_RESULT_CODE = 1002;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerSendOrderComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.other_order_activity_send_order;
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        sendTime = deliveryTimes.get(0);
        List<OrderDetails.DataBean.PRODUCTNAMEBean> productnameBeans = mPresenter.productnameBeans;
        List<OrderDetail> orderDetails = MyOrderManage.getInstance().getOrderFoodList();
        for (int i = 0; i < orderDetails.size(); i++) {
            OrderDetail orderDetail = orderDetails.get(i);
            long foodId = orderDetail.getProductId();
            OrderDetails.DataBean.PRODUCTNAMEBean productnameBean = orderDetailTranProductnameBean(orderDetail);
            if (i + 1 < orderDetails.size() && orderDetails.get(i + 1).getItemType() != 1
                    && orderDetails.get(i + 1).getParentId() == orderDetail.getProductId()) {
                List<OrderDetails.DataBean.PRODUCTNAMEBean.ChildBeanX> childBeanXList = new ArrayList<>();
                OrderDetails.DataBean.PRODUCTNAMEBean.ChildBeanX childBeanX = new OrderDetails.DataBean.PRODUCTNAMEBean.ChildBeanX();
                //如果下一個食品的父級id是當前食品的id
                for (int j = i + 1; j < orderDetails.size(); j++) {
                    OrderDetail secondOrderDetail = orderDetails.get(j);
                    if (secondOrderDetail.getParentId() == foodId) {
                        long secondFoodId = secondOrderDetail.getProductId();
                        //當前食品是orderDetail的子食品，遍歷後面的食品是不是當前食品的子食品（三級子食品）
                        if (j + 1 < orderDetails.size() && orderDetails.get(j + 1).getItemType() != 1
                                && orderDetails.get(j + 1).getItemType() != 2
                                && orderDetails.get(j + 1).getParentId() == secondFoodId) {
                            List<OrderDetails.DataBean.PRODUCTNAMEBean.ChildBeanX.ChildBean> childBeans = new ArrayList<>();
                            OrderDetails.DataBean.PRODUCTNAMEBean.ChildBeanX.ChildBean childBean = new OrderDetails.DataBean.PRODUCTNAMEBean.ChildBeanX.ChildBean();
                            for (int k = 0; k < orderDetails.size(); k++) {
                                OrderDetail thirdOrderDetail = orderDetails.get(j);
                                if (thirdOrderDetail.getParentId() == secondFoodId) {
                                    childBean.setPRODUCT_NAME(thirdOrderDetail.getProductName());
                                    childBean.setNum(thirdOrderDetail.getNumber() + "");
                                    childBean.setOdsId(thirdOrderDetail.getProductId() + "");
                                    childBean.setPid(thirdOrderDetail.getParentId() + "");
                                    childBean.setPRICE(thirdOrderDetail.getPrice() + "");
                                    childBean.setLunchboxPrice(thirdOrderDetail.getLunchboxPrice());
                                    childBeans.add(childBean);
                                    j = k;
                                } else {
                                    j = k - 1;
                                    break;
                                }
                            }
                            childBeanX.setChild(childBeans);
                        } else {
                            childBeanX.setPRODUCT_NAME(secondOrderDetail.getProductName());
                            childBeanX.setNum(secondOrderDetail.getNumber() + "");
                            childBeanX.setPRICE(secondOrderDetail.getPrice() + "");
                            childBeanX.setOdsId(secondOrderDetail.getProductId() + "");
                            childBeanX.setPid(secondOrderDetail.getParentId() + "");
                            childBeanX.setLunchboxPrice(secondOrderDetail.getLunchboxPrice());
                            childBeanXList.add(childBeanX);
                            i = j;
                        }
                    } else {
                        i = j - 1;
                        break;
                    }
                }
                productnameBean.setChild(childBeanXList);
            }
            productnameBeans.add(productnameBean);
        }
        FoodListAdapter adapter = new FoodListAdapter(mContext, productnameBeans);
        rvSendOrderFoods.setAdapter(adapter);
        rvSendOrderFoods.setLayoutManager(new LinearLayoutManager(mContext));

        List<BillOrderMoney> orderMoneyList = MyOrderManage.getInstance().getOrderMoneyList();
        List<BillBean> billBeans = new ArrayList<>();
        for (BillOrderMoney billOrderMoney : orderMoneyList) {
            BillBean billBean = new BillBean();
            billBean.setName(billOrderMoney.getTitle());
            billBean.setAmount(billOrderMoney.getMoney());
        }
        billBeans.add(new BillBean("合計：", MyOrderManage.getInstance().getWholeAmount(), 0));
        billBeans.add(new BillBean("應付金額：", MyOrderManage.getInstance().getTotalAmount(), 0));

        PayBillAdapter payBillAdapter = new PayBillAdapter(R.layout.item_pay_bill, billBeans);
        rvSendOrderBills.setAdapter(payBillAdapter);
        rvSendOrderBills.setLayoutManager(new LinearLayoutManager(mContext));
    }

    private OrderDetails.DataBean.PRODUCTNAMEBean orderDetailTranProductnameBean(OrderDetail orderDetail) {
        OrderDetails.DataBean.PRODUCTNAMEBean productnameBean = new OrderDetails.DataBean.PRODUCTNAMEBean();
        productnameBean.setPRODUCT_NAME(orderDetail.getProductName());
        productnameBean.setNum(orderDetail.getNumber() + "");
        productnameBean.setPRICE(orderDetail.getPrice() + "");
        return productnameBean;
    }

    @Override
    public void initIntent() {

    }

    @Override
    public void initTopBar() {
        sendOrderTopBar.setTitle("送單信息");
        sendOrderTopBar.setBackgroundColor(ContextCompat.getColor(this, R.color.theme_color));
        sendOrderTopBar.addLeftImageButton(R.drawable.icon_return, R.id.iv_left_back).setOnClickListener(v -> killMyself());
    }

    @Override
    public void initLanguage() {

    }

    @Override
    public void initLayoutParams() {

    }

    @Override
    public void initLayoutVisible() {

    }

    @Override
    public void showLoading(String message) {
        if (message != null) {
            LoadingDialog.showDialogForLoading(this, message, true);
        } else {
            LoadingDialog.showDialogForLoading(this);
        }
    }

    @Override
    public void hideLoading() {
        LoadingDialog.cancelDialogForLoading();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(this, message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    private QMUIPopup popup;
    private ListSelectAdapter listSelectAdapter;
    private int select = 0;
    private List<String> deliveryTimes = Arrays.asList("現在送出", "其他時間");
    private String sendTime;

    @OnClick({R2.id.iv_select_member_arrow, R2.id.iv_select_address_arrow, R2.id.tv_continue_add_food, R2.id.iv_send_order_search, R2.id.tv_delivery_time_hour, R2.id.tv_delivery_time_min, R2.id.tv_delivery_time_type, R2.id.iv_select_delivery_time, R2.id.tv_confirm_order})
    @Override
    public void onClick(View v) {
        int viewId = v.getId();
        if (viewId == R.id.tv_delivery_time_type || viewId == R.id.iv_select_delivery_time) {
            switchDeliveryTimeMode();
        } else if (viewId == R.id.tv_confirm_order) {
            if (TextUtil.isNotEmptyOrNullOrUndefined(edSendOrderName)) {
                if (TextUtil.isNotEmptyOrNullOrUndefined(edSendOrderPhone)) {
                    if (TextUtil.isNotEmptyOrNullOrUndefined(edSendOrderAddress)) {
                        mPresenter.submitOrder(edSendOrderName.getText().toString(),
                                edSendOrderPhone.getText().toString(),
                                edSendOrderAddress.getText().toString(), sendTime);
                    } else {
                        showMessage("請輸入送貨地址");
                    }
                } else {
                    showMessage("請輸入顧客電話");
                }
            } else {
                showMessage("請輸入顧客姓名");
            }
        } else if (viewId == R.id.tv_delivery_time_hour || viewId == R.id.tv_delivery_time_min) {
            Calendar startTime = Calendar.getInstance();
            TimePickerUtils.showTimePicker(mContext, startTime, (date, v1) -> {
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(date);
                tvDeliveryTimeHour.setText(calendar.get(Calendar.HOUR_OF_DAY) + "");
                tvDeliveryTimeMin.setText(calendar.get(Calendar.MINUTE) + "");
                sendTime = TimeUtils.getStringByFormat(date, TimeUtils.DEFAULT_DATE_FORMAT_YMDHM);
            });
        } else if (viewId == R.id.iv_send_order_search) {
            //搜索會員信息
            if (TextUtil.isNotEmptyOrNullOrUndefined(edSendOrderPhone)) {
                mPresenter.getMemberAddressInfo(edSendOrderPhone.getText().toString());
            } else {
                showMessage("請輸入顧客電話");
            }
        } else if (viewId == R.id.tv_continue_add_food) {
            killMyself();
        } else if (viewId == R.id.iv_select_member_arrow || viewId == R.id.iv_select_address_arrow) {
            if (mPresenter.addressData == null) {
            } else {
                Intent intent = new Intent(mContext, AddressListActivity.class);
                intent.putExtra(AddressListActivity.REQUEST_ADDRESS_LIST_NAME, (Serializable) mPresenter.addressData);
                intent.putExtra(AddressListActivity.RESULT_CODE, SELECT_ADDRESS_RESULT_CODE);
                startActivityForResult(intent, SELECT_ADDRESS_REQUEST_CODE);
            }
        }
    }

    private void switchDeliveryTimeMode() {
        if (popup == null) {
            //切換時間選擇
            View view = View.inflate(mContext, R.layout.recyclerview, null);
            RecyclerView recyclerView = view.findViewById(R.id.ryview);
            recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
            listSelectAdapter = new ListSelectAdapter(mContext, R.layout.item_list_string_select, deliveryTimes)
                    .setDefaultSelect(select)
                    .setPadding(30, 24, 30, 24)
                    .setSelectBg(R.color.tran_twenty_send_order_btn_bg_color)
                    .setNormalBg(R.color.white)
                    .notifyAdapter();
            listSelectAdapter.setOnItemClickListener((adapter, view1, position) -> {
                select = position;
                popup.dismiss();
                tvDeliveryTimeType.setText(deliveryTimes.get(position));
                timeGroup.setVisibility(position == 0 ? View.GONE : View.VISIBLE);
            });
            recyclerView.setAdapter(listSelectAdapter);
            popup = QMUIPopups.popup(mContext)
                    .preferredDirection(QMUIPopup.DIRECTION_BOTTOM)
                    .view(view)
                    .arrow(false)
                    .offsetYIfTop(0)
                    .radius(0)
                    .animStyle(QMUIPopup.ANIM_AUTO)
                    .show(deliveryTimeLine);
        } else {
            listSelectAdapter.setDefaultSelect(select).notifyAdapter();
            popup.show(deliveryTimeLine);
        }
    }

    @Override
    public void loadMemberInfo(MemberAddressInfoBean.DataBean data) {
        if (data != null) {
            mPresenter.addressId = data.getId() + "";
            edSendOrderName.setText(data.getReceiver());
            edSendOrderPhone.setText(data.getPhone().toString());
            edSendOrderAddress.setText(data.getCurrentAddress());
        } else {
            showMessage("會員地址查詢失敗");
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SELECT_ADDRESS_REQUEST_CODE && resultCode == SELECT_ADDRESS_RESULT_CODE) {
            if (data != null) {
                MemberAddressInfoBean.DataBean dataBean = (MemberAddressInfoBean.DataBean) data.getSerializableExtra(AddressListActivity.RESULT_DATA_NAME);
                if (dataBean != null) {
                    loadMemberInfo(dataBean);
                }
            }
        }
    }
}
