package com.sheep.gamegroup.absBase;

import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.sheep.gamegroup.model.api.BaseMessageConverter;
import com.sheep.gamegroup.model.api.ICallBack;
import com.sheep.gamegroup.model.entity.UploadResult;
import com.sheep.gamegroup.util.ListUtil;
import com.sheep.gamegroup.util.LogUtil;
import com.sheep.gamegroup.util.upfile.UpFileListener;
import com.sheep.gamegroup.util.upfile.UpFileUtils;
import com.sheep.gamegroup.view.dialog.DialogProgress;
import com.sheep.jiuyan.samllsheep.utils.G;
import com.yalantis.ucrop.UCrop;

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

import me.iwf.photopicker.PhotoPicker;

/**
 * Created by realicing on 2018/3/26.
 * realicing@sina.com
 */

public abstract class AbsChooseImageActivity extends BaseActivity implements UpFileListener {
    private boolean isUpload = true;
    private boolean isCrop = true;
    protected int photoCount = 1;

    protected ArrayList<String> photos;
    protected String path;
    protected List<String> urls = new ArrayList<>();

    private DialogProgress dialogShowLoading;
    public static final int DEFAULT_MAX_COUNT = 7;//上传任务截图的最大个数

    public void showChooseDialog() {
        showChooseDialog(true, true,1);
    }

    public void showChooseDialog(boolean isCrop, boolean isUpload, int photoCount) {
        photoCount = Math.max(1,photoCount);
        this.isUpload = isUpload;
        this.isCrop = isCrop && photoCount == 1;
        this.photoCount = photoCount;
        this.photos = null;
        this.path = null;
        this.urls.clear();
        PhotoPicker.builder()
                .setPhotoCount(photoCount)
                .setShowCamera(showCamera)
                .setShowGif(false)
                .setPreviewEnabled(true)
                .start(this, PhotoPicker.REQUEST_CODE);
    }
    public void showChooseDialog(boolean isCrop, boolean isUpload, int photoCount, File dir) {
        LogUtil.println("showChooseDialog", dir.getAbsolutePath(), dir.exists());
        File[] files = dir.listFiles();
        if(dir.exists() && files != null && files.length > 0) {
            photoCount = Math.max(1, photoCount);
            this.isUpload = isUpload;
            this.isCrop = isCrop && photoCount == 1;
            this.photoCount = photoCount;
            this.photos = null;
            this.path = null;
            this.urls.clear();
            PhotoPicker.builder()
                    .setPhotoCount(photoCount)
                    .setShowCamera(showCamera)
                    .setShowGif(false)
                    .setPreviewEnabled(true)
                    .setPicker(ListUtil.asList(new ListUtil.CallBack<File, String>() {
                        @Override
                        public String call(File file) {
                            return file.getAbsolutePath();
                        }
                    }, files))
                    .start(this, PhotoPicker.REQUEST_CODE);
        } else {
            G.showToast("暂无截图（若您已经截图，请查看是否开启查看应用使用情况等权限！）");
        }
    }
    public void showChooseListDialog(boolean isCrop, boolean isUpload, int photoCount, ArrayList<String> imageUriList) {
        if(!ListUtil.isEmpty(imageUriList)) {
            photoCount = Math.max(1, photoCount);
            this.isUpload = isUpload;
            this.isCrop = isCrop && photoCount == 1;
            this.photoCount = photoCount;
            this.photos = null;
            this.path = null;
            this.urls.clear();
            PhotoPicker.builder()
                    .setPhotoCount(photoCount)
                    .setShowCamera(showCamera)
                    .setShowGif(false)
                    .setPreviewEnabled(true)
                    .setPicker(imageUriList)
                    .start(this, PhotoPicker.REQUEST_CODE);
        } else {
            G.showToast("暂无截图（若您已经截图，请查看是否开启查看应用使用情况等权限！）");
        }
    }
    public void showChooseDialog(boolean isCrop, boolean isUpload, int photoCount, ArrayList<String> imageUriList) {
        photoCount = Math.max(1,photoCount);
        this.isUpload = isUpload;
        this.isCrop = isCrop && photoCount == 1;
        this.photoCount = photoCount;
        this.photos = null;
        this.path = null;
        this.urls.clear();

        PhotoPicker.builder()
                .setPhotoCount(photoCount)
                .setShowCamera(showCamera)
                .setShowGif(false)
                .setPreviewEnabled(true)
                .setPickerAll(true)
                .setPicker(imageUriList)
                .start(this, PhotoPicker.REQUEST_CODE);
    }
    private boolean showCamera = false;

