package com.tenlionsoft.baselib.core.widget;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.view.View;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.Target;
import com.hjq.toast.ToastUtils;
import com.tenlionsoft.baselib.R;
import com.tenlionsoft.baselib.R2;
import com.tenlionsoft.baselib.constant.PathConfig;
import com.tenlionsoft.baselib.core.widget.base.BaseActivity;
import com.tenlionsoft.baselib.core.widget.photoview.adapter.ImageAdapter;
import com.tenlionsoft.baselib.utils.UIUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import androidx.viewpager.widget.ViewPager;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableOnSubscribe;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;

/**
 * 相片浏览
 */
@Route(path = PathConfig.PATH_MODULE_BASELIB_SHOW_IMG)
public class PhotoActivity extends BaseActivity {
    @BindView(R2.id.vp_images)
    ViewPager mVpImages;
    @BindView(R2.id.tv_count)
    TextView mTvCount;
    public static final String TAG_IMGURL = "imgUrls";
    private Unbinder mUnbinder;
    private int mPosition = 0;
    private ArrayList<String> mImgUrls;

    @Override
    protected int setLayoutId() {
        return R.layout.activity_photo;
    }


    @Override
    protected void doShowOptions() {

    }

    @Override
    protected void clearSearch() {

    }

    @Override
    protected void doSearchByTitle() {

    }

    @Override
    public void initData() {
        mUnbinder = ButterKnife.bind(this);
        mTvBaseTitle.setText("图片浏览");
        refreshView(STATE_LOAD_SUCCESS);
        mTvPublish.setText("保存");
        mTvPublish.setVisibility(View.VISIBLE);
        mTvPublish.setOnClickListener(v -> downloadImg());

        mImgUrls = getIntent().getStringArrayListExtra(TAG_IMGURL);
        int curItem = getIntent().getIntExtra("curItem", 0);
        if (mImgUrls == null) {
            ToastUtils.show(R.string.check_imgurl);
            finish();
        } else {
            ImageAdapter imageAdapter = new ImageAdapter(this, mImgUrls);
            mVpImages.setAdapter(imageAdapter);
            imageAdapter.addImgClick(this::finish);
            mTvCount.setText(String.format(getResources().getString(R.string.img_position), (curItem + 1), mImgUrls.size()));
            mVpImages.setCurrentItem(curItem);

            mVpImages.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                }

                @Override
                public void onPageSelected(int position) {
                    mTvCount.setText(String.format(getResources().getString(R.string.img_position), ++position, mImgUrls.size()));
                }

                @Override
                public void onPageScrollStateChanged(int state) {

                }
            });
        }
    }

    @SuppressLint("CheckResult")
    private void downloadImg() {
        int currentItem = mVpImages.getCurrentItem();
        if (mImgUrls != null && mImgUrls.size() > 0) {
            String s = mImgUrls.get(currentItem);
            ProgressDialog dialog = UIUtil.initDialog(mActivity, "保存中...");
            dialog.show();
            Observable.create((ObservableOnSubscribe<File>) e -> {
                //通过gilde下载得到file文件,这里需要注意android.permission.INTERNET权限
                e.onNext(Glide.with(mActivity)
                    .load(s)
                    .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                    .get());
                e.onComplete();
            }).subscribeOn(Schedulers.io())
                .observeOn(Schedulers.newThread())
                .subscribe(new Observer<File>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(File file) {
                        dialog.dismiss();
                        String pathStr = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + PathConfig.CATCH_PATH;
                        File appDir = new File(pathStr);
                        if (!appDir.exists()) {
                            appDir.mkdirs();
                        }
                        String fileName = System.currentTimeMillis() + ".jpg";
                        File destFile = new File(appDir, fileName);
                        //把gilde下载得到图片复制到定义好的目录中去
                        copy(file, destFile);
                        // 最后通知图库更新
                        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                            Uri.fromFile(new File(destFile.getPath()))));
                    }

                    @Override
                    public void onError(Throwable e) {
                        dialog.dismiss();
                        ToastUtils.show("保存失败,稍后重试.");
                    }

                    @Override
                    public void onComplete() {

                    }
                });
        } else {
            ToastUtils.show("图片地址有误,请稍后重试.");
        }
    }

    /**
     * 复制文件
     *
     * @param source 输入文件
     * @param target 输出文件
     */
    public void copy(File source, File target) {
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            fileInputStream = new FileInputStream(source);
            fileOutputStream = new FileOutputStream(target);
            byte[] buffer = new byte[1024];
            while (fileInputStream.read(buffer) > 0) {
                fileOutputStream.write(buffer);
            }
            ToastUtils.show("保存成功,前往SD卡查看");
        } catch (Exception e) {
            e.printStackTrace();
            ToastUtils.show("保存失败,请稍后重试");
        } finally {
            try {
                fileInputStream.close();
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onDestroy() {
        mUnbinder.unbind();
        super.onDestroy();
    }
}
