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 android.view.View;

import androidx.annotation.NonNull;
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.KeyboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.UriUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.wisewoods.base.base.BaseActivity;
import com.wisewoods.base.bean.BaseEvent;
import com.wisewoods.base.bean.Results;
import com.wisewoods.base.bean.TeacherCourseList;
import com.wisewoods.base.net.JDCallback;
import com.wisewoods.base.utils.$;
import com.wisewoods.base.utils.ImgUtils;
import com.wisewoods.eduandroid.R;
import com.wisewoods.eduandroid.app.App;
import com.wisewoods.eduandroid.app.ImgManager;
import com.wisewoods.eduandroid.databinding.ActivityAddCourseBinding;
import com.wisewoods.eduandroid.oss.ICloundOS;
import com.wisewoods.eduandroid.oss.OSSManager;
import com.wisewoods.eduandroid.ui.adapter.FileAdapter;

import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.NotNull;

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

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

public class AddCourseActivity extends BaseActivity<ActivityAddCourseBinding> implements OnItemChildClickListener {

    private String title;
    private TeacherCourseList.DataBean item;
    private FileAdapter mAdapter;
    private String cover;

    public static void start(String title, TeacherCourseList.DataBean item) {
        Intent intent = new Intent(ActivityUtils.getTopActivity(), AddCourseActivity.class);
        intent.putExtra("title", title);
        intent.putExtra("item", item);
        ActivityUtils.startActivity(intent);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        title = getIntent().getStringExtra("title");
        item = (TeacherCourseList.DataBean) getIntent().getSerializableExtra("item");
        showBarBack(binding.bar.tvTitle, title, binding.bar.ivBack);
        binding.ivAdd.setOnClickListener(v -> selectCover());
        binding.tvAdd.setOnClickListener(v -> {
            if (isFastClick()){
                addCourse();
            }
        });
        binding.tvUploadFile.setOnClickListener(v -> {
            KeyboardUtils.hideSoftInput(this);
            ImgManager.selectFile(this);
        });
        binding.rvFile.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new FileAdapter();
        mAdapter.setOnItemChildClickListener(this);
        binding.rvFile.setAdapter(mAdapter);
        setData();
    }

    private void setData() {
        if (item != null) {
            mAdapter.setNewInstance(item.enclosureUrlList);
            binding.etName.setText(item.courseName);
            binding.etContent.setText(item.courseSynopsis);
            cover = item.courseThumbnailUrl;
            ImgUtils.load(activity, item.courseThumbnailUrl, R.drawable.ic_add_photo, binding.ivAdd);
        }
    }

    private void selectCover() {
        KeyboardUtils.hideSoftInput(this);
        showLoading();
        OSSManager.getInstance().selectImage(this, OSSManager.OSSPATH, (code, msg, localMedia) -> {
            if (code == ICloundOS.CODE_SUCCESS) {
                ImgUtils.load(activity, msg, binding.ivAdd);
                cover = msg;
            } else {
                $.toast(msg);
            }
            hideLoading();
        });
    }

    private void addCourse() {
        String name = binding.etName.getText().toString().trim();
        if (TextUtils.isEmpty(name)) {
            $.toast("请输入课程名称");
            return;
        }
        String content = binding.etContent.getText().toString().trim();
        if (TextUtils.isEmpty(content)) {
            $.toast("请输入课程描述");
            return;
        }

        if (TextUtils.isEmpty(cover)) {
            $.toast("请上传课程封面");
            return;
        }

        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        HashMap<String, String> map = new HashMap<>();
        if (item != null) {
            map.put("auditId", item.auditId);
            map.put("id", item.id + "");
            map.put("auditStatus", item.auditStatus + "");
        }
        map.put("courseName", name);
        map.put("courseSynopsis", content);
        map.put("courseThumbnailUrl", cover);
        map.put("enclosureUrl", GsonUtils.toJson(mAdapter.getData()));

        RequestBody body = RequestBody.create(GsonUtils.toJson(map), JSON);
        LogUtils.e("数据", GsonUtils.toJson(map));
        App.api.addCourse(body)
                .enqueue(new JDCallback<Results>() {
                    @Override
                    public void onS(Response<Results> response, Results results) {
                        EventBus.getDefault().post(new BaseEvent.TeacherCourseRefreshEvent());
                        if (item != null) {
                            $.toast("修改成功");
                        } else {
                            $.toast("添加成功");
                        }
                        finish();
                    }
                });
    }

    @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) {
        File file = UriUtils.uri2File(uri);
        String name = FileUtils.getFileName(file);
        showLoading();
        OSSManager.getInstance().upload(OSSManager.OSSPATH +name, file.getPath(), (code, msg) -> {
            if (code == ICloundOS.CODE_SUCCESS) {
                TeacherCourseList.Enclosure enclosure = new TeacherCourseList.Enclosure();
                enclosure.name = name;
                enclosure.url = msg;
                mAdapter.addData(enclosure);
            } else {
                $.toast(msg);
            }
            hideLoading();
        });
    }

    @Override
    public void onItemChildClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {
        if (view.getId() == R.id.tv_delete) {
            mAdapter.removeAt(position);
        }
    }
}
