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

import com.alibaba.fastjson.JSON;
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.AddMachineModifyChildEvent;
import com.wd.workoffice.bean.event.RefreshMachineEvent;
import com.wd.workoffice.bean.mesBean.ImageBean;
import com.wd.workoffice.bean.mesBean.MachineDetailBean;
import com.wd.workoffice.bean.mesBean.MesProBean;
import com.wd.workoffice.retrofit.RtfUtils;
import com.wd.workoffice.retrofit.WorkObserver;
import com.wd.workoffice.ui.activity.mes.MesProActivity;
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 MesThreeModifyActivity extends WorkToolBarActivity {
    @BindView(R.id.tv_pro)
    TextView tvPro;
    @BindView(R.id.rl_pro)
    RelativeLayout rlPro;
    @BindView(R.id.et_img_code)
    TextView etImgCode;
    @BindView(R.id.et_type)
    TextView etType;
    @BindView(R.id.et_spec)
    TextView etSpec;
    @BindView(R.id.et_material)
    EditText etMaterial;
    @BindView(R.id.et_requirements)
    EditText etRequirements;
    @BindView(R.id.et_years)
    EditText etYears;
    @BindView(R.id.et_position)
    EditText etPosition;
    @BindView(R.id.et_baking_method)
    EditText etBakingMethod;
    @BindView(R.id.et_baking_temperature)
    EditText etBakingTemperature;
    @BindView(R.id.tv_baking_time)
    EditText tvBakingTime;
    @BindView(R.id.rl_time)
    RelativeLayout rlTime;
    @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 MesProBean.ListBean choosePro;
    private Map<Integer, Object> annexMap = new HashMap<>();
    private MachineDetailBean.ProductListBean dataBean;
    private String from;

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

    @Override
    protected void initData() {
        from = getIntent().getStringExtra("from");
        dataBean = JSON.parseObject(getIntent().getStringExtra("data"), MachineDetailBean.ProductListBean.class);
        param = WorkUtils.simpleParam();
        param.put("continuousCasterCode", dataBean.getContinuousCasterCode());
        param.put("id", dataBean.getId());
        if (!TextUtils.isEmpty(dataBean.getProductsCode())) {
            choosePro = new MesProBean.ListBean();
            choosePro.setProductCode(dataBean.getProductsCode());
            choosePro.setDrawingNumber(dataBean.getFigureNumber());
            choosePro.setProductName(dataBean.getProductsName());
            choosePro.setSpecification(dataBean.getProductsStandards());
            choosePro.setProductType(dataBean.getProductsType());
            tvPro.setText(choosePro.getProductName());
            etImgCode.setText(choosePro.getDrawingNumber());
            etSpec.setText(choosePro.getSpecification());
            etType.setText(choosePro.getProductType());
        }
        if (dataBean.getAttachments() != null) {
            for (int i = 0; i < dataBean.getAttachments().size(); i++) {
                annexMap.put(i + 1, dataBean.getAttachments().get(i));
                switch (i + 1) {
                    case 1:
                        GlideUtils.getRequest().load(dataBean.getAttachments().get(i).getUrl()).into(ivImg1);
                        break;
                    case 2:
                        GlideUtils.getRequest().load(dataBean.getAttachments().get(i).getUrl()).into(ivImg2);
                        break;
                    case 3:
                        GlideUtils.getRequest().load(dataBean.getAttachments().get(i).getUrl()).into(ivImg3);
                        break;
                }
            }
        }
        etMaterial.setText(dataBean.getMaterialsUsed());
        etRequirements.setText(dataBean.getUseRequirement());
        etPosition.setText(dataBean.getSlagLineLocation());
        etYears.setText(dataBean.getUseLife());
        etBakingTemperature.setText(dataBean.getBakingTemperature());
        etBakingMethod.setText(dataBean.getBakingMethod());
        tvBakingTime.setText(dataBean.getBakingDateTime() + "");
        etContent.setText(dataBean.getUseProblemFeedback());
        etRemark.setText(dataBean.getRemark());
        if (!TextUtils.equals(from, "1")) {
            getData();
        }
    }

    private void getData() {
        RtfUtils.getMesRtf().threeDetail(dataBean.getId(), "1").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;
                }
                dataBean = JSON.parseObject(data.getData().toString(), MachineDetailBean.ProductListBean.class);
                if (dataBean.getAttachments() != null) {
                    for (int i = 0; i < dataBean.getAttachments().size(); i++) {
                        annexMap.put(i + 1, dataBean.getAttachments().get(i));
                        switch (i + 1) {
                            case 1:
                                GlideUtils.getRequest().load(dataBean.getAttachments().get(i).getUrl()).into(ivImg1);
                                break;
                            case 2:
                                GlideUtils.getRequest().load(dataBean.getAttachments().get(i).getUrl()).into(ivImg2);
                                break;
                            case 3:
                                GlideUtils.getRequest().load(dataBean.getAttachments().get(i).getUrl()).into(ivImg3);
                                break;
                        }
                    }
                }
            }
        });
    }

    private void submit() {
        String bakingMethods = etBakingMethod.getText().toString();
        String bakingTemperature = etBakingTemperature.getText().toString();
        String bakingTime = tvBakingTime.getText().toString();
        String content = etContent.getText().toString();
        String imgCode = etImgCode.getText().toString();
        String material = etMaterial.getText().toString();
        String position = etPosition.getText().toString();
        String requirements = etRequirements.getText().toString();
        String spec = etSpec.getText().toString();
        String type = etType.getText().toString();
        String years = etYears.getText().toString();
        String remark = etRemark.getText().toString();
        if (choosePro == null) {
            toast("请选择产品");
            return;
        }
        param.put("productsCode", choosePro.getProductCode());
        param.put("productsName", choosePro.getProductName());
        param.put("figureNumber", imgCode);
        param.put("productsType", type);
        param.put("productsStandards", spec);
        param.put("materialsUsed", material);
        param.put("useRequirement", requirements);
        param.put("useLife", years);
        param.put("slagLineLocation", position);
        param.put("bakingMethod", bakingMethods);
        param.put("bakingTemperature", bakingTemperature);
        param.put("bakingDateTime", bakingTime);
        param.put("useProblemFeedback", content);
        param.put("remark", remark);
        param.put("attachments", getUploadImg());
        if (TextUtils.equals(from, "1")) {
            EventBus.getDefault().post(new AddMachineModifyChildEvent(1, JSON.toJSONString(param)
                    , Integer.valueOf(getIntent().getStringExtra("position"))));
            finish();
            return;
        }
        RtfUtils.getMesRtf().threeAdd("1", "2", 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());
            }
        });
    }

    private void delete() {
        RtfUtils.getMesRtf().threeDelete(dataBean.getId(), "1").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_three;
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (TextUtils.equals(from, "1")) {
            getMenuInflater().inflate(R.menu.menu_finish, menu);
        }else{
            getMenuInflater().inflate(R.menu.menu_finish_delete, menu);
        }
        return super.onCreateOptionsMenu(menu);
    }


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


    @OnClick({R.id.iv_img1, R.id.iv_img2, R.id.iv_img3, R.id.rl_time, R.id.rl_pro})
    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;
            case R.id.rl_time:
                break;
            case R.id.rl_pro:
                startActivityForResult(MesProActivity.class, 10001);
                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(MesThreeModifyActivity.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 (requestCode == 10001 && resultCode == 10001) {
            choosePro = JSON.parseObject(data.getStringExtra("data"), MesProBean.ListBean.class);
            tvPro.setText(choosePro.getProductName());
            etImgCode.setText(choosePro.getDrawingNumber());
            etSpec.setText(choosePro.getSpecification());
            etType.setText(choosePro.getProductType());
        }
        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 = WorkUtils.uriToFile(uri, this);
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        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(file.getName());
                imageBean.setSize(FileUtils.getFileLength(file));
                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;
                }
            }
        });
    }

}
