package com.tjzhxx.union.custom_view;

import android.Manifest;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.lifecycle.Lifecycle;

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.entity.BaseResponse;
import com.tjzhxx.union.permission.PermissionHelper;
import com.tjzhxx.union.permission.PermissionInterface;
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.DefaultSubscriber;
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 io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * 描述:
 *
 * @author yanghuaxiong
 * @create 2021/9/8 10:23 PM
 */
public class PhotoSelectLayout extends LinearLayout implements PermissionInterface {
    private TextView title;
    private ImageView image;
    private ImageView remark;
    private String imageUrl;
    private String remarkUrl;
    private Context context;
    private PermissionHelper mPermissionHelper;

    public PhotoSelectLayout(Context context) {
        this(context, null);
    }

    public PhotoSelectLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public PhotoSelectLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.PhotoSelectLayout);
        LayoutInflater.from(context).inflate(R.layout.photo_select, this);
        image = (ImageView) findViewById(R.id.image);
        mPermissionHelper = new PermissionHelper((BaseActivity)context, this);
        image.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                mPermissionHelper.requestPermissions();
            }
        });
        remark = (ImageView) findViewById(R.id.image_remark);
        title = (TextView) findViewById(R.id.title);
        title.setText(a.getText(R.styleable.PhotoSelectLayout_title));
    }

    public String getImageUrl() {
        return imageUrl;
    }

    public void setImageUrl(String imageUrl) {
        this.imageUrl = imageUrl;

    }

    public String getRemarkUrl() {
        return remarkUrl;
    }

    public void setRemarkUrl(String remarkUrl) {
        this.remarkUrl = remarkUrl;
        Glide.with(context)
                .load(remarkUrl)
                .placeholder(R.mipmap.icon_camera)
                .error(R.mipmap.icon_camera)
                .centerCrop()
                .into(remark);
    }
    //上传图片
    private void uploadImage(String path) {
        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)context, Lifecycle.Event.ON_DESTROY)))
                .subscribe(new DefaultSubscriber<BaseResponse<String>>((BaseActivity)context) {
                    @Override
                    public void success(BaseResponse<String> value) {
                       imageUrl = value.getData();
                    }

                });
    }

    @Override
    public int getPermissionsRequestCode() {
        return 999;
    }

    @Override
    public String[] getPermissions() {
        return new String[]{
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.CAMERA
        };
    }

    @Override
    public void requestPermissionsSuccess() {
        EasyPhotos.createAlbum((BaseActivity) context, 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(context)
                                .load(photos.get(0).path)
                                .error(R.mipmap.loading)
                                .placeholder(R.mipmap.loading)
                                .into(image);
                        String compressPath = FileUtils.getCompressFilePath(context) + "/" + 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(context, file, compressPath, 2 * 1024);
                                    ((BaseActivity) context).runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            uploadImage(compressPath);
                                        }
                                    });
                                } else {
                                    uploadImage(photos.get(0).path);
                                }

                            }
                        }).start();

                    }

                    @Override
                    public void onCancel() {
                    }
                });
    }

    @Override
    public void requestPermissionsFail() {

    }
}
