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

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
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.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.ProductBean;
import com.wd.workoffice.retrofit.ApiService;
import com.wd.workoffice.retrofit.RtfUtils;
import com.wd.workoffice.retrofit.WorkObserver;
import com.wd.workoffice.ui.activity.bat.store.StoreClientFactoryActivity;
import com.wd.workoffice.ui.activity.bat.store.StoreOrderSuccessActivity;
import com.wd.workoffice.ui.adapter.StoreCarAdapter;
import com.wd.workoffice.util.DialogUtils;
import com.wd.workoffice.util.Glide4Engine;
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.RtfHelper;
import flexible.xd.android_base.network.rtfhttp.Transformer;
import flexible.xd.android_base.utils.TimeUtils;
import io.reactivex.disposables.Disposable;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * 确认订单
 * author : flexible
 * email : lgd19940421@163.com
 * github: https://github.com/FlexibleXd
 **/
public class AddCrucibleConfirmActivity 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;
    private List<ProductBean.RecordsBean> proList;
    private StoreCarAdapter proAdapter;
    private QMUIDialog.MenuDialogBuilder setDialog;
    private String[] setArray = new String[]{"钢控", "锆碳"};
    private Map<String, Object> param;
    private Map<String, Object> expandInfo;
    private List<JSONObject> orderItems;
    private Integer choosePosition;

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        rvPro.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        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();
            }
        });
    }


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

    /**
     * 转换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");
//            data.put("tranFromStockId", recordsBean.getCarPrice());
            data.put("innerPrice", recordsBean.getInternalPrice());
            data.put("customerBranchFactoryId", recordsBean.getFactoryId());//3.分厂客户ID
            data.put("outerPrice", recordsBean.getCarPrice());
            data.put("productCount", recordsBean.getCarDoubleNum());
            data.put("annex", recordsBean.getUrl());
            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_choose_dep:
                        startActivityForResult(StoreClientFactoryActivity.class, 10001,
                                "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.tv_ok, R.id.rl_set, R.id.rl_time})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_ok:
                if (expandInfo.get("outdeptLedger") == null) {
                    toast("请选择账套");
                    return;
                }
                if (expandInfo.get("requireTime") == null) {
                    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());
                orderItems = coverProInfo(proList);
                submitOrder();
                break;
            case R.id.rl_set:
                setDialog.show();
                break;
            case R.id.rl_time:
                PickTimeUtils.showPickThree(AddCrucibleConfirmActivity.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();
        RtfUtils.getRtf().submitCrucibleSaleOrder(WorkUtils.convertMapToBody(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;
                }
                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.getCarDoubleNum() + "", recordsBean.getInternalPrice() + "", 2), 2);
        }
        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);
                RequestBody requestFile = RequestBody.create(MediaType.parse("image/png"), file);
                RtfHelper.getInstance().getApiService(ApiService.class).
                        upload(MultipartBody.Part.createFormData("newUploadImgs", file.getName(), requestFile)).
                        compose(Transformer.schedule()).subscribe(new WorkObserver<JSONObject>() {
                    @Override
                    public void doOnSubscribe(Disposable d) {

                    }

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

                    @Override
                    public void onSuccess(JSONObject jsonObject) {
                        hideLoading();
                        if (jsonObject.getInteger("status") != 0) {
                            toast(jsonObject.getString("msg"));
                            return;
                        }
                        toast("上传成功");
                        proList.get(choosePosition).setUrl(jsonObject.getString("data"));
                        coverProInfo(proList);
                        proAdapter.notifyDataSetChanged();
                    }
                });
            }
        }
    }

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