package com.chexiang.myhome.module.order.quick.module.service;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chexiang.myhome.BuildConfig;
import com.chexiang.myhome.R;
import com.chexiang.myhome.base.BDialog;
import com.chexiang.myhome.base.http.retrofit.client.RetrofitFactory;
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.external.pull.YRecycleview;
import com.chexiang.myhome.model.BIVModel;
import com.chexiang.myhome.model.DelModel;
import com.chexiang.myhome.model.order.OrderDeleteResponseModel;
import com.chexiang.myhome.model.order.OrderModel;
import com.chexiang.myhome.model.order.OrderServiceAndPkgListModel;
import com.chexiang.myhome.model.order.OrderServiceDeleteRequestModel;
import com.chexiang.myhome.model.order.OrderServiceListModel;
import com.chexiang.myhome.model.order.OrderServiceRemarkRequestModel;
import com.chexiang.myhome.model.order.ServicePkgQueryModel;
import com.chexiang.myhome.model.order.service.SelectPkgReqModel;
import com.chexiang.myhome.model.order.service.SelectServiceReqModel;
import com.chexiang.myhome.model.order.service.askprice.AskPriceRequestModel;
import com.chexiang.myhome.model.order.service.askprice.AskPriceResponse;
import com.chexiang.myhome.model.order.service.getcoupon.AskCouponResponse;
import com.chexiang.myhome.module.order.activity.SurroundTestActivity;
import com.chexiang.myhome.module.order.adapter.OrderServiceAdapter;
import com.chexiang.myhome.module.order.adapter.OrderServiceQueryListAdapter;
import com.chexiang.myhome.module.order.dialog.DeleteDialog;
import com.chexiang.myhome.module.order.dialog.EditFeeDialog;
import com.chexiang.myhome.module.order.dialog.EditTotalFeeDialog;
import com.chexiang.myhome.module.order.dialog.ListSelectDialog;
import com.chexiang.myhome.module.order.dialog.RemarkDialog;
import com.chexiang.myhome.module.order.quick.module.WarrantySubFragment;
import com.chexiang.myhome.module.order.quick.serviceoption.AskGoodsFragment;
import com.chexiang.myhome.module.order.quick.serviceoption.EnsureServiceFinishFragment;
import com.chexiang.myhome.module.order.service.SelectPkgActivity;
import com.chexiang.myhome.module.order.service.SelectPkgFragment;
import com.chexiang.myhome.module.order.service.SelectServiceActivity;
import com.chexiang.myhome.module.order.service.SelectServiceFragment;
import com.chexiang.myhome.module.order.service.SelectServicePkgExModel;
import com.chexiang.myhome.module.quotation.inquiry.InquiryDetailsOneFragment;
import com.chexiang.myhome.module.quotation.inquiry.InquiryDetailsTwoFragment;
import com.chexiang.myhome.module.reserveorder.PkgDetailFragment;
import com.chexiang.myhome.module.reserveorder.ServiceDetailFragment;
import com.chexiang.myhome.service.BService;
import com.chexiang.myhome.utils.LocalContext;
import com.chexiang.myhome.utils.LogUtil;
import com.chexiang.myhome.utils.NormalUtil;
import com.chexiang.myhome.utils.StringUtils;
import com.chexiang.myhome.utils.ToastUtil;
import com.chexiang.myhome.widget.components.EmptyView;
import com.chexiang.myhome.widget.components.FloatActionGroup;
import com.chexiang.myhome.widget.dialog.BaseListenerDialog;
import com.chexiang.myhome.widget.dialog.BaseListenerEditDialog;
import com.chexiang.myhome.widget.dialog.CheckCouponDialog;
import com.chexiang.myhome.widget.dialog.NewDiscountDialog;

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

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static com.chexiang.myhome.R.id.company_audit;
import static com.chexiang.myhome.R.id.edit_paint_cost;
import static com.chexiang.myhome.R.id.repair_audit;

/**
 * 服务项目界面
 * <p>
 * Created by Chexiangjia-MAC on 17/6/30.
 */
