package com.gingersoft.gsa.cloud.manager.mvp.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication;
import com.gingersoft.gsa.cloud.manager.R2;
import com.gingersoft.gsa.cloud.manager.mvp.model.bean.TableArea;
import com.gingersoft.gsa.cloud.manager.mvp.model.bean.TableItem;
import com.gingersoft.gsa.cloud.manager.mvp.model.bean.request.TableRequest;
import com.gingersoft.gsa.cloud.manager.mvp.ui.activity.TableManageActivity;
import com.gingersoft.gsa.cloud.ui.widget.dialog.LoadingDialog;
import com.jess.arms.base.BaseFragment;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.gingersoft.gsa.cloud.manager.di.component.DaggerAddTableComponent;
import com.gingersoft.gsa.cloud.manager.mvp.contract.AddTableContract;
import com.gingersoft.gsa.cloud.manager.mvp.presenter.AddTablePresenter;
import com.gingersoft.gsa.cloud.manager.R;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.util.QMUIResHelper;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet;
import com.qmuiteam.qmui.widget.grouplist.QMUICommonListItemView;
import com.qmuiteam.qmui.widget.grouplist.QMUIGroupListView;
import com.qmuiteam.qmui.widget.popup.QMUIPopup;
import com.qmuiteam.qmui.widget.popup.QMUIPopups;

import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import butterknife.BindView;

import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 05/14/2020 10:16
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
public class AddTableFragment extends BaseFragment<AddTablePresenter> implements AddTableContract.View {

    @BindView(R2.id.topbar)
    QMUITopBarLayout mTopBar;
    @BindView(R2.id.groupListView)
    QMUIGroupListView mGroupListView;

    private TableManageActivity mActivity;

    private QMUIPopup mNormalPopup;
    private QMUICommonListItemView areaItemView;
    private EditText tableNameEditText, peopleNumberEditText, serverchargeEditText, tableSortEditText;

    private static final String TABLE_AREA = "table";
    private TableItem mTableItem;

    private int currentAreaId;