    public void setShowCamera(boolean showCamera) {
        this.showCamera = showCamera;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PhotoPicker.REQUEST_CODE) {//拍照或者选择照片
                if (data != null) {
                    photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                    if (photos != null && !photos.isEmpty() && !TextUtils.isEmpty((path = photos.get(0)))) {
                        if (isCrop) {
                            UCrop.of(Uri.fromFile(new File(path)), Uri.fromFile(new File(new File(path).getParentFile(), "temp.png")))
                                    .withAspectRatio(1, 1)
                                    .withMaxResultSize(500, 500)
                                    .start(AbsChooseImageActivity.this);
                        } else {
                            notCrop();
                        }
                        return;
                    }
                }
                onNotGetImage("没有数据");
            } else if (requestCode == UCrop.REQUEST_CROP) {//裁剪
                Uri resultUri;
                if (data != null && (resultUri = UCrop.getOutput(data))!=null) {
                    String cropPath;
                    if(!TextUtils.isEmpty(cropPath = resultUri.getPath())){
                        path = cropPath;
                        notCrop();
                    }

                } else if(!TextUtils.isEmpty(path)){
                        notCrop();
                }
            }
        } else if (resultCode == UCrop.RESULT_ERROR) {//裁剪出错
            if(!TextUtils.isEmpty(path))
                notCrop();
        }
    }

    private void notCrop() {
        if(photoCount == 1) {
            onGetImage(path);
            if (isUpload) {
                AbsChooseImageActivity.this.dialogShowLoading = DialogProgress.showDialog(AbsChooseImageActivity.this);
                UpFileUtils.upImage(new File(path), AbsChooseImageActivity.this);
            }
        } else if(photos != null && !photos.isEmpty()){
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < photos.size(); i++) {
                if(i != 0)
                    sb.append(";");
                sb.append(photos.get(i));
            }
            path = sb.toString();
            onGetImage(path);
            if (isUpload) {
                upImages();
            }
        } else {
            onNotGetImage("没有数据");
        }
    }

    //上传图片列表
    protected void upImages() {
        AbsChooseImageActivity.this.dialogShowLoading = DialogProgress.showDialog(AbsChooseImageActivity.this);
        UpFileUtils.upImages(photos, AbsChooseImageActivity.this, getCallBack());
    }

    /**
     * 上传图片前的回调
     * @return
     */
    protected ICallBack<Boolean> getCallBack(){
        return null;
    }

    @Override
    public void Success(String msg, int index) {
        if(index == -1 && !urls.isEmpty()) {//多图
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < urls.size(); i++) {
                if(i != 0)
                    sb.append(";");
                sb.append(urls.get(i));
            }
            onSetNetImageUrl(sb.toString());
        } else {
            final String data = parseMsg(msg);

            if (TextUtils.isEmpty(data)) {
                updateError("失败");
                return;
            }
            if(photoCount == 1) {
                onSetNetImageUrl(data);
            } else {
                urls.add(data);
            }
        }
    }
    protected String parseMsg(String msg){
        String json;
        if (TextUtils.isEmpty(msg)) {
            return null;
        }
        if (msg.startsWith("{")) {
            json = msg;
        } else {
            try {
                json = BaseMessageConverter.decrypt(msg);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
        UploadResult uploadResult = JSON.parseObject(json, UploadResult.class);
        if (uploadResult != null && uploadResult.getData() != null) {
            return uploadResult.getData().getUrl();
        }
        return null;
    }

    protected void setLoaddingText(String msg) {
        dialogShowLoading.getTextView().setText(msg);
    }
    protected void dismissLoaddingDialog() {
        dialogShowLoading.getAlertDialog().dismiss();
    }

    protected void updateError(String msg) {
        dialogShowLoading.getTextView().setText(msg);
        onNotGetImage(msg);
        dialogShowLoading.getAlertDialog().dismiss();
    }

    @Override
    public void Progress(String progress, int index) {
        dialogShowLoading.getTextView().setText(progress);
        dialogShowLoading.getTextView().append("%");
        if(index != -1 && photos != null && photos.size() != 1)
            dialogShowLoading.getTextView().append(" "+(index+1)+"/"+photos.size());
    }

    @Override
    public void Failure(String err) {
        onNotGetImage(err);
    }
    //流程：获取图片、裁剪图片、上传图片、设置或者更新图片
    protected abstract void onNotGetImage(String msg);//失败后回调

    protected abstract void onGetImage(String path);//获取图片成功后回调

    protected abstract void onSetNetImageUrl(String url);//获取图片、上传成功后回调--------设置或者更新图片

    protected abstract void onGetNetImageUrl(String url);//获取图片、上传成功并更新后回调


}