public class OrderServiceFragment extends WarrantySubFragment {
    @BindView(R.id.rv_list)
    YRecycleview ycl;
    @BindView(R.id.painVendorName)
    TextView painVendorName;
    @BindView(edit_paint_cost)
    EditText editPaintCost;
    @BindView(R.id.lin_paint)
    LinearLayout linPaint;
    Unbinder unbinder;
    @BindView(R.id.search_service)
    EditText searchService;
    @BindView(R.id.check_coupon_number)
    Button checkCouponNumber;
    @BindView(R.id.spend_card)
    Button spendCard;
    @BindView(R.id.service_list)
    ListView serviceList;
    @BindView(R.id.right_drawer)
    LinearLayout rightDrawer;
    @BindView(R.id.drawer_layout)
    DrawerLayout drawerLayout;
    @BindView(R.id.clear_text)
    TextView clearText;
    @BindView(R.id.ensure_paint)
    Button ensurePaint;
    @BindView(R.id.fab_group)
    FloatActionGroup group;
    @BindView(R.id.text_paint_cost)
    TextView textPaintCost;
    @BindView(R.id.lin_paint_cost)
    LinearLayout linPaintCost;
    @BindView(R.id.surround_test)
    Button surroundTest;
    @BindView(R.id.ask_goods)
    Button askGoods;
    @BindView(R.id.ask_price)
    Button askPrice;
    @BindView(R.id.ensure_finish)
    Button ensureFinish;
    @BindView(R.id.empty_view)
    EmptyView emptyView;
    @BindView(R.id.empty)
    TextView emptyText;
    @BindView(repair_audit)
    Button repairAudit;
    @BindView(company_audit)
    Button companyAudit;
    @BindView(R.id.coupon_no)
    Button couponNo;
    @BindView(R.id.order_no)
    TextView orderNo;
    @BindView(R.id.copy)
    TextView textCopy;
    @BindView(R.id.rel_add_ser)
    RelativeLayout relAdd;

    private String TAG = getClass().getSimpleName();
    private View view;
    private OrderModel argsModel;
    //    private DiscountDialog discountDialog;
    private NewDiscountDialog discountDialog;
    private RemarkDialog remarkDialog;
    private BaseListenerEditDialog baseListenerEditDialog_paint;
    private CheckCouponDialog checkCouponDialog;

    private ServicePkgQueryModel servicePkgQueryModel;
    private OrderServiceListModel orderServiceListModel;
    private List<OrderServiceAndPkgListModel> list;
    private List<Integer> listPos;
    public static final int ADD_FLAG = 1;
    private boolean quickRefresh = false;
    private String orderVersion = "";
    private OrderServiceAdapter adapter;
    private int cou = 0;
    private BIVModel binmodel = new BIVModel();

    @Override
    protected View initRootView(LayoutInflater inflater) {
        if (view == null) {
            view = View.inflate(getActivity(), R.layout.fragment_order_service, null);
        }
        ButterKnife.bind(this, view);
        ViewGroup myparent = (ViewGroup) view.getParent();
        //获取args传递的参数
        if (getArguments() != null) {
            argsModel = (OrderModel) getArguments().getSerializable("args");
            quickRefresh = getArguments().getBoolean("ref");
            Log.d(TAG, "initRootView: " + argsModel.assessScore);
        }
        if (myparent != null) {
            myparent.removeView(view);
        }
        return view;
    }

