package com.wd.workoffice.ui.activity.mes.user;

import android.Manifest;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.UriUtils;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.wd.workoffice.R;
import com.wd.workoffice.app.BaseMesBean;
import com.wd.workoffice.app.WorkToolBarActivity;
import com.wd.workoffice.bean.event.AddMachineAddChildEvent;
import com.wd.workoffice.bean.event.RefreshMachineEvent;
import com.wd.workoffice.bean.mesBean.ImageBean;
import com.wd.workoffice.retrofit.RtfUtils;
import com.wd.workoffice.retrofit.WorkObserver;
import com.wd.workoffice.util.Glide4Engine;
import com.wd.workoffice.util.GlideUtils;
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.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.Nullable;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import flexible.xd.android_base.network.rtfhttp.Transformer;
import flexible.xd.android_base.utils.FileUtils;
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 MesOtherSupplierAddActivity extends WorkToolBarActivity {
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_years)
    EditText etYears;
    @BindView(R.id.et_supply_num)
    EditText etSupplyNum;
    @BindView(R.id.et_stock_num)
    EditText etStockNum;
    @BindView(R.id.et_content)
    EditText etContent;
    @BindView(R.id.iv_img1)
    ImageView ivImg1;
    @BindView(R.id.iv_img2)
    ImageView ivImg2;
    @BindView(R.id.iv_img3)
    ImageView ivImg3;
    @BindView(R.id.et_remark)
    EditText etRemark;
    private Map<String, Object> param;
    private Map<Integer, Object> annexMap = new HashMap<>();
    private String from;

    @Override
    protected void initView() {
        ButterKnife.bind(this);
    }

    @Override
    protected void initData() {
        from = getIntent().getStringExtra("from");
        param = WorkUtils.simpleParam();
        param.put("continuousCasterCode", getIntent().getStringExtra("continuousCasterCode"));
    }

    private void submit() {
        String name = etName.getText().toString();
        String years = etYears.getText().toString();
        String supply = etSupplyNum.getText().toString();
        String stock = etStockNum.getText().toString();
        String content = etContent.getText().toString();
        String remark = etRemark.getText().toString();
        param.put("supplierName", name);
        param.put("supplyNumber", supply);
        param.put("stockNumber", stock);
        param.put("useLife", years);
        param.put("otherSituationDescription", content);
        param.put("remark", remark);
        param.put("attachments", getUploadImg());
        if (TextUtils.equals(from, "1")) {
            EventBus.getDefault().post(new AddMachineAddChildEvent(3, JSON.toJSONString(param)));
            finish();
        } else {
        RtfUtils.getMesRtf().otherSupplierAdd("1", "1", WorkUtils.convertMapToBody(param)).compose(Transformer.schedule()).subscribe(new WorkObserver<BaseMesBean>() {
            @Override
            public void doOnSubscribe(Disposable d) {
            }

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

            @Override
            public void onSuccess(BaseMesBean data) {
                hideLoading();
                if (!data.isSuccess()) {
                    toast(data.getMessage());
                    return;
                }
                finish();
                toast("添加成功");
                EventBus.getDefault().post(new RefreshMachineEvent());
            }
        });}
    }

    @Override
    protected void initEvent() {
    }

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


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_finish, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.finish:
                submit();
                break;
        }
        return super.onOptionsItemSelected(item);
    }


    @OnClick({R.id.iv_img1, R.id.iv_img2, R.id.iv_img3})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_img1:
                addImg(1);
                break;
            case R.id.iv_img2:
                addImg(2);
                break;
            case R.id.iv_img3:
                addImg(3);
                break;
        }
    }

    private List<Object> getUploadImg() {
        List<Object> imgList = new ArrayList<>();
        for (Map.Entry<Integer, Object> integerStringEntry : annexMap.entrySet()) {
            imgList.add(integerStringEntry.getValue());
        }
        return imgList;
    }

    private void addImg(int position) {
        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(MesOtherSupplierAddActivity.this)
                                .choose(MimeType.ofAll())
                                .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(10001 + position);
                    } else {
                        // At least one permission is denied
                        toast("您需要开启拍照、存储权限！");
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 10002:
                    if (Matisse.obtainResult(data).size() != 0) {
                        Uri uri = Matisse.obtainResult(data).get(0);
                        upload(1, uri);
                    }
                    break;
                case 10003:
                    if (Matisse.obtainResult(data).size() != 0) {
                        Uri uri = Matisse.obtainResult(data).get(0);
                        upload(2, uri);
                    }
                    break;
                case 10004:
                    if (Matisse.obtainResult(data).size() != 0) {
                        Uri uri = Matisse.obtainResult(data).get(0);
                        upload(3, uri);
                    }
                    break;
            }
        }

    }

    private void upload(int position, Uri uri) {
        showLoading();
        File  file = UriUtils.uri2File((Uri) uri);
        File smallImg = WorkUtils.getSmallImg(file, this);
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"),smallImg);
        RtfUtils.getMesRtf().
                upload(MultipartBody.Part.createFormData("file", file.getName(), requestFile)).
                compose(Transformer.schedule()).subscribe(new WorkObserver<BaseMesBean>() {
            @Override
            public void doOnSubscribe(Disposable d) {

            }

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

            @Override
            public void onSuccess(BaseMesBean data) {
                hideLoading();
                if (!data.isSuccess()) {
                    toast(data.getMessage());
                    return;
                }
                toast("上传成功");
                ImageBean imageBean = new ImageBean();
                imageBean.setPath(data.getData().toString());
                imageBean.setName(smallImg.getName());
                imageBean.setSize(FileUtils.getFileLength(smallImg));
                imageBean.setType(data.getData().toString().split("\\.")[1]);
                switch (position) {
                    case 1:
                        GlideUtils.getRequest().load(uri).into(ivImg1);
                        annexMap.put(1, imageBean);
                        break;
                    case 2:
                        GlideUtils.getRequest().load(uri).into(ivImg2);
                        annexMap.put(2, imageBean);
                        break;
                    case 3:
                        GlideUtils.getRequest().load(uri).into(ivImg3);
                        annexMap.put(3, imageBean);
                        break;
                }
            }
        });
    }

}
