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.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.EditText;
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.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.base.BaseBean;
import com.ruiwenliu.wrapper.base.BaseStatusActivity;
import com.ruiwenliu.wrapper.base.presenter.CommonPresenter;
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.PaymentTypeSelection;
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.ui.main.home.adapter.SelectedItemAdapter;
import com.rv.home.rv.module.ui.main.home.bean.CarRentalPriceBean;
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.OrderCalendarPriceBean;
import com.rv.home.rv.module.ui.main.home.bean.OrderCarPriceDetailBean;
import com.rv.home.rv.module.ui.main.home.bean.OrderDataBean;
import com.rv.home.rv.module.ui.main.home.bean.OrderMemberBean;
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.dialog.CheckPriceDialog;
import com.rv.home.rv.module.ui.main.home.dialog.OrderCarPriceDetailPw;
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.CarCouponBean;
import com.yuyife.okgo.OkGoUtil;

import java.math.BigDecimal;
import java.util.ArrayList;
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_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;
    @BindView(R2.id.edt_inviter_phone)
    EditText edtInviterPhone;
    @BindView(R2.id.tv_mark)
    TextView tvMark;
    @BindView(R2.id.tv_day_price)
    TextView tvDayPrice;


    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 OrderCarPriceDetailPw detailPw;//显示订单价格明细弹窗
    private OrderCarPriceDetailBean 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<CarCouponBean.DataBean.CarCouponTypeDataBean> 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;
    private List<CarCouponBean.DataBean.CarCouponTypeDataBean.CarCouponDataBean> selectCouponList = null;
    private OrderMemberBean.DataBean memberData;
    private OrderCalendarPriceBean calendarPriceBean;

    private String begDate;
    private String endDate;

    private CheckPriceDialog checkPriceDialog;
    private boolean isDayPrice;

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

    @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");
        priceBean = (OrderPriceBean) intent.getSerializableExtra("priceBean");
        begDate = getIntent().getStringExtra("startTime");
        endDate = getIntent().getStringExtra("endTime");
        intiView();
        initRxBus();

        selectCouponList = new ArrayList<>();

