package com.chexiang.myhome.module.reserveorder;

import android.app.Activity;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.chexiang.myhome.R;
import com.chexiang.myhome.base.BFragment;
import com.chexiang.myhome.base.adapter.table.SimpleTableAdapter;
import com.chexiang.myhome.base.http.retrofit.client.RetrofitFactory;
import com.chexiang.myhome.base.http.retrofit.model.QueryCustAndOrderInfoModel;
import com.chexiang.myhome.base.http.retrofit.stub.RMCallback;
import com.chexiang.myhome.base.http.retrofit.stub.RMResponse;
import com.chexiang.myhome.base.model.BModel;
import com.chexiang.myhome.databinding.FragmentReserveOrderDetailBinding;
import com.chexiang.myhome.model.car.SyncCustomerVehicleInfoRepModel;
import com.chexiang.myhome.model.car.SyncCustomerVehicleInfoReqModel;
import com.chexiang.myhome.model.member.UpdateCustomerModel;
import com.chexiang.myhome.model.order.CustomerModel;
import com.chexiang.myhome.model.order.OrderModel;
import com.chexiang.myhome.model.reserveorder.ReserveOrderModel;
import com.chexiang.myhome.model.reserveorder.ReserveOrderPayModel;
import com.chexiang.myhome.model.reserveorder.ReserveOrderPkgModel;
import com.chexiang.myhome.model.reserveorder.ReserveOrderServiceModel;
import com.chexiang.myhome.model.reserveorder.TurnOrderRepModel;
import com.chexiang.myhome.model.reserveorder.TurnOrderReqModel;
import com.chexiang.myhome.model.reserveorder.UpdateOrderCustVelReqModel;
import com.chexiang.myhome.module.home.HomeFragment;
import com.chexiang.myhome.module.home.SelectCarItemListener;
import com.chexiang.myhome.module.home.SelectCarDialog;
import com.chexiang.myhome.module.order.quick.WarrantyFragment;
import com.chexiang.myhome.module.order.service.SelectPkgActivity;
import com.chexiang.myhome.module.order.service.SelectServiceActivity;
import com.chexiang.myhome.module.reserveorder.adapter.PkgItem;
import com.chexiang.myhome.module.reserveorder.adapter.ReserveOrderServiceEntity;
import com.chexiang.myhome.module.reserveorder.adapter.ServiceItem;
import com.chexiang.myhome.module.user.UseMsgFragment;
import com.chexiang.myhome.service.BService;
import com.chexiang.myhome.utils.StringUtils;
import com.chexiang.myhome.widget.components.UserHeadLayout;
import com.chexiang.myhome.widget.dialog.AlertDialog;

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

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import kale.adapter.CommonAdapter;
import kale.adapter.item.AdapterItem;

import static android.app.Activity.RESULT_OK;

/**
 * 预约单详情界面
 * Created by zhangshunjie on 17/6/30.
 */
public class ReserveOrderDetailFragment extends BFragment implements UserHeadLayout.OnBtnClickListener, SelectCarItemListener {

    private static final String KEY_RESERVE_ORDER_ID = "reserveOrderId";

    @BindView(R.id.drawer_layout)
    DrawerLayout drawerLayout;
    @BindView(R.id.right_drawer)
    LinearLayout rightDrawer;
    @BindView(R.id.cancelReserveBtn)
    TextView cancelReserveBtn;
    @BindView(R.id.reserveTimeBtn)
    TextView reserveTimeBtn;
    @BindView(R.id.turnOrderBtn)
    TextView turnOrderBtn;
    @BindView(R.id.dayView)
    TextView dayView;
    @BindView(R.id.userHeadLayout)
    UserHeadLayout userHeadLayout;
    private View view;
    private ListView serviceList;
    private ListView payList;
    private ListView couponList;
    private ReserveOrderModel reserveOrderModel;
    private FragmentReserveOrderDetailBinding binding;
    private String reserveToHours;

