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.frame.rv.config.RvFrameConfig;
import com.google.gson.Gson;
import com.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.util.ViewHolder;
import com.ruiwenliu.wrapper.util.glide.GlideManager;
import com.ruiwenliu.wrapper.weight.TitleView;
import com.frame.base.bus.PaymentFailedEvent;
import com.frame.base.bus.PaymentSuccessfulEvent;
import com.frame.base.bus.RxBus;
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.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.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_time)
    TextView tvGetTime;
    @BindView(R2.id.tv_get_week)
    TextView tvGetWeek;
    @BindView(R2.id.tv_day)
    TextView tvDay;
    @BindView(R2.id.tv_out_time)
    TextView tvOutTime;
    @BindView(R2.id.tv_out_week)
    TextView tvOutWeek;
    @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_give_car_info)
    TextView tvGiveCarInfo;
    @BindView(R2.id.tv_give_car_content)
    TextView tvGiveCarContent;
    @BindView(R2.id.tv_car_not_hurt)
    TextView tvCarNotHurt;
    @BindView(R2.id.tv_car_not_hurt_money)
    TextView tvCarNotHurtMoney;
    @BindView(R2.id.tv_car_not_hurt_content)
    TextView tvCarNotHurtContent;
    @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;


    private final int TYPE_REQUEST_DRIVING = 3;
    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;

    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;
                tvPayMoney.setText(String.format("¥%1$s", priceBean.getData().getOrderAmount()));
                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);
                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_time, R2.id.tv_get_week, R2.id.tv_out_time, R2.id.tv_out_week, R2.id.tv_get_car_address, R2.id.tv_out_car_address, R2.id.iv_add_driving, R2.id.tv_give_car_info,
            R2.id.tv_give_car_content, 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})
    public void onViewClicked(View view) {

        int i = view.getId();
        if (i == R.id.rl_goods) {
        } else if (i == R.id.tv_get_time) {
        } else if (i == R.id.tv_get_week) {
        } else if (i == R.id.tv_out_time) {
        } else if (i == R.id.tv_out_week) {
        } 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_give_car_info) {
        } else if (i == R.id.tv_give_car_content) {
        } 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);
            getOrderPrice();

        } else if (i == R.id.rb_user_driving) {
            drivingType = 2;
            rbXinDriving.setChecked(false);
            rbUserDriving.setChecked(true);
            if (drivingListBean != null) {
                llAddDriving.setVisibility(View.VISIBLE);
            }
            getOrderPrice();

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

//        if(view.getId()==R.id.iv_add_driving){
//            startActivityForResult(DrivingListActivity.getIntent(mActivity), TYPE_REQUEST_DRIVING);
//        }else if(view.getId()==R.id.tv_detail){
//            showOrderDetail(llBottom);
//        }else if(view.getId()==R.id.tv_confirm_order){
//            confirmOrder();
//        }else if(view.getId()==R.id.tv_delete){
//            drivingListBean = null;
//            llAddDriving.setVisibility(View.GONE);
//        }else if(view.getId()==R.id.iv_add_driving){
//
//        }else if(view.getId()==R.id.iv_add_driving){
//
//        }
    }

    /**
     * 确定订单
     */
    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", drivingType);
        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());
//        Map<String, Object> map = new LinkedHashMap<>();
//        map.put("orderNo",orderNo);
//        map.put("payWay",payWay);
//        map.put("type",type);
        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() {
        drivingType = dataBean.getDriverType();
        rbXinDriving.setChecked(drivingType == 1 ? true : false);
        GlideManager.getInstance(mActivity).loadImage(mCarBean.getVehicleModel().getPicture(), ivGoods);
        tvName.setText(mCarBean.getVehicleModel().getName());
        tvContent.setText(mCarBean.getVehicleModel().getKeyword());
        ratingBar.setRating((float) mCarBean.getVehicleModel().getPoint());
        tvDay.setText(String.format("%1$s%2$s", dataBean.getDayNum(), mActivity.getString(R.string.rv_days)));
        tvPrice.setText(String.format("%1$s%2$s", mCarBean.getVehicleModel().getPrice(), mActivity.getString(R.string.rv_day)));
        tvGetTime.setText(getIntent().getStringExtra("startTime"));
        tvOutTime.setText(getIntent().getStringExtra("endTime"));
        tvGetCarAddress.setText(dataBean.getStartAddr());
        tvOutCarAddress.setText(dataBean.getEndAddr());
    }


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

    }

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

