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

import android.content.Intent;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.view.Gravity;
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.FrameLayout;
import android.widget.TextView;
import com.gingersoft.gsa.cloud.app.GsaCloudApplication;
import com.gingersoft.gsa.cloud.base.table.bean.TableManagerItem;
import com.gingersoft.gsa.cloud.manager.R;
import com.gingersoft.gsa.cloud.manager.R2;
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.model.bean.request.TableRequest;
import com.gingersoft.gsa.cloud.manager.mvp.presenter.AddTablePresenter;
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.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 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 QMUICommonListItemView tableTypeItemView;
    private EditText tableNameEditText, peopleMixNumberEditText, peopleMaxNumberEditText, defalutPeopleNumberEditText, serverchargeEditText;

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

    private int currentAreaId;

    /**
     * 餐檯類型
     */
    private String[] tableTypes = {"堂食", "外賣", "自取"};
    private int tableType = -1;


    public static AddTableFragment newInstance(TableManagerItem item) {
        AddTableFragment fragment = new AddTableFragment();
        if (item != null) {
            Bundle args = new Bundle();
            args.putParcelable(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 =  getArguments().getParcelable(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.getLayoutType() == 0) {
                //修改
                mActivity.updateTable(createUpdateTableRequest(mTableItem.getId()));
            } else {
                if (addCondition()) {
                    mActivity.addTable(createAddTableRequest());
                }
            }
        });
        mTopBar.setBackgroundResource(R.color.theme_color);
        if (mTableItem.getLayoutType() == 0) {
            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);

        /**
         * 區域，餐檯名稱
         */
        QMUICommonListItemView tableAreaItemView = mGroupListView.createItemView("區域");
        tableAreaItemView.setAccessoryType(QMUICommonListItemView.ACCESSORY_TYPE_CUSTOM);
        TextView textView = new TextView(mContext);
        textView.setText(getAreaName());
        textView.setTextSize(16);
        textView.setTextColor(ContextCompat.getColor(mContext, R.color.theme_grey_color));
        tableAreaItemView.addAccessoryCustomView(textView);

        QMUICommonListItemView tableNameItemView = mGroupListView.createItemView("餐檯名稱");
        tableNameItemView.setAccessoryType(QMUICommonListItemView.ACCESSORY_TYPE_CUSTOM);
        tableNameEditText = new EditText(mContext);
        tableNameEditText.setHint("必填");
        if (mTableItem.getLayoutType() == 0) {
            tableNameEditText.setText(mTableItem.getTableName());
        }
        InputFilter[] filters = {new InputFilter.LengthFilter(15)};
        tableNameEditText.setFilters(filters);
        tableNameEditText.setWidth(QMUIDisplayHelper.dp2px(mActivity, 75));
        tableNameEditText.setTextSize(16);
        tableNameEditText.setBackgroundColor(ContextCompat.getColor(mContext, R.color.trans));
        tableNameItemView.addAccessoryCustomView(tableNameEditText);

        FrameLayout.LayoutParams tableNameEditTextParams = (FrameLayout.LayoutParams) tableNameEditText.getLayoutParams();
        tableNameEditTextParams.width = QMUIDisplayHelper.dp2px(mContext, 200);
        tableNameEditText.setLayoutParams(tableNameEditTextParams);
        // 如下是内容为空的配置，需要两个属性结合使用；如果有默认值，进行相反的配置
        // 设置文字的对齐方式
        tableNameEditText.setGravity(Gravity.CENTER | Gravity.RIGHT);
        // 设置文本的显示方向
//        tableNameEditText.setTextDirection(View.TEXT_DIRECTION_RTL);


        int size = QMUIDisplayHelper.dp2px(mContext, 20);
        QMUIGroupListView.newSection(mContext)
                .setLeftIconSize(size, ViewGroup.LayoutParams.WRAP_CONTENT)
                .addItemView(tableAreaItemView, null)
                .addItemView(tableNameItemView, null)
                .setMiddleSeparatorInset(QMUIDisplayHelper.dp2px(mContext, 16), 0)
                .addTo(mGroupListView);

        /**
         * 就餐人數範圍，默認人數
         */
        QMUICommonListItemView peopleNumberItemView = mGroupListView.createItemView("就餐人數");
        peopleNumberItemView.setAccessoryType(QMUICommonListItemView.ACCESSORY_TYPE_CUSTOM);

        peopleMixNumberEditText = new EditText(mContext);
        peopleMixNumberEditText.setHint("最少人數");
        if (mTableItem.getLayoutType() == 0) {
            peopleMixNumberEditText.setText(mTableItem.getMinSeatCount() + "");
        }
        InputFilter[] defalutPeopleNumberFilters = {new InputFilter.LengthFilter(2)};
        peopleMixNumberEditText.setFilters(defalutPeopleNumberFilters);
        peopleMixNumberEditText.setGravity(Gravity.CENTER);
        peopleMixNumberEditText.setTextSize(13);
        peopleMixNumberEditText.setBackgroundColor(ContextCompat.getColor(mContext, R.color.trans));
        peopleMixNumberEditText.setInputType(EditorInfo.TYPE_CLASS_NUMBER);
        peopleMixNumberEditText.setBackground(ArmsUtils.getDrawablebyResource(mContext, R.drawable.shape_delivery_item_btn_normal));

        TextView tv_line = new TextView(mContext);
        tv_line.setGravity(Gravity.CENTER);
        tv_line.setText("一");
        tv_line.setTextSize(14);
        tv_line.setTextColor(ContextCompat.getColor(mContext, R.color.theme_black));

        peopleMaxNumberEditText = new EditText(mContext);
        peopleMaxNumberEditText.setHint("最多人數");
        if (mTableItem.getLayoutType() == 0) {
            peopleMaxNumberEditText.setText(mTableItem.getMaxSeatCount() + "");
        }
        InputFilter[] peopleMaxNumberFilters = {new InputFilter.LengthFilter(2)};
        peopleMaxNumberEditText.setFilters(peopleMaxNumberFilters);
        peopleMaxNumberEditText.setGravity(Gravity.CENTER);
        peopleMaxNumberEditText.setTextSize(13);
        peopleMaxNumberEditText.setBackgroundColor(ContextCompat.getColor(mContext, R.color.trans));
        peopleMaxNumberEditText.setInputType(EditorInfo.TYPE_CLASS_NUMBER);
        peopleMaxNumberEditText.setBackground(ArmsUtils.getDrawablebyResource(mContext, R.drawable.shape_delivery_item_btn_normal));
        peopleNumberItemView.addAccessoryCustomView(peopleMaxNumberEditText);
        peopleNumberItemView.addAccessoryCustomView(tv_line);
        peopleNumberItemView.addAccessoryCustomView(peopleMixNumberEditText);

        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.MATCH_PARENT);
        params.gravity = Gravity.CENTER | Gravity.RIGHT;
        params.width = 180;
        peopleMaxNumberEditText.setLayoutParams(params);

        FrameLayout.LayoutParams params2 = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.MATCH_PARENT);
        params2.gravity = Gravity.CENTER | Gravity.RIGHT;
        params2.width = 30;
        params2.rightMargin = 190;
        tv_line.setLayoutParams(params2);

        FrameLayout.LayoutParams params3 = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.MATCH_PARENT);
        params3.gravity = Gravity.CENTER | Gravity.RIGHT;
        params3.width = 180;
        params3.rightMargin = 250;
        peopleMixNumberEditText.setLayoutParams(params3);


        QMUICommonListItemView defalutPeopleNumberItemView = mGroupListView.createItemView("默認人數");
        defalutPeopleNumberItemView.setAccessoryType(QMUICommonListItemView.ACCESSORY_TYPE_CUSTOM);
        defalutPeopleNumberEditText = new EditText(mContext);
        defalutPeopleNumberEditText.setHint("0");
        if (mTableItem.getLayoutType() == 0) {
            defalutPeopleNumberEditText.setText(mTableItem.getSeatCount() + "");
        }
        InputFilter[] filters2 = {new InputFilter.LengthFilter(3)};
        defalutPeopleNumberEditText.setFilters(filters2);
        defalutPeopleNumberEditText.setTextSize(16);
        defalutPeopleNumberEditText.setBackgroundColor(ContextCompat.getColor(mContext, R.color.trans));
        defalutPeopleNumberEditText.setInputType(EditorInfo.TYPE_CLASS_NUMBER);
        defalutPeopleNumberItemView.addAccessoryCustomView(defalutPeopleNumberEditText);

        TextView tv_people = new TextView(mContext);
        tv_people.setGravity(Gravity.CENTER);
        tv_people.setText("人");
        tv_people.setTextSize(14);
        tv_people.setTextColor(ContextCompat.getColor(mContext, R.color.theme_black));
        defalutPeopleNumberItemView.addAccessoryCustomView(tv_people);

        FrameLayout.LayoutParams params5 = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.MATCH_PARENT);
        params5.gravity = Gravity.CENTER_VERTICAL | Gravity.RIGHT;
        tv_people.setLayoutParams(params5);

        FrameLayout.LayoutParams params6 = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.MATCH_PARENT);
        params6.width = 100;
        params6.gravity = Gravity.CENTER_VERTICAL | Gravity.RIGHT;
        params6.rightMargin = 60;
        defalutPeopleNumberEditText.setLayoutParams(params6);
        // 如下是内容为空的配置，需要两个属性结合使用；如果有默认值，进行相反的配置
        // 设置文字的对齐方式
        defalutPeopleNumberEditText.setGravity(Gravity.START | Gravity.CENTER_VERTICAL);
        // 设置文本的显示方向
