package com.rv.tourism.other;

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.annotation.Nullable;
import android.support.v4.widget.PopupWindowCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
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.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.alipay.sdk.app.PayTask;
import com.base.utils.tools.java.DateUtil;
import com.base.utils.ui.datetime.selector.util.TextUtil;
import com.chad.library.adapter.base.BaseQuickAdapter;
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.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.util.ViewHolder;
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.component.utils.Arith;
import com.rv.component.utils.DateUtils;
import com.rv.tourism.R;
import com.rv.tourism.R2;
import com.rv.tourism.adapter.VisitorInformationAdapter;
import com.rv.tourism.api.TourismApi;
import com.rv.tourism.bean.BeanConfirmOrder;
import com.rv.tourism.bean.BeanOrderParam;
import com.rv.tourism.bean.BeanTourOrderAliPay;
import com.rv.tourism.bean.BeanTourOrderPay;
import com.rv.tourism.bean.BeanTourOrderResponse;
import com.rv.tourism.bean.BeanVisitorInformation;
import com.rv.tourism.presenter.TourismPresenter;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.xxrv.coupon.api.CouponApi;
import com.xxrv.coupon.bean.CouponBean;
import com.yuyife.okgo.OkGoUtil;

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

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

/**
 * 确认下单
 */
public class TravelerConfirmOrderActivity extends BaseStatusActivity<TourismPresenter> {

    @BindView(R2.id.tv_company)
    TextView tvCompany;
    @BindView(R2.id.tv_setoff_company_address)
    TextView tvSetoffCompanyAddress;
    @BindView(R2.id.tv_destination)
    TextView tvDestination;
    @BindView(R2.id.tv_activity_time)
    TextView tvActivityTime;
    @BindView(R2.id.et_name)
    EditText etName;
    @BindView(R2.id.et_phone)
    EditText etPhone;
    @BindView(R2.id.et_mailbox)
    EditText etMailbox;
    @BindView(R2.id.tv_number_of_visitors)
    TextView tvNumberOfVisitors;
    @BindView(R2.id.ll_item_visitor_information)
    LinearLayout llItemVisitorInformation;
    @BindView(R2.id.rv_traveler)
    RecyclerView rvTraveler;
    @BindView(R2.id.tv_insurance_information)
    TextView tvInsuranceInformation;

    @BindView(R2.id.cb_agree_to_know)
    CheckBox cbAgreeToKnow;
    @BindView(R2.id.tv_contract)
    TextView tvContract;
    @BindView(R2.id.tv_payment_amount)
    TextView tvPaymentAmount;
    @BindView(R2.id.tv_detail)
    TextView tvDetail;
    @BindView(R2.id.tv_confirm_order)
    TextView tvConfirmOrder;
    @BindView(R2.id.swbtn_insurance)
    SwitchButton swbtnInsurance;
    @BindView(R2.id.ll_bottom)
    LinearLayout llBottom;
    @BindView(R2.id.tv_coupon_amount)
    TextView tvCouponAmount;

    private static final int SDK_ALI_PAY_FLAG = 11;
    private BeanOrderParam dataBean;
    private VisitorInformationAdapter mVisitorInformationAdapter;
    private List<BeanVisitorInformation> selectData = new ArrayList<>();
    private BeanVisitorInformation tourist;
    private int mPosition;
    private int adultNum;
    private int childNum;
    private double price;
    private IWXAPI api;
    private int isInsuranceType;
    private OrderPriceDetailBean orderPriceDetailBean;//订单价格明细实体类
    private OrderPriceDetailPw detailPw;//显示订单价格明细弹窗
    private BeanConfirmOrder info;
    private int payType = 1;//选择支付类型

    private List<CouponBean.DataBean> couponDataList;//优惠券数据

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


    private List<String> couponIdList = new ArrayList<>(); //选中优惠券

