package com.casic.dcms.view.upload;

import android.app.Activity;
import android.content.Context;
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.core.content.ContextCompat;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.casic.dcms.R;
import com.casic.dcms.databinding.ActivityBriefCaseBinding;
import com.casic.dcms.model.ActionResultBean;
import com.casic.dcms.model.CaseLargeTypeBean;
import com.casic.dcms.model.CaseSmallTypeBean;
import com.casic.dcms.utils.DialogHelper;
import com.casic.dcms.utils.PictureSelectorHelper;
import com.casic.dcms.utils.StringHelper;
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.CaseViewModel;
import com.casic.dcms.vm.CommonDataViewModel;
import com.casic.dcms.vm.UploadViewModel;
import com.gyf.immersionbar.ImmersionBar;
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.hub.ContextHub;
import com.pengxh.androidx.lite.hub.IntHub;
import com.pengxh.androidx.lite.hub.StringHub;
import com.pengxh.androidx.lite.utils.ImmerseStatusBarManager;
import com.pengxh.androidx.lite.vm.LoadState;
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet;

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

public class BriefCaseActivity extends AndroidxBaseActivity<ActivityBriefCaseBinding> {

    private final Context context = BriefCaseActivity.this;
    private final ArrayList<String> realPaths = new ArrayList<>();//真是图片路径
    private final List<String> imageList = new ArrayList<>();//上传到服务器的数据集
    private CaseViewModel caseViewModel;
    private CommonDataViewModel commonDataViewModel;
    private UploadViewModel uploadViewModel;
    private List<CaseLargeTypeBean.DataBean> largeTypeBeans;
    private List<CaseSmallTypeBean.DataBean> smallTypeBeans;
    private EditableImageAdapter imageAdapter;
    private String eorc = "";
    private String typeCode = "";
    private String typeDetailCode = "";//默认值，防止用户不选择直接跳过
    private String gridId;

