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

import android.Manifest;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.wd.workoffice.R;
import com.wd.workoffice.app.BaseBean;
import com.wd.workoffice.app.WorkToolBarActivity;
import com.wd.workoffice.bean.OrderDetail;
import com.wd.workoffice.bean.event.CheckAddStockEvent;
import com.wd.workoffice.bean.listener.HwUploadListener;
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.adapter.ImgAddAdapter;
import com.wd.workoffice.util.Glide4Engine;
import com.wd.workoffice.util.HwObsUtil;
import com.wd.workoffice.util.MathUtils;
import com.wd.workoffice.util.WorkUtils;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.Nullable;
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 AddStockApplyAddActivity extends WorkToolBarActivity {
    @BindView(R.id.tv_bottom)
    TextView tvBottom;
    @BindView(R.id.et_img_code)
    TextView etImgCode;
    @BindView(R.id.tv_num)
    TextView tvNum;
    @BindView(R.id.et_num)
    EditText etNum;
    @BindView(R.id.et_remark)
    EditText etRemark;
    @BindView(R.id.tv_remark_num)
    TextView tvRemarkNum;
    @BindView(R.id.et_box_num)
    EditText etBoxNum;
    @BindView(R.id.rv_photo)
    RecyclerView rvPhoto;
    @BindView(R.id.ll_photo)
    LinearLayout llPhoto;
    @BindView(R.id.ll_box_num)
    LinearLayout llBoxNum;
    @BindView(R.id.et_tax)
    EditText etTax;
    @BindView(R.id.ll_tax)
    LinearLayout llTax;
    @BindView(R.id.et_price)
    EditText etPrice;
    @BindView(R.id.ll_price)
    LinearLayout llPrice;
    private Map<String, Object> param;
    private String orderType;
    private OrderDetail dataBean;
    private List<ImageBean> imgList;
    private ImgAddAdapter imgAddAdapter;

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        WorkUtils.addDecimalsListener(etNum);
        WorkUtils.addDecimalsListener(etPrice);
        WorkUtils.addDecimalsListener(etTax);
        WorkUtils.addNumListener(etRemark, tvRemarkNum);
        rvPhoto.setLayoutManager(new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false));

    }

    @Override
    protected void initData() {
        orderType = getIntent().getStringExtra("orderType");
        //外采购订单入库,添加照片（必传）。供应订单入库取消箱号
        if (TextUtils.equals(orderType, OrderType.SUPPLIER.getCode())) {
            llBoxNum.setVisibility(View.GONE);
//            llPrice.setVisibility(View.VISIBLE);
//            llTax.setVisibility(View.VISIBLE);
        }
        if (TextUtils.equals(orderType, OrderType.OUT_BUY.getCode())) {
            llBoxNum.setVisibility(View.GONE);
            llPhoto.setVisibility(View.VISIBLE);
        } else {
            llPhoto.setVisibility(View.GONE);
        }
        param = new HashMap<>();
        param.put("productId", getIntent().getStringExtra("productId"));
        param.put("simpleCode", getIntent().getStringExtra("simpleCode"));
        etImgCode.setText(getIntent().getStringExtra("simpleCode"));
        imgList = new ArrayList<>();
        ImageBean imageBean = new ImageBean();
        imageBean.setUri(null);
        imgList.add(imageBean);
        imgAddAdapter = new ImgAddAdapter(R.layout.item_mes_ticket_img, imgList);
        imgAddAdapter.bindToRecyclerView(rvPhoto);
        getNum();
    }

    /**
     * 获取数量
     */
    private void getNum() {
        Observable<BaseBean> observable;
        if (TextUtils.equals(orderType, OrderType.SALE.getCode())) {
            observable = RtfUtils.getRtf().saleOrderDetail(getIntent().getStringExtra("id"), "1");
        } else if (TextUtils.equals(orderType, OrderType.OUT_BUY.getCode())) {
            observable = RtfUtils.getRtf().purchaseOrderDetail(getIntent().getStringExtra("id"), "1");
        } else if (TextUtils.equals(orderType, OrderType.SUPPLIER.getCode())) {
            observable = RtfUtils.getRtf().supplierOrderDetail(getIntent().getStringExtra("id"), "1");
        } else if (TextUtils.equals(orderType, OrderType.CRUCIBLE.getCode())) {
            observable = RtfUtils.getRtf().crucibleOrderDetail(getIntent().getStringExtra("id"), "1");
        } else if (TextUtils.equals(orderType, OrderType.IN.getCode())) {
            observable = RtfUtils.getRtf().insideOrderDetail(getIntent().getStringExtra("id"), "1");
        } else {
            observable = RtfUtils.getRtf().insideOrderDetail(getIntent().getStringExtra("id"), "1");
        }
        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;
                }
                dataBean = JSON.parseObject(data.getData().toString(), OrderDetail.class);
                List<OrderDetail.OrderItemsBean> orderItems = dataBean.getOrderItems();
                for (OrderDetail.OrderItemsBean orderItem : orderItems) {
                    if (TextUtils.equals(orderItem.getId(), getIntent().getStringExtra("orderItemId"))) {
                        tvNum.setText(String.format("入库数量(最大入库数量%s)", MathUtils.converData(orderItem.getCanInStoreProductSum(), 3)));
                    }
                }
            }
        });
    }

    @Override
    protected void initEvent() {
        imgAddAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                imgList.remove(position);
                imgAddAdapter.notifyDataSetChanged();
            }
        });
        imgAddAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (position == imgList.size() - 1) {
                    addImg();
                }
            }
        });
    }

    private void addImg() {
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions
                .request(Manifest.permission.CAMERA,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(granted -> {
                    if (granted) {
                        // All requested permissions are granted
                        Matisse.from(AddStockApplyAddActivity.this)
                                .choose(MimeType.ofImage())
                                .countable(true)
                                .maxSelectable(1).capture(true).
                                captureStrategy(new CaptureStrategy(true, "com.wd.workoffice.fileprovider"))
//                                        .addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
//                                        .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                                .thumbnailScale(0.85f)
                                .imageEngine(new Glide4Engine())
                                .forResult(10002);
                    } else {
                        // At least one permission is denied
                        toast("您需要开启拍照、存储权限！");
                    }
                });
    }


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


    @OnClick(R.id.tv_bottom)
    public void onViewClicked() {
        submit();
    }


    private void submit() {
        String num = etNum.getText().toString();
        String remark = etRemark.getText().toString();
        String boxCode = etBoxNum.getText().toString();
        if (TextUtils.isEmpty(num)) {
            toast("请输入入库数量");
            return;
        }
        if (dataBean != null) {
            List<OrderDetail.OrderItemsBean> orderItems = dataBean.getOrderItems();
            for (OrderDetail.OrderItemsBean orderItem : orderItems) {
                if (TextUtils.equals(orderItem.getId(), getIntent().getStringExtra("orderItemId"))) {
                    if (BigDecimal.valueOf(Double.parseDouble(num)).compareTo(new BigDecimal(orderItem.getCanInStoreProductSum())) == 1) {
                        toast(String.format("可申请入库数量最大为%s", MathUtils.converData(orderItem.getCanInStoreProductSum(), 3)));
                        return;
                    }
                }

            }
        }
        param.put("productAmount", num);
        param.put("boxCode", boxCode);
        param.put("orderItemId", getIntent().getStringExtra("orderItemId"));
        param.put("applyRemark", remark);
//        param.put("tax", etTax.getText().toString());
//        param.put("foPrice", etPrice.getText().toString());
        Observable<BaseBean> observable;
        if (TextUtils.equals(orderType, OrderType.SALE.getCode())) {
            observable = RtfUtils.getRtf().addStockApplyAdd(getIntent().getStringExtra("id"), WorkUtils.convertMapToBody(param));
        } else if (TextUtils.equals(orderType, OrderType.OUT_BUY.getCode())) {
            //外采购需要上传图片
            if (imgList.size() == 1) {
                toast("请选择上传图片");
                return;
            }
            StringBuilder image = new StringBuilder();
            for (int i = 0; i < imgList.size() - 1; i++) {
                image.append(imgList.get(i).getPath()).append(",");
            }
            param.put("image", image.substring(0, image.length() - 1));
            observable = RtfUtils.getRtf().addPoStockApplyAdd(getIntent().getStringExtra("id"), WorkUtils.convertMapToBody(param));
        } else if (TextUtils.equals(orderType, OrderType.SUPPLIER.getCode())) {
            observable = RtfUtils.getRtf().addFoStockApplyAdd(getIntent().getStringExtra("id"), WorkUtils.convertMapToBody(param));
        } else if (TextUtils.equals(orderType, OrderType.CRUCIBLE.getCode())) {
            observable = RtfUtils.getRtf().addStockCoApplyAdd(getIntent().getStringExtra("id"), WorkUtils.convertMapToBody(param));
        } else if (TextUtils.equals(orderType, OrderType.IN.getCode())) {
            observable = RtfUtils.getRtf().addStockIoApplyAdd(getIntent().getStringExtra("id"), WorkUtils.convertMapToBody(param));
        } else {
            observable = RtfUtils.getRtf().addStockApplyAdd(getIntent().getStringExtra("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();
            }

        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10002 && resultCode == RESULT_OK) {
            if (Matisse.obtainResult(data).size() != 0) {
                showLoading();
                File file = WorkUtils.uriToFile(Matisse.obtainResult(data).get(0), this);
                HwObsUtil.getInstance().uploadObject(file, this, new HwUploadListener() {
                    @Override
                    public void uploadSuccess(String value) {
                        hideLoading();
                        toast("上传成功");
                        ImageBean imageBean = new ImageBean();
                        imageBean.setPath(value);
                        imageBean.setName(file.getName());
                        imgList.add(imgList.size() - 1, imageBean);
                        imgAddAdapter.notifyDataSetChanged();
                        imageBean.setUri(Matisse.obtainResult(data).get(0));
                    }

                    @Override
                    public void uploadFail(String value) {
                        hideLoading();
                        toast("图片上传失败");
                    }
                });
            }
        }
    }

}