//        defalutPeopleNumberEditText.setTextDirection(View.TEXT_DIRECTION_RTL);

        QMUIGroupListView.newSection(getContext())
                .setLeftIconSize(size, ViewGroup.LayoutParams.WRAP_CONTENT)
                .addItemView(peopleNumberItemView, null)
                .addItemView(defalutPeopleNumberItemView, null)
                .setMiddleSeparatorInset(QMUIDisplayHelper.dp2px(getContext(), 16), 0)
                .addTo(mGroupListView);


        /**
         * 餐桌類型
         */
        tableTypeItemView = mGroupListView.createItemView(null,
                "餐桌類型",
                getTableType(),
                QMUICommonListItemView.HORIZONTAL,
                QMUICommonListItemView.ACCESSORY_TYPE_CHEVRON,
                height);
        tableTypeItemView.setTipPosition(QMUICommonListItemView.TIP_POSITION_RIGHT);

        QMUIGroupListView.newSection(getContext())
                .setLeftIconSize(size, ViewGroup.LayoutParams.WRAP_CONTENT)
                .addItemView(tableTypeItemView, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showTableTypeBottomSheetList(true, true, false, "餐檯類型",
                                tableTypes, true, false);
                    }
                })
                .setMiddleSeparatorInset(QMUIDisplayHelper.dp2px(getContext(), 16), 0)
                .addTo(mGroupListView);

        /**
         * 服務費
         */
        QMUICommonListItemView serverchargeItemView = mGroupListView.createItemView("服務費%");
        serverchargeItemView.setAccessoryType(QMUICommonListItemView.ACCESSORY_TYPE_CUSTOM);
        serverchargeEditText = new EditText(mContext);
        serverchargeEditText.setHint("請輸入服務費");
        if (mTableItem.getLayoutType() == 0 && mTableItem.getServiceCharge() != 0) {
            serverchargeEditText.setText(mTableItem.getServiceCharge() + "");
        }
        InputFilter[] filters3 = {new InputFilter.LengthFilter(2)};
        serverchargeEditText.setFilters(filters3);
        serverchargeEditText.setTextSize(16);
        serverchargeEditText.setBackgroundColor(ContextCompat.getColor(mContext, R.color.trans));
        serverchargeEditText.setInputType(InputType.TYPE_CLASS_NUMBER);
        serverchargeItemView.addAccessoryCustomView(serverchargeEditText);
        // 如下是内容为空的配置，需要两个属性结合使用；如果有默认值，进行相反的配置
        // 设置文字的对齐方式
        serverchargeEditText.setGravity(Gravity.CENTER | Gravity.RIGHT);
        // 设置文本的显示方向
