package com.wisewoods.eduandroid.ui;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;

import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.UriUtils;
import com.wisewoods.base.base.BaseActivity;
import com.wisewoods.base.bean.ResList;
import com.wisewoods.base.bean.Results;
import com.wisewoods.base.net.JCallback;
import com.wisewoods.base.net.JDCallback;
import com.wisewoods.base.utils.$;
import com.wisewoods.base.utils.DialogUtils;
import com.wisewoods.eduandroid.R;
import com.wisewoods.eduandroid.app.App;
import com.wisewoods.eduandroid.databinding.ActivityResBinding;
import com.wisewoods.eduandroid.oss.ICloundOS;
import com.wisewoods.eduandroid.oss.OSSManager;
import com.wisewoods.eduandroid.ui.adapter.ResAdapter;
import com.wisewoods.eduandroid.view.InputDialog;

import java.io.File;
import java.util.HashMap;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Response;

public class ResActivity extends BaseActivity<ActivityResBinding> {

    private String id;
    private String pid;
    private String title;
    private ResAdapter resAdapter;
    private InputDialog dialog;

    public static void start(String id, String pid, String title) {
        Intent intent = new Intent(ActivityUtils.getTopActivity(), ResActivity.class);
        intent.putExtra("id", id);
        intent.putExtra("pid", pid);
        intent.putExtra("title", title);
        ActivityUtils.startActivity(intent);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        id = getIntent().getStringExtra("id");
        pid = getIntent().getStringExtra("pid");
        title = getIntent().getStringExtra("title");
        if (TextUtils.isEmpty(title)) {
            title = "归档资源";
        }
        showBarBack(binding.bar.tvTitle, title, binding.bar.ivBack);
        binding.srf.setOnRefreshListener(() -> {
            getData();
        });

        binding.rvRes.setLayoutManager(new LinearLayoutManager(this));
        resAdapter = new ResAdapter();
        resAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (view.getId() == R.id.tv_delete) {
                DialogUtils.showCommon(
                        "确认删除文件" + resAdapter.getItem(position).directoryName,
                        (DialogUtils.IDialogOnOKListener) dialog -> {
                            App.api.deleteFileOrDir(resAdapter.getItem(position).id + "")
                                    .enqueue(new JDCallback<Results>() {
                                        @Override
                                        public void onS(Response<Results> response, Results results) {
                                            $.toast("删除成功");
                                            getData();
                                        }
                                    });
                        });
            } else if (view.getId() == R.id.card_dir) {
                ResActivity.start(id, resAdapter.getItem(position).id + "",
                        resAdapter.getItem(position).directoryName);
            }
        });
        resAdapter.setOnItemChildLongClickListener((adapter, view, position) -> {
            if (view.getId() == R.id.card_dir) {
                if (resAdapter.getItem(position).hasChildren) {
                    $.toast("存在子目录,不能删除");
                } else {
                    DialogUtils.showCommon(
                            "确认删除文件夹" + resAdapter.getItem(position).directoryName,
                            (DialogUtils.IDialogOnOKListener) dialog -> {
                                App.api.deleteFileOrDir(resAdapter.getItem(position).id + "")
                                        .enqueue(new JDCallback<Results>() {
                                            @Override
                                            public void onS(Response<Results> response, Results results) {
                                                $.toast("删除成功");
                                                getData();
                                            }
                                        });
                            });
                }
            }
            return false;
        });
        binding.rvRes.setAdapter(resAdapter);


        binding.tvAddDir.setOnClickListener(v -> {
            dialog = InputDialog.show(getSupportFragmentManager(),dialog);
            dialog.setListener(text -> {
                if (isFastClick()) {
                    addDir(text);
                }
            });
        });
        binding.tvAddFile.setOnClickListener(v -> {
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("*/*");//设置类型，我这里是任意类型，可以过滤文件类型
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            startActivityForResult(intent, 8000);
        });
        getData();
    }

    private void getData() {
        App.api.getResInfo(id, pid)
                .enqueue(new JCallback<ResList>() {
                    @Override
                    public void onS(Response<ResList> response, ResList resList) {
                        resAdapter.setNewInstance(resList.data);
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                        binding.srf.setRefreshing(false);
                    }
                });
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 8000) {
            if (resultCode == RESULT_OK) {
                Uri uri = data.getData();
                LogUtils.e("uri", uri);
                addFile(uri);
            } else {
                $.toast("取消");
            }
        }
    }

    private void addFile(Uri uri) {
        showLoading();
        File file = UriUtils.uri2File(uri);
        long size = FileUtils.getLength(file);
        String name = FileUtils.getFileName(file);
        String ext = FileUtils.getFileExtension(file);
        LogUtils.e(file, size, name, ext);
        OSSManager.getInstance().upload(OSSManager.OSSPATH+name, file.getPath(),  (code, msg) -> {
            if (code == ICloundOS.CODE_SUCCESS) {
                uploadFile(msg, size + "", name, ext);
            } else {
                $.toast(msg);
                hideLoading();
            }
        });

    }

    private void uploadFile(String path, String size, String name, String ext) {
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        HashMap<String, String> map = new HashMap<>();
        map.put("filePath", path);
        map.put("size", size);
        map.put("directoryName", name);
        map.put("type", "文件");
        map.put("extension", ext);
        map.put("pid", pid);
        map.put("teamId", id);
        RequestBody body = RequestBody.create(GsonUtils.toJson(map), JSON);

        App.api.addFileOrDir(body)
                .enqueue(new JCallback<Results>() {
                    @Override
                    public void onS(Response<Results> response, Results results) {
                        $.toast("添加成功");
                        getData();
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                        hideLoading();
                    }
                });
    }

    private void addDir(String text) {
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        HashMap<String, String> map = new HashMap<>();
        map.put("directoryName", text);
        map.put("type", "目录");
        map.put("pid", pid);
        map.put("teamId", id);
        RequestBody body = RequestBody.create(GsonUtils.toJson(map), JSON);
        App.api.addFileOrDir(body)
                .enqueue(new JDCallback<Results>() {
                    @Override
                    public void onS(Response<Results> response, Results results) {
                        $.toast("添加成功");
                        getData();
                    }
                });
    }
}
