package com.tjzhxx.union.adapter;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.lifecycle.Lifecycle;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.huantansheng.easyphotos.EasyPhotos;
import com.huantansheng.easyphotos.callback.SelectCallback;
import com.huantansheng.easyphotos.models.album.entity.Photo;
import com.tjzhxx.union.R;
import com.tjzhxx.union.activity.PhotoPreviewActivity;
import com.tjzhxx.union.entity.BaseResponse;
import com.tjzhxx.union.entity.Rescuestyle;
import com.tjzhxx.union.public_store.ConstDefine;
import com.tjzhxx.union.public_store.FileUtils;
import com.tjzhxx.union.public_store.GlideEngine;
import com.tjzhxx.union.public_store.ImageUtils;
import com.tjzhxx.union.public_store.retrofit.RetrofitUtils;
import com.tjzhxx.union.public_store.retrofit.UnionServices;
import com.tjzhxx.union.public_store.rx.ProgressSubscriber;
import com.tjzhxx.union.system.BaseActivity;
import com.uber.autodispose.AutoDispose;
import com.uber.autodispose.android.lifecycle.AndroidLifecycleScopeProvider;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * 描述:
 *
 * @author yanghuaxiong
 * @create 2018/5/3 下午4:40
 */
public class RescuestyleAdapter extends RecyclerView.Adapter<RescuestyleAdapter.ViewHolder> {

    Context mContext;
    List<Rescuestyle> mList;
    OnItemClickListener mOnItemClickListener;


    public void setOnItemClickListener(OnItemClickListener listener) {
        this.mOnItemClickListener = listener;
    }

    public RescuestyleAdapter(Context mContext, List<Rescuestyle> list) {
        this.mContext = mContext;
        this.mList = (list == null ? new ArrayList<Rescuestyle>() : list);
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.photo_select, parent, false);
        v.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mOnItemClickListener != null)
                    mOnItemClickListener.onItemClick(view, (Rescuestyle) view.getTag());
            }
        });
        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Rescuestyle bean = mList.get(position);
        holder.itemView.setTag(bean);
        Glide.with(mContext)
                .load(bean.getDemourl())
                .placeholder(R.mipmap.icon_camera)
                .error(R.mipmap.icon_camera)
                .into(holder.imageRemark);
        holder.title.setText(bean.getDockind());
        holder.image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                EasyPhotos.createAlbum((BaseActivity) mContext, true, false, GlideEngine.getInstance())
                        .setFileProviderAuthority("com.tjzhxx.union.FileProvider")
                        .setCount(1)
                        .setPuzzleMenu(false)
                        .setCleanMenu(false)
                        .start(new SelectCallback() {
                            @Override
                            public void onResult(ArrayList<Photo> photos, boolean isOriginal) {
                                Glide.with(mContext)
                                        .load(photos.get(0).path)
                                        .error(R.mipmap.loading)
                                        .placeholder(R.mipmap.loading)
                                        .into(holder.image);
                                String compressPath = FileUtils.getCompressFilePath(mContext) + "/" + photos.get(0).name;
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        if (photos.get(0).size > 2 * 1024) {
                                            File file = new File(photos.get(0).path);
                                            ImageUtils.compressBmp(mContext, file, compressPath, 2 * 1024);
                                            ((BaseActivity) mContext).runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    uploadImage(compressPath,bean);
                                                }
                                            });
                                        } else {
                                            uploadImage(photos.get(0).path,bean);
                                        }

                                    }
                                }).start();

                            }

                            @Override
                            public void onCancel() {
                            }
                        });
            }
        });
        holder.imageRemark.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mContext, PhotoPreviewActivity.class);
                intent.putExtra("url",bean.getDemourl());
                mContext.startActivity(intent);
            }
        });
    }

    @Override
    public int getItemCount() {
        return mList.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.title)
        TextView title;
        @BindView(R.id.image)
        ImageView image;
        @BindView(R.id.image_remark)
        ImageView imageRemark;


        public ViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    public interface OnItemClickListener {
        void onItemClick(View view, Rescuestyle entity);
    }
    //上传图片
    private void uploadImage(String path,Rescuestyle rescuestyle) {
        UnionServices services = RetrofitUtils.createApi(UnionServices.class, ConstDefine.HttpAdress);
        File file = new File(path);
        RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part imageBodyPart = MultipartBody.Part.createFormData("file", file.getName(), imageBody);
        services.uploadImage(imageBodyPart)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .as(AutoDispose.<BaseResponse<String>>autoDisposable(AndroidLifecycleScopeProvider.from((BaseActivity)mContext, Lifecycle.Event.ON_DESTROY)))
                .subscribe(new ProgressSubscriber<BaseResponse<String>>((BaseActivity)mContext) {
                    @Override
                    public void success(BaseResponse<String> value) {
                        rescuestyle.setImageUrl(value.getData());
                    }

                });
    }

}