//        serverchargeEditText.setTextDirection(View.TEXT_DIRECTION_RTL);

        QMUIGroupListView.newSection(getContext())
                .setLeftIconSize(size, ViewGroup.LayoutParams.WRAP_CONTENT)
                .addItemView(serverchargeItemView, null)
                .setMiddleSeparatorInset(QMUIDisplayHelper.dp2px(getContext(), 16), 0)
                .addTo(mGroupListView);
    }


    private void showTableTypeBottomSheetList(boolean gravityCenter,
                                              boolean addCancelBtn,
                                              boolean withIcon,
                                              CharSequence title,
                                              String[] tableTypeList,
                                              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) {
                        tableType = position;
                        tableTypeItemView.setDetailText(tableTypeList[position]);
                        dialog.dismiss();
                    }
                });
        if (withMark) {
            builder.setCheckedIndex(40);
        }
        for (String item : tableTypeList) {
            builder.addItem(item);
        }
        builder.build().show();
    }

    private String getAreaName() {
        String areaName = mTableItem.getRegionName();
        if (TextUtils.isEmpty(areaName)) {
            areaName = "默認";
        }
        currentAreaId = mTableItem.getRegionId();
        return areaName;
    }

    private String getTableType() {
        String tableType = "";
        if (mTableItem != null && mTableItem.getType() != -1) {
            //修改操作
            tableType = tableTypes[mTableItem.getType()];
        }
        return tableType;
    }

    @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.setRegionId(currentAreaId);
        addTableRequest.setRestaurantId(GsaCloudApplication.getRestaurantId());
        addTableRequest.setTableName(tableNameEditText.getText().toString());
        if (!TextUtils.isEmpty(serverchargeEditText.getText().toString())) {
            addTableRequest.setServiceCharge(Double.parseDouble(serverchargeEditText.getText().toString()));
        }
        if (!TextUtils.isEmpty(defalutPeopleNumberEditText.getText().toString())) {
            addTableRequest.setSeatCount(Integer.parseInt(defalutPeopleNumberEditText.getText().toString()));
        }
        if (!TextUtils.isEmpty(peopleMaxNumberEditText.getText().toString())) {
            addTableRequest.setMaxSeatCount(Integer.parseInt(peopleMaxNumberEditText.getText().toString()));
        }
        if (!TextUtils.isEmpty(peopleMixNumberEditText.getText().toString())) {
            addTableRequest.setMinSeatCount(Integer.parseInt(peopleMixNumberEditText.getText().toString()));
        }
        addTableRequest.setType(tableType);
        return addTableRequest;
    }

    public TableRequest.Update createUpdateTableRequest(long id) {
        TableRequest.Update update = new TableRequest.Update();
        update.setId(id);
        update.setRegionId(currentAreaId);
        update.setRestaurantId(GsaCloudApplication.getRestaurantId());
        update.setTableName(tableNameEditText.getText().toString());
        if (!TextUtils.isEmpty(serverchargeEditText.getText().toString())) {
            update.setServiceCharge(Double.parseDouble(serverchargeEditText.getText().toString()));
        }
        if (!TextUtils.isEmpty(defalutPeopleNumberEditText.getText().toString())) {
            update.setSeatCount(Integer.parseInt(defalutPeopleNumberEditText.getText().toString()));
        }
        if (!TextUtils.isEmpty(peopleMaxNumberEditText.getText().toString())) {
            update.setMaxSeatCount(Integer.parseInt(peopleMaxNumberEditText.getText().toString()));
        }
        if (!TextUtils.isEmpty(peopleMixNumberEditText.getText().toString())) {
            update.setMinSeatCount(Integer.parseInt(peopleMixNumberEditText.getText().toString()));
        }
        update.setType(tableType);
        return update;
    }

    public boolean addCondition() {
        if (TextUtils.isEmpty(tableNameEditText.getText().toString())) {
            showMessage("請輸入餐檯名稱");
            return false;
        }
        String peopleMixNumber = peopleMixNumberEditText.getText().toString();
        String peopleMaxNumber = peopleMaxNumberEditText.getText().toString();
        if (!TextUtils.isEmpty(peopleMixNumber)
                && !TextUtils.isEmpty(peopleMaxNumber)
                && Integer.parseInt(peopleMixNumber) > Integer.parseInt(peopleMaxNumber)) {
            showMessage("最少人数不能大于最小人数!");
            return false;
        }
//        if (TextUtils.isEmpty(defalutPeopleNumberEditText.getText().toString())) {
//            showMessage("請輸入就餐人數");
//            return false;
//        }
        if (tableType == -1) {
            showMessage("請選擇餐桌類型");
            return false;
        }

        return true;
    }
}