//        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) {
        getCarPrice();
    }


    @Override
    public void onShowResult(int requestType, BaseBean result) {
        switch (requestType) {
            case 0:
                calendarPriceBean = (OrderCalendarPriceBean) result;
                getMember();
                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:
                CarCouponBean couponBean = (CarCouponBean) result;
                couponData(couponBean);
                break;
            case 6:
                OrderMemberBean orderMemberBean = (OrderMemberBean) result;
                if (orderMemberBean != null) {
                    memberData = orderMemberBean.getData();
                    mCarBean.getVehicleModel().setMember(orderMemberBean.getData());
                }
                intiView();
                getPayMoney();
//                getOrderPrice();
                break;
            case 7:
                checkPrice((CarRentalPriceBean) result);
                break;
        }
    }

    /**
     * 设置价格日历
     *
     * @param result
     */
    private void checkPrice(CarRentalPriceBean result) {
        if (checkPriceDialog != null) {
            checkPriceDialog.setNewData(result.getData());
            checkPriceDialog.show();
        }
    }


    @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:
                    selectCouponList.clear();
                    selectCouponList = JSON.parseArray(data.getStringExtra("selectCoupon"), CarCouponBean.DataBean.CarCouponTypeDataBean.CarCouponDataBean.class);
                    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("-¥" + new BigDecimal(couponAmount).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                    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.ll_item_service_fee, R2.id.ll_item_vehicle_cleaning_fee,
            R2.id.tv_lab3, R2.id.tv_deposit_hint, R2.id.tv_booking_instructions_hint, R2.id.rl_item_select_coupon,
            R2.id.tv_item_caritem, R2.id.tv_item_select_caritem, R2.id.tv_item_loook_price, R2.id.iv_lab3_hint})
    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.ll_item_service_fee) {
            if (serviceFeeShow) {
                tvLayoutServiceFee.setVisibility(View.VISIBLE);
            } else {
                tvLayoutServiceFee.setVisibility(View.GONE);
            }
            serviceFeeShow = !serviceFeeShow;
        } else if (id == R.id.ll_item_vehicle_cleaning_fee) {
            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_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))
                        .withSerializable("selectCoupon", JSON.toJSONString(selectCouponList))
                        .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);
        } else if (id == R.id.tv_item_loook_price) {
            //查看每天价格
            if (checkPriceDialog == null) {
                checkPriceDialog = new CheckPriceDialog(mActivity);
            }
            getDailyPrice();
        } else if (id == R.id.iv_lab3_hint) {
            ARouter.getInstance().build(Constance.ACTIVITY_URL_WEBVIEW)
                    .withString("title", "车损免赔说明")
                    .withString("url", ApiConfig.HTTP_URL_CAR_TYPE_NOTICE)
                    .withInt("type", 5)
                    .navigation();
        }
    }


    /**
     * 确定订单
     */
    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;
        }
        String inviterPhone = edtInviterPhone.getText().toString().trim();
        if (!TextUtils.isEmpty(inviterPhone) && inviterPhone.length() != 11) {
            showToast("请输入正确的邀请人手机号");
            return;
        }
        dataBean.setFacilitatePhone(inviterPhone);

        payType = 1;
        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();
    }

    /**
     * 获取价格日历
     */
    public void getDailyPrice() {
        Map<String, Object> headMap = new LinkedHashMap<>();
        if (OkGoUtil.getToken() != null)
            headMap.put("Authorization", OkGoUtil.getToken());
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("start", begDate);
        map.put("end", endDate);
        mPresenter.getData(RvFrameConfig.HOST, 7, ApiConfig.HTTP_URL_CALENDAR_PRICE + mCarBean.getVehicleModel().getId(), CarRentalPriceBean.class, map, headMap, false);
    }

    /**
     * 获取每天价格
     */
    private void getCarPrice() {
        Map<String, Object> headMap = new LinkedHashMap<>();
        if (OkGoUtil.getToken() != null)
            headMap.put("Authorization", OkGoUtil.getToken());
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("startDate", dataBean.getStartTime());
        map.put("endDate", dataBean.getEndTime());
        map.put("vehicleModelId", mCarBean.getVehicleModel().getId());
        mPresenter.getData(RvFrameConfig.VEHICLE_ORDER, 0, ApiConfig.HTTP_URL_CALENDAR_UNAUTH_PRICE, OrderCalendarPriceBean.class, map, headMap, true);
    }


    /**
     * 创建订单
     */
    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 getMember() {
        Map<String, Object> headMap = new LinkedHashMap<>();
        if (OkGoUtil.getToken() != null) {
            headMap.put("Authorization", OkGoUtil.getToken());
            mPresenter.getDataHead(RvFrameConfig.HOST, 6, ApiConfig.RVENTHUSIAST_GETUSERMEMBER, OrderMemberBean.class, 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(CarCouponBean couponBean) {
        selectCouponList.clear();
        if (couponBean.getData() != null) {
            couponDataList = couponBean.getData().getArray();
            if (couponBean.getData().getCoupon() == null) {
                dataBean.setTickerNos("");
                couponAmount = 0;
                tvCouponAmount.setText("暂无可用优惠券");
                getPayMoney();
            } else {
                couponIdList.clear();
                selectCouponList.add(couponBean.getData().getCoupon());
                couponIdList.add(couponBean.getData().getCoupon().getTickerNo());
                couponAmount = couponBean.getData().getCoupon().getUsedAmount();
                tvCouponAmount.setText("-¥" + couponBean.getData().getCoupon().getUsedAmount());
                getPayMoney();
            }
        } else {
            couponDataList.clear();
            dataBean.setTickerNos("");
            couponAmount = 0;
            tvCouponAmount.setText("暂无优惠券");
        }
    }

    /**
     * 初始化View
     */
    private void intiView() {
        String icon = "";
        if (!TextUtils.isEmpty(mCarBean.getVehicleModel().getCoverPic())) {
            icon = mCarBean.getVehicleModel().getCoverPic();
        } else {
            icon = mCarBean.getVehicleModel().getIcon();
        }
        GlideManager.getInstance(mActivity).loadImage(icon, ivGoods);
        float score = (float) mCarBean.getVehicleModel().getScore() / 10;
        tvMark.setText(score + "分");

        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());

        tvDayPrice.setText(String.format("¥%1$s%2$s", mCarBean.getVehicleModel().getSum(), "/天起"));

//        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 (memberData == null) {
            tvLayoutMemberHint.setVisibility(View.GONE);
            llLayoutMemberHint.setVisibility(View.GONE);
        } else {
            tvLayoutMemberHint.setVisibility(View.VISIBLE);
            llLayoutMemberHint.setVisibility(View.VISIBLE);
            tvFreeCarDays.setText("（剩余" + memberData.getRentFreeDays() + "天）");
            if (memberData.getRentFreeDays() > 0) {
                swbtnMember.setChecked(true);
                isMemberType = 1;
                dataBean.setRentFreeDay(1);
                couponAmount = 0;
                getPayMoney();
            } else {
                dataBean.setRentFreeDay(0);
                isMemberType = 0;
            }
        }

        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);
        }


        swbtnMember.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (memberData != null) {
                    if (memberData.getRentFreeDays() == 0) {
                        swbtnMember.setChecked(false);
                        showToast("免费用车天数为0");
                        return true;
                    }
                }
                return false;
            }
        });

        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 || calendarPriceBean == null || calendarPriceBean.getData() == null || calendarPriceBean.getData().size() <= 0) {
            return;
        }

        ArrayList<OrderCarPriceDetailBean.ChildrenBean> childrenBeanList = new ArrayList<>(); //费用明细
        double payMoney = 0.00;
