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.RatingBar;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.base.utils.ui.datetime.selector.util.TextUtil;
import com.frame.base.bus.PaymentFailedEvent;
import com.frame.base.bus.PaymentSuccessfulEvent;
import com.frame.base.bus.RxBus;
import com.frame.rv.config.RvFrameConfig;
import com.google.gson.Gson;
import com.ruiwenliu.wrapper.SPConstance;
import com.ruiwenliu.wrapper.base.BaseBean;
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.PaymentTypeSelection;
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.bean.BeanUserInfo;
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.bean.OrderPriceDetailBean;
import com.rv.home.rv.module.ui.main.home.dialog.OrderPriceDetailPw;
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.yuyife.okgo.OkGoUtil;

import java.util.LinkedHashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;
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)
    RatingBar 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;


    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 ;//驾驶证类型1、欣新驾驶员2、自驾
    private OrderPriceDetailPw detailPw;//显示订单价格明细弹窗
    private OrderPriceDetailBean orderPriceDetailBean;//订单价格明细实体类
    private IWXAPI api;
    private int payType;//选择支付类型
    private OrderPriceBean priceBean;
    BeanUserInfo.UserInfo info = null;
    private int deductiblePriceType;

    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 Consumer<PaymentSuccessfulEvent>() {
                    @Override
                    public void accept(PaymentSuccessfulEvent payEvent) throws Exception {
                        finish();
                    }
                });

        RxBus.tObservable(PaymentFailedEvent.class)
                .observeOn(Schedulers.newThread())
                .subscribe(new Consumer<PaymentFailedEvent>() {
                    @Override
                    public void accept(PaymentFailedEvent payEvent) throws Exception {
                        showToast("333333");
                        if (mActivity.getClass().equals(ConfirmOrderActivity.class)) {
                            startActivity(OrderListActivity.getIntent(mActivity, 0));
                            finish();
                        }
                    }
                });
    }

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

    @Override
    public void onShowResult(int requestType, BaseBean result) {
        switch (requestType) {
            case 0:
                priceBean = (OrderPriceBean) result;
                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;
        }
    }


    @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())));
                    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.rb_user_driving, R2.id.tv_contract_agreement, R2.id.tv_service_fee_show, R2.id.tv_vehicle_cleaning_fee_show, R2.id.tv_lab3})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.rl_goods) {
        } else if (i == R.id.tv_get_car_address) {
        } else if (i == R.id.tv_out_car_address) {
        } else if (i == R.id.iv_add_driving) {
            startActivityForResult(DrivingListActivity.getIntent(mActivity, drivingListBean), TYPE_REQUEST_DRIVING);
        } else if (i == R.id.tv_detail) {
            showOrderDetail(llBottom);

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

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

        } else if (i == R.id.rb_xin_driving) {
            drivingType = 1;
            rbUserDriving.setChecked(false);
            llAddDriving.setVisibility(View.GONE);
            rbXinDriving.setChecked(true);
            getPayMoney();
        } else if (i == R.id.rb_user_driving) {
            drivingType = 2;
            rbXinDriving.setChecked(false);
            rbUserDriving.setChecked(true);
            if (drivingListBean != null) {
                llAddDriving.setVisibility(View.VISIBLE);
            }
            getPayMoney();
        } else if (i == R.id.tv_contract_agreement) {
            startActivity(WebActivity.getIntent(mActivity, mActivity.getString(R.string.rv_contract_agreement), ApiConfig.HTTP_URL_CAR_TYPE_NOTICE));
        } else if (i == R.id.tv_service_fee_show) {
            if (serviceFeeShow) {
                tvLayoutServiceFee.setVisibility(View.VISIBLE);
            } else {
                tvLayoutServiceFee.setVisibility(View.GONE);
            }
            serviceFeeShow = !serviceFeeShow;
        } else if (i == R.id.tv_vehicle_cleaning_fee_show) {
            if (cleanFeeShow) {
                llLayoutCleanFee.setVisibility(View.VISIBLE);
            } else {
                llLayoutCleanFee.setVisibility(View.GONE);
            }
            cleanFeeShow = !cleanFeeShow;
        } else if (i == R.id.tv_lab3) {
            if (tvLab3.isChecked()) {
                deductiblePriceType = 1;
                dataBean.setDamageSafe(1);
            } else {
                dataBean.setDamageSafe(0);
                deductiblePriceType = 0;
            }
            getPayMoney();
        }
    }

    /**
     * 确定订单
     */
    private void confirmOrder() {
        if (drivingType == 2 && drivingListBean == null) {
            showToast(mActivity.getString(R.string.rv_add_driving_toast));
            return;
        }
        if (tvPassengerKnow.isChecked() == false) {
            showToast("请同意预定须知 ¥");
            return;
        }
//        showToast("token" +RvFrameConfig.APP_TOKEN);

        new PaymentTypeSelection(mActivity) {
            @Override
            public void helper(final ViewHolder helper) {
                super.helper(helper);
                helper.setText(R.id.tv_amount, String.format("¥%1$s", priceBean.getData().getOrderAmount()));
                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> 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, 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);
    }


    /**
     * 初始化View
     */
    private void intiView() {
        GlideManager.getInstance(mActivity).loadImage(mCarBean.getVehicleModel().getIcon(), ivGoods);
        tvName.setText(mCarBean.getVehicleModel().getName());
        tvContent.setText(mCarBean.getVehicleModel().getKeyword());
        ratingBar.setRating((float) mCarBean.getVehicleModel().getPoint());
        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) {
                    dataBean.setRentFreeDay(1);
                } else {
                    dataBean.setRentFreeDay(0);
                }
            }
        });
    }

    /**
     * 支付价格计算
     */
    private void getPayMoney() {
        double payMoney = 0.00;
        double dayPrice = mCarBean.getVehicleModel().getSum();
        int dayNum = dataBean.getDayNum();
        payMoney = dayPrice * dayNum + priceBean.getData().getDeposit();  //租车和押金价格
        if (drivingType == 1) {
            payMoney = payMoney + priceBean.getData().getDriverAmount();  // + 专职司机
        }
        if (deductiblePriceType ==1){
            payMoney = payMoney +priceBean.getData().getDamageSafePrice() * dayNum; //+免赔付价格
        }
        tvPayMoney.setText(String.format("¥%1$s", payMoney));
    }

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

