package com.casic.dcms.view.verify;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;

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

import com.casic.dcms.R;
import com.casic.dcms.databinding.ActivityVerifyDetailBinding;
import com.casic.dcms.model.ActionResultBean;
import com.casic.dcms.model.CaseDetailBean;
import com.casic.dcms.model.CaseLargeTypeBean;
import com.casic.dcms.model.CaseNextNodeBean;
import com.casic.dcms.model.CaseSmallTypeBean;
import com.casic.dcms.utils.MapHelper;
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.CaseOperateViewModel;
import com.casic.dcms.vm.CaseViewModel;
import com.casic.dcms.vm.CommonDataViewModel;
import com.casic.dcms.vm.NodeViewModel;
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.adapter.ReadOnlyImageAdapter;
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.Constant;
import com.pengxh.androidx.lite.utils.LoadState;
import com.pengxh.androidx.lite.utils.LoadingDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.builder.GSYVideoOptionBuilder;
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack;
import com.shuyu.gsyvideoplayer.listener.LockClickListener;
import com.shuyu.gsyvideoplayer.utils.OrientationUtils;

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

public class VerifyDetailActivity extends AndroidxBaseActivity<ActivityVerifyDetailBinding> {

    private final Context context = VerifyDetailActivity.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 CaseViewModel caseViewModel;
    private CommonDataViewModel commonDataViewModel;
    private UploadViewModel uploadViewModel;
    private NodeViewModel nodeViewModel;
    private CaseOperateViewModel operateViewModel;
    private List<CaseLargeTypeBean.DataBean> largeTypeBeans;
    private List<CaseSmallTypeBean.DataBean> smallTypeBeans;
    private String id;
    private String eorc;
    private String typeCode;
    private String typeDetailCode;
    private String gridId;//可能来自案卷详情，也可能来自地图选点
    private double longitude, latitude;
    private String changeState;
    private CaseDetailBean.DataBean data = new CaseDetailBean.DataBean();
    private EditableImageAdapter imageAdapter;
    private OrientationUtils orientationUtils;
    private boolean isPlay;
    private boolean isPause;

