package com.rv.tourism.other;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
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.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.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.CancelOrderEvent;
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.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.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.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.yuyife.okgo.OkGoUtil;

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.functions.Consumer;
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;

    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 float price;
    private IWXAPI api;
    private int isInsuranceType;
    private OrderPriceDetailBean orderPriceDetailBean;//订单价格明细实体类
    private OrderPriceDetailPw detailPw;//显示订单价格明细弹窗
    private BeanConfirmOrder info;

    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());
            int childPrice = Integer.valueOf(dataBean.getChildPrice());
            int adultPrice = Integer.valueOf(dataBean.getPrice());
            price = (childNum * childPrice) + (adultNum * adultPrice);
            tvPaymentAmount.setText(String.format("¥%1$s", price));

            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);
                ARouter.getInstance().build(Constance.ACTIVITY_URL_CHOOSEAVISITOR)
                        .withInt("visitorType", Integer.valueOf(tourist.getIsChild()))
                        .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) {
                        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();
    }

    /**
     * 查询信息
     */
    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:
                ARouter.getInstance().build(Constance.ACTIVITY_URL_ORDERLIST).navigation();
                finish();
                break;
            case 1:
                BeanTourOrderResponse orderBean = (BeanTourOrderResponse) result;
                orderPay(orderBean.getData().getNo(), 1, 1);
                break;
            case 2:
                pay((BeanTourOrderPay) result);
                break;
            case 3:
                setData((BeanConfirmOrder) result);
                break;
        }
    }

    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<>(); //费用明细

        OrderPriceDetailBean.ChildrenBean childrenBean1 = new OrderPriceDetailBean.ChildrenBean();
        childrenBean1.setKey("成人出游人费用");
        childrenBean1.setDetail("¥" + dataBean.getPrice() + "/人 *" + dataBean.getAdultNum() + "人");
        childrenBean1.setVal("¥" + Integer.valueOf(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("¥" + Integer.valueOf(dataBean.getChildPrice()) * Integer.valueOf(dataBean.getChildNum()));
            childrenBeanList.add(childrenBean2);
        }
        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", price + (info.getData().getInsurePrice() * (adultNum + childNum) * day)));
        } else {
            tvPaymentAmount.setText(String.format("¥%1$s", price));
        }

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


    /**
     * 订单支付
     */
    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, TourismApi.COMMIT_ORDER_PAY, BeanTourOrderPay.class, new payBody(orderNo, payWay, type), 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();
                            createOrder(name, phone, 0);
                        } else if (i == R.id.ll_item_wechat) {
                            helper.setChecked(R.id.rb_wechat, true);
                            helper.setChecked(R.id.rb_alipay, false);

                        } else if (i == R.id.ll_item_alipay) {
                            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(name, phone, 1);

                        }
                    }
                }, 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, int payType) {
        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());

        Map<String, Object> headMap = new LinkedHashMap<>();
        if (OkGoUtil.getToken() != null)
            headMap.put("Authorization", OkGoUtil.getToken());
        mPresenter.postBodyData(RvFrameConfig.ADMIN_POST, payType, 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), headMap, true);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (104 == requestCode && resultCode == RESULT_OK) {
            tourist.setName(data.getStringExtra("name"));
            tourist.setPhone(data.getStringExtra("phone"));
            tourist.setIdCard(data.getStringExtra("idcard"));
            tourist.setId(String.valueOf(data.getIntExtra("id", 0)));
            mVisitorInformationAdapter.notifyItemChanged(mPosition);
        }
    }


    /**
     * 显示价格明细弹窗
     */
    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);
    }


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

    }

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

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

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