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

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

import com.alibaba.fastjson.JSON;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
import com.wd.workoffice.R;
import com.wd.workoffice.app.BaseBean;
import com.wd.workoffice.app.WorkToolBarActivity;
import com.wd.workoffice.bean.DeviceBean;
import com.wd.workoffice.bean.DeviceBuyBean;
import com.wd.workoffice.bean.event.CheckDeviceEvent;
import com.wd.workoffice.bean.workEnum.PagePermissionType;
import com.wd.workoffice.retrofit.RtfUtils;
import com.wd.workoffice.retrofit.WorkObserver;
import com.wd.workoffice.ui.adapter.DeviceDetailAdapter;
import com.wd.workoffice.util.DialogUtils;
import com.wd.workoffice.util.MathUtils;
import com.wd.workoffice.util.WorkUtils;

import org.greenrobot.eventbus.EventBus;

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

import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
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 DeviceBuyDetailActivity extends WorkToolBarActivity {
    @BindView(R.id.tv_refuse)
    TextView tvRefuse;
    @BindView(R.id.tv_agree)
    TextView tvAgree;
    @BindView(R.id.ll_bottom)
    LinearLayout llBottom;
    @BindView(R.id.tv_code)
    TextView tvCode;
    @BindView(R.id.tv_status)
    TextView tvStatus;
    @BindView(R.id.tv_receive_dep)
    TextView tvReceiveDep;
    @BindView(R.id.tv_order_people)
    TextView tvOrderPeople;
    @BindView(R.id.tv_order_dep)
    TextView tvOrderDep;
    @BindView(R.id.tv_order_time)
    TextView tvOrderTime;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.tv_remark)
    TextView tvRemark;
    @BindView(R.id.rv_data)
    RecyclerView rvData;
    @BindView(R.id.tv_finish)
    TextView tvFinish;
    @BindView(R.id.ll_check)
    LinearLayout llCheck;
    @BindView(R.id.tv_desc)
    TextView tvDesc;
    private List<DeviceBean.RecordsBean> dataList;
    private DeviceDetailAdapter dataAdapter;
    private Map<String, Object> param;
    private DeviceBuyBean.RecordsBean info;

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        rvData.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));

    }

    @Override
    protected void initData() {
        info = JSON.parseObject(getIntent().getStringExtra("info"), DeviceBuyBean.RecordsBean.class);
        getData(info.getId() + "");
        tvCode.setText(info.getId());
        tvStatus.setText(WorkUtils.getDeviceStatus(info.getStatus()));
        tvReceiveDep.setText(info.getReceiveDeptName());
        tvOrderPeople.setText(info.getLaunchUserName());
        tvOrderDep.setText(info.getLaunchDeptName());
        tvOrderTime.setText(info.getCreatedTime());
        tvPrice.setText(MathUtils.converData(info.getLaunchOrderAmount(), 3));
        tvRemark.setText(info.getRemark());
        changePermissionView();
        dataList = new ArrayList<>();
        dataAdapter = new DeviceDetailAdapter(R.layout.item_device_detail, dataList);
        dataAdapter.bindToRecyclerView(rvData);
        param = new HashMap<>();
        param.put("id", info.getId());
    }

    private void changePermissionView() {
        if (TextUtils.equals("0", getIntent().getStringExtra("from"))) {
            llBottom.setVisibility(View.GONE);
            return;
        }
        if (info.getStatus() == 100) {
            if (!WorkUtils.hasPermission(PagePermissionType.EQUIPMENT_PURCHASE_REPAIR_UPDATE.getPermission())) {
                llBottom.setVisibility(View.GONE);
            } else {
                llBottom.setVisibility(View.VISIBLE);
                llCheck.setVisibility(View.VISIBLE);
            }
        } else if (info.getStatus() == 200) {
            if (!WorkUtils.hasPermission(PagePermissionType.EQUIPMENT_PURCHASE_REPAIR_APPLY.getPermission())) {
                llBottom.setVisibility(View.GONE);
            } else {
                llBottom.setVisibility(View.VISIBLE);
                llCheck.setVisibility(View.VISIBLE);
                tvRefuse.setText("拒单");
                tvAgree.setText("接单");
            }
        } else if (info.getStatus() == 300) {
            if (!WorkUtils.hasPermission(PagePermissionType.EQUIPMENT_PURCHASE_REPAIR_FINISH.getPermission())) {
                llBottom.setVisibility(View.GONE);
            } else {
                llBottom.setVisibility(View.VISIBLE);
                llCheck.setVisibility(View.GONE);
                tvFinish.setVisibility(View.VISIBLE);
            }
        } else {
            llBottom.setVisibility(View.GONE);
        }
    }

    private void getData(String id) {
        RtfUtils.getRtf().equipmentPurchaseItemList(id).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;
                }
                List<DeviceBean.RecordsBean> dataBean = JSON.parseArray(data.getData().toString(), DeviceBean.RecordsBean.class);
                dataList.addAll(dataBean);
                dataAdapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    protected void initEvent() {
    }

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


    @OnClick({R.id.tv_finish, R.id.tv_refuse, R.id.tv_agree})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_refuse:
                if (info.getStatus() == 100) {
                    checkDialog(220);
                } else {
                    checkDialog(320);
                }
                break;
            case R.id.tv_agree:
                if (info.getStatus() == 100) {
                    checkDialog(200);
                } else {
                    checkDialog(300);
                }
                break;
            case R.id.tv_finish:
                QMUIDialog.MessageDialogBuilder dialog = DialogUtils.okAndCancelDialog(DeviceBuyDetailActivity.this);
                dialog.setMessage("是否完成").addAction("取消", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        dialog.dismiss();
                    }
                }).addAction("确定", new QMUIDialogAction.ActionListener() {
                    @Override
                    public void onClick(QMUIDialog dialog, int index) {
                        finishDevice();
                    }
                }).show();
                break;
        }
    }

    private void finishDevice() {
        RtfUtils.getRtf().equipmentPurchaseFinish(info.getId()).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("操作成功");
                EventBus.getDefault().post(new CheckDeviceEvent());
                finish();
            }
        });
    }

    private void checkDialog(int status) {
        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 % 100 == 0 ? "通过" : "拒绝");
        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 (TextUtils.isEmpty(etRemark.getText().toString())) {
                    toast("请填写备注");
                    return;
                }
                check(status, etRemark.getText().toString());
                addCartDialog.dismiss();
            }
        });
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addCartDialog.dismiss();
            }
        });
        addCartDialog.show();
    }


    private void check(int status, String remark) {
        param.put("status", status);
        param.put("id", info.getId());
        Observable<BaseBean> observable;
        if (info.getStatus() == 100) {
            param.put("auditRemark", remark);
            observable = RtfUtils.getRtf().equipmentPurchaseAudit(WorkUtils.convertMapToBody(param));
        } else {
            param.put("ensureComment", remark);
            observable = RtfUtils.getRtf().equipmentPurchaseApply(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("操作成功");
                EventBus.getDefault().post(new CheckDeviceEvent());
                finish();
            }
        });
    }

}