    /**
     * @param reserveOrderId 预约单id
     * @return
     */
    public static ReserveOrderDetailFragment newInstance(String reserveOrderId) {
        ReserveOrderDetailFragment fragment = new ReserveOrderDetailFragment();
        Bundle bundle = new Bundle();
        bundle.putString(KEY_RESERVE_ORDER_ID, reserveOrderId);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected View initRootView(LayoutInflater inflater) {
        if (view == null) {
            view = View.inflate(getActivity(), R.layout.fragment_reserve_order_detail, null);
        }
        ButterKnife.bind(this, view);
        binding = DataBindingUtil.bind(view);
        ViewGroup myparent = (ViewGroup) view.getParent();
        if (myparent != null) {
            myparent.removeView(view);
        }
        return view;
    }

    @Override
    public void initView() {
        UseMsgFragment.setSaveOkListener(new UseMsgFragment.ResultConver() {
            @Override
            public void converModel(UpdateCustomerModel model) {
                reserveOrderModel.custName = model.custName;
                reserveOrderModel.mobile = model.mobile;
                reserveOrderModel.plates = model.plates;
                reserveOrderModel.velModelName = model.carModelFullName;
                binding.setReserveOrderModel(reserveOrderModel);
            }
        });
        loadDate();
    }

    private void loadDate() {
        showProgress();
        String reserveOrderId = getArguments().getString(KEY_RESERVE_ORDER_ID);
        RetrofitFactory.getInstance()
                .create(BService.ReserveOrderService.class)
                .queryReserveDetail(reserveOrderId)
                .enqueue(new RMCallback<RMResponse<ReserveOrderModel>>(activity) {
                    @Override
                    protected void onSuccess(RMResponse<ReserveOrderModel> result) {
                        Log.d("RetrofitFactory----", "onSuccess: ");
                        dismissProgress();

                        reserveOrderModel = result.content;
                        binding.setReserveOrderModel(reserveOrderModel);
                        updateDate();
                    }

                    @Override
                    protected void onFail(String errorCode, String errorInfo) {
                        Log.d("RetrofitFactory----", "onFail: " + errorCode + "  " + errorInfo);
                        dismissProgress();
                        showToast(errorInfo);
                        activity.popFragment();
                    }
                });
    }

    private void updateDate() {
        userHeadLayout.init(reserveOrderModel, reserveOrderModel, this);
        dayView.setText(reserveOrderModel.reserveCheckInTime);
        updateServiceList();
        updatePsyList();
        updateCouponList();
    }

    private void updateServiceList() {
        List<ReserveOrderServiceEntity> data3 = new ArrayList<>();
        ReserveOrderServiceEntity set3;
        if (reserveOrderModel.orderServiceList != null) {
            for (ReserveOrderServiceModel serviceModel : reserveOrderModel.orderServiceList) {
                set3 = new ReserveOrderServiceEntity();
                set3.type = ReserveOrderServiceEntity.TYPE_SERVICE;
                set3.service = serviceModel;
                data3.add(set3);
            }
        }
        if (reserveOrderModel.orderPkgList != null) {
            for (ReserveOrderPkgModel serviceModel : reserveOrderModel.orderPkgList) {
                set3 = new ReserveOrderServiceEntity();
                set3.type = ReserveOrderServiceEntity.TYPE_PKG;
                set3.pkg = serviceModel;
                data3.add(set3);
            }
        }
        serviceList = (ListView) findViewById(R.id.serviceList);
        serviceList.setAdapter(new CommonAdapter<ReserveOrderServiceEntity>(data3, 2) {
            @NonNull
            @Override
            public AdapterItem createItem(Object o) {
                int type = (int) o;
                switch (type) {
                    case ReserveOrderServiceEntity.TYPE_SERVICE:
                        return new ServiceItem(activity, ReserveOrderDetailFragment.this, reserveOrderModel);
                    default:
                        return new PkgItem(activity, ReserveOrderDetailFragment.this, reserveOrderModel);
                }
            }

            @Override
            public Object getItemType(ReserveOrderServiceEntity o) {
                return o.type;
            }
        });
        setViewHeight(serviceList.getLayoutParams(), 48, data3.size());
    }

    private void updatePsyList() {
        List<List<String>> data = new ArrayList<>();
        List set;
        if (reserveOrderModel.reserveOrderPayList != null) {
            for (ReserveOrderPayModel payModel : reserveOrderModel.reserveOrderPayList) {
                if (payModel.couponCode != null) {
                    continue;
                }
                set = new ArrayList();
                set.add(payModel.moneyTypeName);
                set.add(payModel.payNo);
                set.add(payModel.payChannelName);
                set.add(payModel.txnNo);
                set.add(payModel.payTime);
                set.add(payModel.payMoney);
                data.add(set);
            }
        }
        int[] resIds = new int[]{R.id.v1, R.id.v2, R.id.v3, R.id.v4, R.id.v5, R.id.v6};
        payList = (ListView) findViewById(R.id.payList);
        payList.setAdapter(new SimpleTableAdapter(data, R.layout.fragment_reserve_order_detail_pay_item, resIds,
                payList, 48, activity));
    }

    private void updateCouponList() {
        List<List<String>> data2 = new ArrayList<>();
        List set2;
        if (reserveOrderModel.reserveOrderPayList != null) {
            for (ReserveOrderPayModel payModel : reserveOrderModel.reserveOrderPayList) {
                if (payModel.couponCode == null) {
                    continue;
                }
                set2 = new ArrayList();
                set2.add(payModel.couponCode);
                set2.add(payModel.couponActivityName);
                set2.add(payModel.couponFaceValue);
                set2.add(payModel.payTime);
                data2.add(set2);
            }
        }
        int[] resIds2 = new int[]{R.id.v1, R.id.v2, R.id.v3, R.id.v4};
        couponList = (ListView) findViewById(R.id.couponList);
        couponList.setAdapter(new SimpleTableAdapter(data2, R.layout.fragment_reserve_order_detail_coupon_item, resIds2,
                couponList, 48, activity));
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case SelectServiceActivity.REQUEST_CODE:
            case SelectPkgActivity.REQUEST_CODE:
                if (resultCode == Activity.RESULT_OK) {
                    loadDate();
                }
                break;
        }
    }