    public static Intent getIntent(Context context, BeanOrderParam dataBean) {
        return new Intent(context, TravelerConfirmOrderActivity.class)
                .putExtra("dataBean", dataBean);
    }

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

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
        titleView.setTitle("确认订单");
        api = WXAPIFactory.createWXAPI(this, RvFrameConfig.APP_ID);
        dataBean = (BeanOrderParam) intent.getSerializableExtra("dataBean");
        if (dataBean != null) {
            tvCompany.setText(dataBean.getStartCompanyName());
            tvSetoffCompanyAddress.setText(dataBean.getStartAddr());
            tvDestination.setText(dataBean.getEndAddr());
            tvActivityTime.setText(dataBean.getTime());
            tvNumberOfVisitors.setText(dataBean.getAdultNum() + "成人" + dataBean.getChildNum() + "儿童");

            adultNum = Integer.valueOf(dataBean.getAdultNum());
            childNum = Integer.valueOf(dataBean.getChildNum());
            double childPrice = dataBean.getChildPrice();
            double adultPrice = dataBean.getPrice();
            price = Arith.mul(Double.valueOf(childNum), Double.valueOf(childPrice)) + Arith.mul(Double.valueOf(adultNum), Double.valueOf(adultPrice));
            tvPaymentAmount.setText(String.format("¥%1$s", new BigDecimal(price).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()));

            for (int i = 0; i < Integer.valueOf(dataBean.getAdultNum()); i++) {
                BeanVisitorInformation travelMember = new BeanVisitorInformation();
                travelMember.setIsChild("0");
                selectData.add(travelMember);
            }
            for (int i = 0; i < Integer.valueOf(dataBean.getChildNum()); i++) {
                BeanVisitorInformation travelMember = new BeanVisitorInformation();
                travelMember.setIsChild("1");
                selectData.add(travelMember);
            }
        }

        mVisitorInformationAdapter = new VisitorInformationAdapter();
        rvTraveler.setLayoutManager(new LinearLayoutManager(mActivity, LinearLayoutManager.VERTICAL, false));
        rvTraveler.setNestedScrollingEnabled(false);
        rvTraveler.setAdapter(mVisitorInformationAdapter);
        mVisitorInformationAdapter.addData(selectData);

        mVisitorInformationAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                mPosition = position;
                tourist = (BeanVisitorInformation) adapter.getItem(position);
                StringBuffer bufferAdults = new StringBuffer();
                StringBuffer bufferChilds = new StringBuffer();
                for (BeanVisitorInformation information : mVisitorInformationAdapter.getData()) {
                    if (information != null) {
                        if ("0".equals(information.getIsChild()) && !TextUtils.isEmpty(information.getId())) {
                            bufferAdults.append(information.getId()).append(";");
                        } else if ("1".equals(information.getIsChild()) && !TextUtils.isEmpty(information.getId())) {
                            bufferChilds.append(information.getId()).append(";");
                        }
                    }
                }

