package com.rv.home.rv.module.ui.main.home;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.PopupWindowCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.alipay.sdk.app.PayTask;
import com.base.utils.ui.datetime.selector.util.TextUtil;
import com.frame.base.bus.LoginUserInfoEvent;
import com.frame.base.bus.Observer;
import com.frame.base.bus.PaymentFailedEvent;
import com.frame.base.bus.PaymentSuccessfulEvent;
import com.frame.base.bus.RxBus;
import com.frame.base.url.Constance;
import com.frame.base.view.StarBar;
import com.frame.rv.config.RvFrameConfig;
import com.frame.rv.widget.PayResult;
import com.ruiwenliu.wrapper.SPConstance;
import com.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.bean.BeanUserInfo;
import com.ruiwenliu.wrapper.util.UtilsManager;
import com.ruiwenliu.wrapper.util.ViewHolder;
import com.ruiwenliu.wrapper.util.glide.GlideManager;
import com.ruiwenliu.wrapper.weight.TitleView;
import com.rv.component.control.FlowLayout;
import com.rv.component.control.SwitchButton;
import com.rv.component.dialog.OrderPriceDetailPw;
import com.rv.component.dialog.PaymentTypeSelection;
import com.rv.component.dialog.bean.OrderPriceDetailBean;
import com.rv.component.utils.DisplayUtil;
import com.rv.home.R;
import com.rv.home.R2;
import com.rv.home.rv.module.ApiConfig;
import com.rv.home.rv.module.basic.BaseStatusActivity;
import com.rv.home.rv.module.basic.presenter.CommonPresenter;
import com.rv.home.rv.module.ui.main.home.adapter.SelectedItemAdapter;
import com.rv.home.rv.module.ui.main.home.bean.CarTypeListBean;
import com.rv.home.rv.module.ui.main.home.bean.ConfirmOrderBean;
import com.rv.home.rv.module.ui.main.home.bean.DrivingListBean;
import com.rv.home.rv.module.ui.main.home.bean.OrderAliPayBean;
import com.rv.home.rv.module.ui.main.home.bean.OrderDataBean;
import com.rv.home.rv.module.ui.main.home.bean.OrderPayBean;
import com.rv.home.rv.module.ui.main.home.bean.OrderPriceBean;
import com.rv.home.rv.module.ui.main.home.bean.SelectItemBean;
import com.rv.home.rv.module.ui.main.home.order.OrderListActivity;
import com.rv.home.rv.module.ui.main.home.other.SelectItemActivity;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.xxrv.coupon.api.CouponApi;
import com.xxrv.coupon.bean.CouponBean;
import com.yuyife.okgo.OkGoUtil;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.schedulers.Schedulers;

/**
 * Created :Auser
 * Date: 2019/5/20.
 * Desc:确认订单
 */
public class ConfirmOrderActivity extends BaseStatusActivity<CommonPresenter> {
    private static final int SDK_ALI_PAY_FLAG = 11;
    @BindView(R2.id.iv_goods)
    ImageView ivGoods;
    @BindView(R2.id.tv_name)
    TextView tvName;
    @BindView(R2.id.tv_content)
    TextView tvContent;
    @BindView(R2.id.rating_bar)
    StarBar ratingBar;
    @BindView(R2.id.tv_price)
    TextView tvPrice;
    @BindView(R2.id.tv_get_car_address)
    TextView tvGetCarAddress;
    @BindView(R2.id.tv_out_car_address)
    TextView tvOutCarAddress;
    @BindView(R2.id.rb_xin_driving)
    CheckBox rbXinDriving;
    @BindView(R2.id.rb_user_driving)
    CheckBox rbUserDriving;
    @BindView(R2.id.ll_add_driving)
    LinearLayout llAddDriving;
    @BindView(R2.id.tv_deposit)
    TextView tvDeposit;
    @BindView(R2.id.tv_car_not_hurt)
    TextView tvCarNotHurt;
    @BindView(R2.id.tv_car_not_hurt_money)
    TextView tvCarNotHurtMoney;
    @BindView(R2.id.tv_passenger_know)
    CheckBox tvPassengerKnow;
    @BindView(R2.id.tv_contract_agreement)
    TextView tvContractAgreement;
    @BindView(R2.id.tv_pay_money)
    TextView tvPayMoney;
    @BindView(R2.id.tv_detail)
    TextView tvDetail;
    @BindView(R2.id.tv_confirm_order)
    TextView tvConfirmOrder;
    @BindView(R2.id.tv_person)
    TextView tvPerson;
    @BindView(R2.id.tv_id_card)
    TextView tvIdCard;
    @BindView(R2.id.ll_bottom)
    LinearLayout llBottom;
    @BindView(R2.id.tv_layout_service_fee)
    TextView tvLayoutServiceFee;
    @BindView(R2.id.ll_layout_clean_fee)
    LinearLayout llLayoutCleanFee;
    @BindView(R2.id.swbtn_member)
    SwitchButton swbtnMember;
    @BindView(R2.id.tv_event_date)
    TextView tvEventDate;
    @BindView(R2.id.tv_activity_day)
    TextView tvActivityDay;
    @BindView(R2.id.tv_lab3)
    CheckBox tvLab3;
    @BindView(R2.id.tv_layout_member_hint)
    TextView tvLayoutMemberHint;
    @BindView(R2.id.ll_layout_member_hint)
    LinearLayout llLayoutMemberHint;
    @BindView(R2.id.tv_free_car_days)
    TextView tvFreeCarDays;
    @BindView(R2.id.tv_xin_driving_price)
    TextView tvXinDrivingPrice;
    @BindView(R2.id.tv_coupon_amount)
    TextView tvCouponAmount;
    @BindView(R2.id.rv_content_select)
    FlowLayout rvContentSelect;