    @OnClick({R.id.cancelReserveBtn, R.id.reserveTimeBtn, R.id.turnOrderBtn, R.id.time8, R.id.time9,
            R.id.time10, R.id.time11, R.id.time12, R.id.time13, R.id.time14, R.id.time15, R.id.time16,
            R.id.time17, R.id.time18, R.id.time19})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.cancelReserveBtn:
                cancel();
                break;
            case R.id.reserveTimeBtn:
                drawerLayout.openDrawer(rightDrawer);
                break;
            case R.id.turnOrderBtn:
                turnOrder();
                break;
            case R.id.time8:
            case R.id.time9:
            case R.id.time10:
            case R.id.time11:
            case R.id.time12:
            case R.id.time13:
            case R.id.time14:
            case R.id.time15:
            case R.id.time16:
            case R.id.time17:
            case R.id.time18:
            case R.id.time19:
                reserveToHours = ((TextView) view).getText().toString().replace(":00", "").replace(":00", "");
                drawerLayout.closeDrawer(rightDrawer);
                break;
        }
    }

    private void cancel() {
        final AlertDialog dialog = new AlertDialog(activity);
        dialog.setMsg(R.string.reserve_order_cancel_confrim);
        dialog.setPositiveBtn(android.R.string.yes).setPositiveBtnOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showProgress();
                RetrofitFactory.getInstance()
                        .create(BService.ReserveOrderService.class)
                        .cancelReserveOrder(reserveOrderModel.reserveOrderId)
                        .enqueue(new RMCallback<RMResponse<BModel>>(activity) {
                            @Override
                            protected void onSuccess(RMResponse<BModel> result) {
                                Log.d("RetrofitFactory----", "onSuccess: ");
                                dismissProgress();
                                showToast(R.string.reserve_order_cancel_success);
                                dialog.dismiss();
                                popFragment();
                            }

                            @Override
                            protected void onFail(String errorCode, String errorInfo) {
                                Log.d("RetrofitFactory----", "onFail: " + errorCode + "  " + errorInfo);
                                dismissProgress();
                                showToast(errorInfo);
                            }
                        });
            }
        }).show();
    }

    private void turnOrder() {
        // check
        if (StringUtils.isBlank(reserveOrderModel.custId)) {
            showToast("请先补全当前车辆车型信息!");
            return;
        }
        if (StringUtils.isBlank(reserveOrderModel.custVelId)) {
            showToast("请先补全当前车辆车型信息!");
            return;
        }
        if (StringUtils.isBlank(reserveOrderModel.plates)) {
            showToast("请先补全当前车辆车型信息!");
            return;
        }
        if (reserveOrderModel.plates.contains(" ") || reserveOrderModel.plates.contains(" ")) {
            showToast("请先补全当前车辆车型信息!");
            return;
        }
        if (StringUtils.isBlank(reserveOrderModel.carYearIds)) {
            showToast("请先补全当前车辆车型信息!");
            return;
        }
        if (reserveOrderModel.orderServiceList != null) {
            for (ReserveOrderServiceModel m : reserveOrderModel.orderServiceList) {
                if (!m.isSelected()) {
                    showToast("您有服务项目未选择配件!");
                    return;
                }
            }
        }
        if (reserveOrderModel.orderPkgList != null) {
            for (ReserveOrderPkgModel m : reserveOrderModel.orderPkgList) {
                if (!m.isSelected()) {
                    showToast("您有服务项目未选择配件!");
                    return;
                }
            }
        }

        showProgress();
        TurnOrderReqModel model = new TurnOrderReqModel();
        model.reserveOrderId = reserveOrderModel.reserveOrderId;
        model.reserveToHours = reserveToHours;
        RetrofitFactory.getInstance()
                .create(BService.ReserveOrderService.class)
                .turnOrder(model)
                .enqueue(new RMCallback<RMResponse<TurnOrderRepModel>>(activity) {
                    @Override
                    protected void onSuccess(RMResponse<TurnOrderRepModel> result) {
                        Log.d("RetrofitFactory----", "onSuccess: ");
                        dismissProgress();
                        OrderModel model = new OrderModel();
                        model.orderId = result.content.orderId;
                        model.orderNo = result.content.orderNo;
                        WarrantyFragment fr = WarrantyFragment.newInstance(model);
                        activity.replaceFragment(R.id.panel_content, fr);
                    }

                    @Override
                    protected void onFail(String errorCode, String errorInfo) {
                        Log.d("RetrofitFactory----", "onFail: " + errorCode + "  " + errorInfo);
                        dismissProgress();
                        showToast(errorInfo);
                    }
                });
    }

    @Override
    public void onEditClick() {
        if (StringUtils.isBlank(reserveOrderModel.custVelId)) {
            queryCustomer(reserveOrderModel.mobile);
        } else {
            UseMsgFragment uwf = UseMsgFragment.newInstanceForUpdate(reserveOrderModel.custId, reserveOrderModel.custVelId, UseMsgFragment.SAVE_TYPE_NORMAL,"");
            pushFragment(R.id.panel_content, uwf, HomeFragment.REQUEST_CODE_NEW_CAR);
        }
    }

    private void queryCustomer(String mobile) {
        activity.showProgress();
        Map<String, String> params = new HashMap<>();
        params.put("mobile", mobile);
        RetrofitFactory.getInstance()
                .create(BService.UserService.class)
                .queryCustomerByMobile(params)
                .enqueue(new RMCallback<RMResponse<CustomerModel>>(activity) {
                    @Override
                    protected void onSuccess(RMResponse<CustomerModel> result) {
                        Log.d("RetrofitFactory----", "onSuccess: ");
                        activity.dismissProgress();
                        if (result.content != null && !StringUtils.isBlank(result.content.custId)) {
                            showCustomerDialog(result.content);
                        } else {
                            // 非会员
                            showToast("找不到会员信息");
                        }
                    }

                    @Override
                    protected void onFail(String errorCode, String errorInfo) {
                        Log.d("RetrofitFactory----", "onFail: " + errorCode + "  " + errorInfo);
                        activity.dismissProgress();
                        showToast(errorInfo);
                    }
                });
    }

    private void updateOrderCustVel(String custVelId, String plates) {
        activity.showProgress();
        UpdateOrderCustVelReqModel model = new UpdateOrderCustVelReqModel();
        model.reserveOrderId = reserveOrderModel.reserveOrderId;
        model.custId = reserveOrderModel.custId;
        model.custVelId = custVelId;
        model.plates = plates;
        RetrofitFactory.getInstance()
                .create(BService.ReserveOrderService.class)
                .updateOrderCustVel(model)
                .enqueue(new RMCallback<RMResponse<BModel>>(activity) {
                    @Override
                    protected void onSuccess(RMResponse<BModel> result) {
                        Log.d("RetrofitFactory----", "onSuccess: ");
                        activity.dismissProgress();
                        loadDate();
                    }

                    @Override
                    protected void onFail(String errorCode, String errorInfo) {
                        Log.d("RetrofitFactory----", "onFail: " + errorCode + "  " + errorInfo);
                        activity.dismissProgress();
                        showToast(errorInfo);
                    }
                });
    }

    private void showCustomerDialog(final CustomerModel model) {
        new SelectCarDialog(activity, this, this, model, reserveOrderModel.plates).show();
    }

    @Override
    public void onSelectCar(QueryCustAndOrderInfoModel model) {
        SyncCustomerVehicleInfoReqModel m = new SyncCustomerVehicleInfoReqModel();
        m.cxId = model.cxId;
        m.assetId = model.assetId;
        m.mobile = model.mobile;
        m.custName = model.custName;
        showProgress();
        RetrofitFactory.getInstance()
                .create(BService.UserService.class)
                .syncCustomerVehicleInfo(m)
                .enqueue(new RMCallback<RMResponse<SyncCustomerVehicleInfoRepModel>>(activity) {
                    @Override
                    protected void onSuccess(RMResponse<SyncCustomerVehicleInfoRepModel> result) {
                        Log.d("RetrofitFactory----", "onSuccess: ");
                        dismissProgress();
                        updateOrderCustVel(result.content.custVelId, result.content.plates);
                    }

                    @Override
                    protected void onFail(String errorCode, String errorInfo) {
                        Log.d("RetrofitFactory----", "onFail: " + errorCode + "  " + errorInfo);
                        dismissProgress();
                        showToast(errorInfo);
                    }
                });
    }

    @Override
    public void onNewCar(String mobile, String plates) {
        UseMsgFragment uwf = UseMsgFragment.newInstanceForNew(mobile, plates, reserveOrderModel.reserveOrderId, UseMsgFragment.SAVE_TYPE_NORMAL);
        pushFragment(R.id.panel_content, uwf, HomeFragment.REQUEST_CODE_NEW_CAR);
    }

    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        super.onFragmentResult(requestCode, resultCode, data);
        switch (requestCode) {
            case HomeFragment.REQUEST_CODE_NEW_CAR:
                if (resultCode == RESULT_OK) {
                    UpdateCustomerModel model = (UpdateCustomerModel) data.getSerializable("UpdateCustomerModel");
                    updateOrderCustVel(model.custVelId, model.plates);
                }
                break;
        }
    }
}