                ARouter.getInstance().build(Constance.ACTIVITY_URL_CHOOSEAVISITOR)
                        .withInt("adult_number", Integer.valueOf(dataBean.getAdultNum()))
                        .withInt("child_number", Integer.valueOf(dataBean.getChildNum()))
                        .withString("hasChoiceAdults", bufferAdults.length() == 0 ? "" : bufferAdults.substring(0, bufferAdults.length() - 1))
                        .withString("hasChoiceChilds", bufferChilds.length() == 0 ? "" : bufferChilds.substring(0, bufferChilds.length() - 1))
                        .withInt("openType", 1)
                        .navigation(mActivity, 104);
            }
        });

        swbtnInsurance.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                if (isChecked) {
                    isInsuranceType = 1;
                } else {
                    isInsuranceType = 0;
                }
                getPayMoney();
            }
        });

        initRxBus();
    }

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

        RxBus.tObservable(PaymentSuccessfulEvent.class)
                .observeOn(Schedulers.newThread())
                .subscribe(new Observer<PaymentSuccessfulEvent>(disposable) {
                    @Override
                    public void onNext(PaymentSuccessfulEvent event) {
                        ARouter.getInstance().build(Constance.ACTIVITY_URL_ORDERLIST)
                                .withInt("position", 1)
                                .navigation();
                        finish();
                    }
                });

        RxBus.tObservable(PaymentFailedEvent.class)
                .observeOn(Schedulers.newThread())
                .subscribe(new Observer<PaymentFailedEvent>(disposable) {
                    @Override
                    public void onNext(PaymentFailedEvent event) {
                        if (mActivity.getClass().equals(TravelerConfirmOrderActivity.class)) {
                            ARouter.getInstance().build(Constance.ACTIVITY_URL_ORDERLIST).navigation();
                            finish();
                        }
                    }
                });
    }

    @Override
    protected void loadData(Bundle savedInstanceState, Intent intent) {
        super.loadData(savedInstanceState, intent);
        loadTravelerData();
        geCouponDataList();
    }

    /**
     * 查询信息
     */
    private void loadTravelerData() {
        mPresenter.getData(3, TourismApi.COMMIT_COLLECT_ORDERUNITPRICE, BeanConfirmOrder.class, false);
    }

    @Override
    public void onShowResult(int requestType, BaseBean result) {
        switch (requestType) {
            case 0:
                BeanTourOrderResponse orderBean = (BeanTourOrderResponse) result;
                if (orderBean.getData().getRealAmount() == 0) {
                    ARouter.getInstance().build(Constance.ACTIVITY_URL_ORDERLIST)
                            .withInt("position", 1)
                            .navigation();
                    finish();
                } else {
                    orderPay(orderBean.getData().getNo());
                }
                break;
            case 1:
                pay((BeanTourOrderPay) result);
                break;
            case 2:
                aliPayData((BeanTourOrderAliPay) result);
                break;
            case 3:
                setData((BeanConfirmOrder) result);
                break;
            case 4:
                CouponBean couponBean = (CouponBean) result;
                couponData(couponBean);
                break;
        }
    }

    /**
     * 优惠券返回
     *
     * @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)) {
                couponAmount = couponDataList.get(0).getUsedAmount();
                tvCouponAmount.setText("-¥" + couponDataList.get(0).getUsedAmount());
                couponDataList.get(0).setCheck(true);
                couponIdList.add(couponDataList.get(0).getTickerNo());
                getPayMoney();
            } else {
                tvCouponAmount.setText("暂无优惠券");
            }
        } else {
            tvCouponAmount.setText("暂无优惠券");
        }
    }


    private void setData(BeanConfirmOrder data) {
        info = data;
        tvInsuranceInformation.setText(String.format("¥%1$s%2$s", data.getData().getInsurePrice(), "/人"));
        getPayMoney();
    }

    private void getPayMoney() {
        ArrayList<OrderPriceDetailBean.ChildrenBean> childrenBeanList = new ArrayList<>(); //费用明细
        price = Arith.mul(Double.valueOf(childNum), Double.valueOf(dataBean.getChildPrice())) + Arith.mul(Double.valueOf(adultNum), Double.valueOf(dataBean.getPrice()));

        OrderPriceDetailBean.ChildrenBean childrenBean1 = new OrderPriceDetailBean.ChildrenBean();
        childrenBean1.setKey("成人出游人费用");
        childrenBean1.setDetail("¥" + dataBean.getPrice() + "/人 *" + dataBean.getAdultNum() + "人");
        childrenBean1.setVal("¥" + dataBean.getPrice() * Integer.valueOf(dataBean.getAdultNum()));
        childrenBeanList.add(childrenBean1);
        if (childNum > 0) {
            OrderPriceDetailBean.ChildrenBean childrenBean2 = new OrderPriceDetailBean.ChildrenBean();
            childrenBean2.setKey("儿童出游人费用");
            childrenBean2.setDetail("¥" + dataBean.getChildPrice() + "/人 *" + dataBean.getChildNum() + "人");
            childrenBean2.setVal("¥" + dataBean.getChildPrice() * Integer.valueOf(dataBean.getChildNum()));
            childrenBeanList.add(childrenBean2);
        }

        if (price > couponAmount) {
            price = price - couponAmount; // 优惠券减
        } else {
            price = 0.00;
        }


        if (isInsuranceType == 1) {
            long day = DateUtils.compareDateDay(dataBean.getEndTime(), dataBean.getStartTime());
            OrderPriceDetailBean.ChildrenBean childrenBean3 = new OrderPriceDetailBean.ChildrenBean();
            childrenBean3.setKey("保险费用");
            childrenBean3.setDetail("¥" + info.getData().getInsurePrice() + "/人 *" + (adultNum + childNum) + "人 *" + day + "天");
            childrenBean3.setVal("¥" + info.getData().getInsurePrice() * (adultNum + childNum) * day);
            childrenBeanList.add(childrenBean3);

            tvPaymentAmount.setText(String.format("¥%1$s", new BigDecimal(price + (info.getData().getInsurePrice() * (adultNum + childNum) * day)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()));
        } else {
            tvPaymentAmount.setText(String.format("¥%1$s", new BigDecimal(price).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()));
        }

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

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

    @OnClick({R2.id.ll_item_visitor_information, R2.id.tv_detail, R2.id.tv_confirm_order, R2.id.rl_item_notice, R2.id.tv_contract, R2.id.rl_item_select_coupon})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.ll_item_visitor_information) {
            //出游人信息
        } else if (id == R.id.tv_detail) {
            //明细
            showOrderDetail(llBottom);
        } else if (id == R.id.tv_confirm_order) {
            //确认订单
            confirmOrder();
        } else if (id == R.id.rl_item_notice) {
            ARouter.getInstance().build(Constance.ACTIVITY_URL_WEBVIEW)
                    .withString("title", "预订须知")
                    .withString("url", TourismApi.HTTP_URL_CAR_TYPE_NOTICE)
                    .withInt("type", 14)
                    .navigation();
        } else if (id == R.id.tv_contract) {
            ARouter.getInstance().build(Constance.ACTIVITY_URL_WEBVIEW)
                    .withString("title", "合同协议")
                    .withString("url", TourismApi.HTTP_URL_CAR_TYPE_NOTICE)
                    .withInt("type", 16)
                    .navigation();
        } else if (id == R.id.rl_item_select_coupon) {
            //优惠券选择
            if (couponDataList != null) {
                //优惠券
                ARouter.getInstance()
                        .build(Constance.ACTIVITY_URL_CARCOUPON)
                        .withSerializable("coupon", JSON.toJSONString(couponDataList))
                        .navigation(this, 134);
            }
        }
    }

    /**
     * 优惠券请求数据
     */
    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", "2");
        map.put("amount", price);
        mPresenter.getData(RvFrameConfig.HOST, 4, CouponApi.HTTP_URL_COUPON_LIST, CouponBean.class, map, headMap, false);
    }


    /**
     * 订单支付
     */
    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, 1, TourismApi.COMMIT_ORDER_PAY, BeanTourOrderPay.class, new payBody(orderNo, payType, 1), headMap, true);
        } else {
            mPresenter.postBodyData(RvFrameConfig.VEHICLE_ORDER, 2, TourismApi.COMMIT_ORDER_PAY, BeanTourOrderAliPay.class, new payBody(orderNo, payType, 1), headMap, true);
        }
    }


    /**
     * 确认下单
     */
    private void confirmOrder() {
        final String name = etName.getText().toString().trim();
        if (TextUtil.isEmpty(name)) {
            showToast("联系人姓名不能为空！");
            return;
        }

        final String phone = etPhone.getText().toString().trim();
        if (TextUtil.isEmpty(phone)) {
            showToast("联系人手机号不能为空！");
            return;
        }

        int count = adultNum + childNum;
        for (int i = 0; i < selectData.size(); i++) {
            if (!TextUtil.isEmpty(selectData.get(i).getId())) {
                count -= 1;
            }
        }
        if (count != 0) {
            showToast("请选择出旅游人");
            return;
        }

        if (!cbAgreeToKnow.isChecked()) {
            showToast("请勾选同意须知和《合同协议》");
            return;
        }

        new PaymentTypeSelection(mActivity) {
            @Override
            public void helper(final ViewHolder helper) {
                super.helper(helper);
                helper.setText(R.id.tv_amount, tvPaymentAmount.getText().toString().trim());
                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(name, phone);

                        }
                    }
                }, R.id.iv_close, R.id.ll_item_wechat, R.id.ll_item_alipay, R.id.tv_pay_immediately);
            }
        }.show();
    }

    private void createOrder(String name, String phone) {
        List<String> idList = new ArrayList<>();

        for (BeanVisitorInformation bean : selectData) {
            idList.add(bean.getId());
        }
        String ids = idList.toString().replace("[", "").replace("]", "");
        String endTime = "" + DateUtil.getDateByYYYYMMDD_java(dataBean.getEndTime());
        String startTime = "" + DateUtil.getDateByYYYYMMDD_java(dataBean.getStartTime());
        String couponIds = couponIdList.toString().replace("[", "").replace("]", "").replaceAll(" ", "");

        Map<String, Object> headMap = new LinkedHashMap<>();
        if (OkGoUtil.getToken() != null)
            headMap.put("Authorization", OkGoUtil.getToken());
        mPresenter.postBodyData(RvFrameConfig.ADMIN_POST, 0, TourismApi.COMMIT_ORDER, BeanTourOrderResponse.class, new Tourist(etMailbox.getText().toString().trim(), name, phone, dataBean.getEndAddr(), endTime, dataBean.getGoodId(), ids, dataBean.getSpePriceId(), dataBean.getStartAddr(), dataBean.getStartCompanyId(), startTime, dataBean.getSiteId(), isInsuranceType, couponIds), headMap, true);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (104 == requestCode && resultCode == RESULT_OK) {
            if (selectData != null) {
                ArrayList<String> names = data.getStringArrayListExtra("name");
                ArrayList<String> phones = data.getStringArrayListExtra("phone");
                ArrayList<String> idcards = data.getStringArrayListExtra("idcard");
                ArrayList<String> ids = data.getStringArrayListExtra("id");
                if (selectData.size() != names.size() || selectData.size() != phones.size() || selectData.size() != idcards.size() || selectData.size() != ids.size()) {
                    return;
                }
                for (int i = 0; i < selectData.size(); i++) {
                    BeanVisitorInformation information = selectData.get(i);
                    information.setName(names.get(i));
                    information.setPhone(phones.get(i));
                    information.setIdCard(idcards.get(i));
                    information.setId(ids.get(i));
                }
            }
            mVisitorInformationAdapter.notifyDataSetChanged();
        } else if (134 == requestCode && resultCode == RESULT_OK) {
            List<CouponBean.DataBean> selectCouponList = JSON.parseArray(data.getStringExtra("selectCoupon"), CouponBean.DataBean.class);
            List<CouponBean.DataBean> resultCouponList = JSON.parseArray(data.getStringExtra("resultCouponList"), CouponBean.DataBean.class);
            if (resultCouponList != null && resultCouponList.size() > 0) {
                couponDataList = resultCouponList;
            }
            couponIdList.clear();
            double couponPrice = 0;
            if (selectCouponList != null && selectCouponList.size() > 0) {
                for (int i = 0; i < selectCouponList.size(); i++) {
                    couponIdList.add(selectCouponList.get(i).getTickerNo());
                    couponPrice = +couponPrice + selectCouponList.get(i).getUsedAmount();
                }
            }
            couponAmount = couponPrice;
            tvCouponAmount.setText("-¥" + couponAmount);
            getPayMoney();
        }
    }


    /**
     * 显示价格明细弹窗
     */
    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 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(BeanTourOrderPay 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 BeanTourOrderAliPay bean) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(TravelerConfirmOrderActivity.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")) {
                        ARouter.getInstance().build(Constance.ACTIVITY_URL_ORDERLIST)
                                .withInt("position", 1)
                                .navigation();
                        finish();
                    } else if ("6001".equals(resultStatus)) {
                        showToast("支付取消！");
                        ARouter.getInstance().build(Constance.ACTIVITY_URL_ORDERLIST).navigation();
                        finish();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
//                        showToast(payResult.toString());
                    }
                    break;
                }
            }
        }
    };


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


    private class Tourist {
        private String contactEmail;
        private String contactMan;
        private String contactPhone;
        private String endAddr;
        private String endTime;
        private String goodId;
        private String tourUserIds;
        private String spePriceId;
        private String startAddr;
        private String startCompanyId;
        private String startTime;
        private String siteId;
        private int hasInsure;
        private String tickerNos;

        public Tourist(String contactEmail, String contactMan, String contactPhone, String endAddr, String endTime, String goodId, String tourUserIds, String spePriceId, String startAddr, String startCompanyId, String startTime, String siteId, int hasInsure, String tickerNos) {
            this.contactEmail = contactEmail;
            this.contactMan = contactMan;
            this.contactPhone = contactPhone;
            this.endAddr = endAddr;
            this.endTime = endTime;
            this.goodId = goodId;
            this.tourUserIds = tourUserIds;
            this.spePriceId = spePriceId;
            this.startAddr = startAddr;
            this.startCompanyId = startCompanyId;
            this.startTime = startTime;
            this.siteId = siteId;
            this.hasInsure = hasInsure;
            this.tickerNos = tickerNos;
        }

        public String getContactEmail() {
            return contactEmail;
        }

        public void setContactEmail(String contactEmail) {
            this.contactEmail = contactEmail;
        }

        public String getContactMan() {
            return contactMan;
        }

        public void setContactMan(String contactMan) {
            this.contactMan = contactMan;
        }

        public String getContactPhone() {
            return contactPhone;
        }

        public void setContactPhone(String contactPhone) {
            this.contactPhone = contactPhone;
        }

        public String getEndAddr() {
            return endAddr;
        }

        public void setEndAddr(String endAddr) {
            this.endAddr = endAddr;
        }

        public String getEndTime() {
            return endTime;
        }

        public void setEndTime(String endTime) {
            this.endTime = endTime;
        }

        public String getGoodId() {
            return goodId;
        }

        public void setGoodId(String goodId) {
            this.goodId = goodId;
        }

        public String getTourUserIds() {
            return tourUserIds;
        }

        public void setTourUserIds(String tourUserIds) {
            this.tourUserIds = tourUserIds;
        }

        public String getSpePriceId() {
            return spePriceId;
        }

        public void setSpePriceId(String spePriceId) {
            this.spePriceId = spePriceId;
        }

        public String getStartAddr() {
            return startAddr;
        }

        public void setStartAddr(String startAddr) {
            this.startAddr = startAddr;
        }

        public String getStartCompanyId() {
            return startCompanyId;
        }

        public void setStartCompanyId(String startCompanyId) {
            this.startCompanyId = startCompanyId;
        }

        public String getStartTime() {
            return startTime;
        }

        public void setStartTime(String startTime) {
            this.startTime = startTime;
        }

        public String getSiteId() {
            return siteId;
        }

        public void setSiteId(String siteId) {
            this.siteId = siteId;
        }

        public int getHasInsure() {
            return hasInsure;
        }

        public void setHasInsure(int hasInsure) {
            this.hasInsure = hasInsure;
        }

        public String getTickerNos() {
            return tickerNos;
        }

        public void setTickerNos(String tickerNos) {
            this.tickerNos = tickerNos;
        }
    }

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