package com.rv.travel.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.base.utils.base.BaseFragment;
import com.base.utils.tools.android.LogUtil;
import com.base.utils.tools.android.VerifyUtil;
import com.base.utils.ui.datetime.selector.util.TextUtil;
import com.frame.base.FrameApp;
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.OnModuleEventListener;
import com.frame.rv.config.RvFrameConfig;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.rv.travel.R;
import com.rv.travel.R2;
import com.rv.travel.adapter.AdapterTravelMember;
import com.rv.travel.api.ApiUtil;
import com.rv.travel.api.OnApiResponseCallback;
import com.rv.travel.bean.BeanOrderParam;
import com.rv.travel.bean.BeanOrderPay;
import com.rv.travel.bean.BeanOrderResponse;
import com.rv.travel.bean.BeanTravelMember;
import com.rv.travel.bean.BeanTravelMoneyDetail;
import com.rv.travel.dialog.TravelDialogUtil;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

//确认下单
public class TravelFragmentCommitOrder extends BaseFragment {

    private IWXAPI api;

    public void commit() {
        if (!judge()) {
            return;
        }

        showSweetProgressDialog("请稍等");
        List<String> idList = new ArrayList<>();

        for (BeanTravelMember bean : selectData) {
            idList.add(bean.getId());
        }
        String ids = idList.toString().replace("[", "").replace("]", "");
        ApiUtil.commitOrder(
                emailInput.getText().toString(),
                nameInput.getText().toString(),
                mobileInput.getText().toString(),
                beanOrderParam.getEndAddr(),
                "" + com.base.utils.tools.java.DateUtil.getDateByYYYYMMDD_java(beanOrderParam.getEndTime()),
                beanOrderParam.getGoodId(),
                ids,
                beanOrderParam.getSpePriceId(),
                beanOrderParam.getStartAddr(),
                beanOrderParam.getStartCompanyId(),
                "" + com.base.utils.tools.java.DateUtil.getDateByYYYYMMDD_java(beanOrderParam.getStartTime()),
                new OnApiResponseCallback<BeanOrderResponse, String>() {
                    @Override
                    public void done(final BeanOrderResponse data, String errorMessage) {
                        dismissSweetDialog();
                        if (data != null) {
                            showSweetSuccessDialogAndDelayClose("ok");
                            FrameApp.getMainHandler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    if (getActivity() != null) {
                                        ApiUtil.payOrder(data.getNo(), "1", "1", new OnApiResponseCallback<BeanOrderPay, String>() {
                                            @Override
                                            public void done(BeanOrderPay data, String errorMessage) {
                                                pay(data);
                                            }
                                        });
//                                        getActivity().finish();
//                                        if (ModuleEventUtil.getOnModuleEventListener()!=null){
//                                            ModuleEventUtil.getOnModuleEventListener().onPay(OnModuleEventListener.MODULE_PAY_FINISH,data.getNo());
//                                        }
                                    }
                                }
                            }, 1200);
                        } else {
                            showSweetErrorDialog(errorMessage);
                        }
                    }
                }


        );
    }


    private void pay(BeanOrderPay data) {
        try {
            PayReq req = new PayReq();
            req.appId = data.getAppid();
            req.partnerId = data.getPartnerid();
            req.prepayId = data.getPrepayid();
            req.nonceStr = data.getNoncestr();
            req.timeStamp = data.getTimestamp();
            req.packageValue = data.getPackageX();
            req.sign = data.getSign();
            req.extData = "app data"; // optional
            api.sendReq(req);

        } catch (Exception e) {
            showErrorShort("异常");
        }

    }

    private boolean judge() {
        if (TextUtil.isEmpty(nameInput.getText().toString())) {
            showToastShort("请输入联系人姓名");
            return false;

        }
        if (TextUtil.isEmpty(mobileInput.getText().toString())) {
            showToastShort("请输入联系人手机");
            return false;

        }
        if (!VerifyUtil.isValidMobileNumber(mobileInput.getText().toString())) {
            showToastShort("请输入正确的联系人手机");
            return false;

        }

        int count = adultNum + childNum;
        if (count == 0) {
            showToastShort("没有选择出游人");
            return false;

        }
        for (int i = 0; i < selectData.size(); i++) {
            if (!TextUtil.isEmpty(selectData.get(i).getId())) {
                count -= 1;
            }
        }
        if (count != 0) {
            showToastShort("请选择成员");
            return false;

        }

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

        return true;
    }

    private BeanOrderParam beanOrderParam;

    public static TravelFragmentCommitOrder getInstance(String orderJson) {
        TravelFragmentCommitOrder instance = new TravelFragmentCommitOrder();
        LogUtil.e(TravelFragmentCommitOrder.class, "orderJson:" + orderJson);
        if (!TextUtil.isEmpty(orderJson)) {
            instance.beanOrderParam = new Gson().fromJson(orderJson,
                    new TypeToken<BeanOrderParam>() {
                    }.getType());
        }
        return instance;
    }

    @BindView(R2.id.commit_order_check_box)
    CheckBox commitCheck;
    @BindView(R2.id.commit_order_member_recycler)
    RecyclerView memberRecycler;
    @BindView(R2.id.commit_order_name_input)
    EditText nameInput;
    @BindView(R2.id.commit_order_mobile_input)
    EditText mobileInput;
    @BindView(R2.id.commit_order_email_input)
    EditText emailInput;
    @BindView(R2.id.commit_order_company)
    TextView companyText;
    @BindView(R2.id.commit_order_company_address)
    TextView companyAddressText;
    @BindView(R2.id.commit_order_aim_address)
    TextView aimText;
    @BindView(R2.id.commit_order_time)
    TextView timeText;
    @BindView(R2.id.commit_order_member_count)
    TextView memberCountText;
    @BindView(R2.id.commit_order_money)
    TextView moneyText;

    @OnClick({
            R2.id.commit_order_agree,
            R2.id.commit_order_button,
            R2.id.commit_order_select_member_text,
            R2.id.commit_order_select_member_icon,
            R2.id.commit_order_money_detail,
    })
    public void onTravelFragmentCommitOrderClick(View view) {
        int id = view.getId();
        if (id == R.id.commit_order_agree) {
            //合同协议
            showToastShort("查看合同");
        } else if (id == R.id.commit_order_button) {

            if (!judge()) {
                return;
            }
            //提交订单
            TravelDialogUtil.showPaySelectDialog(baseContext, moneyText.getText().toString(), new TravelDialogUtil.OnDialogDoneCallback<Boolean>() {
                @Override
                public void done(Boolean aBoolean) {
                    if (aBoolean) {
                        //微信支付
                    } else {
                        //支付宝支付
                    }
                    commit();
                }
            });
        } else if (id == R.id.commit_order_money_detail) {

            //费用明细
            TravelDialogUtil.showCommitOrderMoneyDetail(TravelFragmentCommitOrder.this);

        } else if (id == R.id.commit_order_select_member_text || id == R.id.commit_order_select_member_icon) {
            //选人员

        }
    }

    @SuppressLint("CheckResult")
    private void initRxBus() {
        RxBus.tObservable(PaymentSuccessfulEvent.class)
                .observeOn(Schedulers.newThread())
                .subscribe(new Consumer<PaymentSuccessfulEvent>() {
                    @Override
                    public void accept(PaymentSuccessfulEvent payEvent) throws Exception {
                        getActivity().finish();
                    }
                });

        RxBus.tObservable(PaymentFailedEvent.class)
                .observeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<PaymentFailedEvent>() {
                    @Override
                    public void accept(PaymentFailedEvent payEvent) throws Exception {
//                        showToast("333333");
//                        if (baseContext.getClass().equals(TravelFragmentCommitOrder.class)) {
//                            startActivity(OrderListActivity.getIntent(getActivity(), 0));
                        ARouter.getInstance().build(Constance.ACTIVITY_URL_ORDERLIST).navigation();
//                        getActivity().finish();
//                        }
                    }
                });
    }


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_travel_commit_order, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    Unbinder unbinder;

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        onData();
        onView();
        initRxBus();
        api = WXAPIFactory.createWXAPI(baseContext, RvFrameConfig.APP_ID);
    }


    @Override
    public void onData() {

    }

    @Override
    public void onView() {

        getMember();

        setOrderParam();
    }

    private BeanTravelMoneyDetail moneyDetail;

    public BeanTravelMoneyDetail getMoneyDetailBean() {
        return moneyDetail;
    }

    private void getMoneyDetail() {

        ApiUtil.getTravelMoneyDetail(
                beanOrderParam.getGoodId(),
                beanOrderParam.getSpePriceId(),
                beanOrderParam.getAdultNum(),
                beanOrderParam.getChildNum(),
                new OnApiResponseCallback<BeanTravelMoneyDetail, String>() {
                    @Override
                    public void done(BeanTravelMoneyDetail data, String errorMessage) {
                        moneyDetail = data;
                        if (moneyDetail != null) {
                            //float money = Float.valueOf(moneyDetail.getOrderAmount());
                            float money = Float.valueOf(moneyDetail.getRealAmount());
                            moneyText.setText(String.valueOf(money));
                        }

                    }
                }
        );

    }


    List<BeanTravelMember> dataAdult;
    List<BeanTravelMember> dataChild;

    private void getMember() {
        //查成年人
        ApiUtil.getTravelMember("0", new OnApiResponseCallback<List<BeanTravelMember>, String>() {
            @Override
            public void done(List<BeanTravelMember> data, String errorMessage) {
                dataAdult = data;
            }
        });
        //查儿童
        ApiUtil.getTravelMember("1", new OnApiResponseCallback<List<BeanTravelMember>, String>() {
            @Override
            public void done(List<BeanTravelMember> data, String errorMessage) {
                dataChild = data;
            }
        });
    }


    private AdapterTravelMember adapterTravelMember;
    private List<BeanTravelMember> selectData = new ArrayList<>();

    private int adultNum, childNum;
    private int adultPrice, childPrice;

    private void setOrderParam() {
        if (beanOrderParam != null) {
            getMoneyDetail();

            companyText.setText(beanOrderParam.getStartCompanyName());
            companyAddressText.setText(beanOrderParam.getStartAddr());
            aimText.setText(beanOrderParam.getEndAddr());
            timeText.setText(beanOrderParam.getTime());
            adultNum = Integer.valueOf(beanOrderParam.getAdultNum());
            childNum = Integer.valueOf(beanOrderParam.getChildNum());
            childPrice = Integer.valueOf(beanOrderParam.getChildPrice());
            adultPrice = Integer.valueOf(beanOrderParam.getPrice());
            String member = beanOrderParam.getAdultNum() + "成人" + beanOrderParam.getChildNum() + "儿童";
            memberCountText.setText(member);


            float price = (childNum * childPrice) + (adultNum * adultPrice);
            moneyText.setText(String.valueOf(price));
            for (int i = 0; i < Integer.valueOf(beanOrderParam.getAdultNum()); i++) {

                BeanTravelMember travelMember = new BeanTravelMember();
                travelMember.setIsChild("0");
                selectData.add(travelMember);
            }
            for (int i = 0; i < Integer.valueOf(beanOrderParam.getChildNum()); i++) {

                BeanTravelMember travelMember = new BeanTravelMember();
                travelMember.setIsChild("1");
                selectData.add(travelMember);
            }

            adapterTravelMember = new AdapterTravelMember(R.layout.item_travel_member, selectData);
            adapterTravelMember.setItemRootClickListener(new AdapterTravelMember.OnItemAllClickListener() {
                @Override
                public void onItemRootClick(final BeanTravelMember bean) {
                    final List<BeanTravelMember> data = new ArrayList<>();
                    if (bean.getIsChild().equals("0")) {
                        if (dataAdult != null) {
                            data.addAll(dataAdult);
                        }
                    } else {
                        if (dataChild != null) {
                            data.addAll(dataChild);
                        }
                    }

                    TravelDialogUtil.showSelectTravel(baseContext, data, new TravelDialogUtil.OnDialogDoneCallback<BeanTravelMember>() {
                        @Override
                        public void done(BeanTravelMember beanTravelMember) {
                            if (beanTravelMember == null) {
                                //showToastShort("无成员，跳转到添加");
//                                if (ModuleEventUtil.getOnModuleEventListener() != null) {
//                                    ModuleEventUtil.getOnModuleEventListener().onTravelMember(OnModuleEventListener.MODULE_TRAVEL_MEMBER_ADD);
//                                }
                                return;
                            }
                            if (selectData.contains(beanTravelMember)) {
                                showToastShort("此成员已添加！");
                                return;
                            }
                            selectData.remove(bean);
                            selectData.add(beanTravelMember);
                            adapterTravelMember.setNewData(selectData);
                        }
                    });
                }

                @Override
                public void onItemDeleteClick(BeanTravelMember bean) {
                    BeanTravelMember newBean = new BeanTravelMember();
                    newBean.setIsChild(bean.getIsChild());
                    selectData.remove(bean);
                    selectData.add(newBean);
                    adapterTravelMember.setNewData(selectData);
                }
            });
            memberRecycler.setLayoutManager(new LinearLayoutManager(baseContext));
            memberRecycler.setAdapter(adapterTravelMember);
        }
    }
}