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

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

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.UriUtils;
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.AddLogEvent;
import com.wd.workoffice.bean.mesBean.ImageBean;
import com.wd.workoffice.bean.mesBean.MesProBean;
import com.wd.workoffice.bean.mesBean.TicketBean;
import com.wd.workoffice.retrofit.RtfUtils;
import com.wd.workoffice.retrofit.WorkObserver;
import com.wd.workoffice.ui.activity.mes.ImageActivity;
import com.wd.workoffice.ui.activity.mes.VideoActivity;
import com.wd.workoffice.ui.adapter.ImgAddAdapter;
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 androidx.recyclerview.widget.GridLayoutManager;
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.FileUtils;
import io.reactivex.disposables.Disposable;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

import static flexible.xd.android_base.utils.ActivityUtils.startActivity;

/**
 * 工单新增
 * author : flexible
 * email : lgd19940421@163.com
 * github: https://github.com/FlexibleXd
 **/
public class MesTicketAddLogActivity extends WorkToolBarActivity {
    @BindView(R.id.tv_code)
    TextView tvCode;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.tv_create_person)
    TextView tvCreatePerson;
    @BindView(R.id.et_content)
    EditText etContent;
    @BindView(R.id.et_question_desc)
    EditText etQuestionDesc;
    @BindView(R.id.et_client)
    EditText etClient;
    @BindView(R.id.iv_img1)
    ImageView ivImg1;
    @BindView(R.id.iv_img2)
    ImageView ivImg2;
    @BindView(R.id.iv_img3)
    ImageView ivImg3;
    @BindView(R.id.rv_img)
    RecyclerView rvImg;
    private Map<String, Object> param;
    private TicketBean.ListBean data;
    private Map<Integer, Object> annexMap = new HashMap<>();
    private List<ImageBean> imgList;
    private ImgAddAdapter imgAddAdapter;

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        data = JSON.parseObject(getIntent().getStringExtra("data"), TicketBean.ListBean.class);
        tvCode.setText(data.getJobNo());
        tvTime.setText(data.getCreateDateTime());
        tvCreatePerson.setText(data.getCreateUserName());
        rvImg.setLayoutManager(new GridLayoutManager(this, 3, RecyclerView.VERTICAL, false));
//        ivImg1.setImageResource(R.mipmap.ic_launcher);
//        GlideUtils.getRequest().load(R.mipmap.ic_launcher).into(ivImg1);
    }

    @Override
    protected void initData() {
        param = WorkUtils.simpleParam();
        param.put("jobNo", data.getJobNo());
        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() {
        RtfUtils.getMesRtf().logAdd("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();
                EventBus.getDefault().post(new AddLogEvent());
                toast("添加成功");
            }
        });
    }

    @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) {
                    if (imgList.size() > 3) {
                        toast("最大上传3张");
                        return;
                    }
                    addImg();
                }else {
                    if (!WorkUtils.isImg(imgList.get(position).getType())) {
//                    JzvdStd.startFullscreenDirectly(context,
//                            JzvdStd.class, imgList.get(position).getUrl(), "");
                        Intent intent =new Intent(MesTicketAddLogActivity.this, VideoActivity.class);
                        intent.putExtra( "url","http://124.129.27.194:81/" +imgList.get(position).getPath());
                        startActivity(intent);

                    }else {
                        Intent intent =new Intent(MesTicketAddLogActivity.this, ImageActivity.class);
                        intent.putExtra( "url","http://124.129.27.194:81/" + imgList.get(position).getPath());
                        startActivity(intent);
                    }
                }
            }
        });
    }

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

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.report:
                String client = etClient.getText().toString();
                String content = etContent.getText().toString();
                String desc = etQuestionDesc.getText().toString();
                param.put("customerDemand", client);
                param.put("jobContent", content);
                param.put("problemDescription", desc);
                List<ImageBean> uploadImg = new ArrayList<>();
                for (int i = 0; i < imgList.size() - 1; i++) {
                    uploadImg.add(imgList.get(i));
                }
                param.put("attachments", uploadImg);
                submit();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

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


    @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 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(MesTicketAddLogActivity.this)
                                .choose(MimeType.ofAll())
                                .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(10001);
                    } 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 10001:
//                    if (Matisse.obtainResult(data).size() != 0) {
//                        Uri uri = Matisse.obtainResult(data).get(0);
//                        upload(1, uri);
//                    }
                    List<Uri> dataUri = Matisse.obtainResult(data);
                    for (Uri uri : dataUri) {
                        upload(uri);
                    }
                    break;
                case 10002:
//                    if (Matisse.obtainResult(data).size() != 0) {
//                        Uri uri = Matisse.obtainResult(data).get(0);
//                        upload(2, uri);
//                    }
                    break;
                case 10003:
//                    if (Matisse.obtainResult(data).size() != 0) {
//                        Uri uri = Matisse.obtainResult(data).get(0);
//                        upload(3, uri);
//                    }
                    break;
            }
        }
    }

    private void upload(Uri uri) {
        showLoading();
//        File file = WorkUtils.uriToFile(uri, this);
        File file;
        if (uri instanceof Uri) {
//            file = WorkUtils.uriToFile((Uri) uri, this);
            file = UriUtils.uri2File((Uri) uri);
        } else {
            file = new File(uri.toString());
        }
        File uploadFile;
        if (WorkUtils.isImg(file.getName().split("\\.")[1])){
             uploadFile = WorkUtils.getSmallImg(file, this);
        }else {
            uploadFile =file;
        }
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), uploadFile);
        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;
                }
                if (imgList.size() < 10) {
                    toast("上传成功");
                    ImageBean imageBean = new ImageBean();
                    imageBean.setPath(data.getData().toString());
                    imageBean.setName(uploadFile.getName());
                    imageBean.setSize(FileUtils.getFileLength(uploadFile));
                    imageBean.setType(data.getData().toString().split("\\.")[1]);

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

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

}
