<template>
  <div class="process" v-loading="loading">
    <el-page-header :icon="ArrowLeft" :content="$t('common.back')" @back="goBack" class="page-header">
      <template #content>
        <span class="page-title">{{ $t('btn.process') }}</span>
      </template>
    </el-page-header>

    <el-card shadow="never" v-if="detail.id" class="form-card">
      <template #header>
        <span class="card-title">{{ $t('btn.process') }}</span>
      </template>

      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        style="max-width: 800px"
      >
        <!-- 工单号（只读） -->
        <el-form-item :label="$t('table.id')">
          <el-input :model-value="detail.orderNo" readonly />
        </el-form-item>

        <!-- 问题描述（只读，富文本展示） -->
        <el-form-item :label="$t('label.description')">
          <div class="readonly-html" v-html="detail.description || '—'" />
        </el-form-item>

        <!-- 处理说明（wangEditor 富文本编辑器，与提交工单页面一致） -->
        <el-form-item :label="$t('common.remark')" prop="processRemark">
          <div class="rich-editor">
            <Toolbar
              :editor="editorRef"
              :default-config="toolbarConfig"
              mode="default"
              style="border-bottom: 1px solid #dcdfe6"
            />
            <Editor
              v-model="form.processRemark"
              :default-config="editorConfig"
              mode="default"
              style="height: 200px; overflow-y: auto"
              @on-created="handleEditorCreated"
              @custom-paste="handleEditorPasteImage"
            />
          </div>
        </el-form-item>

        <!-- 新状态（只允许"已完成"） -->
        <el-form-item :label="$t('table.status')" prop="status">
          <el-select v-model="form.status" style="width: 240px">
            <el-option :label="$t('status.completed')" value="已完成" />
          </el-select>
        </el-form-item>

        <!-- 处理人（取当前登录用户名） -->
        <el-form-item :label="$t('table.handler')">
          <el-input :model-value="handlerName" readonly style="width: 240px" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :loading="submitting" @click="submit">{{ $t('btn.confirm') }}</el-button>
          <el-button @click="goBack">{{ $t('common.cancel') }}</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { computed, nextTick, onBeforeUnmount, onMounted, reactive, ref, shallowRef } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { ArrowLeft } from "@element-plus/icons-vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import "@wangeditor/editor/dist/css/style.css";
import { useI18n } from "vue-i18n";
import { getAdminOrderDetail, processAdminOrder } from "@/service/modular/admin";
import { useUserStore } from "@/stores/api/user";

const { t: $t } = useI18n();
const route = useRoute();
const router = useRouter();
const userStore = useUserStore();

const loading = ref(false);
const submitting = ref(false);
const detail = ref({});
const formRef = ref();

// 处理人显示当前登录用户名
const handlerName = computed(
  () => userStore.userInfo?.name || userStore.userInfo?.userName || userStore.userInfo?.account || '管理员',
);

// 新状态只能为"已完成"
const form = reactive({
  status: "已完成",
  processRemark: "",
});

const rules = {
  status: [{ required: true, message: () => $t('table.status'), trigger: "change" }],
  processRemark: [
    {
      required: true,
      validator: (_, value, callback) => {
        const hasImage = /<img\s/i.test(value || "");
        const text = (value || "")
          .replace(/<[^>]*>/g, "")
          .replace(/&nbsp;/gi, "")
          .trim();
        if (!text && !hasImage) return callback(new Error($t('placeholder.remark')));
        callback();
      },
      trigger: "change",
    },
  ],
};

// wangEditor
const editorRef = shallowRef();
const toolbarConfig = {
  excludeKeys: [
    "uploadImage",
    "insertVideo",
    "uploadVideo",
    "group-video",
    "emotion",
    "group-emoji",
  ],
};
const editorConfig = {
  placeholder: $t('placeholder.remark'),
};

// 粘贴到富文本的图片大小上限（base64 内联存储，避免 HTML 过大）
const MAX_PASTE_IMAGE_SIZE = 5 * 1024 * 1024;

// 从剪贴板中捞出图片文件（同时兼容 items 和 files 两种来源）
const collectPastedImages = (clipboardData) => {
  const files = [];
  const items = clipboardData?.items;
  if (items) {
    for (let i = 0; i < items.length; i++) {
      const item = items[i];
      if (item.kind === "file" && item.type?.startsWith("image/")) {
        const file = item.getAsFile();
        if (file) files.push(file);
      }
    }
  }
  if (files.length === 0 && clipboardData?.files) {
    for (let i = 0; i < clipboardData.files.length; i++) {
      const file = clipboardData.files[i];
      if (file.type?.startsWith("image/")) files.push(file);
    }
  }
  return files;
};