    private final ActivityResultLauncher<Intent> quickCaseLauncher = 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;
                }
                double longitude = data.getDoubleExtra("longitude", 0);
                double latitude = data.getDoubleExtra("latitude", 0);
                gridId = data.getStringExtra("gridId");
                String community = data.getStringExtra("community");

                viewBinding.longitudeView.setText(String.valueOf(longitude));
                viewBinding.latitudeView.setText(String.valueOf(latitude));
                viewBinding.communityNameView.setText(community);
            }
        }
    });

    @Override
    protected void setupTopBarLayout() {
        ImmerseStatusBarManager.setColor(this, IntHub.convertColor(this, R.color.white));
        ImmersionBar.with(this).statusBarDarkFont(true).init();

        viewBinding.titleBarLayout.titleView.setText("快速上报");
        viewBinding.titleBarLayout.leftBackView.setOnClickListener(v -> finish());
    }

    @Override
    protected void observeRequestState() {
        caseViewModel.loadState.observe(this, new Observer<LoadState>() {
            @Override
            public void onChanged(LoadState loadState) {
                if (loadState == LoadState.Loading) {
                    DialogHelper.showLoadingDialog(context, "案卷提交中，请稍后...");
                } else if (loadState == LoadState.Success) {
                    DialogHelper.dismissLoadingDialog();
                    finish();
                } else {
                    StringHub.show(context, "提交失败，请重试");
                    DialogHelper.dismissLoadingDialog();
                }
            }
        });

        uploadViewModel.loadState.observe(this, new Observer<LoadState>() {
            @Override
            public void onChanged(LoadState loadState) {
                if (loadState == LoadState.Loading) {
                    DialogHelper.showLoadingDialog(context, "上传中，请稍后...");
                } else {
                    DialogHelper.dismissLoadingDialog();
                }
            }
        });
    }

    @Override
    public void initData() {
        largeTypeBeans = new ArrayList<>();
        smallTypeBeans = new ArrayList<>();

        caseViewModel = new ViewModelProvider(this).get(CaseViewModel.class);

        commonDataViewModel = new ViewModelProvider(this).get(CommonDataViewModel.class);
        commonDataViewModel.largeTypeModel.observe(this, new Observer<CaseLargeTypeBean>() {
            @Override
            public void onChanged(CaseLargeTypeBean typeBean) {
                if (typeBean.getCode() == 200) {
                    //设置大类数据
                    largeTypeBeans = typeBean.getData();
                }
            }
        });
        commonDataViewModel.smallTypeModel.observe(this, new Observer<CaseSmallTypeBean>() {
            @Override
            public void onChanged(CaseSmallTypeBean typeBean) {
                if (typeBean.getCode() == 200) {
                    //设置小类数据
                    smallTypeBeans = typeBean.getData();
                }
            }
        });

        uploadViewModel = new ViewModelProvider(this).get(UploadViewModel.class);
        uploadViewModel.imageModel.observe(this, new Observer<ActionResultBean>() {
            @Override
            public void onChanged(ActionResultBean resultBean) {
                if (resultBean.getCode() == 200) {
                    if (imageAdapter.getItemCount() <= 4) {
                        String url = resultBean.getData();
                        imageList.add(url);
                        realPaths.add(StringHelper.appendCompleteURL(url));
                        imageAdapter.setupImage(realPaths);
                    } else {
                        StringHub.show(context, "最多只能上传3张图片");
                    }
                }
            }
        });

        imageAdapter = new EditableImageAdapter(this, 3, 13);
        viewBinding.addImageRecyclerView.setAdapter(imageAdapter);
    }

    @Override
    public void initEvent() {
        /**
         * 选择案卷类型
         * */
        viewBinding.caseClassLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new QMUIBottomSheet.BottomListSheetBuilder(context)
                        .setTitle("案卷类型")
                        .addItem("事件")
                        .addItem("部件")
                        .setGravityCenter(true)
                        .setOnSheetItemClickListener(new QMUIBottomSheet.BottomListSheetBuilder.OnSheetItemClickListener() {
                            @Override
                            public void onClick(QMUIBottomSheet dialog, View itemView, int position, String tag) {
                                dialog.dismiss();
                                viewBinding.caseClassView.setText(tag);
                                viewBinding.caseClassView.setTextColor(ContextCompat.getColor(context, R.color.mainTextColor));

                                //获取案卷大类
                                commonDataViewModel.obtainLargeType(String.valueOf(position + 1));
                            }
                        }).build().show();
            }
        });

        /**
         * 选择案卷大类
         * */
        viewBinding.caseLargeClassLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (largeTypeBeans.size() > 1) {
                    QMUIBottomSheet.BottomListSheetBuilder sheetBuilder = new QMUIBottomSheet.BottomListSheetBuilder(context);
                    sheetBuilder.setTitle("案卷大类");
                    for (CaseLargeTypeBean.DataBean dataBean : largeTypeBeans) {
                        sheetBuilder.addItem(dataBean.getTypeName());
                    }
                    sheetBuilder.setGravityCenter(true).setOnSheetItemClickListener(new QMUIBottomSheet.BottomListSheetBuilder.OnSheetItemClickListener() {
                        @Override
                        public void onClick(QMUIBottomSheet dialog, View itemView, int position, String tag) {
                            dialog.dismiss();
                            viewBinding.caseLargeClassView.setText(tag);
                            viewBinding.caseLargeClassView.setTextColor(ContextCompat.getColor(context, R.color.mainTextColor));

                            //获取案卷小类
                            CaseLargeTypeBean.DataBean dataBean = largeTypeBeans.get(position);
                            eorc = dataBean.getEorc();
                            typeCode = dataBean.getTypeCode();
                            String typeId = dataBean.getId();

                            commonDataViewModel.obtainSmallType(eorc, typeId);
                        }
                    }).build().show();
                }
            }
        });

        /**
         * 选择案卷小类
         * */
        viewBinding.caseSmallClassLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (smallTypeBeans.size() > 1) {
                    QMUIBottomSheet.BottomListSheetBuilder sheetBuilder = new QMUIBottomSheet.BottomListSheetBuilder(context);
                    sheetBuilder.setTitle("案卷小类");
                    for (CaseSmallTypeBean.DataBean dataBean : smallTypeBeans) {
                        sheetBuilder.addItem(dataBean.getTypeDetailName());
                    }
                    sheetBuilder.setGravityCenter(true).setOnSheetItemClickListener(new QMUIBottomSheet.BottomListSheetBuilder.OnSheetItemClickListener() {
                        @Override
                        public void onClick(QMUIBottomSheet dialog, View itemView, int position, String tag) {
                            dialog.dismiss();
                            viewBinding.caseSmallClassView.setText(tag);
                            viewBinding.caseSmallClassView.setTextColor(ContextCompat.getColor(context, R.color.mainTextColor));

                            typeDetailCode = smallTypeBeans.get(position).getTypeDetailCode();
                        }
                    }).build().show();
                }
            }
        });

        /**
         * 选择经纬度
         * */
        viewBinding.locationMapView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //根据情况加载不同图层
                String type = viewBinding.caseClassView.getText().toString();
                if (type.equals("")) {
                    StringHub.show(context, "请先选择案卷类型");
                    return;
                }
                Intent intent = new Intent(context, ArcGISMapActivity.class);
                intent.putExtra("type", type);
                quickCaseLauncher.launch(intent);
            }
        });

        /**
         * 图片九宫格事件处理
         * */
        imageAdapter.setOnItemClickListener(new EditableImageAdapter.OnItemClickListener() {
            @Override
            public void onAddImageClick() {
                PictureSelectorHelper.selectPicture(context, new ISelectorListener() {
                    @Override
                    public void onSuccess(ArrayList<LocalMedia> result) {
                        if (result.size() == 1) {
                            uploadViewModel.uploadImage(new File(result.get(0).getRealPath()));
                        } else {
                            for (LocalMedia localMedia : result) {
                                uploadViewModel.uploadImage(new File(localMedia.getRealPath()));
                            }
                        }
                    }
                });
            }

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

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

        viewBinding.submitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                submitCase();
            }
        });
    }

    /**
     * 案卷提交
     */
    private void submitCase() {
        String longitude = viewBinding.longitudeView.getText().toString();
        String latitude = viewBinding.latitudeView.getText().toString();
        if (longitude.equals("0") || latitude.equals("0") || TextUtils.isEmpty(longitude) || TextUtils.isEmpty(latitude)) {
            StringHub.show(this, "经纬度异常，请重新选择位置");
            return;
        }
        if (eorc.equals("") || typeCode.equals("")) {
            StringHub.show(this, "案卷大类还未选择");
            return;
        }
        if (typeDetailCode.equals("")) {
            StringHub.show(this, "案卷小类还未选择");
            return;
        }
        if (TextUtils.isEmpty(gridId)) {
            StringHub.show(this, "网格ID异常，请重新地图选点");
            return;
        }
        String fieldIntro = viewBinding.caseLocationView.getText().toString().trim().replace(" ", "");
        if (TextUtils.isEmpty(fieldIntro)) {
            StringHub.show(this, "案卷地点还未填写");
            return;
        }
        String description = viewBinding.caseDetailEditView.getText().toString().trim().replace(" ", "");
        if (TextUtils.isEmpty(description)) {
            StringHub.show(this, "案卷情况还未填写");
            return;
        }
        caseViewModel.submitCase("0", "0", longitude, latitude,
                "1", "1", eorc, typeCode, typeDetailCode,
                gridId.substring(0, 6),
                gridId.substring(0, 9),
                gridId.substring(0, 12),
                gridId, description, fieldIntro,
                StringHelper.reformatURL(imageList), "", "", 0, 0);
    }
}