    private final ActivityResultLauncher<Intent> verifyCaseLauncher = 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;
                }
                longitude = data.getDoubleExtra("longitude", 0);
                latitude = data.getDoubleExtra("latitude", 0);
                gridId = data.getStringExtra("gridId");
                String community = data.getStringExtra("community");
                String casePlace = data.getStringExtra("pos");
                binding.caseCommunityView.setText(community);
                if (TextUtils.isEmpty(casePlace)) {
                    binding.casePlaceView.setText(community);
                } else {
                    binding.casePlaceView.setText(casePlace);
                }
            }
        }
    });

    @Override
    protected void setupTopBarLayout() {
        ViewGroupKit.initImmersionBar(binding.rootView, this, true, R.color.white);

        binding.titleBarLayout.titleView.setText("案卷核实");
        binding.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) {
                    LoadingDialog.show(VerifyDetailActivity.this, "获取数据中...");
                } else {
                    LoadingDialog.dismiss();
                }
            }
        });

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

        operateViewModel.loadState.observe(this, new Observer<LoadState>() {
            @Override
            public void onChanged(LoadState loadState) {
                if (loadState == LoadState.Loading) {
                    LoadingDialog.show(VerifyDetailActivity.this, "案卷核实中，请稍后...");
                } else if (loadState == LoadState.Success) {
                    LoadingDialog.dismiss();
                    finish();
                } else {
                    StringKit.show(context, "核实失败，请重试");
                    LoadingDialog.dismiss();
                }
            }
        });
    }

    @Override
    public void initOnCreate(@Nullable Bundle savedInstanceState) {
        orientationUtils = new OrientationUtils(this, binding.videoPlayerView);
        //初始化不打开外部的旋转
        orientationUtils.setEnable(false);

        id = getIntent().getStringExtra(Constant.INTENT_PARAM_KEY);

        largeTypeBeans = new ArrayList<>();
        smallTypeBeans = new ArrayList<>();

        caseViewModel = new ViewModelProvider(this).get(CaseViewModel.class);
        caseViewModel.getCaseDetail(this, id);
        caseViewModel.caseDetailModel.observe(this, new Observer<CaseDetailBean>() {
            @Override
            public void onChanged(CaseDetailBean resultBean) {
                if (resultBean.getCode() == 200) {
                    data = resultBean.getData().get(0);
                    gridId = data.getGridId();
                    String lng = data.getLng();
                    if (!TextUtils.isEmpty(lng)) {
                        longitude = Double.parseDouble(lng);
                    }
                    String lat = data.getLat();
                    if (!TextUtils.isEmpty(lat)) {
                        latitude = Double.parseDouble(lat);
                    }
                    binding.caseNumberView.setText(data.getCaseid());
                    binding.caseTypeView.setText(data.getEorcName());
                    binding.caseLargeTypeView.setText(data.getCasetypeName());
                    binding.caseSmallTypeView.setText(data.getCasetypeDetailName());
                    binding.caseCommunityView.setText(data.getCommunityName().equals("") ? "无更详细社区信息" : data.getCommunityName());
                    binding.casePlaceView.setText(data.getFieldintro());
                    binding.caseHandleView.setText(data.getCaseStateName().equals("") ? "无处理意见" : data.getCaseStateName());
                    binding.caseStartTimeView.setText(data.getCreateTime());
                    binding.caseEndTimeView.setText(data.getNodeLimittime());
                    binding.caseSituationView.setText(data.getDescription());

                    //图片
                    String images = data.getFileIdVerify();
                    if (!TextUtils.isEmpty(images)) {
                        ArrayList<String> urls = new ArrayList<>();
                        String[] split = images.split(",");
                        for (String s : split) {
                            if (s.endsWith(".jpg") || s.contains(".jpeg") || s.contains(".png")) {
                                urls.add(StringHelper.appendCompleteURL(s));
                            }
                        }
                        ReadOnlyImageAdapter imageAdapter = new ReadOnlyImageAdapter(context, urls);
                        binding.imageGridView.setAdapter(imageAdapter);
                        //九宫格点击事件
                        binding.imageGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                if (urls.get(position).isEmpty()) {
                                    StringKit.show(context, "图片加载失败，无法查看大图");
                                } else {
                                    ContextKit.navigatePageTo(context, BigImageActivity.class, position, urls);
                                }
                            }
                        });
                    }

                    //音频
                    String audioFile = data.getAudioIdVerify();
                    if (!TextUtils.isEmpty(audioFile)) {
                        binding.audioPlayerView.setVisibility(View.VISIBLE);
                        String url = StringHelper.appendCompleteURL(audioFile);
                        try {
                            binding.audioPlayerView.setAudioSource(new File(url));
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }

                    //视频
                    String videoFile = data.getVideoIdVerify();
                    if (!TextUtils.isEmpty(videoFile)) {
                        binding.videoPlayerView.setVisibility(View.VISIBLE);
                        String videoUrl = StringHelper.appendCompleteURL(videoFile);
                        GSYVideoOptionBuilder videoOption = new GSYVideoOptionBuilder();
                        videoOption.setIsTouchWiget(true)
                                .setRotateViewAuto(false)
                                .setLockLand(false)
                                .setAutoFullWithSize(true)
                                .setShowFullAnimation(false)
                                .setNeedLockFull(true)
                                .setUrl(videoUrl)
                                .setCacheWithPlay(false)
                                .setVideoTitle(data.getDescription())
                                .setVideoAllCallBack(new GSYSampleCallBack() {
                                    @Override
                                    public void onPrepared(String url, Object... objects) {
                                        super.onPrepared(url, objects);
                                        //开始播放了才能旋转和全屏
                                        orientationUtils.setEnable(true);
                                        isPlay = true;
                                    }

                                    @Override
                                    public void onQuitFullscreen(String url, Object... objects) {
                                        super.onQuitFullscreen(url, objects);
                                        if (orientationUtils != null) {
                                            orientationUtils.backToProtVideo();
                                        }
                                    }
                                }).setLockClickListener(new LockClickListener() {
                                    @Override
                                    public void onClick(View view, boolean lock) {
                                        if (orientationUtils != null) {
                                            //配合下方的onConfigurationChanged
                                            orientationUtils.setEnable(!lock);
                                        }
                                    }
                                }).build(binding.videoPlayerView);
                        binding.videoPlayerView.getFullscreenButton().setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                //直接横屏
                                orientationUtils.resolveByClick();
                                binding.videoPlayerView.startWindowFullscreen(context, true, true);
                            }
                        });
                    }
                }
            }
        });

        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) {
                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, "图片上传失败，请重试");
                }
            }
        });

        nodeViewModel = new ViewModelProvider(this).get(NodeViewModel.class);
        nodeViewModel.nodeModel.observe(this, new Observer<CaseNextNodeBean>() {
            @Override
            public void onChanged(CaseNextNodeBean resultBean) {
                if (resultBean.isSuccess()) {
                    List<CaseNextNodeBean.DataBean> dataBeans = resultBean.getData();
                    QMUIBottomSheet.BottomListSheetBuilder sheetBuilder = new QMUIBottomSheet.BottomListSheetBuilder(context);
                    sheetBuilder.setTitle("核实情况");
                    for (CaseNextNodeBean.DataBean dataBean : dataBeans) {
                        sheetBuilder.addItem(dataBean.getNextOperation());
                    }
                    sheetBuilder.setGravityCenter(true).setOnSheetItemClickListener(new QMUIBottomSheet.BottomListSheetBuilder.OnSheetItemClickListener() {
                        @Override
                        public void onClick(QMUIBottomSheet dialog, View itemView, int position, String tag) {
                            dialog.dismiss();

                            CaseNextNodeBean.DataBean dataBean = dataBeans.get(position);
                            binding.caseConditionView.setText(dataBean.getNextOperation());
                            changeState = String.valueOf(dataBean.getNextState());
                        }
                    }).build().show();
                } else {
                    StringKit.show(context, "该案卷无下级流转节点");
                }
            }
        });

        operateViewModel = new ViewModelProvider(this).get(CaseOperateViewModel.class);

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

    @Override
    public void initEvent() {
        binding.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();
                                binding.caseTypeView.setText(tag);
                                //获取案卷大类
                                commonDataViewModel.getLargeType(context, String.valueOf(position + 1));
                            }
                        }).build().show();
            }
        });

        binding.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();
                            typeCode = largeTypeBeans.get(position).getTypeCode();

                            binding.caseLargeTypeView.setText(tag);

                            //获取案卷小类
                            CaseLargeTypeBean.DataBean dataBean = largeTypeBeans.get(position);
                            eorc = dataBean.getEorc();
                            String typeId = dataBean.getId();
                            commonDataViewModel.getSmallType(context, eorc, typeId);
                        }
                    }).build().show();
                }
            }
        });

        binding.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();
                            typeDetailCode = smallTypeBeans.get(position).getTypeDetailCode();

                            binding.caseSmallTypeView.setText(tag);
                        }
                    }).build().show();
                }
            }
        });

        binding.locationMapView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String type = binding.caseTypeView.getText().toString();
                if (type.equals("请选择")) {
                    StringKit.show(context, "请先选择案卷类型");
                    return;
                }
                int source = data.getSource();
                if (source == 11 || source == 12) {
                    Intent intent = new Intent(context, ArcGISMapActivity.class);
                    intent.putExtra("type", type);
                    verifyCaseLauncher.launch(intent);
                } else {
                    MapHelper.displayOnMap(context, data.getEorcName(), data.getLng(), data.getLat());
                }
            }
        });

        binding.caseConditionLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                nodeViewModel.getNextNode(context, String.valueOf(data.getCaseState()));
            }
        });

        //图片九宫格事件处理
        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(View view, int position) {
                imageList.remove(position);
                realPaths.remove(position);
                imageAdapter.notifyItemRemoved(position);
                imageAdapter.notifyItemRangeChanged(position, realPaths.size() - position);
            }
        });

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

    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;
        }
    }

    private void submitCase() {
        String remarks = binding.caseConditionView.getText().toString();
        if (TextUtils.isEmpty(remarks)) {
            StringKit.show(this, "核实意见不能为空");
            return;
        }
        if (TextUtils.isEmpty(changeState)) {
            StringKit.show(this, "核实情况还未选择");
            return;
        }
        int source = data.getSource();
        if (source != 11 && source != 12) {
            //修改案卷
            operateViewModel.checkCase(this, data.getProcessId(), id, String.valueOf(data.getCaseState()),
                    changeState, remarks, StringHelper.reformatURL(imageList));
        } else {
            //补全案卷
            if (TextUtils.isEmpty(gridId)) {
                StringKit.show(this, "网格ID异常，请重新选择");
                return;
            }
            String fieldIntro = binding.casePlaceView.getText().toString();
            if (TextUtils.isEmpty(fieldIntro)) {
                StringKit.show(this, "案卷地点还未填写");
            }
            if (longitude == 0 || latitude == 0) {
                StringKit.show(this, "经纬度异常，请重新选择位置");
                return;
            }
            if (imageAdapter.getItemCount() < 1) {
                StringKit.show(context, "至少上传一张照片");
                return;
            }
            operateViewModel.verifyCase(this, data.getProcessId(), id, String.valueOf(data.getCaseState()),
                    changeState, remarks, StringHelper.reformatURL(imageList),
                    eorc == null ? data.getEorc() : eorc,
                    typeCode == null ? data.getCasetypeCode() : typeCode,
                    typeDetailCode == null ? data.getCasetypeDetailCode() : typeDetailCode,
                    String.valueOf(longitude), String.valueOf(latitude),
                    "1", gridId.substring(0, 6),
                    gridId.substring(0, 9), data.getCommunityCode(), gridId, fieldIntro);
        }
    }

    @Override
    public void onBackPressed() {
        if (orientationUtils != null) {
            orientationUtils.backToProtVideo();
        }
        if (GSYVideoManager.backFromWindowFull(this)) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onPause() {
        binding.videoPlayerView.getCurrentPlayer().onVideoPause();
        super.onPause();
        isPause = true;
    }

    @Override
    protected void onResume() {
        binding.videoPlayerView.getCurrentPlayer().onVideoResume(false);
        super.onResume();
        isPause = false;
    }

    @Override
    protected void onDestroy() {
        if (isPlay) {
            binding.videoPlayerView.getCurrentPlayer().release();
        }
        if (orientationUtils != null) {
            orientationUtils.releaseListener();
        }
        super.onDestroy();
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        //如果旋转了就全屏
        if (isPlay && !isPause) {
            binding.videoPlayerView.onConfigurationChanged(this, newConfig, orientationUtils, true, true);
        }
    }
}
