package com.casic.dcms.ui;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
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.recyclerview.widget.GridLayoutManager;

import com.casic.dcms.R;
import com.casic.dcms.adapter.NineGridImageAdapter;
import com.casic.dcms.base.AndroidxBaseActivity;
import com.casic.dcms.bean.ActionResultBean;
import com.casic.dcms.databinding.ActivityChangeShopBinding;
import com.casic.dcms.mvp.presenter.impl.ShopChangePresenterImpl;
import com.casic.dcms.mvp.presenter.impl.UploadImagePresenterImpl;
import com.casic.dcms.mvp.view.IShopInfoChangeView;
import com.casic.dcms.mvp.view.IUploadFileView;
import com.casic.dcms.utils.Constant;
import com.casic.dcms.utils.OtherUtils;
import com.casic.dcms.utils.StringHelper;
import com.casic.dcms.utils.ToastHelper;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog.MenuDialogBuilder;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;

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

public class ChangeShopInfoActivity extends AndroidxBaseActivity<ActivityChangeShopBinding> implements IUploadFileView, IShopInfoChangeView {

    private final Context context = ChangeShopInfoActivity.this;
    private final ArrayList<String> realPaths = new ArrayList<>(); //真实图片路径
    private final List<String> imageList = new ArrayList<>(); //上传到服务器的数据集
    private UploadImagePresenterImpl uploadImagePresenter;
    private ShopChangePresenterImpl shopChangePresenter;
    private String merchantId;  //商户id
    private String merchantName;
    private NineGridImageAdapter imageAdapter;
    private QMUITipDialog submitDialog;

    //新版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");
                viewBinding.communityNameView.setText(community);
                viewBinding.shopView.setText(merchantName);
                viewBinding.shopView.setTextColor(ContextCompat.getColor(context, R.color.textColor));
            }
        }
    });

    @Override
    protected void setupTopBarLayout() {
        viewBinding.titleBarLayout.titleView.setText("商铺变更");
        viewBinding.titleBarLayout.leftBackView.setOnClickListener(v -> finish());
    }

    @Override
    protected void initData() {
        uploadImagePresenter = new UploadImagePresenterImpl(this);
        shopChangePresenter = new ShopChangePresenterImpl(this);
        submitDialog = new QMUITipDialog.Builder(this)
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                .setTipWord("处理中，请稍后")
                .create();

        viewBinding.nineGridImageView.setLayoutManager(new GridLayoutManager(this, 2));
        imageAdapter = new NineGridImageAdapter(this);
        viewBinding.nineGridImageView.setAdapter(imageAdapter);
    }

    @Override
    protected void initEvent() {
        viewBinding.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 NineGridImageAdapter.OnItemClickListener() {
            @Override
            public void onAddImageClick() {
                new MenuDialogBuilder(context).addItem("相册中选取", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int i) {
                        dialog.dismiss();
                        OtherUtils.selectPicture(ChangeShopInfoActivity.this);
                    }
                }).addItem("相机拍照", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int i) {
                        dialog.dismiss();
                        OtherUtils.takePicture(ChangeShopInfoActivity.this);
                    }
                }).setCanceledOnTouchOutside(false).create().show();
            }

            @Override
            public void onItemClick(int position) {
                OtherUtils.showBigImage(context, position, realPaths);
            }

            @Override
            public void onItemLongClick(@Nullable View view, int position) {
                imageList.remove(position);
                imageAdapter.deleteImage(position);
            }
        });

        viewBinding.submitButton.setChangeAlphaWhenPress(true);
        viewBinding.submitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String phoneNumber = viewBinding.phoneNumberView.getText().toString().trim().replace(" ", "");
                if (TextUtils.isEmpty(phoneNumber)) {
                    ToastHelper.showToast("电话号码还未填写", ToastHelper.WARING);
                    return;
                }
                if (StringHelper.isPhoneNumber(phoneNumber)) {
                    String shopLocation = viewBinding.shopLocationView.getText().toString().trim().replace(" ", "");
                    if (TextUtils.isEmpty(shopLocation)) {
                        ToastHelper.showToast("店铺地址还未填写", ToastHelper.WARING);
                        return;
                    }
                    String shopKeeper = viewBinding.shopKeeperView.getText().toString().trim().replace(" ", "");
                    if (TextUtils.isEmpty(shopKeeper)) {
                        ToastHelper.showToast("店主名还未填写", ToastHelper.WARING);
                        return;
                    }
                    if (imageAdapter.getItemCount() != 2) {
                        ToastHelper.showToast("必须选择两张图片", ToastHelper.WARING);
                        return;
                    }
                    shopChangePresenter.onReadyRetrofitRequest(merchantId, merchantName,
                            shopKeeper, phoneNumber, StringHelper.reformatURL(imageList)
                    );
                } else {
                    ToastHelper.showToast("电话号码格式不对", ToastHelper.WARING);
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    for (LocalMedia media : selectList) {
                        File file = new File(media.getCompressPath());
                        if (file.length() <= Constant.IMAGE_MINUS_SIZE) {
                            ToastHelper.showToast("图片尺寸太小，请重新选择", ToastHelper.ERROR);
                            continue;
                        }
                        uploadImagePresenter.onReadyRetrofitRequest(file);
                    }
                    break;
                case PictureConfig.REQUEST_CAMERA:
                    LocalMedia localMedia = PictureSelector.obtainMultipleResult(data).get(0);
                    uploadImagePresenter.onReadyRetrofitRequest(new File(localMedia.getCompressPath()));
                    break;
            }
        }
    }

    @Override
    public void showProgress() {
        submitDialog.show();
    }

    @Override
    public void hideProgress() {
        submitDialog.dismiss();
    }

    @Override
    public void obtainChangeResult(ActionResultBean resultBean) {
        if (resultBean.getCode() == 200) {
            ToastHelper.showToast("提交成功", ToastHelper.SUCCESS);
            finish();
        } else {
            ToastHelper.showToast("提交失败，请重试", ToastHelper.ERROR);
        }
    }

    @Override
    public void obtainUploadAudioResult(ActionResultBean resultBean) {

    }

    @Override
    public void obtainUploadImageResult(ActionResultBean resultBean) {
        if (resultBean.getCode() == 200) {
            PictureFileUtils.deleteAllCacheDirFile(this);
            /**
             * 系统路径static拼接图片返回路径
             * http://111.198.10.15:11409/static/2021-04/000bcf78345f4c1c86484efa3f9d68a2.jpeg
             */
            //2021-04\\000bcf78345f4c1c86484efa3f9d68a2.jpeg
            if (imageAdapter.getItemCount() <= 2) {
                String url = resultBean.getData();
                imageList.add(url);
                realPaths.add(StringHelper.appendCompleteURL(url));
                imageAdapter.setupImage(realPaths);
            } else {
                ToastHelper.showToast("最多只能上传2张图片", ToastHelper.WARING);
            }
        }
    }

    @Override
    public void obtainUploadVideoResult(ActionResultBean resultBean) {

    }

    @Override
    public void obtainDataFail() {
        ToastHelper.showToast("操作失败", ToastHelper.ERROR);
    }

    @Override
    protected void onDestroy() {
        uploadImagePresenter.disposeRetrofitRequest();
        shopChangePresenter.disposeRetrofitRequest();
        super.onDestroy();
    }
}