package com.wisewoods.eduandroid.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.recyclerview.widget.GridLayoutManager;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.RegexUtils;
import com.google.gson.reflect.TypeToken;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.decoration.GridSpacingItemDecoration;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.ScreenUtils;
import com.wisewoods.base.bean.BaseEvent;
import com.wisewoods.base.bean.BaseInfo;
import com.wisewoods.base.bean.Results;
import com.wisewoods.base.bean.UploadImgBean;
import com.wisewoods.base.net.JDCallback;
import com.wisewoods.base.utils.$;
import com.wisewoods.eduandroid.R;
import com.wisewoods.eduandroid.app.App;
import com.wisewoods.eduandroid.app.BasePhotoActivity;
import com.wisewoods.eduandroid.app.ImgManager;
import com.wisewoods.eduandroid.area.AreaView;
import com.wisewoods.eduandroid.databinding.ActivityChangeBuildingBinding;
import com.wisewoods.eduandroid.oss.ICloundOS;
import com.wisewoods.eduandroid.oss.OSSManager;
import com.wisewoods.eduandroid.ui.adapter.photo.FullyGridLayoutManager;
import com.wisewoods.eduandroid.ui.adapter.photo.GridImageAdapter;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

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

public class ChangeBuildingActivity extends BasePhotoActivity<ActivityChangeBuildingBinding> {

    private GridImageAdapter mAdapter;
    private GridImageAdapter mAdapter2;
    private BaseInfo.DataBean data;
    private List<LocalMedia> imgs;
    private List<LocalMedia> videos;
    private List<String> ids;
    private AreaView dialog;

    public static void start(BaseInfo.DataBean data) {
        Intent intent = new Intent(ActivityUtils.getTopActivity(), ChangeBuildingActivity.class);
        intent.putExtra("data", data);
        ActivityUtils.startActivity(intent);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        showBarBack(binding.bar.tvTitle, "编辑基地", binding.bar.ivBack);
        data = (BaseInfo.DataBean) getIntent().getSerializableExtra("data");
        binding.tvChangeInfo.setOnClickListener(v -> {
            changeInfo();
        });

        dialog = new AreaView(activity);
        dialog.setListener((code, area) -> {
            binding.tvArea.setText(area);
            if (code != null) {
                this.ids = Arrays.asList(code.split(",").clone());
            }
        });
        binding.tvArea.setOnClickListener(v -> {
            if (dialog != null && !dialog.isShowing()) {
                dialog.show();
            }
        });
//        binding.lv.setLocationSelectListener((location, ids) -> {
//            this.ids = ids;
//        });

        FullyGridLayoutManager manager = new FullyGridLayoutManager(this,
                3, GridLayoutManager.VERTICAL, false);
        manager.setAutoMeasureEnabled(true);
        FullyGridLayoutManager manager2 = new FullyGridLayoutManager(this,
                3, GridLayoutManager.VERTICAL, false);
        manager2.setAutoMeasureEnabled(true);
        binding.rvPhoto.setLayoutManager(manager);
        binding.rvVideo.setLayoutManager(manager2);

        binding.rvPhoto.addItemDecoration(new GridSpacingItemDecoration(3,
                ScreenUtils.dip2px(this, 8), false));
        binding.rvVideo.addItemDecoration(new GridSpacingItemDecoration(3,
                ScreenUtils.dip2px(this, 8), false));

        mAdapter = new GridImageAdapter(this, R.drawable.ic_photo_add, () -> {
            KeyboardUtils.hideSoftInput(this);
            showLoading();
            OSSManager.getInstance().selectImage(this, OSSManager.OSSPATH, (code, msg, localMedia) -> {
                if (code == ICloundOS.CODE_SUCCESS) {
                    mAdapter.getData().add(localMedia);
                    mAdapter.notifyDataSetChanged();
                }
                hideLoading();
            });
        });
        mAdapter2 = new GridImageAdapter(this, R.drawable.ic_video_add, () -> {
            KeyboardUtils.hideSoftInput(this);
            showLoading();
            OSSManager.getInstance().selectVideo(this, OSSManager.OSSPATH, (code, msg, localMedia) -> {
                if (code == ICloundOS.CODE_SUCCESS) {
                    mAdapter2.getData().add(localMedia);
                    mAdapter2.notifyDataSetChanged();
                }
                hideLoading();
            });
        });
        mAdapter.setOnItemClickListener(listener);
        mAdapter2.setOnItemClickListener(listener);
        binding.rvPhoto.setAdapter(mAdapter);
        binding.rvVideo.setAdapter(mAdapter2);


        binding.etName.setText(data.baseName);
        binding.etAddress.setText(data.baseLocation);
        binding.etPeople.setText(data.linkmanName);
        binding.etTel.setText(data.linkmanTel + "");
        binding.etDes.setText(data.baseDesc);
        this.ids = GsonUtils.fromJson(data.baseRegion, new TypeToken<List<String>>() {
        }.getType());

        imgs = new ArrayList<>();
        if (data.basePicture != null) {
            for (String url : data.basePicture) {
                LocalMedia localMedia = new LocalMedia();
                localMedia.setCompressed(true);
                localMedia.setCompressPath(url);
                imgs.add(localMedia);
            }
        }
        mAdapter.setList(imgs);
        mAdapter.notifyDataSetChanged();

        videos = new ArrayList<>();
        if (data.baseVideo != null) {
            for (UploadImgBean uploadImgBean : data.baseVideo) {
                LocalMedia localMedia = new LocalMedia();
                localMedia.setCompressed(true);
                localMedia.setCompressPath(uploadImgBean.url);
                localMedia.setFileName(uploadImgBean.name);
                localMedia.setMimeType(PictureMimeType.MIME_TYPE_VIDEO);
                videos.add(localMedia);
            }
        }
        mAdapter2.setList(videos);
        mAdapter2.notifyDataSetChanged();
//        binding.lv.setData(data.baseRegion, data.baseRegion2);
        dialog.setData(data.getBaseRegion());
    }