    public static AddTableFragment newInstance(TableItem item) {
        AddTableFragment fragment = new AddTableFragment();
        if (item != null) {
            Bundle args = new Bundle();
            args.putSerializable(TABLE_AREA, item);
            fragment.setArguments(args);
        }
        return fragment;
    }

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

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mTableItem = (TableItem) getArguments().getSerializable(TABLE_AREA);
    }

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

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mActivity = (TableManageActivity) _mActivity;

        initTopbar();
        initGroupListView();
    }

    private void initTopbar() {
        mTopBar.addLeftBackImageButton().setOnClickListener(v -> killMyself());
        Button rightButton = mTopBar.addRightTextButton("保存", R.id.qmui_dialog_edit_right_icon);
        rightButton.setTextColor(ContextCompat.getColor(mContext, R.color.theme_white_color));
        rightButton.setOnClickListener(v -> {
            if (mTableItem != null) {
                //修改
                mActivity.updateTable(createAddTableRequest());
            } else {
                if (addCondition()) {
                    mActivity.addTable(createAddTableRequest());
                }
            }
        });
        mTopBar.setBackgroundResource(R.color.theme_color);
        if (mTableItem != null) {
            mTopBar.setTitle("修改餐檯").setTextColor(ContextCompat.getColor(mContext, R.color.theme_white_color));
        } else {
            mTopBar.setTitle("添加餐檯").setTextColor(ContextCompat.getColor(mContext, R.color.theme_white_color));
        }
    }

    private void initGroupListView() {

        int height = QMUIResHelper.getAttrDimen(mContext, com.qmuiteam.qmui.R.attr.qmui_list_item_height);

        areaItemView = mGroupListView.createItemView(null,
                "區域",
                getAreaName(),
                QMUICommonListItemView.HORIZONTAL,
                QMUICommonListItemView.ACCESSORY_TYPE_CHEVRON,
                height);
        areaItemView.setTipPosition(QMUICommonListItemView.TIP_POSITION_RIGHT);

        QMUICommonListItemView tableNameItemView = mGroupListView.createItemView("餐檯名稱");
        tableNameItemView.setAccessoryType(QMUICommonListItemView.ACCESSORY_TYPE_CUSTOM);
        tableNameEditText = new EditText(mContext);
        tableNameEditText.setHint("必填");
        if (mTableItem != null) {
            tableNameEditText.setText(mTableItem.getTableName());
        }
        tableNameEditText.setWidth(QMUIDisplayHelper.dp2px(mActivity,65));
        tableNameEditText.setTextSize(QMUIDisplayHelper.dpToPx(8));
        tableNameEditText.setBackgroundColor(ContextCompat.getColor(mContext, R.color.trans));
        tableNameItemView.addAccessoryCustomView(tableNameEditText);

        QMUICommonListItemView peopleNumberItemView = mGroupListView.createItemView("就餐人數");
        peopleNumberItemView.setAccessoryType(QMUICommonListItemView.ACCESSORY_TYPE_CUSTOM);
        peopleNumberEditText = new EditText(mContext);
        peopleNumberEditText.setHint("必填");
        if (mTableItem != null) {
            peopleNumberEditText.setText(mTableItem.getSeatCount() + "");
        }
        peopleNumberEditText.setWidth(QMUIDisplayHelper.dp2px(mActivity,65));
        peopleNumberEditText.setTextSize(QMUIDisplayHelper.dpToPx(8));
        peopleNumberEditText.setBackgroundColor(ContextCompat.getColor(mContext, R.color.trans));
        peopleNumberEditText.setInputType(EditorInfo.TYPE_CLASS_NUMBER);
        peopleNumberItemView.addAccessoryCustomView(peopleNumberEditText);


        QMUICommonListItemView serverchargeItemView = mGroupListView.createItemView("服務費");
        serverchargeItemView.setAccessoryType(QMUICommonListItemView.ACCESSORY_TYPE_CUSTOM);
        serverchargeEditText = new EditText(mContext);
        serverchargeEditText.setHint("0");
        if (mTableItem != null) {
            serverchargeEditText.setText(mTableItem.getServiceCharge() + "");
        }
        serverchargeEditText.setWidth(QMUIDisplayHelper.dp2px(mActivity,65));
        serverchargeEditText.setTextSize(QMUIDisplayHelper.dpToPx(8));
        serverchargeEditText.setBackgroundColor(ContextCompat.getColor(mContext, R.color.trans));
        serverchargeEditText.setInputType(EditorInfo.TYPE_CLASS_NUMBER);
        serverchargeItemView.addAccessoryCustomView(serverchargeEditText);


        QMUICommonListItemView tableSortItemView = mGroupListView.createItemView("餐桌排序");
        tableSortItemView.setAccessoryType(QMUICommonListItemView.ACCESSORY_TYPE_CUSTOM);
        tableSortEditText = new EditText(mContext);
        tableSortEditText.setHint("100");
        if (mTableItem != null) {
            tableSortEditText.setText(mTableItem.getSort() + "");
        }
        tableSortEditText.setWidth(QMUIDisplayHelper.dp2px(mActivity,65));
        tableSortEditText.setTextSize(QMUIDisplayHelper.dpToPx(8));
        tableSortEditText.setBackgroundColor(ContextCompat.getColor(mContext, R.color.trans));
        tableSortEditText.setInputType(EditorInfo.TYPE_CLASS_NUMBER);
        tableSortItemView.addAccessoryCustomView(tableSortEditText);
        tableSortItemView.showNewTip(true);
        tableSortItemView.setNewTipImage(R.drawable.ic_delete_bill_method);
        tableSortItemView.setNewTipClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showSortTip(v);
            }
        });

        int size = QMUIDisplayHelper.dp2px(mContext, 20);
        QMUIGroupListView.newSection(mContext)
                .setLeftIconSize(size, ViewGroup.LayoutParams.WRAP_CONTENT)
                .addItemView(areaItemView, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showAreaBottomSheetList(true, true, false, "所在區域",
                                mActivity.getTableAreaList(), true, false);
                    }
                })
                .addItemView(tableNameItemView, null)
                .addItemView(peopleNumberItemView, null)
                .addItemView(serverchargeItemView, null)
                .addItemView(tableSortItemView, null)
                .setMiddleSeparatorInset(QMUIDisplayHelper.dp2px(mContext, 16), 0)
                .addTo(mGroupListView);
    }


    private void showAreaBottomSheetList(boolean gravityCenter,
                                         boolean addCancelBtn,
                                         boolean withIcon,
                                         CharSequence title,
                                         List<TableArea> areaList,
                                         boolean allowDragDismiss,
                                         boolean withMark) {
        QMUIBottomSheet.BottomListSheetBuilder builder = new QMUIBottomSheet.BottomListSheetBuilder(mContext);
        builder.setGravityCenter(gravityCenter)
                .setTitle(title)
                .setAddCancelBtn(addCancelBtn)
                .setAllowDrag(allowDragDismiss)
                .setNeedRightMark(withMark)
                .setOnSheetItemClickListener(new QMUIBottomSheet.BottomListSheetBuilder.OnSheetItemClickListener() {
                    @Override
                    public void onClick(QMUIBottomSheet dialog, View itemView, int position, String tag) {
                        dialog.cancel();
                        currentAreaId = areaList.get(position).getId();
                        areaItemView.setDetailText(tag);
                    }
                });
        if (withMark) {
            builder.setCheckedIndex(40);
        }
        for (TableArea item : areaList) {
            builder.addItem(item.getRegionName());
        }
        builder.build().show();
    }

    private void showSortTip(View v) {
        TextView textView = new TextView(mContext);
        textView.setLineSpacing(QMUIDisplayHelper.dp2px(mContext, 4), 1.0f);
        int padding = QMUIDisplayHelper.dp2px(mContext, 20);
        textView.setPadding(padding, padding, padding, padding);
        textView.setText("默认值為100，數字越小排序\n" + "越靠前！");
        int color = QMUIResHelper.getAttrColor(mContext, R.attr.app_skin_common_title_text_color);
        textView.setTextColor(ArmsUtils.getColor(mContext, R.color.theme_black));
//        QMUISkinValueBuilder builder = QMUISkinValueBuilder.acquire();
//        builder.textColor(R.attr.app_skin_common_title_text_color);
//        QMUISkinHelper.setSkinValue(textView, builder);
//        builder.release();
        mNormalPopup = QMUIPopups.popup(mContext, QMUIDisplayHelper.dp2px(mContext, 250))
                .preferredDirection(QMUIPopup.DIRECTION_BOTTOM)
                .view(textView)
                .edgeProtection(QMUIDisplayHelper.dp2px(mContext, 20))
                .dimAmount(0.6f)
                .animStyle(QMUIPopup.ANIM_GROW_FROM_CENTER)
                .onDismiss(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {

                    }
                })
                .show(v);
    }

    private String getAreaName() {
        String areaName = "";
        if (mTableItem != null) {
            //修改操作
            mTableItem.getRegionName();
            currentAreaId = mTableItem.getId();
        } else {
            //添加操作
            if (mActivity.getTableAreaList().size() > 0) {
                areaName = mActivity.getTableAreaList().get(0).getRegionName();
            } else {
                areaName = "大廳";
            }
        }
        return areaName;
    }

    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void showLoading(String message) {
        if (message != null)
            LoadingDialog.showDialogForLoading(mContext, message, true);
        else
            LoadingDialog.showDialogForLoading(mContext);
    }

    @Override
    public void hideLoading() {
        LoadingDialog.cancelDialogForLoading();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(mContext, message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        _mActivity.onBackPressed();
    }

    public TableRequest.Add createAddTableRequest() {
        TableRequest.Add addTableRequest = new TableRequest.Add();
        addTableRequest.setAreaId(currentAreaId);
        addTableRequest.setRestaurantId(GsaCloudApplication.getRestaurantId(mActivity));
        addTableRequest.setTableName(tableNameEditText.getText().toString());
        if (!TextUtils.isEmpty(serverchargeEditText.getText().toString())) {
            addTableRequest.setServiceCharge(Double.parseDouble(serverchargeEditText.getText().toString()));
        }
        if (!TextUtils.isEmpty(peopleNumberEditText.getText().toString())) {
            addTableRequest.setSeatCount(Integer.parseInt(peopleNumberEditText.getText().toString()));
        }
        if (!TextUtils.isEmpty(tableSortEditText.getText().toString())) {
            addTableRequest.setSort(Integer.parseInt(tableSortEditText.getText().toString()));
        }
        return addTableRequest;
    }

    public boolean addCondition() {
        if (TextUtils.isEmpty(tableNameEditText.getText().toString())) {
            showMessage("請輸入餐檯名稱");
            return false;
        }
        if (TextUtils.isEmpty(peopleNumberEditText.getText().toString())) {
            showMessage("請輸入就餐人數");
            return false;
        }
        return true;
    }
}
