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.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.base.table.bean.TableArea;
import com.gingersoft.gsa.cloud.manager.R;
import com.gingersoft.gsa.cloud.manager.R2;
import com.gingersoft.gsa.cloud.manager.di.component.DaggerAddAreaComponent;
import com.gingersoft.gsa.cloud.manager.mvp.contract.AddAreaContract;
import com.gingersoft.gsa.cloud.manager.mvp.model.bean.request.AreaRequest;
import com.gingersoft.gsa.cloud.manager.mvp.presenter.AddAreaPresenter;
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.grouplist.QMUICommonListItemView;
import com.qmuiteam.qmui.widget.grouplist.QMUIGroupListView;
import com.qmuiteam.qmui.widget.popup.QMUIPopup;
import com.qmuiteam.qmui.widget.popup.QMUIPopups;

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 AddAreaFragment extends BaseFragment<AddAreaPresenter> implements AddAreaContract.View {

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

    private TableManageActivity mActivity;

    private QMUIPopup mNormalPopup;
    private EditText ed_area_name, ed_area_sort;

    private TableArea mTableArea;
    private static final String TABLE_AREA = "area";

    public static AddAreaFragment newInstance(TableArea area) {
        AddAreaFragment fragment = new AddAreaFragment();
        if (area != null) {
            Bundle args = new Bundle();
            args.putSerializable(TABLE_AREA, area);
            fragment.setArguments(args);
        }
        return fragment;
    }

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

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

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_add_area, 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 (mTableArea != null) {
                //修改
                mActivity.updateArea(createUpateAreaRequest(mTableArea.getId()));
            } else {
                if (addCondition()) {
                    mActivity.addArea(createAddAreaRequest());
                }
            }
        });
        mTopBar.setBackgroundResource(R.color.theme_color);
        if (mTableArea != 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() {
        QMUICommonListItemView areaNameItemView = mGroupListView.createItemView("區域名稱");
        areaNameItemView.setAccessoryType(QMUICommonListItemView.ACCESSORY_TYPE_CUSTOM);
        ed_area_name = new EditText(mContext);
        ed_area_name.setHint("請輸入名稱");
        if (mTableArea != null) {
            ed_area_name.setText(mTableArea.getRegionName());
        }
        ed_area_name.setWidth(QMUIDisplayHelper.dp2px(mActivity,75));
        ed_area_name.setTextSize(16);
        ed_area_name.setBackgroundColor(ContextCompat.getColor(mContext, R.color.trans));
        areaNameItemView.addAccessoryCustomView(ed_area_name);


        QMUICommonListItemView areaSortItemView = mGroupListView.createItemView("排序");
        areaSortItemView.setAccessoryType(QMUICommonListItemView.ACCESSORY_TYPE_CUSTOM);
        ed_area_sort = new EditText(mContext);
        ed_area_sort.setHint("10");
        if (mTableArea != null) {
            ed_area_sort.setText(mTableArea.getSort() + "");
        }
        ed_area_sort.setWidth(QMUIDisplayHelper.dp2px(mActivity,75));
        ed_area_sort.setTextSize(16);
        ed_area_sort.setBackgroundColor(ContextCompat.getColor(mContext, R.color.trans));
        areaSortItemView.addAccessoryCustomView(ed_area_sort);
        areaSortItemView.showNewTip(true);
        areaSortItemView.setNewTipImage(R.drawable.question_prompt);
        areaSortItemView.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(areaNameItemView, null)
                .addItemView(areaSortItemView, null)
                .setMiddleSeparatorInset(QMUIDisplayHelper.dp2px(mContext, 16), 0)
                .addTo(mGroupListView);
    }

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

    @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 AreaRequest.Add createAddAreaRequest() {
        int restaurantId = GsaCloudApplication.getRestaurantId();
        AreaRequest.Add areaRequest = new AreaRequest.Add();
        areaRequest.setRestaurantId(restaurantId);
        areaRequest.setRegionName(ed_area_name.getText().toString());
        areaRequest.setSort(Integer.parseInt(ed_area_sort.getText().toString()));
        return areaRequest;
    }

    public AreaRequest.Update createUpateAreaRequest(int id) {
        AreaRequest.Update areaRequest = new AreaRequest.Update();
        areaRequest.setId(id);
        areaRequest.setRegionName(ed_area_name.getText().toString());
        areaRequest.setSort(Integer.parseInt(ed_area_sort.getText().toString()));
        return areaRequest;
    }

    public boolean addCondition() {
        if (TextUtils.isEmpty(ed_area_name.getText().toString())) {
            showMessage("請輸入區域名稱");
            return false;
        }
        if (TextUtils.isEmpty(ed_area_sort.getText().toString())) {
            showMessage("請輸入區域排序");
            return false;
        }
        return true;
    }


}
