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

import android.os.Bundle;
import android.text.TextUtils;
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.chad.library.adapter.base.BaseQuickAdapter;
import com.wd.workoffice.R;
import com.wd.workoffice.app.BaseBean;
import com.wd.workoffice.app.WorkToolBarActivity;
import com.wd.workoffice.bean.AddStockBean;
import com.wd.workoffice.bean.AddStockChooseBean;
import com.wd.workoffice.bean.event.CheckAddStockEvent;
import com.wd.workoffice.bean.mesBean.ImageBean;
import com.wd.workoffice.bean.workEnum.OrderType;
import com.wd.workoffice.retrofit.RtfUtils;
import com.wd.workoffice.retrofit.WorkObserver;
import com.wd.workoffice.ui.activity.mes.ImageActivity;
import com.wd.workoffice.ui.adapter.AddStockCrucibleChooseAdapter;
import com.wd.workoffice.ui.adapter.ImgAdapter;
import com.wd.workoffice.util.HwObsUtil;
import com.wd.workoffice.util.MathUtils;
import com.wd.workoffice.util.WorkUtils;

import org.greenrobot.eventbus.EventBus;

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

import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.GridLayoutManager;
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 AddStockApplyDetailActivity 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_num)
    TextView tvNum;
    @BindView(R.id.tv_person)
    TextView tvPerson;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_remark)
    TextView tvRemark;
    @BindView(R.id.tv_check_person)
    TextView tvCheckPerson;
    @BindView(R.id.tv_check_time)
    TextView tvCheckTime;
    @BindView(R.id.tv_check_remark)
    TextView tvCheckRemark;
    @BindView(R.id.tv_check_status)
    TextView tvCheckStatus;
    @BindView(R.id.ll_check)
    LinearLayout llCheck;
    @BindView(R.id.tv_box_num)
    TextView tvBoxNum;
    @BindView(R.id.rv_data)
    RecyclerView rvData;
    @BindView(R.id.ll_stock)
    LinearLayout llStock;
    @BindView(R.id.rl_box_num)
    RelativeLayout rlBoxNum;
    @BindView(R.id.rv_img)
    RecyclerView rvImg;
    @BindView(R.id.tv_tax)
    TextView tvTax;
    @BindView(R.id.rl_tax)
    RelativeLayout rlTax;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.rl_price)
    RelativeLayout rlPrice;
    @BindView(R.id.ll_supplier)
    LinearLayout llSupplier;
    private AddStockBean.RecordsBean info;
    private String orderType;
    private List<AddStockChooseBean.RecordsBean> productList;
    private AddStockCrucibleChooseAdapter productAdapter;
    private List<ImageBean> imgList;
    private ImgAdapter imgAdapter;

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

    @Override
    protected void initData() {
        imgList = new ArrayList<>();
        imgAdapter = new ImgAdapter(R.layout.item_mes_ticket_img, imgList);
        imgAdapter.bindToRecyclerView(rvImg);
        productList = new ArrayList<>();
        productAdapter = new AddStockCrucibleChooseAdapter(R.layout.item_add_stock_choose, productList, 2);
        productAdapter.bindToRecyclerView(rvData);
        productAdapter.notifyDataSetChanged();
        info = JSON.parseObject(getIntent().getStringExtra("info"), AddStockBean.RecordsBean.class);
        orderType = getIntent().getStringExtra("orderType");
        if (TextUtils.equals(orderType, OrderType.OUT_BUY.getCode())) {
            rlBoxNum.setVisibility(View.GONE);
            String[] image = info.getImage().split(",");
            List<ImageBean> imageList = new ArrayList<>();
            for (String s : image) {
                if (!TextUtils.isEmpty(s)) {
                    ImageBean imageBean = new ImageBean();
                    imageBean.setUrl(HwObsUtil.IMG_DOMAIN + s);
                    imageList.add(imageBean);
                }
            }
            imgList.addAll(imageList);
            imgAdapter.notifyDataSetChanged();
        }
        if (TextUtils.equals(orderType, OrderType.SUPPLIER.getCode())) {
            rlBoxNum.setVisibility(View.GONE);
            llSupplier.setVisibility(View.VISIBLE);
            tvTax.setText(MathUtils.converData(info.getTax(), 3));
            tvPrice.setText(MathUtils.converData(info.getFoPrice(), 3));
        }
        tvNum.setText(MathUtils.converData(info.getProductAmount(), 3));
        tvBoxNum.setText(info.getBoxCode());
        tvPerson.setText(info.getCreatedByName());
        tvTime.setText(info.getCreatedTime());
        tvRemark.setText(info.getApplyRemark());
        if (TextUtils.equals(info.getStatus(), "0")) {
            if (TextUtils.equals(getIntent().getStringExtra("hasPermission"), "1")) {
                llBottom.setVisibility(View.VISIBLE);
            } else {
                llBottom.setVisibility(View.GONE);
            }
            llCheck.setVisibility(View.GONE);
        } else {
            llBottom.setVisibility(View.GONE);
            llCheck.setVisibility(View.VISIBLE);
            tvCheckPerson.setText(info.getUpdatedByName());
            tvCheckTime.setText(info.getUpdatedTime());
            tvCheckRemark.setText(info.getAuditRemark());
            tvCheckStatus.setText(WorkUtils.getFinancialStatus(Integer.valueOf(info.getStatus())));
        }

        String isCrucible = getIntent().getStringExtra("isCrucible");
        if (TextUtils.equals("1", isCrucible)) {
            llStock.setVisibility(View.VISIBLE);
            getStockData();
        }
    }

    private void getStockData() {
        Map<String, Object> param = WorkUtils.simpleParam();
        param.put("enterApplyId", info.getId());
        RtfUtils.getRtf().enterCrucibleDetail(param).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<AddStockChooseBean.RecordsBean> getList = JSON.parseObject(data.getData().toString(), AddStockChooseBean.class).getRecords();
                productList.clear();
                productList.addAll(getList);
                productAdapter.notifyDataSetChanged();
            }
        });
    }


    @Override
    protected void initEvent() {
        imgAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (!TextUtils.isEmpty(imgList.get(position).getUrl()))
                    startActivity(ImageActivity.class, "url", HwObsUtil.IMG_DOMAIN + imgList.get(position).getUrl());
            }
        });
    }

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


    @OnClick({R.id.tv_refuse, R.id.tv_agree})
    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;
        }
    }

    private void checkDialog(int status, int id) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view;
        if (TextUtils.equals(orderType, OrderType.SUPPLIER.getCode())) {
            view = LayoutInflater.from(this).inflate(R.layout.view_supply_stock, null);
            EditText etPrice = view.findViewById(R.id.et_price);
            EditText etTax = view.findViewById(R.id.et_tax);
            WorkUtils.addDecimalsListener(etPrice);
            WorkUtils.addDecimalsListener(etTax);
        } else {
            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) {
                String price = "";
                String tax = "";
                if (TextUtils.equals(orderType, OrderType.SUPPLIER.getCode())) {
                    EditText etPrice = view.findViewById(R.id.et_price);
                    EditText etTax = view.findViewById(R.id.et_tax);
                    price = etPrice.getText().toString();
                    tax = etTax.getText().toString();
                    if (TextUtils.isEmpty(price)) {
                        toast("请填写价格");
                        return;
                    }
//                    if (TextUtils.isEmpty(tax)) {
//                        toast("请填写税率");
//                        return;
//                    }
                }
                if (status != 1 && TextUtils.isEmpty(etRemark.getText().toString())) {
                    toast("请填写备注");
                    return;
                }
                check(status, etRemark.getText().toString(), id, price, tax);
                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, String price, String tax) {
        Map<String, Object> param = WorkUtils.simpleParam();
        param.put("result", status);
        param.put("comment", remark);
//        param.put("tax", tax);
        param.put("foPrice", price);
        param.put("id", id);
        Observable<BaseBean> observable;
        if (TextUtils.equals(orderType, OrderType.SALE.getCode())) {
            observable = RtfUtils.getRtf().addStockApplyCheck(id + "", WorkUtils.convertMapToBody(param));
        } else if (TextUtils.equals(orderType, OrderType.OUT_BUY.getCode())) {
            observable = RtfUtils.getRtf().addPoStockApplyCheck(id + "", WorkUtils.convertMapToBody(param));
        } else if (TextUtils.equals(orderType, OrderType.SUPPLIER.getCode())) {
            observable = RtfUtils.getRtf().addFoStockApplyCheck(id + "", WorkUtils.convertMapToBody(param));
        } else if (TextUtils.equals(orderType, OrderType.SUPPLIER.getCode())) {
            observable = RtfUtils.getRtf().addCoStockApplyCheck(id + "", WorkUtils.convertMapToBody(param));
        } else if (TextUtils.equals(orderType, OrderType.IN.getCode())) {
            observable = RtfUtils.getRtf().addIoStockApplyCheck(id + "", WorkUtils.convertMapToBody(param));
        } else {
            observable = RtfUtils.getRtf().addStockApplyCheck(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("操作成功");
                EventBus.getDefault().post(new CheckAddStockEvent());
                finish();
            }
        });
    }


}
