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.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
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.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.dialog.PaymentTypeSelection;
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.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.suke.widget.SwitchButton;
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.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.btn_insurance)
    SwitchButton btnInsurance;
    @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;

    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;

    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).navigation(mActivity, 104);
            }
        });

        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 {
                        if (mActivity.getClass().equals(TravelerConfirmOrderActivity.class)) {
                            ARouter.getInstance().build(Constance.ACTIVITY_URL_ORDERLIST).navigation();
                            finish();
                        }
                    }
                });
    }

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


    @OnClick({R2.id.ll_item_visitor_information, R2.id.btn_insurance, R2.id.tv_detail, R2.id.tv_confirm_order})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.ll_item_visitor_information) {
            //出游人信息
        } else if (id == R.id.btn_insurance) {
            //同意预定须知

        } else if (id == R.id.tv_detail) {
            //明细

        } else if (id == R.id.tv_confirm_order) {
            //确认订单
            confirmOrder();
        }
    }


    /**
     * 订单支付
     */
    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, String.format("￥%1$s", price));
                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()),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 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("异常");
        }

    }


    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;

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

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