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.support.v4.widget.PopupWindowCompat;
import android.text.Html;
import android.util.Log;
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.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.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.SwitchButton;
import com.rv.component.dialog.OrderPriceDetailPw;
import com.rv.component.dialog.PaymentTypeSelection;
import com.rv.component.dialog.bean.OrderPriceDetailBean;
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.WebActivity;
import com.rv.home.rv.module.basic.presenter.CommonPresenter;
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.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.order.OrderListActivity;
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.io.Serializable;
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> {
    @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;

    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;//选择支付类型
    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 int selectPosition;//新选中
    private int oldSelectPosition;//上一次选中
    private double couponAmount = 0; //优惠券金额
    private String status = "1";// 优惠券状态

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

    @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(), 1, 1);
//                startActivity(OrderListActivity.getIntent(mActivity,OrderListActivity.TYPE_FOR_PAYMENT));
                break;
            case 2:
                pay((OrderPayBean) result);
                break;
            case 3:
                startActivity(OrderListActivity.getIntent(mActivity, 0));
                finish();
                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);
                    if (drivingListBean != null) {
                        llAddDriving.setVisibility(View.VISIBLE);
                    }
                    getPayMoney();
                    break;
                case 133:
                    selectPosition = data.getIntExtra("position", 0);
                    if (couponDataList != null && couponDataList.size() > 0) {
                        dataBean.setTickerNos(couponDataList.get(selectPosition).getTickerNo());
                        couponAmount = couponDataList.get(selectPosition).getUsedAmount();
                        tvCouponAmount.setText("-¥" + couponAmount);
                    }
                    getPayMoney();
                    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})
    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.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 || id == R.id.tv_user_driving_hint) {
            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) {
            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) {
                if (couponDataList.size() > 0 && "1".equals(status)) {
                    couponDataList.get(oldSelectPosition).setCheck(false);
                    couponDataList.get(selectPosition).setCheck(true);
                    oldSelectPosition = selectPosition;
                }
                //优惠券
                ARouter.getInstance()
                        .build(Constance.ACTIVITY_URL_CARCOUPON)
                        .withSerializable("coupon", JSON.toJSONString(couponDataList))
                        .navigation(this, 133);
            }
        }
    }


    /**
     * 确定订单
     */
    private void confirmOrder() {

        if (drivingType == 0) {
            showToast("未选择驾驶人");
            return;
        }

        if (drivingType == 2 && drivingListBean == null) {
            showToast(mActivity.getString(R.string.rv_add_driving_toast));
            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();
                            createOrder(3);
                        } else if (i == R.id.ll_item_wechat) {
                            payType = 1;
                            helper.setChecked(R.id.rb_wechat, true);
                            helper.setChecked(R.id.rb_alipay, false);

                        } else if (i == R.id.ll_item_alipay) {
                            payType = 2;
                            showToast("该功能还没有开通！");
//                                helper.setChecked(R.id.rb_wechat,false);
//                                helper.setChecked(R.id.rb_alipay,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());
        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, int payWay, int type) {
        Map<String, Object> headMap = new LinkedHashMap<>();
        if (OkGoUtil.getToken() != null)
            headMap.put("Authorization", OkGoUtil.getToken());
        mPresenter.postBodyData(RvFrameConfig.VEHICLE_ORDER, 2, ApiConfig.HTTP_URL_PAY_THE_CALLBACK, OrderPayBean.class, new payBody(orderNo, payWay, type), 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());
                getPayMoney();
            } else {
                tvCouponAmount.setText("暂无可用优惠券");
            }
        } else {
            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;
                }
                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);
        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);
    }

    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("异常");
        }

    }

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

