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

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

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.BaseMesBean;
import com.wd.workoffice.app.WorkToolBarActivity;
import com.wd.workoffice.bean.event.CheckFeedbackEvent;
import com.wd.workoffice.bean.mesBean.FeedbackDetailBean;
import com.wd.workoffice.bean.mesBean.ImageBean;
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.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.List;
import java.util.Map;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
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 MesQualityManagerActivity extends WorkToolBarActivity {


    @BindView(R.id.tv_desc)
    EditText tvDesc;
    @BindView(R.id.tv_use_status)
    EditText tvUseStatus;
    @BindView(R.id.tv_suggest)
    EditText tvSuggest;
    @BindView(R.id.rv_img)
    RecyclerView rvImg;
    private Map<String, Object> param;
    private List<ImageBean> imgList;
    private ImgAddAdapter imgAddAdapter;
    @Override
    protected void initView() {
        ButterKnife.bind(this);
        rvImg.setLayoutManager( new GridLayoutManager(this,3,RecyclerView.VERTICAL,false));

    }

    @Override
    protected void initData() {
        param = WorkUtils.simpleParam();
        FeedbackDetailBean data = JSON.parseObject(getIntent().getStringExtra("data"), FeedbackDetailBean.class);
        param.put("id",data.getId());
        param.put("status",2);
        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(rvImg);
    }

    private void submit() {
        param.put("feedbackDescription",tvDesc.getText().toString());
        param.put("otherProviderBehavior",tvUseStatus.getText().toString());
        param.put("salerOpinion",tvSuggest.getText().toString());
        List<ImageBean> uploadImg =new ArrayList<>();
        for (int i = 0; i < imgList.size()-1; i++) {
            uploadImg.add(imgList.get(i));
        }
        param.put("attachments",uploadImg);
        RtfUtils.getMesRtf().feedbackCheck("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;
                }
                EventBus.getDefault().post(new CheckFeedbackEvent());
                toast("审核成功");
                finish();
            }
        });
    }

    @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);
    }

    @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();
                }
            }
        });
    }

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

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
       if (requestCode == 10002 && resultCode == RESULT_OK) {
            List<Uri> dataUri = Matisse.obtainResult(data);
            for (Uri uri : dataUri) {
                upload( uri);
            }
        }
    }
    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(MesQualityManagerActivity.this)
                                .choose(MimeType.ofImage())
                                .countable(true)
                                .maxSelectable(3).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("您需要开启拍照、存储权限！");
                    }
                });
    }
    /**
     *
     * @param uri
     */
    private void upload( Object uri) {
        showLoading();
        File file;
        if (uri instanceof  Uri){
            file = WorkUtils.uriToFile((Uri) uri, this);
        }
        else {
            file =new File(uri.toString());
        }
        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]);

                    imgList.add(imgList.size()-1, imageBean);
                    imgAddAdapter.notifyDataSetChanged();
                    imageBean.setUri((Uri) uri);
            }
        });
    }
}
