package com.casic.dcms.view.sanbao;

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

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.casic.dcms.R;
import com.casic.dcms.databinding.ActivityChangeShopBinding;
import com.casic.dcms.model.ActionResultBean;
import com.casic.dcms.utils.PictureSelectorHelper;
import com.casic.dcms.utils.StringHelper;
import com.casic.dcms.utils.ViewGroupKit;
import com.casic.dcms.utils.callback.ISelectorListener;
import com.casic.dcms.view.BigImageActivity;
import com.casic.dcms.view.map.ArcGISMapActivity;
import com.casic.dcms.vm.ShopViewModel;
import com.casic.dcms.vm.UploadViewModel;
import com.luck.picture.lib.entity.LocalMedia;
import com.pengxh.androidx.lite.adapter.EditableImageAdapter;
import com.pengxh.androidx.lite.base.AndroidxBaseActivity;
import com.pengxh.androidx.lite.kit.ContextKit;
import com.pengxh.androidx.lite.kit.IntKit;
import com.pengxh.androidx.lite.kit.StringKit;
import com.pengxh.androidx.lite.utils.LoadState;
import com.pengxh.androidx.lite.widget.TitleBarView;

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

public class ChangeShopInfoActivity extends AndroidxBaseActivity<ActivityChangeShopBinding> {

    private final Context context = this;
    private final ArrayList<String> realPaths = new ArrayList<>(); //真实图片路径
    private final List<String> imageList = new ArrayList<>(); //上传到服务器的数据集
    private final Queue<LocalMedia> uploadQueue = new LinkedList<>(); // 用于存储待上传的图片
    private boolean isUploading = false; // 标记是否正在上传图片
    private UploadViewModel uploadViewModel;
    private ShopViewModel shopViewModel;
    private String merchantId;  //商户id
    private String merchantName;
    private EditableImageAdapter imageAdapter;

    //新版onActivityResult
    private final ActivityResultLauncher<Intent> changeShopInfoLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
        @Override
        public void onActivityResult(ActivityResult result) {
            if (result.getResultCode() == Activity.RESULT_OK) {
                Intent data = result.getData();
                if (data == null) {
                    return;
                }
                String community = data.getStringExtra("community");
                merchantName = data.getStringExtra("shopName");
                merchantId = data.getStringExtra("shopID");
                binding.communityNameView.setText(community);
                binding.shopView.setText(merchantName);
                binding.shopView.setTextColor(ContextCompat.getColor(context, R.color.mainTextColor));
            }
        }
    });

    @Override
    protected void setupTopBarLayout() {
        ViewGroupKit.initImmersionBar(binding.rootView, this, true, R.color.white);
        binding.titleView.setOnClickListener(new TitleBarView.OnClickListener() {
            @Override
            public void onLeftClick() {
                finish();
            }

            @Override
            public void onRightClick() {

            }
        });
    }

    @Override
    protected void observeRequestState() {
        uploadViewModel.loadState.observe(this, new Observer<LoadState>() {
            @Override
            public void onChanged(LoadState loadState) {
                if (loadState == LoadState.Loading) {
                    StringKit.show(ChangeShopInfoActivity.this, "上传中，请稍后...");
                }
            }
        });

        shopViewModel.changeResultModel.observe(this, new Observer<ActionResultBean>() {
            @Override
            public void onChanged(ActionResultBean resultBean) {
                if (resultBean.getCode() == 200) {
                    StringKit.show(context, "提交成功");
                    finish();
                } else {
                    StringKit.show(context, "提交失败，请重试");
                }
            }
        });
    }

    @Override
    protected void initOnCreate(@Nullable Bundle savedInstanceState) {
        uploadViewModel = new ViewModelProvider(this).get(UploadViewModel.class);
        shopViewModel = new ViewModelProvider(this).get(ShopViewModel.class);

        int width = ContextKit.getScreenWidth(this) - IntKit.dp2px(this, 20);
        imageAdapter = new EditableImageAdapter(this, realPaths, width, 2, 3);
        binding.addImageRecyclerView.setAdapter(imageAdapter);
    }

    @Override
    protected void initEvent() {
        binding.shopLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(context, ArcGISMapActivity.class);
                intent.putExtra("type", "商铺变更");
                changeShopInfoLauncher.launch(intent);
            }
        });

        imageAdapter.setOnItemClickListener(new EditableImageAdapter.OnItemClickListener() {
            @Override
            public void onAddImageClick() {
                PictureSelectorHelper.selectPicture(context, 2, new ISelectorListener() {
                    @Override
                    public void onSuccess(ArrayList<LocalMedia> result) {
                        uploadQueue.addAll(result); // 将选中的图片加入队列
                        startUploadNextImage();
                    }
                });
            }

            @Override
            public void onItemClick(int position) {
                if (realPaths.get(position).isEmpty()) {
                    StringKit.show(context, "图片加载失败，无法查看大图");
                } else {
                    ContextKit.navigatePageTo(context, BigImageActivity.class, position, realPaths);
                }
            }

            @Override
            public void onItemLongClick(@Nullable View view, int position) {
                imageList.remove(position);
                realPaths.remove(position);
                imageAdapter.notifyItemRemoved(position);
                imageAdapter.notifyItemRangeChanged(position, realPaths.size() - position);
            }
        });

        uploadViewModel.imageModel.observe(this, new Observer<ActionResultBean>() {
            @Override
            public void onChanged(ActionResultBean resultBean) {
                isUploading = false;
                if (resultBean.getCode() == 200) {
                    String url = resultBean.getData();
                    imageList.add(url);
                    int oldSize = realPaths.size();
                    realPaths.add(StringHelper.appendCompleteURL(url));
                    imageAdapter.notifyItemRangeChanged(oldSize, 1);
                    startUploadNextImage(); // 上传下一张图片
                } else {
                    StringKit.show(context, "图片上传失败，请重试");
                }
            }
        });

        binding.submitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String phoneNumber = binding.phoneNumberView.getText().toString().trim().replace(" ", "");
                if (TextUtils.isEmpty(phoneNumber)) {
                    StringKit.show(context, "电话号码还未填写");
                    return;
                }
                if (!StringHelper.isPhoneNumber(phoneNumber)) {
                    StringKit.show(context, "电话号码格式不对");
                    return;
                }
                String shopLocation = binding.shopLocationView.getText().toString().trim().replace(" ", "");
                if (TextUtils.isEmpty(shopLocation)) {
                    StringKit.show(context, "店铺地址还未填写");
                    return;
                }
                String shopKeeper = binding.shopKeeperView.getText().toString().trim().replace(" ", "");
                if (TextUtils.isEmpty(shopKeeper)) {
                    StringKit.show(context, "店主名还未填写");
                    return;
                }
                if (imageAdapter.getItemCount() < 1) {
                    StringKit.show(context, "至少上传一张照片");
                    return;
                }
                shopViewModel.changeShopInfo(context, merchantId, merchantName, shopKeeper, phoneNumber, StringHelper.reformatURL(imageList));
            }
        });
    }

    private void startUploadNextImage() {
        if (isUploading || uploadQueue.isEmpty()) {
            return;
        }

        isUploading = true;
        LocalMedia media = uploadQueue.poll();
        if (media != null) {
            uploadViewModel.uploadImage(this, new File(media.getRealPath()));
        } else {
            isUploading = false;
        }
    }
}