    private final int TYPE_REQUEST_DRIVING = 3;


    private boolean serviceFeeShow = true;
    private boolean cleanFeeShow = true;
    private OrderDataBean dataBean;
    private CarTypeListBean.DataBeanX.DataBean mCarBean;
    private DrivingListBean.DataBeanX.DataBean drivingListBean;
    private int drivingType = 0;//驾驶证类型1、欣新驾驶员2、自驾
    private OrderPriceDetailPw detailPw;//显示订单价格明细弹窗
    private OrderPriceDetailBean orderPriceDetailBean;//订单价格明细实体类
    private IWXAPI api;
    private int payType = 1;//选择支付类型
    private OrderPriceBean priceBean;
    BeanUserInfo.UserInfo info = null;
    private int deductiblePriceType;
    private int isMemberType;
    private double carAmount;  //请求优惠券金额
    private double oldCarAmount;//
    private List<CouponBean.DataBean> couponDataList;//优惠券数据

    private SelectedItemAdapter mSelectedItemAdapter;

    private double couponAmount = 0; //优惠券金额
    private String status = "1";// 优惠券状态

    private List<String> couponIdList = new ArrayList<>(); //选中优惠券
    private List<String> selectItemList = new ArrayList<>();//随车物品

    private List<SelectItemBean.DataBean> selectItem;

    public static Intent getIntent(Context context, OrderDataBean bean, CarTypeListBean.DataBeanX.DataBean carBean, String startTime, String endTime) {
        return new Intent(context, ConfirmOrderActivity.class)
                .putExtra("bean", bean)
                .putExtra("carBean", carBean)
                .putExtra("startTime", startTime)
                .putExtra("endTime", endTime);
    }