    private void changeInfo() {
        String name = binding.etName.getText().toString().trim();
        if (TextUtils.isEmpty(name)) {
            $.toast("基地名称不能为空");
            return;
        }

        if (ids == null || ids.size() == 0) {
            $.toast("基地地点不能为空");
            return;
        }

        String address = binding.etAddress.getText().toString().trim();
        if (TextUtils.isEmpty(address)) {
            $.toast("详细地点不能为空");
            return;
        }

        String people = binding.etPeople.getText().toString().trim();
        if (TextUtils.isEmpty(people)) {
            $.toast("联系人不能为空");
            return;
        }

        String tel = binding.etTel.getText().toString().trim();
        if (TextUtils.isEmpty(tel)) {
            $.toast("联系电话不能为空");
            return;
        }

        if (!RegexUtils.isMobileSimple(tel)) {
            $.toast("请输入正确的联系电话");
            return;
        }

        String des = binding.etDes.getText().toString().trim();
        if (TextUtils.isEmpty(des)) {
            $.toast("基地介绍不能为空");
            return;
        }

        if (mAdapter.getData().size() == 0) {
            $.toast("请上传基地照片");
            return;
        }

        if (mAdapter2.getData().size() == 0) {
            $.toast("请上传基地视频");
            return;
        }

        ArrayList<String> imgDatas = new ArrayList<>();
        ArrayList<UploadImgBean> videoDatas = new ArrayList<>();
        for (LocalMedia localMedia : mAdapter.getData()) {
            imgDatas.add(localMedia.getCompressPath());
        }

        for (LocalMedia localMedia : mAdapter2.getData()) {
            videoDatas.add(new UploadImgBean(localMedia.getFileName(), localMedia.getCompressPath()));
        }

        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        HashMap<String, String> map = new HashMap<>();
        map.put("id", data.Id + "");
        map.put("baseName", name);
        map.put("baseRegion", GsonUtils.toJson(ids));
        map.put("baseLocation", address);
        map.put("linkmanName", people);
        map.put("linkmanTel", tel);
        map.put("baseDesc", des);
        map.put("basePicture", GsonUtils.toJson(imgDatas));
        map.put("baseVideo", GsonUtils.toJson(videoDatas));
        LogUtils.e("参数", GsonUtils.toJson(map));
        RequestBody body = RequestBody.create(GsonUtils.toJson(map), JSON);

        App.api.changeBaseInfo(body)
                .enqueue(new JDCallback<Results>() {
                    @Override
                    public void onS(Response<Results> response, Results results) {
                        $.toast("修改成功");
                        EventBus.getDefault().post(new BaseEvent.BaseInfoEvent());
                        finish();
                    }
                });
    }

}