//        double dayPrice = mCarBean.getVehicleModel().getSum();
        double totalCarPrice = 0.00;   //租车总价
        double totalMemberDays = 0;    //会员天数

        for (int i = 0; i < calendarPriceBean.getData().size(); i++) {
            totalCarPrice = totalCarPrice + calendarPriceBean.getData().get(i).getPrice();
            totalMemberDays = totalMemberDays + calendarPriceBean.getData().get(i).getFreeDays();
        }

        double onePrice = calendarPriceBean.getData().get(0).getPrice();//取第一天价格，比较全部价格是否相同
        for (int i = 0; i < calendarPriceBean.getData().size(); i++) {
            if (onePrice != calendarPriceBean.getData().get(i).getPrice()) {
                isDayPrice = true;
                break;
            }
        }

        int dayNum = this.dataBean.getDayNum();

        OrderCarPriceDetailBean.ChildrenBean childrenBean2 = new OrderCarPriceDetailBean.ChildrenBean();
        childrenBean2.setKey("车辆租赁费");
        childrenBean2.setDetail(dayNum + "天");
        childrenBean2.setVal("¥" + new BigDecimal(totalCarPrice).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
        childrenBean2.setDataBean(calendarPriceBean.getData());
        childrenBean2.setDayPrice(isDayPrice);
        childrenBeanList.add(childrenBean2);

        if (isMemberType == 0) {  //是否使用会员  0 不使用
            payMoney = totalCarPrice + priceBean.getData().getDeposit();  //租车和押金价格
            carAmount = totalCarPrice;

        } else {
            if (memberData != null) {
                if (totalMemberDays > memberData.getRentFreeDays()) {  //个人会员天数小于租车使用会员天数
                    double useTotalMemberPrice = 0.00;
                    double useTotalMemberDays = 0;
                    double memberPrice = 0;
                    for (int j = 0; j < calendarPriceBean.getData().size(); j++) {
                        if (useTotalMemberDays < memberData.getRentFreeDays()) {
                            useTotalMemberDays = useTotalMemberDays + calendarPriceBean.getData().get(j).getFreeDays();
                            useTotalMemberPrice = useTotalMemberPrice + calendarPriceBean.getData().get(j).getPrice();
                            memberPrice = calendarPriceBean.getData().get(j).getPrice() / calendarPriceBean.getData().get(j).getFreeDays();  //计算最后使用会员单价
                        } else {
                            break;
                        }
                    }
                    useTotalMemberPrice = useTotalMemberPrice - (useTotalMemberDays - memberData.getRentFreeDays()) * memberPrice;
                    payMoney = totalCarPrice - useTotalMemberPrice + priceBean.getData().getDeposit();
                    carAmount = totalCarPrice - useTotalMemberPrice;

//                    payMoney = dayPrice * (dayNum - memberData.getRentFreeDays()) + priceBean.getData().getDeposit();

                    OrderCarPriceDetailBean.ChildrenBean childrenBean1 = new OrderCarPriceDetailBean.ChildrenBean();
                    childrenBean1.setKey("免费天数");
                    childrenBean1.setDetail("会员天数" + (memberData.getRentFreeDays()) + "天");
                    childrenBean1.setVal("-¥" + new BigDecimal(useTotalMemberPrice).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                    childrenBeanList.add(childrenBean1);
                } else if (totalMemberDays <= memberData.getRentFreeDays()) {
                    payMoney = priceBean.getData().getDeposit();
                    carAmount = 0;

                    OrderCarPriceDetailBean.ChildrenBean childrenBean1 = new OrderCarPriceDetailBean.ChildrenBean();
                    childrenBean1.setKey("免费天数");
                    childrenBean1.setDetail("会员天数" + totalMemberDays + "天");
                    childrenBean1.setVal("-¥" + new BigDecimal(totalCarPrice).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                    childrenBeanList.add(childrenBean1);
                }
            }
        }
        if (drivingType == 1) {
            payMoney = payMoney + priceBean.getData().getDriverAmount();  // + 专职司机
            OrderCarPriceDetailBean.ChildrenBean childrenBean3 = new OrderCarPriceDetailBean.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; //+免赔付价格

            OrderCarPriceDetailBean.ChildrenBean childrenBean4 = new OrderCarPriceDetailBean.ChildrenBean();
            childrenBean4.setKey("车损免赔费");
            childrenBean4.setDetail("¥" + priceBean.getData().getDamageSafePrice() + "/天 *" + dayNum + "天");
            childrenBean4.setVal("¥" + new BigDecimal(priceBean.getData().getDamageSafePrice() * dayNum).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
            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 OrderCarPriceDetailBean();
        orderPriceDetailBean.setKey("费用明细");

        OrderCarPriceDetailBean.ChildrenBean childrenBean = new OrderCarPriceDetailBean.ChildrenBean();
        childrenBean.setKey("租房车押金");
        childrenBean.setVal("¥" + new BigDecimal(priceBean.getData().getDeposit()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
        childrenBeanList.add(childrenBean);

        if (couponAmount > 0) {
            OrderCarPriceDetailBean.ChildrenBean childrenBean5 = new OrderCarPriceDetailBean.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_TYPELIST, CarCouponBean.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 OrderCarPriceDetailPw(mActivity) {
                };
            }

            if (detailPw != null) {
                detailPw.setNewData(orderPriceDetailBean);
                detailPw.show();
            }
         /*   View contentView = detailPw.getContentView();
            //需要先测量，PopupWindow还未弹出时，宽高为0
            contentView.measure(makeDropDownMeasureSpec(detailPw.getWidth()), makeDropDownMeasureSpec(detailPw.getHeight()));
            detailPw.setHeight(detailPw.getContentView().getMeasuredHeight());


            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;
        }
    }
}

