package com.gingersoft.supply_chain.mvp.ui.fragment.order;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import com.gingersoft.gsa.cloud.common.utils.ClipboardUtils;
import com.gingersoft.gsa.cloud.common.utils.other.TextUtil;
import com.gingersoft.gsa.cloud.common.utils.toast.ToastUtils;
import com.gingersoft.supply_chain.R;
import com.gingersoft.supply_chain.R2;
import com.gingersoft.supply_chain.di.component.DaggerSendMsgComponent;
import com.gingersoft.supply_chain.mvp.bean.ConfirmOrderBean;
import com.gingersoft.supply_chain.mvp.bean.SendSupplierMsgBean;
import com.gingersoft.supply_chain.mvp.contract.SendMsgContract;
import com.gingersoft.supply_chain.mvp.presenter.SendMsgPresenter;
import com.gingersoft.supply_chain.mvp.ui.adapter.SendSupplierMsgAdapter;
import com.gingersoft.supply_chain.mvp.ui.fragment.BaseSupplyChainFragment;
import com.gingersoft.supply_chain.mvp.ui.widget.TextPopup;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.DeviceUtils;
import com.lxj.xpopup.XPopup;
import com.qmuiteam.qmui.alpha.QMUIAlphaButton;
import com.qmuiteam.qmui.widget.QMUITopBar;

import java.io.Serializable;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.gingersoft.supply_chain.mvp.bean.SupplierInfoBean.SupplierContacts.Kakao_Talk;
import static com.gingersoft.supply_chain.mvp.bean.SupplierInfoBean.SupplierContacts.Line;
import static com.gingersoft.supply_chain.mvp.bean.SupplierInfoBean.SupplierContacts.WeChat;
import static com.gingersoft.supply_chain.mvp.bean.SupplierInfoBean.SupplierContacts.Whatsapp;


/**
 * Description: 發送消息到供應商
 */
public class SendMsgFragment extends BaseSupplyChainFragment<SendMsgPresenter> implements SendMsgContract.View {


    private final static String KEY_PURCHASE_ORDER_INFO = "purchaseOrders";
    @BindView(R2.id.supply_top_bar)
    QMUITopBar supplyTopBar;
    @BindView(R2.id.rv_send_select_supplier)
    RecyclerView rvSupplier;
    @BindView(R2.id.btn_supplier_confirm)
    QMUIAlphaButton btnSupplierConfirm;
    @BindView(R2.id.btn_supplier_cancel)
    QMUIAlphaButton btnSupplierCancel;
    private List<ConfirmOrderBean.PurchaseOrder> purchaseOrders;

    private SendSupplierMsgAdapter sendSupplierMsgAdapter;

    public static SendMsgFragment newInstance(List<ConfirmOrderBean.PurchaseOrder> purchaseOrders) {
        SendMsgFragment fragment = new SendMsgFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(KEY_PURCHASE_ORDER_INFO, (Serializable) purchaseOrders);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerSendMsgComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_send_msg, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        initTopBar(supplyTopBar, "發送");
        supplyTopBar.addRightTextButton(R.string.str_preview, R.id.qmui_preview).setOnClickListener(this::onClick);
        Bundle arguments = getArguments();
        if (arguments != null) {
            purchaseOrders = (List<ConfirmOrderBean.PurchaseOrder>) arguments.getSerializable(KEY_PURCHASE_ORDER_INFO);
            mPresenter.getSupplierListByOrders(purchaseOrders);
        } else {
            showMessage("訂單信息獲取失敗，請重試");
            killMyself();
        }
    }

    @OnClick({R2.id.btn_supplier_confirm, R2.id.btn_supplier_cancel})
    public void onClick(View view) {
        int viewId = view.getId();
        if (viewId == R.id.btn_supplier_confirm) {
            //發送
            mPresenter.sendMsg();
        } else if (viewId == R.id.btn_supplier_cancel) {
            backToOrderList();
        } else if (viewId == R.id.qmui_preview) {
            //預覽
            String sendUrl = mPresenter.getSendUrl();
            if (TextUtil.isNotEmptyOrNullOrUndefined(sendUrl)) {
                new XPopup.Builder(requireContext())
                        .asCustom(new TextPopup(requireContext(), "發送鏈接預覽", mPresenter.getSendUrl()))
                        .show();
            } else {
                showMessage("未獲取到採購單信息，請退出重試");
            }
        }
    }

    @Override
    public void shareThirdApp(String url, int type) {
        ClipboardUtils.copyText(url);
//        Intent intent = new Intent(Intent.ACTION_SEND);
//        intent.putExtra(Intent.EXTRA_SUBJECT, "");
//        intent.putExtra(Intent.EXTRA_TEXT, url);
//        intent.setType("text/*");
//        startActivity(intent);
        if (type == Whatsapp) {
            //分享到WhatsApp
            DeviceUtils.shareWhatsApp(mContext, url);
        } else if (type == WeChat) {
            DeviceUtils.shareWeChatFriend(mContext, url);
        } else if (type == Line) {
            //分享到Line
            DeviceUtils.shareLine(mContext, "", url);
        } else if (type == Kakao_Talk) {
            //分享到kakao
            ToastUtils.show(mContext, "暫未開放此應用發送，訂單鏈接已複製，請手動打開應用粘貼發送");
        }
    }

    @Override
    public void loadSupplierList(List<SendSupplierMsgBean> sendSupplierMsgBeans) {
        isSend = false;
        if (sendSupplierMsgAdapter == null) {
            sendSupplierMsgAdapter = new SendSupplierMsgAdapter(sendSupplierMsgBeans);
            rvSupplier.setAdapter(sendSupplierMsgAdapter);
            sendSupplierMsgAdapter.setOnItemClickListener((adapter, view, position) -> {
                //切換供應商
                //選擇默認的聯繫方式
                //獲取信息鏈接
                mPresenter.getContactsBySupplier(position);
            });
        } else {
            sendSupplierMsgAdapter.setList(sendSupplierMsgBeans);
        }
    }

    @Override
    public void sendSuccess() {
        isSend = true;
        mPresenter.setSendSuccess();
    }

    @Override
    public void backToOrderList() {
        List<Fragment> fragments = requireActivity().getSupportFragmentManager().getFragments();
        for (Fragment fragment : fragments) {
            if (fragment instanceof PurchaseListFragment) {
                //有訂單列表
                popTo(PurchaseListFragment.class, false);
                return;
            }
        }
        //沒有訂單列表
        startWithPop(PurchaseListFragment.newInstance());
//        startWithPopTo(PurchaseListFragment.newInstance(), this, false);
    }

    private boolean isSend = false;

    @Override
    public void killMyself() {
        backToOrderList();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isSend) {
            sendSupplierMsgAdapter.notifyDataSetChanged();
            mPresenter.getContactsBySupplier(mPresenter.getCurrentSelectedSupplier() + 1);
        }
    }

    @Override
    public boolean onBackPressedSupport() {
        backToOrderList();
        return true;
    }
}
