package com.wd.workoffice.ui.activity.bat.order;

import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.wd.workoffice.R;
import com.wd.workoffice.app.BaseBean;
import com.wd.workoffice.app.WorkToolBarActivity;
import com.wd.workoffice.bean.ReturnApplyBean;
import com.wd.workoffice.bean.event.CheckAddStockEvent;
import com.wd.workoffice.bean.event.CheckReturnEvent;
import com.wd.workoffice.bean.workEnum.OrderType;
import com.wd.workoffice.bean.workEnum.PagePermissionType;
import com.wd.workoffice.retrofit.RtfUtils;
import com.wd.workoffice.retrofit.WorkObserver;
import com.wd.workoffice.util.WorkUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.Map;

import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import flexible.xd.android_base.network.rtfhttp.Transformer;
import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;

/**
 * 退件详情
 * author : flexible
 * email : lgd19940421@163.com
 * github: https://github.com/FlexibleXd
 **/
public class ReturnDetailActivity extends WorkToolBarActivity {
    @BindView(R.id.tv_status)
    TextView tvStatus;
    @BindView(R.id.ll_top)
    RelativeLayout llTop;
    @BindView(R.id.tv_refuse)
    TextView tvRefuse;
    @BindView(R.id.tv_agree)
    TextView tvAgree;
    @BindView(R.id.ll_check)
    LinearLayout llCheck;
    @BindView(R.id.ll_bottom)
    LinearLayout llBottom;
    @BindView(R.id.rv_process)
    RecyclerView rvProcess;
    @BindView(R.id.rl_history)
    RelativeLayout rlHistory;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_pro_code)
    TextView tvProCode;
    @BindView(R.id.tv_pro_name)
    TextView tvProName;
    @BindView(R.id.tv_return_num)
    TextView tvReturnNum;
    @BindView(R.id.tv_return_type)
    TextView tvReturnType;
    @BindView(R.id.tv_stock)
    TextView tvStock;
    @BindView(R.id.tv_person)
    TextView tvPerson;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_remark)
    TextView tvRemark;
    @BindView(R.id.rl_order)
    RelativeLayout rlOrder;
    @BindView(R.id.tv_top1)
    TextView tvTop1;
    @BindView(R.id.tv_top2)
    TextView tvTop2;
    @BindView(R.id.tv_top3)
    TextView tvTop3;
    @BindView(R.id.tv_top4)
    TextView tvTop4;
    @BindView(R.id.tv_top5)
    TextView tvTop5;
    @BindView(R.id.view_node1)
    View viewNode1;
    @BindView(R.id.view_line1)
    View viewLine1;
    @BindView(R.id.view_node2)
    View viewNode2;
    @BindView(R.id.view_line2)
    View viewLine2;
    @BindView(R.id.view_node3)
    View viewNode3;
    @BindView(R.id.view_line3)
    View viewLine3;
    @BindView(R.id.view_node4)
    View viewNode4;
    @BindView(R.id.view_line4)
    View viewLine4;
    @BindView(R.id.view_node5)
    View viewNode5;
    @BindView(R.id.view_line5)
    View viewLine5;
    @BindView(R.id.tv_dep1)
    TextView tvDep1;
    @BindView(R.id.tv_dep2)
    TextView tvDep2;
    @BindView(R.id.tv_dep3)
    TextView tvDep3;
    @BindView(R.id.tv_dep4)
    TextView tvDep4;
    @BindView(R.id.tv_dep5)
    TextView tvDep5;
    @BindView(R.id.ll_process)
    LinearLayout llProcess;
    private ReturnApplyBean.RecordsBean info;
    private String orderType;

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        rvProcess.setLayoutManager(new GridLayoutManager(this, 5, RecyclerView.VERTICAL, false));
    }

    @Override
    protected void initData() {
        info = JSON.parseObject(getIntent().getStringExtra("info"), ReturnApplyBean.RecordsBean.class);
        orderType = getIntent().getStringExtra("orderType");
        changeView();
        //ReturnProcessAdapter returnProcessAdapter =new ReturnProcessAdapter(R.layout.item_return_process,info.getStatus());
//        returnProcessAdapter.bindToRecyclerView(rvProcess);

    }

    private void changeView() {
        tvName.setText(info.getProductSimpleCode());
        tvProName.setText(info.getProductName());
        tvProCode.setText(info.getProductSoleCode());
        tvReturnNum.setText(String.valueOf(info.getProductAmount()));
        tvReturnType.setText(info.getReturnTypeName());
        tvStock.setText(info.getBackStockName());
        tvPerson.setText(String.valueOf(info.getCreatedByName()));
        tvTime.setText(info.getCreatedTime());
        tvRemark.setText(String.valueOf(info.getApplyRemark()));
        tvStatus.setText(WorkUtils.getReturnStatus(Integer.valueOf(info.getStatus())));
        changeProcess(info.getStatus());
        changeCheckView(info.getStatus());
        changePermission(info.getStatus());
    }

    /**
     * 修改审核显示隐藏
     *
     * @param status
     */
    private void changeCheckView(String status) {
        if (TextUtils.equals(orderType, OrderType.SALE.getCode())) {
            if (status.startsWith("1") && !status.endsWith("4")) {
                llBottom.setVisibility(View.VISIBLE);
                llCheck.setVisibility(View.VISIBLE);
            } else {
                llBottom.setVisibility(View.GONE);
                llCheck.setVisibility(View.GONE);
            }
        } else if (TextUtils.equals(orderType, OrderType.OUT_BUY.getCode())) {
            if (status.startsWith("1") && !status.endsWith("4")) {
                llBottom.setVisibility(View.VISIBLE);
                llCheck.setVisibility(View.VISIBLE);
            } else {
                llBottom.setVisibility(View.GONE);
                llCheck.setVisibility(View.GONE);
            }
            rlHistory.setVisibility(View.GONE);
            llProcess.setVisibility(View.GONE);
        }
    }

    /**
     * 退件状态
     * 10未审核
     * 11 12 13 14已通过
     * 21 22 23 24不通过
     * (尾号1部门管理员 2业务部 3财务部 4集团，首数字1：通过，2:驳回)
     *
     * @param status
     * @return
     */
    private void changeProcess(String status) {
        if (status.startsWith("1")) {
            if (status.endsWith("1")) {
                changeProcessView(viewNode2, viewLine2, 0);
                changeProcessView(viewNode3, viewLine3, 1);
                tvTop2.setText("通过");
                tvTop3.setText("待审核");
            } else if (status.endsWith("2")) {
                changeProcessView(viewNode2, viewLine2, 0);
                changeProcessView(viewNode3, viewLine3, 0);
                changeProcessView(viewNode4, viewLine4, 1);
                tvTop2.setText("通过");
                tvTop3.setText("通过");
                tvTop4.setText("待审核");
            } else if (status.endsWith("3")) {
                changeProcessView(viewNode2, viewLine2, 0);
                changeProcessView(viewNode3, viewLine3, 0);
                changeProcessView(viewNode4, viewLine4, 0);
                changeProcessView(viewNode5, viewLine5, 1);
                tvTop2.setText("通过");
                tvTop3.setText("通过");
                tvTop4.setText("通过");
                tvTop5.setText("待审核");
            } else if (status.endsWith("4")) {
                changeProcessView(viewNode2, viewLine2, 0);
                changeProcessView(viewNode3, viewLine3, 0);
                changeProcessView(viewNode4, viewLine4, 0);
                changeProcessView(viewNode5, viewLine5, 0);
                tvTop2.setText("通过");
                tvTop3.setText("通过");
                tvTop4.setText("通过");
                tvTop5.setText("通过");
            }
        } else if (status.startsWith("2")) {
            if (status.endsWith("1")) {
                changeProcessView(viewNode2, viewLine2, 1);
                tvTop2.setText("驳回");
            } else if (status.endsWith("2")) {
                changeProcessView(viewNode2, viewLine2, 0);
                changeProcessView(viewNode3, viewLine3, 1);
                tvTop2.setText("通过");
                tvTop3.setText("驳回");
            } else if (status.endsWith("3")) {
                changeProcessView(viewNode2, viewLine2, 0);
                changeProcessView(viewNode3, viewLine3, 0);
                changeProcessView(viewNode4, viewLine4, 1);
                tvTop2.setText("通过");
                tvTop3.setText("通过");
                tvTop4.setText("驳回");
            } else if (status.endsWith("4")) {
                changeProcessView(viewNode2, viewLine2, 0);
                changeProcessView(viewNode3, viewLine3, 0);
                changeProcessView(viewNode4, viewLine4, 0);
                changeProcessView(viewNode4, viewLine5, 1);
                tvTop2.setText("通过");
                tvTop3.setText("通过");
                tvTop4.setText("通过");
                tvTop5.setText("驳回");
            }
        }
    }

    /**
     * status 1 变红
     * 0 变蓝
     *
     * @param changeView
     * @param changeLine
     * @param status
     */
    private void changeProcessView(View changeView, View changeLine, int status) {
        if (status == 0) {
            changeView.setBackgroundResource(R.drawable.shape_circle);
            changeLine.setBackgroundColor(Color.parseColor("#5D99C4"));
        } else {
            changeView.setBackgroundResource(R.drawable.shape_red_circle);
            changeLine.setBackgroundColor(getResources().getColor(R.color.flexible_gray_background));
        }

    }


    @Override
    protected void initEvent() {
    }

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


    private void changePermission(String status) {
        boolean hasPermission = true;
        if (TextUtils.equals(orderType, OrderType.SALE.getCode())) {
            if (status.startsWith("1")) {
                if (status.endsWith("0")) {
                    hasPermission = WorkUtils.hasPermission(PagePermissionType.SO_RETURN_EDIT_DEPT_ADMIN.getPermission());
                } else if (status.endsWith("1")) {
                    hasPermission = WorkUtils.hasPermission(PagePermissionType.SO_RETURN_EDIT_BUSINESS_DEPARTMENT.getPermission());
                } else if (status.endsWith("2")) {
                    hasPermission = WorkUtils.hasPermission(PagePermissionType.SO_RETURN_EDIT_FINANCE_DEPT.getPermission());
                } else if (status.endsWith("3")) {
                    hasPermission = WorkUtils.hasPermission(PagePermissionType.SO_RETURN_EDIT_GROUP.getPermission());
                }
            }
        } else if (TextUtils.equals(orderType, OrderType.OUT_BUY.getCode())) {
            hasPermission = WorkUtils.hasPermission(PagePermissionType.PO_RETURN_EDIT.getPermission());
        }


        if (!hasPermission) {
            tvRefuse.setVisibility(View.GONE);
            tvAgree.setVisibility(View.GONE);
        }
    }

    private void checkDialog(int status, int id) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = LayoutInflater.from(this).inflate(R.layout.view_check, null);
        TextView tvOk = view.findViewById(R.id.tv_ok);
        TextView tvDesc = view.findViewById(R.id.tv_desc);
        tvDesc.setText(status == 1 ? "通过" : "拒绝");
        TextView tvNum = view.findViewById(R.id.tv_num);
        TextView tvCancel = view.findViewById(R.id.tv_cancel);
        EditText etRemark = view.findViewById(R.id.et_content);
        WorkUtils.addNumListener(etRemark,tvNum);
        builder.setView(view);
        AlertDialog addCartDialog = builder.create();
        tvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (status!=1 && TextUtils.isEmpty(etRemark.getText().toString()) && status == 2) {
                    toast("请填写备注");
                    return;
                }
                check(status, etRemark.getText().toString(), id);
                addCartDialog.dismiss();
            }
        });
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addCartDialog.dismiss();
            }
        });
        addCartDialog.show();
    }


    private void check(int status, String remark, int id) {
        Map<String, Object> param = WorkUtils.simpleParam();
        if (TextUtils.equals(orderType, OrderType.SALE.getCode())) {
            param.put("status", status == 1 ? Integer.valueOf(info.getStatus()) + 1 : Integer.valueOf(info.getStatus()) + 11);
        } else if (TextUtils.equals(orderType, OrderType.OUT_BUY.getCode())) {
            param.put("status", status);
            param.put("productAmount", info.getProductAmount());
        }
        param.put("auditRemark", remark);
        param.put("productAmount", info.getProductAmount());
        param.put("id", id);
        Observable<BaseBean> observable;
        if (TextUtils.equals(orderType, OrderType.SALE.getCode())) {
            if (info.getStatus().endsWith("0")) {
                observable = RtfUtils.getRtf().soReturnApply(id + "", WorkUtils.convertMapToBody(param));
            } else if (info.getStatus().endsWith("1")) {
                observable = RtfUtils.getRtf().soBusinessReturnApply(id + "", WorkUtils.convertMapToBody(param));
            } else if (info.getStatus().endsWith("2")) {
                observable = RtfUtils.getRtf().soFinanceReturnApply(id + "", WorkUtils.convertMapToBody(param));
            } else if (info.getStatus().endsWith("3")) {
                observable = RtfUtils.getRtf().soGroupReturnApply(id + "", WorkUtils.convertMapToBody(param));
            } else {
                observable = RtfUtils.getRtf().soReturnApply(id + "", WorkUtils.convertMapToBody(param));
            }
        } else if (TextUtils.equals(orderType, OrderType.OUT_BUY.getCode())) {
            observable = RtfUtils.getRtf().poGroupReturnApply(id + "", WorkUtils.convertMapToBody(param));
        } else {
            observable = RtfUtils.getRtf().soReturnApply(id + "", WorkUtils.convertMapToBody(param));
        }
        observable.compose(Transformer.schedule()).subscribe(new WorkObserver<BaseBean>() {
            @Override
            public void doOnSubscribe(Disposable d) {
            }

            @Override
            public void onFail(String errorMsg) {
                hideLoading();
                toast(errorMsg);
            }

            @Override
            public void onSuccess(BaseBean data) {
                hideLoading();
                if (data.getCode() != 0) {
                    toast(data.getMessage());
                    return;
                }
                toast("操作成功");
                if (TextUtils.equals(orderType, OrderType.SALE.getCode())) {
                    int changeStatus = status == 1 ? Integer.valueOf(info.getStatus()) + 1 : Integer.valueOf(info.getStatus()) + 11;
                    info.setStatus(changeStatus + "");
                    changeView();
                } else if (TextUtils.equals(orderType, OrderType.OUT_BUY.getCode())) {
                    llBottom.setVisibility(View.GONE);
                }
                EventBus.getDefault().post(new CheckReturnEvent());
            }
        });
    }

    @OnClick({R.id.tv_refuse, R.id.tv_agree, R.id.rl_history, R.id.rl_order})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_refuse:
                checkDialog(2, info.getId());
                break;
            case R.id.tv_agree:
                checkDialog(1, info.getId());
                break;
            case R.id.rl_history:
                if (!WorkUtils.hasPermission(PagePermissionType.SO_RETURN_FLOW_LIST.getPermission())) {
                    toast(R.string.permission);
                    return;
                }
                startActivity(ReturnApplyHistoryActivity.class,"id",info.getId()+"");
                break;
            case R.id.rl_order:
                if (TextUtils.equals(orderType, OrderType.SALE.getCode())) {
                    startActivity(SaleOrderDetailActivity.class,
                            "identity", getIntent().getStringExtra("identity"),
                            "id", getIntent().getStringExtra("id"),
                            "status", getIntent().getStringExtra("status"));
                } else if (TextUtils.equals(orderType, OrderType.OUT_BUY.getCode())) {
                    startActivity(OutOrderDetailActivity.class,
                            "identity", getIntent().getStringExtra("identity"),
                            "id", getIntent().getStringExtra("id"),
                            "status", getIntent().getStringExtra("status"));
                }
                break;
        }
    }
}
