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

import android.Manifest;
import android.content.DialogInterface;
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.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;
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.MarkBean;
import com.wd.workoffice.bean.OrderBillBean;
import com.wd.workoffice.bean.ProductBean;
import com.wd.workoffice.bean.listener.HwUploadListener;
import com.wd.workoffice.bean.workEnum.PermissionType;
import com.wd.workoffice.retrofit.RtfUtils;
import com.wd.workoffice.retrofit.WorkObserver;
import com.wd.workoffice.ui.adapter.StoreCarAdapter;
import com.wd.workoffice.util.DialogUtils;
import com.wd.workoffice.util.Glide4Engine;
import com.wd.workoffice.util.HwObsUtil;
import com.wd.workoffice.util.MathUtils;
import com.wd.workoffice.util.PickTimeUtils;
import com.wd.workoffice.util.UserKeeper;
import com.wd.workoffice.util.WorkUtils;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
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 flexible.xd.android_base.utils.TimeUtils;
import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;

/**
 * 商店-销售/供应/外采购/坩埚-产品-确认订单
 * author : flexible
 * email : lgd19940421@163.com
 * github: https://github.com/FlexibleXd
 **/
public class StoreSaleConfirmActivity extends WorkToolBarActivity {

    @BindView(R.id.tv_num)
    TextView tvNum;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.tv_ok)
    TextView tvOk;
    @BindView(R.id.ll_bottom)
    RelativeLayout llBottom;
    @BindView(R.id.rv_pro)
    RecyclerView rvPro;
    @BindView(R.id.tv_set)
    TextView tvSet;
    @BindView(R.id.rl_set)
    RelativeLayout rlSet;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.rl_time)
    RelativeLayout rlTime;
    @BindView(R.id.et_address)
    EditText etAddress;
    @BindView(R.id.et_input1)
    EditText etInput1;
    @BindView(R.id.tv_input1)
    TextView tvInput1;
    @BindView(R.id.et_input2)
    EditText etInput2;
    @BindView(R.id.tv_input2)
    TextView tvInput2;
    @BindView(R.id.et_input3)
    EditText etInput3;
    @BindView(R.id.tv_input3)
    TextView tvInput3;
    @BindView(R.id.et_input4)
    EditText etInput4;
    @BindView(R.id.tv_input4)
    TextView tvInput4;
    @BindView(R.id.et_input5)
    EditText etInput5;
    @BindView(R.id.tv_input5)
    TextView tvInput5;
    @BindView(R.id.tv_bill)
    TextView tvBill;
    @BindView(R.id.rl_bill)
    RelativeLayout rlBill;
    @BindView(R.id.et_company)
    EditText etCompany;
    @BindView(R.id.et_machine)
    EditText etMachine;
    @BindView(R.id.et_send_company)
    EditText etSendCompany;
    @BindView(R.id.et_country_company)
    EditText etCountryCompany;
    @BindView(R.id.ll_sale_mark)
    LinearLayout llSaleMark;
    private List<ProductBean.RecordsBean> proList;
    private StoreCarAdapter proAdapter;
    private QMUIDialog.MenuDialogBuilder receiveDialog;
    private QMUIDialog.MenuDialogBuilder setDialog;
    private String[] setArray = new String[]{"钢控", "锆碳"};
    String[] receiveArray = new String[]{"接单方生产", "接单方采购"};
    private Map<String, Object> param;
    private Map<String, Object> expandInfo;
    private List<JSONObject> orderItems;
    private Integer choosePosition;
    private QMUIDialog.MenuDialogBuilder billDialog;
    private List<String> billNameList = new ArrayList<>();
    private List<OrderBillBean> billList = new ArrayList<>();
    private OrderBillBean chooseBill;
    private int receivePosition;

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        rvPro.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        receiveDialog = DialogUtils.listDialog(this);
        receiveDialog.addItems(receiveArray, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                proList.get(receivePosition).setProvideMethod(String.valueOf(which + 1));
                proList.get(receivePosition).setProvideMethodName(receiveArray[which]);
                proAdapter.notifyItemChanged(receivePosition);
                dialog.dismiss();
            }
        });
        setDialog = DialogUtils.listDialog(this);
        setDialog.addItems(setArray, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (which == 0) {
                    expandInfo.put("outdeptLedger", "gk");
                } else {
                    expandInfo.put("outdeptLedger", "gt");
                }
                tvSet.setText(setArray[which]);
                dialog.dismiss();
            }
        });
        billDialog = DialogUtils.listDialog(this);
        String code = getIntent().getStringExtra("code");
        if (TextUtils.equals(code, PermissionType.PROCESS_PURCHASE.getCode()) ||
                TextUtils.equals(code, PermissionType.PROCESS_SALE.getCode()) ||
                TextUtils.equals(code, PermissionType.PROCESS_SUPPLY.getCode())) {
            rlBill.setVisibility(View.VISIBLE);
        } else {
            rlBill.setVisibility(View.GONE);
        }
        //隐藏唛头
        if (!TextUtils.equals(code, PermissionType.PROCESS_SALE.getCode())) {
            llSaleMark.setVisibility(View.GONE);
        }
        expandInfo = new HashMap<>();
        //外采购、供应账套默认设为钢控
        if (TextUtils.equals(code, PermissionType.PROCESS_PURCHASE.getCode()) ||
                TextUtils.equals(code, PermissionType.PROCESS_SUPPLY.getCode())) {
            expandInfo.put("outdeptLedger", "gk");
            tvSet.setText(setArray[0]);
        }
    }


    @Override
    protected void initData() {
        proList = new ArrayList<>();
        proAdapter = new StoreCarAdapter(R.layout.item_confirm_pro, proList, 1);
        proAdapter.bindToRecyclerView(rvPro);
        proAdapter.setOrderType(getIntent().getStringExtra("code"));
        proList.addAll(JSON.parseArray(getIntent().getStringExtra("pro"), ProductBean.RecordsBean.class));
        proAdapter.notifyDataSetChanged();
        changeNumAndPrice();
        param = new HashMap<>();
        if (!TextUtils.isEmpty(getIntent().getStringExtra("supplierId"))) {
            param.put("supplierId", getIntent().getStringExtra("supplierId"));
        }
        if (!TextUtils.isEmpty(getIntent().getStringExtra("subProcessId"))) {
            param.put("subProcessId", getIntent().getStringExtra("subProcessId"));
        }
        if (!TextUtils.isEmpty(getIntent().getStringExtra("customerId"))) {
            param.put("customerId", getIntent().getStringExtra("customerId"));
        }
        if (!TextUtils.isEmpty(getIntent().getStringExtra("inStockId"))) {
            param.put("inStockId", getIntent().getStringExtra("inStockId"));
        }
        param.put("receiveDeptId", getIntent().getStringExtra("receiveDeptId"));
        param.put("launchOrderAmount", getIntent().getStringExtra("launchOrderAmount"));
        param.put("launchUserId", UserKeeper.getInstance().getUserId());
        param.put("launchDeptId", UserKeeper.getInstance().getUserDepId());
        getBillData();
    }

    private void getBillData() {
        RtfUtils.getRtf().getBill().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<OrderBillBean> dataList = JSON.parseArray(data.getData().toString(), OrderBillBean.class);
                billList.clear();
                billList.addAll(dataList);
                billNameList.clear();
                for (OrderBillBean process : dataList) {
                    billNameList.add(process.getName());
                }
                billDialog.addItems(billNameList.toArray(new String[billNameList.size()]), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        chooseBill = billList.get(which);
                        tvBill.setText(billNameList.get(which));
                        dialog.dismiss();
                    }
                });
            }
        });
    }

    /**
     * 转换pro，生成上传参数
     *
     * @param proList
     * @return
     */
    private List<JSONObject> coverProInfo(List<ProductBean.RecordsBean> proList) {
        List<JSONObject> orderItems = new ArrayList<>();
        for (ProductBean.RecordsBean recordsBean : proList) {
            JSONObject data = new JSONObject();
            data.put("productId", recordsBean.getId());
            data.put("type", "PDS");
            if (!TextUtils.equals(getIntent().getStringExtra("code"),
                    PermissionType.PROCESS_CRUCIBLE.getCode())) {
                data.put("innerPrice", MathUtils.converData(recordsBean.getInternalPrice(), 3));
            }
            if (TextUtils.equals(getIntent().getStringExtra("code"),
                    PermissionType.PROCESS_SALE.getCode())) {
                if (null != recordsBean.getMarkOrderRel()) {
                    recordsBean.getMarkOrderRel().setReceiveCompany(etCompany.getText().toString());
                    recordsBean.getMarkOrderRel().setContinuousCastingMachine(etMachine.getText().toString());
                    recordsBean.getMarkOrderRel().setShipCompany(etSendCompany.getText().toString());
                    recordsBean.getMarkOrderRel().setDomesticShipCompany(etCountryCompany.getText().toString());
                }
                data.put("markOrderRel", recordsBean.getMarkOrderRel());
            }
//            data.put("tranFromStockId", recordsBean.getCarPrice());
            data.put("customerBranchFactoryId", recordsBean.getFactoryId());//3.分厂客户ID
            data.put("outerPrice", recordsBean.getCarPrice());
            data.put("productCount", recordsBean.getCarNum());
            data.put("annex", recordsBean.getUrl());
//            data.put("provideMethod", recordsBean.getProvideMethod());
            orderItems.add(data);
        }
        return orderItems;
    }


    @Override
    protected void initEvent() {
        addNumListener(etInput1, tvInput1);
        addNumListener(etInput2, tvInput2);
        addNumListener(etInput3, tvInput3);
        addNumListener(etInput4, tvInput4);
        addNumListener(etInput5, tvInput5);
        proAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.rl_upload:
                        choosePosition = position;
                        addImg();
                        break;
                    case R.id.rl_receive_order:
                        receivePosition = position;
                        receiveDialog.show();
                        break;
                    case R.id.rl_choose_dep:
                        startActivityForResult(StoreClientFactoryActivity.class, 10001,
                                "customerId", getIntent().getStringExtra("customerId"), "position", position + "");
                        break;
                    case R.id.rl_mark:
                        startActivityForResult(ChooseHeadActivity.class, 10003,
                                "product", JSON.toJSONString(proList.get(position)),
                                "customerId", getIntent().getStringExtra("customerId"), "position", position + "");
                        break;
                }
            }
        });
    }

    /**
     * 添加字数监听器
     *
     * @param et
     * @param tv
     */
    private void addNumListener(EditText et, TextView tv) {
        WorkUtils.addNumListener(et, tv);
    }

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


    @OnClick({R.id.rl_bill, R.id.tv_ok, R.id.rl_set, R.id.rl_time})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_bill:
                billDialog.show();
                break;
            case R.id.tv_ok:
                if (expandInfo.get("outdeptLedger") == null) {
                    toast("请选择账套");
                    return;
                }
                String code = getIntent().getStringExtra("code");
                if (TextUtils.equals(code, PermissionType.PROCESS_PURCHASE.getCode()) ||
                        TextUtils.equals(code, PermissionType.PROCESS_SALE.getCode()) ||
                        TextUtils.equals(code, PermissionType.PROCESS_SUPPLY.getCode())) {
                    if (chooseBill == null) {
                        toast("请选择单据");
                        return;
                    } else {
                        param.put("erpSpcNo", chooseBill.getSpcNo());
                    }
                }
                if (expandInfo.get("requireTime") == null) {
                    toast("请选择客户要求交货时间");
                    return;
                }
                String company = etCompany.getText().toString();
                //验证唛头收货单位
                if (TextUtils.equals(code, PermissionType.PROCESS_SALE.getCode())) {
                    if (TextUtils.isEmpty(company)) {
                        toast("请输入收货单位");
                        return;
                    }
                }
                expandInfo.put("demond1", etInput2.getText().toString());
                expandInfo.put("demond2", etInput3.getText().toString());
                expandInfo.put("demond3", etInput4.getText().toString());
                expandInfo.put("demond4", etAddress.getText().toString());
                expandInfo.put("demond5", etInput1.getText().toString());
                expandInfo.put("comments", etInput5.getText().toString());
                if (!TextUtils.isEmpty(getIntent().getStringExtra("intoStore"))) {
                    expandInfo.put("intoStore", getIntent().getStringExtra("intoStore"));
                }
                if (!TextUtils.isEmpty(getIntent().getStringExtra("outerStore"))) {
                    expandInfo.put("outerStore", getIntent().getStringExtra("outerStore"));
                }
                orderItems = coverProInfo(proList);
                //去掉30天交付判断
