package com.wd.workoffice.ui.fg;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.wd.workoffice.R;
import com.wd.workoffice.app.WorkBaseFg;
import com.wd.workoffice.bean.ProductBean;
import com.wd.workoffice.bean.listener.ThreeMenuClickListener;
import com.wd.workoffice.bean.workEnum.PagePermissionType;
import com.wd.workoffice.contract.WorkProContract;
import com.wd.workoffice.presenter.WorkProPresenter;
import com.wd.workoffice.ui.activity.bat.work.WorkProDetailActivity;
import com.wd.workoffice.ui.adapter.WorkProductAdapter;
import com.wd.workoffice.util.ddmfilter.ProFilterData;
import com.wd.workoffice.util.WorkUtils;
import com.wd.workoffice.widget.DropDownMenu;

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

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;


/**
 * author : flexible
 * email : lgd19940421@163.com
 * github: https://github.com/FlexibleXd
 **/
public class WorkProFragment extends WorkBaseFg implements WorkProContract.View {

    @BindView(R.id.ddm_choose)
    DropDownMenu ddmChoose;
    private String ofKind;
    private RecyclerView rvData;
    private int page = 1;
    private Map<String, Object> param;
    private SmartRefreshLayout srlRefresh;
    private WorkProPresenter workProPresenter;
    private WorkProductAdapter workProductAdapter;
    private List<ProductBean.RecordsBean> dataList;

    @Override
    protected void initView() {
        ButterKnife.bind(this, getContentView());
        workProPresenter = new WorkProPresenter();
        workProPresenter.onAttach(this);
        ProFilterData filterData = new ProFilterData(getActivity(),ddmChoose, new ThreeMenuClickListener() {
            @Override
            public void clickOne(String value) {
                if (TextUtils.equals(value, "全部状态")) {
                    param.put("status", "");
                } else if (TextUtils.equals(value, "正常")) {
                    param.put("status", "1");
                } else {
                    param.put("status", "0");
                }
                page = 1;
                param.put("current", page);
                workProPresenter.getPro(param);
            }

            @Override
            public void clickTwo(String value) {
                if (TextUtils.equals(value, "全部状态")) {
                    param.put("status", "");
                } else if (TextUtils.equals(value, "正常")) {
                    param.put("status", "1");
                } else {
                    param.put("status", "0");
                }
                page = 1;
                param.put("current", page);
                workProPresenter.getPro(param);
            }

            @Override
            public void clickThree(String value) {
                if (TextUtils.equals(value, "全部")) {
                    param.put("isExpectOut", "");
                } else if (TextUtils.equals(value, "已上架")) {
                    param.put("isExpectOut", true);
                } else {
                    param.put("isExpectOut", false);
                }
                page = 1;
                param.put("current", page);
                workProPresenter.getPro(param);
            }
        });
        rvData = filterData.getRvData();
        srlRefresh = filterData.getSrlRefresh();
    }


    @Override
    protected void initData() {
        param = WorkUtils.pageKey();
        param.put("ofKind", ofKind);
        page = 1;
        param.put("current", page);
        dataList = new ArrayList<>();
        workProductAdapter = new WorkProductAdapter(R.layout.item_work_product, dataList);
        workProductAdapter.bindToRecyclerView(rvData);
        workProductAdapter.setEmptyView(R.layout.view_empty_content, rvData);
        if (!WorkUtils.hasPermission(PagePermissionType.PRODUCT.getPermission())){
            toast(R.string.permission);
            return;
        }
        workProPresenter.getPro(param);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle arguments = getArguments();
        if (arguments != null) {
            ofKind = arguments.getString("ofKind");
        }
    }

    @Override
    protected void initEvent() {
        srlRefresh.setOnRefreshListener(refreshLayout -> {
            page = 1;
            param.put("current", page);
            workProPresenter.getPro(param);
        });
        workProductAdapter.setOnLoadMoreListener(() -> {
            param.put("current", page);
            workProPresenter.getPro(param);
        }, rvData);
        workProductAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                startActivity(WorkProDetailActivity.class, "pro", JSON.toJSONString(dataList.get(position)));
            }
        });
        workProductAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.btn_modify:
                        openModify(dataList.get(position).getId());
                        break;
                    case R.id.btn_on_sale:
                        openOnSale(dataList.get(position));
                        break;
                }
            }
        });
    }

    /**
     * 修改弹窗
     *
     * @param id
     */
    private void openModify(int id) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.view_pro_modify_price, null);
        TextView tvOk = view.findViewById(R.id.tv_ok);
        TextView tvCancel = view.findViewById(R.id.tv_cancel);
        EditText etPrice = view.findViewById(R.id.et_price);
        EditText etRemark = view.findViewById(R.id.et_remark);
        builder.setView(view);
        AlertDialog addCartDialog = builder.create();
        tvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(etPrice.getText().toString())) {
                    toast("请填写内部价格");
                    return;
                }
                if (TextUtils.isEmpty(etRemark.getText().toString())) {
                    toast("请填写备注");
                    return;
                }
                workProPresenter.modify(id, etPrice.getText().toString(), etRemark.getText().toString());
                addCartDialog.dismiss();
            }
        });
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addCartDialog.dismiss();
            }
        });
        addCartDialog.show();
    }

    /**
     * 修改上下架
     *
     * @param data
     */
    private void openOnSale(ProductBean.RecordsBean data) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.view_pro_on_sale, null);
        TextView tvOk = view.findViewById(R.id.tv_ok);
        TextView tvCancel = view.findViewById(R.id.tv_cancel);
        TextView tvTitle = view.findViewById(R.id.tv_title);
        String shelfAction;
        if (data.getIsExpectOut() == 0) {//未上架
            tvTitle.setText("确认上架？");
            shelfAction="up";
        } else {
            tvTitle.setText( "确认下架？");
            shelfAction="down";

        }
        TextView tvPrice = view.findViewById(R.id.tv_price);
        TextView tvName = view.findViewById(R.id.tv_name);
        tvPrice.setText(String.valueOf(data.getInternalPrice()).concat("/").concat(data.getUnit()));
        tvName.setText(data.getName());
        builder.setView(view);
        AlertDialog addCartDialog = builder.create();
        tvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                workProPresenter.onSale(data.getId(), shelfAction);
                addCartDialog.dismiss();
            }
        });
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addCartDialog.dismiss();
            }
        });
        addCartDialog.show();
    }

    @Override
    protected int layoutId() {
        return R.layout.fg_work_pro;
    }


    @Override
    public void getPro(List<ProductBean.RecordsBean> data) {
        if (page == 1) {
            dataList.clear();
            dataList.addAll(data);
            workProductAdapter.notifyDataSetChanged();
            workProductAdapter.loadMoreComplete();
            srlRefresh.finishRefresh();
        } else {
            workProductAdapter.loadMoreComplete();
            dataList.addAll(data);
            workProductAdapter.notifyDataSetChanged();
        }
        if (data.size() == 0) {
            workProductAdapter.loadMoreEnd();
        } else {
            page++;
        }
    }

    @Override
    public void modify(String msg) {
        page = 1;
        param.put("current", page);
        workProPresenter.getPro(param);
        toast(msg);
    }

    @Override
    public void onSale(String msg) {
        toast(msg);
    }
}
