package cc.winboll.studio.positions.views;

/**
 * @Author ZhanGSKen&豆包大模型<zhangsken@qq.com>
 * @Date 2025/09/30 08:09
 * @Describe 位置任务列表视图（支持简单/编辑模式，含 isBingo 红点标识）
 */
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import cc.winboll.studio.positions.R;
import cc.winboll.studio.positions.models.PositionTaskModel;
import java.util.ArrayList;
import java.util.List;

public class PositionTaskListView extends LinearLayout {
    // 视图模式常量
    public static final int VIEW_MODE_SIMPLE = 1;
    public static final int VIEW_MODE_EDIT = 2;

    // 核心成员变量
    private String mBindPositionId;
    private ArrayList<PositionTaskModel> mTaskList;
    private int mCurrentViewMode;
    private TaskListAdapter mTaskAdapter;
    private RecyclerView mRvTasks;

    // 任务修改回调接口
    public interface OnTaskUpdatedListener {
        void onTaskUpdated(String positionId, ArrayList<PositionTaskModel> updatedTasks);
    }

    private OnTaskUpdatedListener mOnTaskUpdatedListener;

    // ---------------------- 构造函数 ----------------------
    public PositionTaskListView(Context context) {
        super(context);
        initView(context);
    }

    public PositionTaskListView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public PositionTaskListView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }

    // 初始化视图（绑定控件+设置布局）
    private void initView(Context context) {
        setOrientation(VERTICAL);
        LayoutInflater.from(context).inflate(R.layout.view_position_task_list, this, true);

        mRvTasks = (RecyclerView) findViewById(R.id.rv_position_tasks);
        mRvTasks.setLayoutManager(new LinearLayoutManager(context));

        mTaskList = new ArrayList<PositionTaskModel>();
        mTaskAdapter = new TaskListAdapter(mTaskList);
        mRvTasks.setAdapter(mTaskAdapter);

        mCurrentViewMode = VIEW_MODE_SIMPLE;
    }

    // ---------------------- 对外API ----------------------
    public void init(ArrayList<PositionTaskModel> taskList, String positionId) {
        this.mBindPositionId = positionId;
        if (this.mTaskList.isEmpty()) {
            ArrayList<PositionTaskModel> matchedTasks = new ArrayList<PositionTaskModel>();
            if (taskList != null && !taskList.isEmpty()) {
                for (PositionTaskModel task : taskList) {
                    if (task != null && positionId.equals(task.getPositionId())) {
                        matchedTasks.add(task);
                    }
                }
            }
            mTaskList.clear();
            mTaskList.addAll(matchedTasks);
        }
        mTaskAdapter.notifyDataSetChanged();
    }

    public void setViewStatus(int viewMode) {
        if (viewMode != VIEW_MODE_SIMPLE && viewMode != VIEW_MODE_EDIT) {
            return;
        }
        mCurrentViewMode = viewMode;
        mTaskAdapter.notifyDataSetChanged();
    }

    public void setOnTaskUpdatedListener(OnTaskUpdatedListener listener) {
        this.mOnTaskUpdatedListener = listener;
    }

    public ArrayList<PositionTaskModel> getAllTasks() {
        return new ArrayList<PositionTaskModel>(mTaskList);
    }

    public void clearData() {
        mTaskList.clear();
        if (mTaskAdapter != null && mTaskAdapter.mData != null) {
            mTaskAdapter.mData.clear();
        }
        mTaskAdapter.notifyDataSetChanged();
        mBindPositionId = null;
    }

    public void triggerTaskSync() {
        if (mOnTaskUpdatedListener != null && mBindPositionId != null) {
            mOnTaskUpdatedListener.onTaskUpdated(mBindPositionId, new ArrayList<PositionTaskModel>(mTaskList));
        }
    }

    // ---------------------- 内部工具方法 ----------------------
    private boolean isTaskMatchedWithPosition(PositionTaskModel task) {
        if (task == null || mBindPositionId == null || mBindPositionId.trim().isEmpty()) {
            return false;
        }
        return mBindPositionId.equals(task.getPositionId());
    }

    // ---------------------- 内部Adapter：适配 isBingo 红点（核心调整） ----------------------
    private class TaskListAdapter extends RecyclerView.Adapter<TaskListAdapter.TaskViewHolder> {
        private final List<PositionTaskModel> mData;

        public TaskListAdapter(List<PositionTaskModel> data) {
            this.mData = data;
        }

        @Override
        public int getItemCount() {
            return mData.isEmpty() ? 1 : mData.size();
        }

        // 调整：根据“是否空列表”+“视图模式”区分视图类型（确保简单/编辑模式加载对应布局）
        @Override
        public int getItemViewType(int position) {
            if (mData.isEmpty()) {
                return 0; // 0=空提示
            } else {
                return mCurrentViewMode; // 1=简单模式，2=编辑模式（复用视图模式常量）
            }
        }

        // 调整：按视图类型加载布局（简单模式加载带红点的布局，编辑模式加载原有布局）
        @NonNull
        @Override
        public TaskViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            Context context = parent.getContext();
            LayoutInflater inflater = LayoutInflater.from(context);

            if (viewType == 0) {
                // 空提示布局
                View emptyView = inflater.inflate(R.layout.item_task_empty, parent, false);
                return new EmptyViewHolder(emptyView);
            } else if (viewType == VIEW_MODE_SIMPLE) {
                // 简单模式布局（带 isBingo 红点）
                View simpleTaskView = inflater.inflate(R.layout.item_position_task_simple, parent, false);
                return new SimpleTaskViewHolder(simpleTaskView);
            } else {
                // 编辑模式布局（原有布局不变）
                View editTaskView = inflater.inflate(R.layout.item_task_content, parent, false);
                return new TaskContentViewHolder(editTaskView);
            }
        }

        // 调整：按视图类型绑定数据（简单模式绑定红点+文本，编辑模式绑定原有逻辑）
        @Override
        public void onBindViewHolder(@NonNull TaskViewHolder holder, int position) {
            // 空提示处理（不变）
            if (holder instanceof EmptyViewHolder) {
                EmptyViewHolder emptyHolder = (EmptyViewHolder) holder;
                TextView tvEmptyTip = (TextView) emptyHolder.itemView.findViewById(R.id.tv_task_empty_tip);
                tvEmptyTip.setText(mCurrentViewMode == VIEW_MODE_EDIT ? "暂无任务，点击\"添加新任务\"创建" : "暂无启用的任务");
                return;
            }

            // 任务项有效性校验（不变）
            if (position >= mData.size()) {
                return;
            }
            final PositionTaskModel task = mData.get(position);
            if (task == null) {
                return;
            }

            // 简单模式：绑定红点（isBingo）和文本数据
            if (holder instanceof SimpleTaskViewHolder) {
                SimpleTaskViewHolder simpleHolder = (SimpleTaskViewHolder) holder;
                // 绑定任务描述
                simpleHolder.tvSimpleTaskDesc.setText(String.format("任务：%s", task.getTaskDescription()));
                // 绑定距离条件
                String distanceCond = task.isGreaterThan() ? "大于" : "小于";
                simpleHolder.tvSimpleDistanceCond.setText(String.format("条件：距离 %s %d 米", distanceCond, task.getDiscussDistance()));
                // 绑定启用状态
                simpleHolder.tvSimpleIsEnable.setText(task.isEnable() ? "状态：已启用" : "状态：已禁用");
                // 核心：根据 isBingo 控制红点显示（true=显示，false=隐藏）
                simpleHolder.vBingoDot.setVisibility(task.isBingo() ? View.VISIBLE : View.GONE);
            }
            // 编辑模式：沿用原有绑定逻辑（核心修复在此处）
            else if (holder instanceof TaskContentViewHolder) {
                TaskContentViewHolder contentHolder = (TaskContentViewHolder) holder;
                bindTaskData(contentHolder, task, position);
            }
        }

        // ---------------------- 核心修复：编辑模式绑定逻辑（解决布局中通知异常） ----------------------
        private void bindTaskData(final TaskContentViewHolder holder, final PositionTaskModel task, final int position) {
            String taskDesc = (task.getTaskDescription() == null) ? "未设置描述" : task.getTaskDescription();
            holder.tvTaskDesc.setText(String.format("任务：%s", taskDesc));

            String distanceCondition = task.isGreaterThan() ? "大于" : "小于";
            holder.tvTaskDistance.setText(String.format("条件：%s %d 米", distanceCondition, task.getDiscussDistance()));

            // 修复点1：先移除开关监听，再设置状态（避免设值时触发回调导致异常）
            holder.cbTaskEnable.setOnCheckedChangeListener(null);
            holder.cbTaskEnable.setChecked(task.isEnable());
            holder.cbTaskEnable.setEnabled(mCurrentViewMode == VIEW_MODE_EDIT);

            if (mCurrentViewMode == VIEW_MODE_EDIT) {
                holder.btnEditTask.setVisibility(View.VISIBLE);
                holder.btnDeleteTask.setVisibility(View.VISIBLE);

                // 删除按钮逻辑（不变，本身在点击时执行，不涉及布局中通知）
                holder.btnDeleteTask.setOnClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							mData.remove(position);
							notifyItemRemoved(position);
							notifyItemRangeChanged(position, mData.size());
							if (mOnTaskUpdatedListener != null && mBindPositionId != null) {
								mOnTaskUpdatedListener.onTaskUpdated(mBindPositionId, new ArrayList<PositionTaskModel>(mData));
							}
							Toast.makeText(getContext(), "任务已删除", Toast.LENGTH_SHORT).show();
						}
					});

                // 编辑按钮逻辑（不变，弹窗保存时修复通知时机）
                holder.btnEditTask.setOnClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							showTaskEditDialog(task, position);
						}
					});

                // 修复点2：开关监听-用 RecyclerView.post 延迟执行 notify（避免布局中调用）
                holder.cbTaskEnable.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
						@Override
						public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
							task.setIsEnable(isChecked); // 先更新数据源（必须执行）
							// 关键：通过 mRvTasks.post 延迟通知，确保在布局计算/滚动结束后执行
							mRvTasks.post(new Runnable() {
									@Override
									public void run() {
										notifyItemChanged(position);
										if (mOnTaskUpdatedListener != null && mBindPositionId != null) {
											mOnTaskUpdatedListener.onTaskUpdated(mBindPositionId, new ArrayList<PositionTaskModel>(mData));
										}
									}
								});
						}
					});
            } else {
                holder.btnEditTask.setVisibility(View.GONE);
                holder.btnDeleteTask.setVisibility(View.GONE);
                holder.cbTaskEnable.setOnCheckedChangeListener(null);
            }
        }

        // ---------------------- 修复：编辑弹窗保存逻辑（延迟通知，避免极端场景异常） ----------------------
        private void showTaskEditDialog(final PositionTaskModel task, final int position) {
            final Context context = getContext();
            View dialogView = LayoutInflater.from(context).inflate(R.layout.dialog_edit_task, null);

            final EditText etEditDesc = (EditText) dialogView.findViewById(R.id.et_edit_task_desc);
            final RadioGroup rgDistanceCondition = (RadioGroup) dialogView.findViewById(R.id.rg_distance_condition);
            final EditText etEditDistance = (EditText) dialogView.findViewById(R.id.et_edit_distance);
            Button btnCancel = (Button) dialogView.findViewById(R.id.btn_dialog_cancel);
            Button btnSave = (Button) dialogView.findViewById(R.id.btn_dialog_save);

            etEditDesc.setText(task.getTaskDescription());
            etEditDesc.setSelection(etEditDesc.getText().length());

            if (task.isGreaterThan()) {
                rgDistanceCondition.check(R.id.rb_greater_than);
            } else {
                rgDistanceCondition.check(R.id.rb_less_than);
            }

            etEditDistance.setText(String.valueOf(task.getDiscussDistance()));

            final android.app.AlertDialog dialog = new android.app.AlertDialog.Builder(context)
				.setView(dialogView)
				.create();
            dialog.show();

            btnCancel.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						dialog.dismiss();
					}
				});

            btnSave.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						String newDesc = etEditDesc.getText().toString().trim();
						String distanceStr = etEditDistance.getText().toString().trim();

						if (distanceStr.isEmpty()) {
							Toast.makeText(context, "请输入有效距离", Toast.LENGTH_SHORT).show();
							return;
						}

						int newDistance;
						try {
							newDistance = Integer.parseInt(distanceStr);
							if (newDistance < 1) {
								Toast.makeText(context, "距离不能小于1米", Toast.LENGTH_SHORT).show();
								return;
							}
						} catch (NumberFormatException e) {
							Toast.makeText(context, "距离请输入数字", Toast.LENGTH_SHORT).show();
							return;
						}

						task.setTaskDescription(newDesc);
						task.setDiscussDistance(newDistance);
						boolean isGreater = rgDistanceCondition.getCheckedRadioButtonId() == R.id.rb_greater_than;
						task.setIsGreaterThan(isGreater);
						task.setPositionId(mBindPositionId);

						// 修复点3：弹窗保存后延迟通知（同开关逻辑，避免列表滚动时异常）
						mRvTasks.post(new Runnable() {
								@Override
								public void run() {
									notifyItemChanged(position);
									if (mOnTaskUpdatedListener != null && mBindPositionId != null) {
										mOnTaskUpdatedListener.onTaskUpdated(mBindPositionId, new ArrayList<PositionTaskModel>(mData));
									}
								}
							});

						dialog.dismiss();
						Toast.makeText(context, "任务已更新", Toast.LENGTH_SHORT).show();
					}
				});
        }

        // ---------------------- ViewHolder 定义（完全不变） ----------------------
        // 基础抽象 ViewHolder（不变）
        public abstract class TaskViewHolder extends RecyclerView.ViewHolder {
            public TaskViewHolder(@NonNull View itemView) {
                super(itemView);
            }
        }

        // 空提示 Holder（不变）
        public class EmptyViewHolder extends TaskViewHolder {
            public EmptyViewHolder(@NonNull View itemView) {
                super(itemView);
            }
        }

        // 新增：简单模式 Holder（绑定带红点的布局控件）
        public class SimpleTaskViewHolder extends TaskViewHolder {
            TextView tvSimpleTaskDesc;    // 任务描述
            TextView tvSimpleDistanceCond;// 距离条件
            TextView tvSimpleIsEnable;    // 启用状态
            View vBingoDot;               // isBingo 红点控件

            public SimpleTaskViewHolder(@NonNull View itemView) {
                super(itemView);
                // 绑定简单模式布局中的控件（与 item_task_simple.xml 完全对应）
                tvSimpleTaskDesc = itemView.findViewById(R.id.tv_simple_task_desc);
                tvSimpleDistanceCond = itemView.findViewById(R.id.tv_simple_distance_cond);
                tvSimpleIsEnable = itemView.findViewById(R.id.tv_simple_is_enable);
                vBingoDot = itemView.findViewById(R.id.v_bingo_dot);
            }
        }

        // 编辑模式 Holder（原有逻辑，完全不变）
        public class TaskContentViewHolder extends TaskViewHolder {
            TextView tvTaskDesc;
            TextView tvTaskDistance;
            CompoundButton cbTaskEnable;
            Button btnEditTask;
            Button btnDeleteTask;

            public TaskContentViewHolder(@NonNull View itemView) {
                super(itemView);
                tvTaskDesc = (TextView) itemView.findViewById(R.id.tv_task_desc);
                tvTaskDistance = (TextView) itemView.findViewById(R.id.tv_task_distance);
                cbTaskEnable = (CompoundButton) itemView.findViewById(R.id.cb_task_enable);
                btnEditTask = (Button) itemView.findViewById(R.id.btn_edit_task);
                btnDeleteTask = (Button) itemView.findViewById(R.id.btn_delete_task);
            }
        }
    }
}