//                String stringByNow = TimeUtils.getFitTimeSpanByNow(tvTime.getText().toString(), new SimpleDateFormat("yyyy-MM-dd"), 1);
//                if (stringByNow.endsWith("天")) {
//                    String day = stringByNow.substring(0, stringByNow.length() - 1);
//                    if (Integer.valueOf(day) < 30) {
//                        QMUIDialog.MessageDialogBuilder builder = DialogUtils.okAndCancelDialog(this);
//                        builder.setTitle("提示").setMessage("交付日期小于30天，订单价格会增加").
//                                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) {
//                                        submitOrder();
//                                        dialog.dismiss();
//                                    }
//                                }).show();
//                        return;
//                    }
//                }
                submitOrder();
                break;
            case R.id.rl_set:
                setDialog.show();
                break;
            case R.id.rl_time:
                PickTimeUtils.showPickThree(StoreSaleConfirmActivity.this, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        String time = TimeUtils.date2String(date, new SimpleDateFormat("yyyy-MM-dd"));
                        expandInfo.put("requireTime", time);
                        tvTime.setText(time);
                    }
                }).show();
                break;
        }
    }

    /**
     * 下单
     */
    private void submitOrder() {
        param.put("expandInfo", expandInfo);
        param.put("orderItems", orderItems);
        showLoading();
        Observable<BaseBean> observable;
        String code = getIntent().getStringExtra("code");
        if (TextUtils.equals(code, PermissionType.PROCESS_PURCHASE.getCode())) {
            observable = RtfUtils.getRtf().submitPurchaseOrder(WorkUtils.convertMapToBody(param));
        } else if (TextUtils.equals(code, PermissionType.PROCESS_SALE.getCode())) {
            observable = RtfUtils.getRtf().submitSaleOrder(WorkUtils.convertMapToBody(param));
        } else if (TextUtils.equals(code, PermissionType.PROCESS_INSIDE.getCode())) {
            observable = RtfUtils.getRtf().submitInsideOrder(WorkUtils.convertMapToBody(param));
        } else if (TextUtils.equals(code, PermissionType.PROCESS_SUPPLY.getCode())) {
            observable = RtfUtils.getRtf().submitSupplierOrder(WorkUtils.convertMapToBody(param));
        } else if (TextUtils.equals(code, PermissionType.PROCESS_CRUCIBLE.getCode())) {
            observable = RtfUtils.getRtf().submitCrucibleOrder(WorkUtils.convertMapToBody(param));
        } else {
            observable = RtfUtils.getRtf().submitPurchaseOrder(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("下单成功");
                startActivity(StoreOrderSuccessActivity.class);
            }

        });
    }

    private void changeNumAndPrice() {
        tvNum.setText("共 ".concat(proList.size() + "").concat(" 件"));
        String allPrice = "";
        for (ProductBean.RecordsBean recordsBean : proList) {
            allPrice = MathUtils.add(allPrice, MathUtils.multiply(recordsBean.getCarNum() + "", recordsBean.getInternalPrice() + "", 3), 3);
        }
        tvPrice.setText("总计: ¥ ".concat(allPrice));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10001 && resultCode == 10001) {
            Integer clientId = data.getIntExtra("id", 0);
            String name = data.getStringExtra("name");
            Integer position = Integer.valueOf(data.getStringExtra("position"));
            proList.get(position).setFactoryId(clientId);
            proList.get(position).setFactoryName(name);
            proAdapter.notifyItemChanged(position);
        } else 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("上传成功");
                        proList.get(choosePosition).setUrl(value);
                        coverProInfo(proList);
                        proAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void uploadFail(String value) {
                        hideLoading();
                        toast("图片上传失败");
                    }
                });
            }
        } else if (requestCode == 10003 && resultCode == 10003) {
            String mark = data.getStringExtra("mark");
            Integer position = Integer.valueOf(data.getStringExtra("position"));
            proList.get(position).setMarkOrderRel(JSON.parseObject(mark, MarkBean.class));
            proAdapter.notifyItemChanged(position);
        }
    }

    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(StoreSaleConfirmActivity.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("您需要开启拍照、存储权限！");
                    }
                });
    }


}