// 共用的图片粘贴处理逻辑（customPaste 和原生监听都走这里，用事件标记防重复）
const handleEditorPasteImage = (editor, event) => {
  if (event.__wpsImageHandled) return;
  const imageFiles = collectPastedImages(event.clipboardData);
  if (imageFiles.length === 0) return;
  event.__wpsImageHandled = true;
  event.preventDefault();
  if (typeof event.stopPropagation === "function") event.stopPropagation();
  if (typeof event.stopImmediatePropagation === "function")
    event.stopImmediatePropagation();

  // 同步先拿到当前 selection，等 FileReader 异步回调里恢复
  if (typeof editor.focus === "function") editor.focus();
  const savedSelection = editor.selection;

  imageFiles.forEach((file) => {
    if (file.size > MAX_PASTE_IMAGE_SIZE) {
      ElMessage.warning("粘贴的图片不能超过 5MB");
      return;
    }
    const reader = new FileReader();
    reader.onload = (e) => {
      const dataUrl = e.target?.result;
      if (!dataUrl) {
        ElMessage.error("图片读取失败");
        return;
      }
      try {
        if (savedSelection) editor.select(savedSelection);
      } catch (_) {
        if (typeof editor.focus === "function") editor.focus();
      }
      if (typeof editor.focus === "function") editor.focus();
      editor.dangerouslyInsertHtml(
        `<img src="${dataUrl}" style="max-width:100%;height:auto;" />`,
      );
      if (typeof editor.updateView === "function") editor.updateView();
      // ElMessage.success("图片插入成功");
    };
    reader.onerror = () => {
      ElMessage.error("图片处理失败");
    };
    reader.readAsDataURL(file);
  });
  return false; // 告诉 wangEditor 跳过默认处理
};

let pasteHandlerRef = null;
const handleEditorCreated = (editor) => {
  editorRef.value = editor;
  // 额外在 contentEditable 上绑一份 capture 监听（防 customPaste 未生效的兜底）
  nextTick(() => {
    const root = typeof editor.$el === "function" ? editor.$el() : editor.$el;
    if (!root) return;
    const editable =
      root.querySelector?.('[contenteditable="true"]') || root;
    if (pasteHandlerRef) {
      editable.removeEventListener("paste", pasteHandlerRef, { capture: true });
    }
    pasteHandlerRef = (event) => handleEditorPasteImage(editor, event);
    editable.addEventListener("paste", pasteHandlerRef, { capture: true });
  });
};

const loadDetail = async () => {
  loading.value = true;
  try {
    detail.value = await getAdminOrderDetail(route.params.id);
  } finally {
    loading.value = false;
  }
};

const submit = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid) => {
    if (!valid) return;
    submitting.value = true;
    try {
      await processAdminOrder(route.params.id, {
        status: form.status,
        processRemark: form.processRemark,
      });
      ElMessage.success($t('msg.editSuccess'));
      router.replace("/admin/orders");
    } finally {
      submitting.value = false;
    }
  });
};

const goBack = () => router.back();

const removePasteListener = () => {
  const editor = editorRef.value;
  if (!editor || !pasteHandlerRef) return;
  const root = typeof editor.$el === "function" ? editor.$el() : editor.$el;
  if (!root) return;
  const editable = root.querySelector?.('[contenteditable="true"]') || root;
  editable.removeEventListener("paste", pasteHandlerRef, { capture: true });
};

onMounted(loadDetail);

onBeforeUnmount(() => {
  removePasteListener();
  pasteHandlerRef = null;
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});
</script>

<style scoped lang="scss">
.page-header {
  margin-bottom: 12px;
  .page-title {
    font-size: 16px;
    font-weight: 600;
  }
}

.form-card {
  .card-title {
    font-size: 16px;
    font-weight: 600;
  }
}

// 只读富文本展示
.readonly-html {
  width: 100%;
  min-height: 60px;
  padding: 10px 12px;
  background: #fafafa;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  line-height: 1.6;
  word-break: break-word;
  :deep(img) {
    max-width: 100%;
  }
}

// wangEditor 富文本容器（与提交工单页面一致）
.rich-editor {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  width: 100%;
  overflow: hidden;
  background: #fff;
}
.rich-editor :deep(.w-e-toolbar) {
  background: #fafafa;
}
</style>