    @Override
    protected int setLayout() {
        return R.layout.rv_act_confim_order;
    }

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
        titleView.setTitle(mActivity.getString(R.string.rv_confirm_order));
        api = WXAPIFactory.createWXAPI(this, RvFrameConfig.APP_ID);
        dataBean = (OrderDataBean) intent.getSerializableExtra("bean");
        mCarBean = (CarTypeListBean.DataBeanX.DataBean) intent.getSerializableExtra("carBean");
        intiView();
        initRxBus();

//        mSelectedItemAdapter = new SelectedItemAdapter();
//        rvContentSelect.setLayoutManager(new LinearLayoutManager(this));
//        rvContentSelect.setAdapter(mSelectedItemAdapter);

    }


    private TextView buildLabel(String text) {
        TextView textView = new TextView(this);
        textView.setText(text);
        textView.setTextColor(getResources().getColor(R.color.textGray));
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
        textView.setPadding((int) DisplayUtil.dpToPx(mActivity, 15), (int) DisplayUtil.dpToPx(mActivity, 8), (int) DisplayUtil.dpToPx(mActivity, 15), (int) DisplayUtil.dpToPx(mActivity, 8));

        return textView;
    }

    @SuppressLint("CheckResult")
    private void initRxBus() {

        RxBus.tObservable(PaymentSuccessfulEvent.class)
                .observeOn(Schedulers.newThread())
                .subscribe(new Observer<PaymentSuccessfulEvent>(disposable) {
                    @Override
                    public void onNext(PaymentSuccessfulEvent event) {
                        startActivity(OrderListActivity.getIntent(mActivity, 1));
                        finish();
                    }
                });

        RxBus.tObservable(PaymentFailedEvent.class)
                .observeOn(Schedulers.newThread())
                .subscribe(new Observer<PaymentFailedEvent>(disposable) {
                    @Override
                    public void onNext(PaymentFailedEvent event) {
                        if (mActivity.getClass().equals(ConfirmOrderActivity.class)) {
                            startActivity(OrderListActivity.getIntent(mActivity, 0));
                            finish();
                        }
                    }
                });

        RxBus.tObservable(LoginUserInfoEvent.class)
                .observeOn(Schedulers.newThread())
                .subscribe(new Observer<LoginUserInfoEvent>(disposable) {
                    @Override
                    public void onNext(LoginUserInfoEvent event) {
                        tvPrice.setText(String.format("¥%1$s%2$s", mCarBean.getVehicleModel().getSum(), mActivity.getString(R.string.rv_day)));
                        if (info != null) {
                            if (0 == info.getIsMember()) {
                                tvLayoutMemberHint.setVisibility(View.GONE);
                                llLayoutMemberHint.setVisibility(View.GONE);
                            } else if (1 == info.getIsMember()) {
                                tvLayoutMemberHint.setVisibility(View.VISIBLE);
                                llLayoutMemberHint.setVisibility(View.VISIBLE);
                                tvFreeCarDays.setText("（剩余" + info.getRentFreeDays() + "天）");
                            }
                        }
                    }
                });
    }

    @Override
    protected void loadData(Bundle savedInstanceState, Intent intent) {
        getOrderPrice();
    }

    @Override
    public void onShowResult(int requestType, BaseBean result) {
        switch (requestType) {
            case 0:
                priceBean = (OrderPriceBean) result;
                if (priceBean.getData() != null) {
                    tvXinDrivingPrice.setText(String.format("(¥%1$s%2$s", priceBean.getData().getDriverPrice(), "/天)"));
                    tvCarNotHurtMoney.setText(String.format("¥%1$s%2$s", priceBean.getData().getDamageSafePrice(), "/天"));
                    tvDeposit.setText(String.format("¥%1$s%2$s", priceBean.getData().getDeposit(), mActivity.getString(R.string.rv_rb)));
//                orderPriceDetailBean = new Gson().fromJson(priceBean.getData().getCostDetail(), OrderPriceDetailBean.class);
                    getPayMoney();
                }
                break;
            case 1:
                ConfirmOrderBean orderBean = (ConfirmOrderBean) result;
                orderPay(orderBean.getData().getNo());
//                startActivity(OrderListActivity.getIntent(mActivity,OrderListActivity.TYPE_FOR_PAYMENT));
                break;
            case 2:
                pay((OrderPayBean) result);
                break;
            case 3:
                aliPayData((OrderAliPayBean) result);
                break;
            case 4:
                CouponBean couponBean = (CouponBean) result;
                couponData(couponBean);
                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case TYPE_REQUEST_DRIVING:
                    drivingListBean = (DrivingListBean.DataBeanX.DataBean) data.getSerializableExtra("bean");
                    llAddDriving.setVisibility(View.VISIBLE);
                    if (dataBean != null) {
                        dataBean.setMyDriverIds(String.valueOf(drivingListBean.getId()));
                    }

                    tvPerson.setText(Html.fromHtml(getContent(drivingListBean.getName(), drivingListBean.getPhone())));
                    tvIdCard.setText(Html.fromHtml(getContent(mActivity.getString(R.string.rv_id_card), drivingListBean.getIdCard())));
                    drivingType = 2;
                    rbXinDriving.setChecked(false);
                    rbUserDriving.setChecked(true);
                    dataBean.setDriverType(2);
                    if (drivingListBean != null) {
                        llAddDriving.setVisibility(View.VISIBLE);
                    }
                    getPayMoney();
                    break;
                case 133:

                    List<CouponBean.DataBean> selectCouponList = JSON.parseArray(data.getStringExtra("selectCoupon"), CouponBean.DataBean.class);
                    List<CouponBean.DataBean> resultCouponList = JSON.parseArray(data.getStringExtra("resultCouponList"), CouponBean.DataBean.class);
                    if (resultCouponList != null && resultCouponList.size() > 0) {
                        couponDataList = resultCouponList;
                    }
                    couponIdList.clear();
                    double couponPrice = 0;
                    if (selectCouponList != null && selectCouponList.size() > 0) {
                        for (int i = 0; i < selectCouponList.size(); i++) {
                            couponIdList.add(selectCouponList.get(i).getTickerNo());
                            couponPrice = +couponPrice + selectCouponList.get(i).getUsedAmount();
                        }
                    }
                    couponAmount = couponPrice;
                    tvCouponAmount.setText("-¥" + couponAmount);

//                    selectPosition = data.getIntExtra("position", 0);
//                    if (couponDataList != null && couponDataList.size() > 0) {
//                        dataBean.setTickerNos(couponDataList.get(selectPosition).getTickerNo());
//                        couponAmount = couponDataList.get(selectPosition).getUsedAmount();
//
//                    }
                    getPayMoney();
                    break;

                case 134:
                    selectItem = JSON.parseArray(data.getStringExtra("selectItem"), SelectItemBean.DataBean.class);
                    rvContentSelect.removeAllViews();
                    selectItemList.clear();

                    if (selectItem != null && selectItem.size() > 0) {
                        for (int i = 0; i < selectItem.size(); i++) {
                            rvContentSelect.addView(buildLabel(selectItem.get(i).getName()));
                            selectItemList.add(selectItem.get(i).getId() + "," + selectItem.get(i).getNumber());
                        }
                    }
                    break;
            }
        }
    }

    @OnClick({R2.id.rl_goods, R2.id.tv_get_car_address, R2.id.tv_out_car_address, R2.id.iv_add_driving,
            R2.id.tv_detail, R2.id.tv_confirm_order, R2.id.tv_delete, R2.id.rb_xin_driving, R2.id.ll_item_xin_driving,
            R2.id.rb_user_driving, R2.id.tv_user_driving_hint, R2.id.tv_contract_agreement, R2.id.tv_service_fee_show, R2.id.tv_vehicle_cleaning_fee_show,
            R2.id.tv_lab3, R2.id.tv_deposit_hint, R2.id.tv_privilege_service_hint, R2.id.tv_booking_instructions_hint, R2.id.rl_item_select_coupon,
            R2.id.tv_item_caritem, R2.id.tv_item_select_caritem})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.rl_goods) {
        } else if (id == R.id.tv_get_car_address) {
        } else if (id == R.id.tv_out_car_address) {
        } else if (id == R.id.tv_user_driving_hint || id == R.id.iv_add_driving) {
            startActivityForResult(DrivingListActivity.getIntent(mActivity, drivingListBean, 1), TYPE_REQUEST_DRIVING);
        } else if (id == R.id.tv_detail) {
            showOrderDetail(llBottom);

        } else if (id == R.id.tv_confirm_order) {
            confirmOrder();

        } else if (id == R.id.tv_delete) {
            drivingListBean = null;
            llAddDriving.setVisibility(View.GONE);

        } else if (id == R.id.rb_xin_driving || id == R.id.ll_item_xin_driving) {
            drivingType = 1;
            rbUserDriving.setChecked(false);
            llAddDriving.setVisibility(View.GONE);
            rbXinDriving.setChecked(true);
            dataBean.setDriverType(1);

            getPayMoney();
        } else if (id == R.id.rb_user_driving) {
            drivingType = 2;
            rbXinDriving.setChecked(false);
            rbUserDriving.setChecked(true);
            dataBean.setDriverType(2);
            if (drivingListBean != null) {
                llAddDriving.setVisibility(View.VISIBLE);
            }
            getPayMoney();
        } else if (id == R.id.tv_contract_agreement) {
            ARouter.getInstance().build(Constance.ACTIVITY_URL_WEBVIEW)
                    .withString("title", mActivity.getString(R.string.rv_contract_agreement))
                    .withString("url", ApiConfig.HTTP_URL_CAR_TYPE_NOTICE)
                    .withInt("type", 25)
                    .navigation();
//            startActivity(WebActivity.getIntent(mActivity, mActivity.getString(R.string.rv_contract_agreement), ApiConfig.HTTP_URL_CAR_TYPE_NOTICE));
        } else if (id == R.id.tv_service_fee_show) {
            if (serviceFeeShow) {
                tvLayoutServiceFee.setVisibility(View.VISIBLE);
            } else {
                tvLayoutServiceFee.setVisibility(View.GONE);
            }
            serviceFeeShow = !serviceFeeShow;
        } else if (id == R.id.tv_vehicle_cleaning_fee_show) {
            if (cleanFeeShow) {
                llLayoutCleanFee.setVisibility(View.VISIBLE);
            } else {
                llLayoutCleanFee.setVisibility(View.GONE);
            }
            cleanFeeShow = !cleanFeeShow;
        } else if (id == R.id.tv_lab3) {
            if (tvLab3.isChecked()) {
                deductiblePriceType = 1;
                dataBean.setDamageSafe(1);
            } else {
                dataBean.setDamageSafe(0);
                deductiblePriceType = 0;
            }
            getPayMoney();
        } else if (id == R.id.tv_deposit_hint) {
            //欣新平台租车押金
            ARouter.getInstance().build(Constance.ACTIVITY_URL_WEBVIEW)
                    .withString("title", "欣新平台租车押金")
                    .withString("url", ApiConfig.HTTP_URL_CAR_TYPE_NOTICE)
                    .withInt("type", 4)
                    .navigation();
        } else if (id == R.id.tv_privilege_service_hint) {
            //尊享服务
            ARouter.getInstance().build(Constance.ACTIVITY_URL_WEBVIEW)
                    .withString("title", "尊享服务")
                    .withString("url", ApiConfig.HTTP_URL_CAR_TYPE_NOTICE)
                    .withInt("type", 5)
                    .navigation();
        } else if (id == R.id.tv_booking_instructions_hint) {
            //预订须知
            ARouter.getInstance().build(Constance.ACTIVITY_URL_WEBVIEW)
                    .withString("title", "预订须知")
                    .withString("url", ApiConfig.HTTP_URL_CAR_TYPE_NOTICE)
                    .withInt("type", 2)
                    .navigation();
        } else if (id == R.id.rl_item_select_coupon) {
            if (couponDataList != null) {
                //优惠券
                ARouter.getInstance()
                        .build(Constance.ACTIVITY_URL_CARCOUPON)
                        .withSerializable("coupon", JSON.toJSONString(couponDataList))
                        .navigation(this, 133);
            }
        } else if (id == R.id.tv_item_caritem) {
            //随车物品
            ARouter.getInstance().build(Constance.ACTIVITY_URL_WEBVIEW)
                    .withString("title", "随车物品说明")
                    .withString("url", ApiConfig.HTTP_URL_WEBVIEW_CARGOODS)
                    .navigation();

        } else if (id == R.id.tv_item_select_caritem) {
            //选择随车物品
            startActivityForResult(SelectItemActivity.getIntent(mActivity, JSON.toJSONString(selectItem)), 134);
        }
    }


    /**
     * 确定订单
     */
    private void confirmOrder() {
//
//        if (drivingType == 0) {
//            showToast("未选择驾驶人");
//            return;
//        }

//        if (drivingType == 2 && drivingListBean == null) {
//            showToast(mActivity.getString(R.string.rv_add_driving_toast));
//            return;
//        }

        if (drivingListBean == null) {
            showToast("请添加驾驶人！");
            return;
        }

        if (tvPassengerKnow.isChecked() == false) {
            showToast("请同意预定须知");
            return;
        }

        new PaymentTypeSelection(mActivity) {
            @Override
            public void helper(final ViewHolder helper) {
                super.helper(helper);
                helper.setText(R.id.tv_amount, tvPayMoney.getText().toString());
                helper.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int i = v.getId();
                        if (i == R.id.iv_close) {
                            dismiss();
                        } else if (i == R.id.ll_item_wechat) {
                            payType = 1;
                            helper.getView(R.id.iv_wx_select).setSelected(true);
                            helper.getView(R.id.iv_alipy_select).setSelected(false);
                        } else if (i == R.id.ll_item_alipay) {
                            payType = 2;
                            helper.getView(R.id.iv_wx_select).setSelected(false);
                            helper.getView(R.id.iv_alipy_select).setSelected(true);
                        } else if (i == R.id.tv_pay_immediately) {
                            dismiss();
                            createOrder(1);
                        }
                    }
                }, R.id.iv_close, R.id.ll_item_wechat, R.id.ll_item_alipay, R.id.tv_pay_immediately);
            }
        }.show();
    }

    /**
     * 创建订单
     */
    private void createOrder(int payType) {
        Map<String, Object> headMap = new LinkedHashMap<>();
        if (OkGoUtil.getToken() != null)
            headMap.put("Authorization", OkGoUtil.getToken());

        String ids = couponIdList.toString().replace("[", "").replace("]", "").replaceAll(" ", "");
        dataBean.setTickerNos(ids);

        dataBean.setAccompanyStrs(selectItemList);
        Log.i("confirmorderactivity", "createOrder: " + dataBean.toString());
        mPresenter.postBodyData(RvFrameConfig.VEHICLE_ORDER, payType, ApiConfig.HTTP_URL_CONFIRM_ORDER, ConfirmOrderBean.class, dataBean, headMap, true);
    }

    /**
     * 获得订单价格
     */
    private void getOrderPrice() {
        Map<String, Object> headMap = new LinkedHashMap<>();
        if (OkGoUtil.getToken() != null)
            headMap.put("Authorization", OkGoUtil.getToken());
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("driverType", 1);
        map.put("modelId", dataBean.getModelId());
        map.put("startTime", dataBean.getStartTime());
        map.put("endTime", dataBean.getEndTime());
        map.put("dayNum", dataBean.getDayNum());
        mPresenter.getData(RvFrameConfig.VEHICLE_ORDER, 0, ApiConfig.HTTP_URL_GET_ORDER_PRICE, OrderPriceBean.class, map, headMap, true);
    }

    /**
     * 订单支付
     */
    private void orderPay(String orderNo) {
        Map<String, Object> headMap = new LinkedHashMap<>();
        if (OkGoUtil.getToken() != null)
            headMap.put("Authorization", OkGoUtil.getToken());
        if (payType == 1) {
            mPresenter.postBodyData(RvFrameConfig.VEHICLE_ORDER, 2, ApiConfig.HTTP_URL_PAY_THE_CALLBACK, OrderPayBean.class, new payBody(orderNo, payType, 1), headMap, true);
        } else {
            mPresenter.postBodyData(RvFrameConfig.VEHICLE_ORDER, 3, ApiConfig.HTTP_URL_PAY_THE_CALLBACK, OrderAliPayBean.class, new payBody(orderNo, payType, 1), headMap, true);
        }

    }

    /**
     * 优惠券返回
     *
     * @param couponBean
     */
    private void couponData(CouponBean couponBean) {

        if (couponBean.getData() != null && couponBean.getData().size() > 0) {
            couponDataList = couponBean.getData();
            status = couponDataList.get(0).getStatus();

            if ("1".equals(status)) {
                dataBean.setTickerNos(couponDataList.get(0).getTickerNo());
                couponAmount = couponDataList.get(0).getUsedAmount();
                tvCouponAmount.setText("-¥" + couponDataList.get(0).getUsedAmount());
                couponDataList.get(0).setCheck(true);
                couponIdList.add(couponDataList.get(0).getTickerNo());
                getPayMoney();
            } else {
                dataBean.setTickerNos("");
                couponAmount = 0;
                tvCouponAmount.setText("暂无可用优惠券");
                getPayMoney();
            }
        } else {
            dataBean.setTickerNos("");
            couponAmount = 0;
            tvCouponAmount.setText("暂无优惠券");
        }
    }

    /**
     * 初始化View
     */
    private void intiView() {
        GlideManager.getInstance(mActivity).loadImage(mCarBean.getVehicleModel().getIcon(), ivGoods);
        tvName.setText(mCarBean.getVehicleModel().getName());
        tvContent.setText(mCarBean.getVehicleModel().getKeyword());
        ratingBar.setStarMark((float) mCarBean.getVehicleModel().getScore() / 10);
        tvPrice.setText(String.format("¥%1$s%2$s", mCarBean.getVehicleModel().getSum(), mActivity.getString(R.string.rv_day)));
        tvEventDate.setText(getIntent().getStringExtra("startTime") + "~" + getIntent().getStringExtra("endTime"));
        tvActivityDay.setText(String.format("%1$s%2$s", dataBean.getDayNum(), mActivity.getString(R.string.rv_days)));
        tvGetCarAddress.setText(dataBean.getStartAddr());
        tvOutCarAddress.setText(dataBean.getEndAddr());

        String spStringCode = UtilsManager.getInstance(OkGoUtil.application).getSPStringCode(SPConstance.USER_JSON, SPConstance.USER_JSON_USERINFO);
        if (!TextUtil.isEmpty(spStringCode)) {
            info = JSON.parseObject(spStringCode, BeanUserInfo.UserInfo.class);
        }

        if (info != null) {
            if (0 == info.getIsMember()) {
                tvLayoutMemberHint.setVisibility(View.GONE);
                llLayoutMemberHint.setVisibility(View.GONE);
            } else if (1 == info.getIsMember()) {
                tvLayoutMemberHint.setVisibility(View.VISIBLE);
                llLayoutMemberHint.setVisibility(View.VISIBLE);
                tvFreeCarDays.setText("（剩余" + info.getRentFreeDays() + "天）");
            }
        }

        swbtnMember.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                if (isChecked) {
                    isMemberType = 1;
                    dataBean.setRentFreeDay(1);
                } else {
                    dataBean.setRentFreeDay(0);
                    isMemberType = 0;
                }
                couponAmount = 0;
                getPayMoney();
            }
        });
    }

    /**
     * 支付价格计算
     */
    private void getPayMoney() {
        if (priceBean == null || priceBean.getData() == null || dataBean == null) {
            return;
        }

        ArrayList<OrderPriceDetailBean.ChildrenBean> childrenBeanList = new ArrayList<>(); //费用明细
        double payMoney = 0.00;
        double dayPrice = mCarBean.getVehicleModel().getSum();
        int dayNum = dataBean.getDayNum();
        if (isMemberType == 0) {  //是否使用会员  0 不使用
            payMoney = dayPrice * dayNum + priceBean.getData().getDeposit();  //租车和押金价格

            carAmount = dayPrice * dayNum;
            OrderPriceDetailBean.ChildrenBean childrenBean2 = new OrderPriceDetailBean.ChildrenBean();
            childrenBean2.setKey("车辆租赁费");
            childrenBean2.setDetail("¥" + dayPrice + "/天 *" + dayNum + "天");
            childrenBean2.setVal("¥" + dayPrice * dayNum);
            childrenBeanList.add(childrenBean2);
        } else {
            if (info != null) {
                if (dayNum > info.getRentFreeDays()) {
                    payMoney = dayPrice * (dayNum - info.getRentFreeDays()) + priceBean.getData().getDeposit();

                    carAmount = dayPrice * (dayNum - info.getRentFreeDays());
                    OrderPriceDetailBean.ChildrenBean childrenBean1 = new OrderPriceDetailBean.ChildrenBean();
                    childrenBean1.setKey("车辆租赁费");
                    childrenBean1.setDetail("¥" + dayPrice + "/天 *" + (dayNum - info.getRentFreeDays()) + "天");
                    childrenBean1.setVal("¥" + dayPrice * (dayNum - info.getRentFreeDays()));
                    childrenBeanList.add(childrenBean1);
                } else if (dayNum <= info.getRentFreeDays()) {
                    payMoney = priceBean.getData().getDeposit();
                    carAmount = 0;
                }
            }
        }
        if (drivingType == 1) {
            payMoney = payMoney + priceBean.getData().getDriverAmount();  // + 专职司机
            OrderPriceDetailBean.ChildrenBean childrenBean3 = new OrderPriceDetailBean.ChildrenBean();
            childrenBean3.setKey("专职司机服务费");
            childrenBean3.setDetail("¥" + priceBean.getData().getDriverPrice() + "/天 *" + dayNum + "天");
            childrenBean3.setVal("¥" + priceBean.getData().getDriverAmount());
            childrenBeanList.add(childrenBean3);
        }

        if (deductiblePriceType == 1) {
            payMoney = payMoney + priceBean.getData().getDamageSafePrice() * dayNum; //+免赔付价格

            OrderPriceDetailBean.ChildrenBean childrenBean4 = new OrderPriceDetailBean.ChildrenBean();
            childrenBean4.setKey("车损免赔费");
            childrenBean4.setDetail("¥" + priceBean.getData().getDamageSafePrice() + "/天 *" + dayNum + "天");
            childrenBean4.setVal("¥" + priceBean.getData().getDamageSafePrice() * dayNum);
            childrenBeanList.add(childrenBean4);
        }

        if (carAmount > couponAmount) { //租车金额大于 优惠券
            payMoney = payMoney - couponAmount;//优惠券
        } else {
            payMoney = payMoney - carAmount;   //不用支付租车钱
        }

        tvPayMoney.setText(String.format("¥%1$s", new BigDecimal(payMoney).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()));

        orderPriceDetailBean = new OrderPriceDetailBean();
        orderPriceDetailBean.setKey("费用明细");

        OrderPriceDetailBean.ChildrenBean childrenBean = new OrderPriceDetailBean.ChildrenBean();
        childrenBean.setKey("租房车押金");
        childrenBean.setVal("¥" + priceBean.getData().getDeposit());
        childrenBeanList.add(childrenBean);

        if (couponAmount > 0) {
            OrderPriceDetailBean.ChildrenBean childrenBean5 = new OrderPriceDetailBean.ChildrenBean();
            childrenBean5.setKey("优惠券");
            childrenBean5.setVal("-¥" + couponAmount);
            childrenBeanList.add(childrenBean5);
        }

        orderPriceDetailBean.setChildren(childrenBeanList);

        if (carAmount != oldCarAmount) {
            geCouponDataList();
            oldCarAmount = carAmount;
        }
    }

    /**
     * 优惠券请求数据
     */
    private void geCouponDataList() {
        Map<String, Object> headMap = new LinkedHashMap<>();
        if (OkGoUtil.getToken() != null)
            headMap.put("Authorization", OkGoUtil.getToken());
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("type", 0);
        map.put("channel", "1");
        map.put("amount", carAmount);
        mPresenter.getData(RvFrameConfig.HOST, 4, CouponApi.HTTP_URL_COUPON_LIST, CouponBean.class, map, headMap, false);
    }

    private String getContent(String name, String card) {
        return String.format("%1$s <font color='#666666'>%2$s</font>", name, card);
    }

    /**
     * 显示价格明细弹窗
     */
    private void showOrderDetail(final View view) {
        if (orderPriceDetailBean != null) {
            if (detailPw == null) {
                detailPw = new OrderPriceDetailPw(mActivity) {
                };
            }
            detailPw.setNewData(orderPriceDetailBean);
            View contentView = detailPw.getContentView();
            //需要先测量，PopupWindow还未弹出时，宽高为0
            contentView.measure(makeDropDownMeasureSpec(detailPw.getWidth()), makeDropDownMeasureSpec(detailPw.getHeight()));
//            int[] location = new int[2];
//
//            view.getLocationOnScreen(location);
//            int hh=location[1]-detailPw.getHeight();
//            detailPw.showAtLocation(view, Gravity.NO_GRAVITY,
//                    location[0], hh);

//            detailPw.showAsDropDown(view, 0,0, Gravity.NO_GRAVITY);
//            int kk=detailPw.getContentView().getMeasuredHeight();
//            int cc=view.getHeight();

            int offsetX = Math.abs(detailPw.getContentView().getMeasuredWidth() - view.getWidth()) / 2;
            int offsetY = -(detailPw.getContentView().getMeasuredHeight() + view.getHeight());
            PopupWindowCompat.showAsDropDown(detailPw, view, offsetX, offsetY, Gravity.START);

            /**
             * 点击popupWindow让背景变暗
             */
            final WindowManager.LayoutParams lp = getWindow().getAttributes();
            lp.alpha = 0.5f;//代表透明程度，范围为0 - 1.0f
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
            getWindow().setAttributes(lp);
            /**
             * 退出popupWindow时取消暗背景
             */
            detailPw.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    lp.alpha = 1.0f;
                    getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                    getWindow().setAttributes(lp);
                }
            });
        }
    }

    @SuppressWarnings("ResourceType")
    private int makeDropDownMeasureSpec(int measureSpec) {
        int mode;
        if (measureSpec == ViewGroup.LayoutParams.WRAP_CONTENT) {
            mode = View.MeasureSpec.UNSPECIFIED;
        } else {
            mode = View.MeasureSpec.EXACTLY;
        }
        return View.MeasureSpec.makeMeasureSpec(View.MeasureSpec.getSize(measureSpec), mode);
    }

    /**
     * 微信支付
     *
     * @param data
     */
    private void pay(OrderPayBean data) {
        try {

            PayReq req = new PayReq();
            req.appId = data.getData().getAppid();
            req.partnerId = data.getData().getPartnerid();
            req.prepayId = data.getData().getPrepayid();
            req.nonceStr = data.getData().getNoncestr();
            req.timeStamp = data.getData().getTimestamp();
            req.packageValue = data.getData().getPackageX();
            req.sign = data.getData().getSign();
            req.extData = "app data"; // optional
            api.sendReq(req);
        } catch (Exception e) {
            showToast("异常");
        }
    }

    /**
     * 显示支付宝签名
     */
    public void aliPayData(final OrderAliPayBean bean) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(ConfirmOrderActivity.this);
                Map<String, String> result = alipay.payV2(bean.getData(), true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = SDK_ALI_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }


    /**
     * 支付宝返回数据handler
     */
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {

        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_ALI_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);

                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        startActivity(OrderListActivity.getIntent(mActivity, 1));
                        finish();
                    } else if ("6001".equals(resultStatus)) {
                        startActivity(OrderListActivity.getIntent(mActivity, 0));
                        showToast("支付取消！");
                        finish();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        showToast(payResult.toString());
                    }
                    break;
                }
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    public class payBody {
        private String orderNo;
        private int payWay;
        private int type;

        public payBody(String orderNo, int payWay, int type) {
            this.orderNo = orderNo;
            this.payWay = payWay;
            this.type = type;
        }

        public String getOrderNo() {
            return orderNo;
        }

        public void setOrderNo(String orderNo) {
            this.orderNo = orderNo;
        }

        public int getPayWay() {
            return payWay;
        }

        public void setPayWay(int payWay) {
            this.payWay = payWay;
        }

        public int getType() {
            return type;
        }

        public void setType(int type) {
            this.type = type;
        }
    }
}