    @Override
    public void initView() {
        drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
        activity.getStackNum();
        if (StringUtils.isEquals(argsModel.orderCustType, "1")) {//企业大客户
            companyAudit.setVisibility(View.VISIBLE);
            checkCouponNumber.setVisibility(View.GONE);
            spendCard.setVisibility(View.GONE);
        } else {
            companyAudit.setVisibility(View.GONE);
            checkCouponNumber.setVisibility(View.VISIBLE);
            spendCard.setVisibility(View.VISIBLE);
        }
        if (StringUtils.isEquals(argsModel.orderType, "2")) {//返修
            if (StringUtils.isEquals(argsModel.orderSourceKey, "11") || StringUtils.isEquals(argsModel.orderSourceKey, "13")) {
                relAdd.setVisibility(View.GONE);
            } else {
                relAdd.setVisibility(View.VISIBLE);
            }
            askPrice.setVisibility(View.GONE);
            repairAudit.setVisibility(View.VISIBLE);
        } else if (StringUtils.isEquals(argsModel.orderType, "4")) {//内部订单
            group.setVisibility(View.GONE);
            relAdd.setVisibility(View.GONE);
            couponNo.setVisibility(View.VISIBLE);
            checkCouponNumber.setVisibility(View.GONE);
            spendCard.setVisibility(View.GONE);
            askPrice.setVisibility(View.VISIBLE);
            repairAudit.setVisibility(View.GONE);
        } else {
            if (StringUtils.isEquals(argsModel.orderSourceKey, "11") || StringUtils.isEquals(argsModel.orderSourceKey, "13")) {
                relAdd.setVisibility(View.GONE);
            } else {
                relAdd.setVisibility(View.VISIBLE);
            }
            askPrice.setVisibility(View.VISIBLE);
            repairAudit.setVisibility(View.GONE);
        }

        initDrawer();
        orderNo.setText(argsModel.orderNo);
        searchService.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
                    LogUtil.d("手指弹起时执行确认功能");
                    String s_text = searchService.getText().toString().trim();
                    if (!StringUtils.isEmpty(s_text)) {
                        doSearchService(s_text);
                        clearText.setVisibility(View.VISIBLE);
                    } else {
//                        clearText.setVisibility(View.GONE);
                    }
                    return true;
                }
                return false;
            }
        });
        initAdapter(new ArrayList<OrderServiceAndPkgListModel>());
        initData(true);
    }

    private void initAdapter(List<OrderServiceAndPkgListModel> model) {
        adapter = new OrderServiceAdapter(getActivity(), model, argsModel.orderType);
        adapter.setOnItemClickListener(new OrderServiceAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {
//                activity.pushFragment(R.id.panel_content, new ReserveOrderDetailFragment());
            }

            @Override
            public void onItemLongClick(View v, int position) {
//                ToastUtil.showToast(getActivity(), position + "   onItemLongClick");
            }
        });
        adapter.setOnButtonClickListener(new OrderServiceAdapter.ButtonClickListener() {
            @Override
            public void onCheckDetailButtonClick(int position) {
                OrderServiceAndPkgListModel m = list.get(position);
                if (StringUtils.isEmpty(m.getOrderPkgId())) {
                    ServiceDetailFragment fragment = ServiceDetailFragment.newInstance(ServiceDetailFragment.SOURCE_ORDER, m.getOrderServiceId(), R.id.fv_order_contain);
                    pushFragment(R.id.fv_order_contain, fragment, ServiceDetailFragment.REQUEST_CODE);
                } else {
                    PkgDetailFragment fragment = PkgDetailFragment.newInstance(PkgDetailFragment.SOURCE_ORDER, m.getOrderPkgId(), R.id.fv_order_contain);
                    pushFragment(R.id.fv_order_contain, fragment, PkgDetailFragment.REQUEST_CODE);
                }
            }

            @Override
            public void onRemarkButtonClick(final int position) {
                //订单组合id、订单服务id、精品id、托外服务id
                String projectId = "";
                //服务组合标识  1:精品 2:服务   3:组合 4:托外服务
                String flag = "";
                if (StringUtils.isEmpty(list.get(position).getOrderPkgId())) {
                    projectId = list.get(position).getOrderServiceId();
                    flag = "2";
                } else {
                    projectId = list.get(position).getOrderPkgId();
                    flag = "3";
                }
                OrderServiceRemarkRequestModel model = new OrderServiceRemarkRequestModel();
                model.flg = flag;
                model.projectId = projectId;
                model.orderId = argsModel.orderId;
                model.remark = list.get(position).getRemark();

                remarkDialog = new RemarkDialog(activity, model);
                remarkDialog.setFinishListener(new RemarkDialog.FinishClickListener() {
                    @Override
                    public void finishClick() {
                        initData(false);
                    }
                });
                remarkDialog.show();
            }

            @Override
            public void onDeleteButtonClick(final int position) {
                //订单组合id、订单服务id、精品id、托外服务id
                String projectId = "";
                //服务组合标识  1:精品 2:服务   3:组合 4:托外服务
                String flag = "";
                if (StringUtils.isEmpty(list.get(position).getOrderPkgId())) {
                    projectId = list.get(position).getOrderServiceId();
                    flag = "2";
                } else {
                    projectId = list.get(position).getOrderPkgId();
                    flag = "3";
                }
                OrderServiceDeleteRequestModel model = new OrderServiceDeleteRequestModel();
                model.flg = flag;
                model.projectId = projectId;
                model.orderId = argsModel.orderId;
                model.remark = list.get(position).getRemark();
                model.orderVersion = orderServiceListModel.getOrderVersion();

                DeleteDialog remarkDialog = new DeleteDialog(activity, model);
                remarkDialog.setFinishListener(new DeleteDialog.FinishClickListener() {
                    @Override
                    public void finishClick(DelModel model1) {
                        initData(true);
                    }
                });
                remarkDialog.show();
            }

            @Override
            public void onDetailButtonClick(int position) {

            }

            @Override
            public void onWorkerFeeButtonClick(int position) {
//                discountDialog = new DiscountDialog(activity, list,position,orderServiceListModel.getOrderVersion());
//                discountDialog.setFinishListener(new DiscountDialog.FinishClickListener() {
//                    @Override
//                    public void finishClick(String orderVersion) {
//                        //刷新页面
//                        initData(true);
//                    }
//                });
//                discountDialog.show();
                discountDialog = new NewDiscountDialog(activity, list, position, orderServiceListModel.getOrderVersion());
                discountDialog.setFinishListener(new NewDiscountDialog.FinishClickListener() {
                    @Override
                    public void finishClick(String orderVersion) {
                        //刷新页面
                        initData(true);
                    }
                });
                discountDialog.show();
            }

            @Override
            public void onTogtherClick(int position) {
                OrderServiceAndPkgListModel sap = list.get(position);
                activity.pushFragment(R.id.fv_order_contain, SelectWorkerAndSalerFragment.newInstance(orderServiceListModel, sap));
            }

            @Override
            public void onConstructorClick(int position) {
                ListSelectDialog dialog = new ListSelectDialog(activity, orderServiceListModel, 0, list.get(position).getOrderServiceId(), argsModel.orderId);
                dialog.setFinishListener(new ListSelectDialog.FinishClickListener() {
                    @Override
                    public void finishClick() {
                        //刷新页面
                        initData(false);
                    }
                });
                dialog.show();
            }

            @Override
            public void onSailPersonClick(int position) {
                ListSelectDialog dialog = new ListSelectDialog(activity, orderServiceListModel, 1, list.get(position).getOrderServiceId(), argsModel.orderId);
                dialog.setFinishListener(new ListSelectDialog.FinishClickListener() {
                    @Override
                    public void finishClick() {
                        //刷新页面
                        initData(false);
                    }
                });
                dialog.show();
            }

            @Override
            public void onWorkerFeeClick(int position) {
                EditFeeDialog dialog = new EditFeeDialog(activity, orderServiceListModel, position);
                dialog.setFinishListener(new EditFeeDialog.FinishClickListener() {
                    @Override
                    public void finishClick() {
                        //刷新页面
                        initData(true);
                    }
                });
                dialog.show();
            }

            @Override
            public void onCheckChange(int position, boolean check) {
                if (check) {//选中
                    listPos.add(position);
                } else {
                    if (listPos.size() == 0) {
                        return;
                    }
                    listPos.remove((Integer) position);
                }
            }

            @Override
            public void onRepairCostClick(int position) {
                EditTotalFeeDialog dialog = new EditTotalFeeDialog(activity, orderServiceListModel, position);
                dialog.setFinishListener(new EditTotalFeeDialog.FinishClickListener() {
                    @Override
                    public void finishClick() {
                        //刷新页面
                        initData(true);
                    }
                });
                dialog.show();
            }


        });
        //禁止加载更多
        ycl.setLoadMoreEnabled(false);
        ycl.setLayoutManager(new LinearLayoutManager(getActivity()));
        ycl.setAdapter(adapter);

        ycl.setRefreshAndLoadMoreListener(new YRecycleview.OnRefreshAndLoadMoreListener() {
            @Override
            public void onRefresh() {
                initData(true);
                ycl.setReFreshComplete();
            }

            @Override
            public void onLoadMore() {
//              InquiryLookOuterAdapter.addRLoadMOreData();
                ycl.setloadMoreComplete();
            }
        });
    }

    public void initDrawer() {
        registerDrawer(drawerLayout);
    }

    private void initData(boolean b) {
        quickRefresh = b;
        queryOrderServiceList(argsModel.orderId);
    }

    //利用setArgues传递参数
    public static OrderServiceFragment newInstance(OrderModel model, boolean ref) {
        OrderServiceFragment fragment = new OrderServiceFragment();
        Bundle args = new Bundle();
        args.putSerializable("args", model);
        args.putBoolean("ref", ref);
        fragment.setArguments(args);
        return fragment;
    }

    public void queryOrderServiceList(final String orderId) {
        showProgress();
        RetrofitFactory.getInstance()
                .create(BService.OrderService.class)
                .queryOrderServiceList(orderId)
                .enqueue(new RMCallback<RMResponse<OrderServiceListModel>>(getActivity()) {
                    @Override
                    protected void onSuccess(RMResponse<OrderServiceListModel> result) {
                        dismissProgress();
                        orderServiceListModel = result.content;

                        orderVersion = orderServiceListModel.getOrderVersion();
                        binmodel.orderId = argsModel.orderId;
                        binmodel.orderVersion = orderVersion;
                        group.setModel(binmodel, activity);

                        showListView();
                        if (quickRefresh) {
                            reloadPanel(orderId, orderServiceListModel.getOrderVersion());
                        }
                    }

                    @Override
                    protected void onFail(String errorCode, String errorInfo) {
                        dismissProgress();
                    }
                });
    }

    private void showListView() {
     /*  1. 判断是否有"油漆供应商"有才显示,没有不要显示
     * 2. 如果有喷漆类服务油漆成本必须填写
     * 3. 结算的时候需要进行验证2的条件*/
        if (StringUtils.isEmpty(orderServiceListModel.getPainVendorName())) {
            linPaint.setVisibility(View.GONE);
        } else {
            linPaint.setVisibility(View.VISIBLE);
            painVendorName.setText(orderServiceListModel.getPainVendorName());
            if (orderServiceListModel.getAllowInputPainCost().equals("1")) {
                linPaintCost.setClickable(true);
                if (StringUtils.isEmpty(orderServiceListModel.getPaintCost())) {
                    textPaintCost.setText("请维护油漆成本");
                } else {
                    textPaintCost.setText(orderServiceListModel.getPaintCost());
                }
            } else {
                linPaintCost.setClickable(false);
                textPaintCost.setText("无需维护油漆成本");
            }
        }
        //lyy 2017-8-7 大客户审核显示标志
        if (StringUtils.isEquals(orderServiceListModel.allowNeedAuditFlag, "1")) {
            companyAudit.setVisibility(View.VISIBLE);
        } else {
            companyAudit.setVisibility(View.GONE);
        }
        //列表无数据
        if (orderServiceListModel.getOrderPkgList().size() == 0 && orderServiceListModel.getOrderServiceList().size() == 0) {
//            emptyText.setText("当前未查到任何服务项目信息");
            emptyView.setVisibility(View.VISIBLE);
            ycl.setVisibility(View.GONE);
        } else {
            emptyView.setVisibility(View.GONE);
            ycl.setVisibility(View.VISIBLE);
        }
        listPos = new ArrayList<>();
        //组合list
        list = new ArrayList<>();
        if (orderServiceListModel.getOrderPkgList() != null) {
            for (int i = 0; i < orderServiceListModel.getOrderPkgList().size(); i++) {
                list.add(orderServiceListModel.getOrderPkgList().get(i));
            }
        }
        if (orderServiceListModel.getOrderServiceList() != null) {
            for (int i = 0; i < orderServiceListModel.getOrderServiceList().size(); i++) {
                list.add(orderServiceListModel.getOrderServiceList().get(i));
            }
        }

        //刷新页面
//        initAdapter(list);
//        if (cou == 0){
        adapter.orderServiceListAdd(list);
//        }else {
//            adapter.notifyDataSetChanged();
//        }
//        cou++;
    }

    private void doSearchService(String s_text) {
        showProgress();
        RetrofitFactory.getInstance()
                .create(BService.OrderService.class)
                .queryOrderServiceCodeList(s_text)
                .enqueue(new RMCallback<RMResponse<ServicePkgQueryModel>>(getActivity()) {
                    @Override
                    protected void onSuccess(RMResponse<ServicePkgQueryModel> result) {
                        dismissProgress();
                        servicePkgQueryModel = result.content;
                        if (servicePkgQueryModel.getServicePkgList() != null && servicePkgQueryModel.getServicePkgList().size() > 0) {
                            showRightList(servicePkgQueryModel);
                        } else {
                            ToastUtil.showToast(getActivity(), "未查询到相关服务");
                        }
                    }

                    @Override
                    protected void onFail(String errorCode, String errorInfo) {
                        ToastUtil.showToast(getActivity(), errorInfo);
                        dismissProgress();
                    }
                });
    }

    private void showRightList(final ServicePkgQueryModel servicePkgQueryModel) {

        OrderServiceQueryListAdapter adapter = new OrderServiceQueryListAdapter(getActivity(), servicePkgQueryModel.getServicePkgList());
        adapter.setOnItemClickListener(new OrderServiceQueryListAdapter.ItemClickListener() {
            @Override
            public void onItemClick(int position) {

                ServicePkgQueryModel.ServicePkgListBean model2 = servicePkgQueryModel.getServicePkgList().get(position);

                // 根据flg进行判断,如果是服务,选择调用服务的弹出接口。如果是组合,选择调用组合的弹出接口
                // flg 组合、服务标识(2:服务,3:组合)
                if (model2.getFlg().equals("2")) {

                    SelectServicePkgExModel exModel = new SelectServicePkgExModel();
                    exModel.orderId = argsModel.orderId;
                    exModel.serviceId = model2.getProjectId();

                    SelectServiceReqModel model = new SelectServiceReqModel();
                    model.orderId = argsModel.orderId;
                    model.serviceId = model2.getProjectId();

                    Intent intent = new Intent(getContext(), SelectServiceActivity.class);
                    Bundle bundle = SelectServiceFragment.newBundle(SelectServiceFragment.SOURCE_ORDER, exModel, model);
                    intent.putExtras(bundle);
                    startActivityForResult(intent, SelectServiceActivity.REQUEST_CODE);
                } else {

                    SelectServicePkgExModel exModel = new SelectServicePkgExModel();
                    exModel.orderId = argsModel.orderId;
                    exModel.pkgId = model2.getProjectId();

                    SelectPkgReqModel model = new SelectPkgReqModel();
                    model.orderId = argsModel.orderId;
                    model.pkgId = model2.getProjectId();

                    Intent intent = new Intent(activity, SelectPkgActivity.class);
                    Bundle bundle = SelectPkgFragment.newBundle(SelectPkgFragment.SOURCE_ORDER, exModel, model);
                    intent.putExtras(bundle);
                    startActivityForResult(intent, SelectPkgActivity.REQUEST_CODE);
                }
            }
        });
        serviceList.setAdapter(adapter);

        drawerLayout.openDrawer(rightDrawer);
    }

    private void doSavePaint(String s_text) {

        HashMap map = new HashMap();
        map.put("paintCost", s_text);
        map.put("orderId", argsModel.orderId);
        showProgress();
        RetrofitFactory.getInstance()
                .create(BService.OrderService.class)
                .savePaint(map)
                .enqueue(new RMCallback<RMResponse<OrderDeleteResponseModel>>(getActivity()) {
                    @Override
                    protected void onSuccess(RMResponse<OrderDeleteResponseModel> result) {
                        dismissProgress();
                        ToastUtil.showToast(getActivity(), "油漆成本维护成功");
                        initData(true);
                    }

                    @Override
                    protected void onFail(String errorCode, String errorInfo) {
                        ToastUtil.showToast(getActivity(), errorInfo);
                        dismissProgress();
                    }
                });
    }

    private void askPrice() {
        if (listPos.size() < 1) {
            ToastUtil.showToast(activity, "请选择至少一条服务项目!");
            return;
        }
        AskPriceRequestModel askPriceRequestModel = new AskPriceRequestModel();
        List<AskPriceRequestModel.OrderServiceIdsBean> orderServiceIds = new ArrayList<>();
        List<AskPriceRequestModel.OrderPkgIdsBean> orderPkgIds = new ArrayList<>();

        for (int i = 0; i < listPos.size(); i++) {
            AskPriceRequestModel.OrderServiceIdsBean orderServiceIdsBean = new AskPriceRequestModel.OrderServiceIdsBean();
            AskPriceRequestModel.OrderPkgIdsBean orderPkgIdsBean = new AskPriceRequestModel.OrderPkgIdsBean();
            int pos = listPos.get(i);
            if (StringUtils.isEmpty(list.get(pos).getOrderServiceId())) {//非服务,组合信息
                orderPkgIdsBean.setOrderPkgId(list.get(pos).getOrderPkgId());
                orderPkgIds.add(orderPkgIdsBean);
            } else {
                orderServiceIdsBean.setOrderServiceId(list.get(pos).getOrderServiceId());
                orderServiceIds.add(orderServiceIdsBean);
            }
        }
        askPriceRequestModel.setOrderId(argsModel.orderId);
        askPriceRequestModel.setOrderPkgIds(orderPkgIds);
        askPriceRequestModel.setOrderServiceIds(orderServiceIds);
        LogUtil.d("ttttttt" + orderPkgIds.size() + orderServiceIds.size());

        activity.showProgress();
        RetrofitFactory.getInstance()
                .create(BService.OrderService.class)
                .order2QuotePrice(askPriceRequestModel)
                .enqueue(new RMCallback<RMResponse<AskPriceResponse>>(activity) {
                    @Override
                    protected void onSuccess(RMResponse<AskPriceResponse> result) {
                        activity.dismissProgress();
                        AskPriceResponse response = result.content;
                        ToastUtil.showToast(getActivity(), "操作成功");
                        if (StringUtils.isEquals(response.getStoreDirectEnquiry(), "1")) {
                            pushFragment(R.id.fv_order_contain, InquiryDetailsOneFragment.getInstance(response.getQuotePriceId(), true), LocalContext.REFRESHREQUESTCODE);
                        } else {
                            pushFragment(R.id.fv_order_contain, InquiryDetailsTwoFragment.getInstance(response.getQuotePriceId()), LocalContext.REFRESHREQUESTCODE);
                        }
//                        initData(false);
                    }

                    @Override
                    protected void onFail(String errorCode, String errorInfo) {
                        ToastUtil.showToast(getContext(), errorInfo);
                        activity.dismissProgress();
                    }
                });
    }

    //返修审核
    private void submitRepair() {
        activity.showProgress();
        RetrofitFactory.getInstance()
                .create(BService.OrderService.class)
                .submitRepairAudit(argsModel.orderId)
                .enqueue(new RMCallback<RMResponse<BModel>>(activity) {
                    @Override
                    protected void onSuccess(RMResponse<BModel> result) {
                        activity.dismissProgress();
                        ToastUtil.showToast(getActivity(), "操作成功");
                    }

                    @Override
                    protected void onFail(String errorCode, String errorInfo) {
                        ToastUtil.showToast(getContext(), errorInfo);
                        activity.dismissProgress();
                    }
                });
    }

    //大客户审核
    private void comAudit() {
        HashMap<String, String> map = new HashMap<>();
        map.put("orderId", argsModel.orderId);
        map.put("orderVersion", orderVersion);
        activity.showProgress();
        RetrofitFactory.getInstance()
                .create(BService.OrderService.class)
                .applyMonthCustAudit(map)
                .enqueue(new RMCallback<RMResponse<BModel>>(activity) {
                    @Override
                    protected void onSuccess(RMResponse<BModel> result) {
                        activity.dismissProgress();
                        ToastUtil.showToast(getActivity(), "操作成功");
                    }

                    @Override
                    protected void onFail(String errorCode, String errorInfo) {
                        ToastUtil.showToast(getContext(), errorInfo);
                        activity.dismissProgress();
                    }
                });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case ADD_FLAG:
                //执行刷新
                initData(true);
                break;
            case SelectServiceActivity.REQUEST_CODE:
            case SelectPkgActivity.REQUEST_CODE:
                drawerLayout.closeDrawer(rightDrawer);
                if (resultCode == Activity.RESULT_OK) {
                    //执行刷新
                    String orderId = data.getStringExtra("orderId");
                    String orderVersion = data.getStringExtra("orderVersion");
                    reloadPanelWhenPriceChanged(orderId, orderVersion);
                    initData(true);
                }
                break;
        }
    }

    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        super.onFragmentResult(requestCode, resultCode, data);
        switch (requestCode) {
            case ServiceDetailFragment.REQUEST_CODE:
            case PkgDetailFragment.REQUEST_CODE:
                if (resultCode == Activity.RESULT_OK) {
                    String orderVersion = data.getString("orderVersion");
                    reloadPanelWhenPriceChanged(argsModel.orderId, orderVersion);
                    initData(true);
                }
                break;
            case LocalContext.REFRESHREQUESTCODE:
                if (resultCode == Activity.RESULT_OK) {
                    initData(true);
                }
                break;
        }
    }

    public class AddDialog extends BDialog {
        private String title;
        private String desc;
        private int type;

        public AddDialog(Context context, String title, String desc, int type) {
            super(context);
            this.title = title;
            this.desc = desc;
            this.type = type;
        }

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            if (type == 1) {
                setContentView(R.layout.dialog_rejest);
            } else {
                setContentView(R.layout.dialog_broken);
            }
            final EditText des = (EditText) findViewById(R.id.broken_desc);
            des.setHint(desc);
            final TextView titles = (TextView) findViewById(R.id.title);
            titles.setText(title);
            TextView calcle = (TextView) findViewById(R.id.cancle);
            TextView ok = (TextView) findViewById(R.id.ok);
            calcle.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismiss();
                }
            });
            ok.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (type == 1) {
                        // 推荐码
                        //todo 验证码查询1029是否需要
                        String recommendedCode = des.getText().toString();
                        if (recommendedCode.isEmpty()) {
                            ToastUtil.showToast(activity, "内容不能为空");
                            return;
                        }
                        HashMap<String, String> map = new HashMap<String, String>();
                        map.put("orderId", argsModel.orderId);
                        map.put("recommendedCode", recommendedCode);
                        RetrofitFactory.getInstance()
                                .create(BService.OrderService.class)
                                .ReferralCode(map)
                                .enqueue(new RMCallback<RMResponse<BModel>>(activity) {
                                    @Override
                                    protected void onSuccess(RMResponse<BModel> result) {
                                        dismiss();
                                    }

                                    @Override
                                    protected void onFail(String errorCode, String errorInfo) {
                                        ToastUtil.showToast(getContext(), errorInfo);
                                        dismiss();
                                    }
                                });
                    } else if (type == 2) {
                        if (des.getText().toString().isEmpty()) {
                            ToastUtil.showToast(activity, "内容不能为空");
                            return;
                        }
                        // 申请折扣--保存
                        HashMap<String, String> map = new HashMap<String, String>();
                        map.put("orderId", argsModel.orderId);
                        if (argsModel != null)
                            map.put("orderVersion", orderVersion);
                        map.put("orderDiscountReason", des.getText().toString());
                        RetrofitFactory.getInstance()
                                .create(BService.OrderService.class)
                                .submitDiscount(map)
                                .enqueue(new RMCallback<RMResponse<BModel>>(activity) {
                                    @Override
                                    protected void onSuccess(RMResponse<BModel> result) {
                                        ToastUtil.showToast(getContext(), result.message);
                                        dismiss();
                                    }

                                    @Override
                                    protected void onFail(String errorCode, String errorInfo) {
                                        ToastUtil.showToast(getContext(), errorInfo);
                                        dismiss();
                                    }
                                });
                    }
                }
            });
        }
    }

    @OnClick({R.id.check_coupon_number, R.id.spend_card, R.id.clear_text, R.id.ensure_paint, R.id.lin_paint_cost
            , R.id.surround_test, R.id.ask_goods, R.id.ask_price, R.id.ensure_finish, R.id.repair_audit, R.id.copy
            , company_audit, R.id.coupon_no})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.check_coupon_number:
                checkCouponDialog = new CheckCouponDialog(activity, argsModel);
                checkCouponDialog.setFinishListener(new CheckCouponDialog.FinishClickListener() {
                    @Override
                    public void finishClick(AskCouponResponse response) {
                        checkCouponDialog.dismiss();
                        if (response == null) {//代金券返回刷新列表
                            initData(true);
                            return;
                        }
                        //跳转选择券服务列表
                        SelectCouponServiceFragment hf = SelectCouponServiceFragment.newInstance(argsModel, response);
                        activity.pushFragment(R.id.fv_order_contain, hf);
                    }
                });
                checkCouponDialog.show();
                break;
            case R.id.spend_card:
                SelectMoneyCardFragment sm = new SelectMoneyCardFragment(argsModel);
                activity.pushFragment(R.id.fv_order_contain, sm);
                break;
            case R.id.clear_text:
//                searchService.setText("");
//                clearText.setVisibility(View.GONE);
                if (BuildConfig.DEBUG) {
//                    discountDialog = new DiscountDialog(activity, new OrderServiceListModel());
//                    discountDialog.show();
//                    remarkDialog = new RemarkDialog(activity, new OrderServiceRemarkRequestModel());
//                    remarkDialog.show();
//                    ListSelectDialog dialog = new ListSelectDialog(activity,new OrderServiceListModel(),0,0);
//                    dialog.show();
                }
                break;
            case R.id.ensure_paint:
                String s_text = editPaintCost.getText().toString().trim();
                if (!StringUtils.isEmpty(s_text)) {
                    doSavePaint(s_text);
                }
                break;
            case R.id.lin_paint_cost:
                baseListenerEditDialog_paint = new BaseListenerEditDialog(activity);
//                baseListenerEditDialog_paint.setMsg("");
                baseListenerEditDialog_paint.setTitle("维护油漆成本");
                baseListenerEditDialog_paint.setMoneyInput();
                baseListenerEditDialog_paint.setFinishListener(new BaseListenerEditDialog.FinishClickListener() {
                    @Override
                    public void finishClick() {
                        String s = baseListenerEditDialog_paint.getMsg();
                        if (!StringUtils.isEmpty(s)) {
                            doSavePaint(s);
                        } else {
                            ToastUtil.showToast(getContext(), "请输入内容");
                        }
                    }
                });
                baseListenerEditDialog_paint.show();
                break;
            case R.id.surround_test:
                Intent intent = new Intent(getContext(), SurroundTestActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("argsModel", argsModel);
                intent.putExtras(bundle);
                startActivity(intent);
                break;
            case R.id.ask_goods:
                pushFragment(R.id.fv_order_contain, AskGoodsFragment.newInstance(argsModel), LocalContext.REFRESHREQUESTCODE);
                break;
            case R.id.ask_price:
//                activity.pushFragment(R.id.fv_order_contain, AskOrderPriceFragment.newInstance(argsModel));
                askPrice();
                break;
            case R.id.ensure_finish:
                activity.pushFragment(R.id.fv_order_contain, EnsureServiceFinishFragment.newInstance(argsModel));
                break;
            case R.id.repair_audit:
                //返修审核
                BaseListenerDialog dialog = new BaseListenerDialog(activity);
                dialog.setMsg("确认提交审核吗?");
                dialog.setFinishListener(new BaseListenerDialog.FinishClickListener() {
                    @Override
                    public void finishClick() {
                        submitRepair();
                    }
                });
                dialog.show();
                break;
            case R.id.copy:
                NormalUtil.doCopy(activity, orderNo.getText().toString().trim());
                break;
            case R.id.coupon_no:
                new AddDialog(getContext(), "推荐码", "", 1).show();
                break;
            case company_audit:
                BaseListenerDialog cDia = new BaseListenerDialog(activity);
                cDia.setMsg("确认提交审核吗?");
                cDia.setFinishListener(new BaseListenerDialog.FinishClickListener() {
                    @Override
                    public void finishClick() {
                        comAudit();
                    }
                });
                cDia.show();
                break;
        }
    }
}