<template>
  <el-drawer
    v-model="visible"
    :title="isAdd ? '新增投诉建议' : '处理投诉建议'"
    size="520px"
    destroy-on-close
    @closed="onClosed"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" v-loading="loading">
      <el-form-item label="产品分类" prop="categoryId">
        <el-select
          v-model="form.categoryId"
          placeholder="请选择"
          style="width: 100%"
          filterable
          :disabled="!isAdd"
        >
          <el-option
            v-for="c in categoryOptions"
            :key="c.id"
            :label="c.name"
            :value="Number(c.id)"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="标题" prop="title">
        <el-input v-model="form.title" placeholder="标题" :disabled="!isAdd" />
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <el-input
          v-model="form.content"
          type="textarea"
          :rows="6"
          placeholder="建议或投诉内容"
          :disabled="!isAdd"
        />
      </el-form-item>
      <el-form-item label="联系人">
        <el-input v-model="form.contactName" :disabled="!isAdd" />
      </el-form-item>
      <el-form-item label="电话">
        <el-input v-model="form.contactPhone" :disabled="!isAdd" />
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="form.contactEmail" :disabled="!isAdd" />
      </el-form-item>
      <template v-if="!isAdd">
        <el-divider />
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" style="width: 100%">
            <el-option :value="0" label="待处理" />
            <el-option :value="1" label="处理中" />
            <el-option :value="2" label="已回复" />
            <el-option :value="3" label="已关闭" />
          </el-select>
        </el-form-item>
        <el-form-item label="平台回复">
          <el-input v-model="form.replyContent" type="textarea" :rows="5" placeholder="填写后保存将记录回复时间" />
        </el-form-item>
        <el-form-item label="内部备注">
          <el-input v-model="form.remark" type="textarea" :rows="2" />
        </el-form-item>
      </template>
    </el-form>
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" :loading="saving" @click="submit">保存</el-button>
    </template>
  </el-drawer>
</template>

<script setup>
import { ref, reactive, nextTick } from "vue";
import { ElMessage } from "element-plus";
import {
  getComplaintDetail,
  createComplaint,
  updateComplaint,
  getComplaintCategorySelect,
} from "@/api/complaint";

const emit = defineEmits(["saved"]);

const visible = ref(false);
const loading = ref(false);
const saving = ref(false);
const isAdd = ref(false);
const formRef = ref(null);
const categoryOptions = ref([]);

const form = reactive({
  id: 0,
  categoryId: null,
  title: "",
  content: "",
  contactName: "",
  contactPhone: "",
  contactEmail: "",
  status: 0,
  replyContent: "",
  remark: "",
});

const rules = {
  categoryId: [{ required: true, message: "请选择产品分类", trigger: "change" }],
  title: [{ required: true, message: "请输入标题", trigger: "blur" }],
  content: [{ required: true, message: "请输入内容", trigger: "blur" }],
};

async function loadCategories() {
  const res = await getComplaintCategorySelect();
  if (res?.code === 200 && Array.isArray(res.data)) {
    categoryOptions.value = res.data;
  } else {
    categoryOptions.value = [];
  }
}

function resetForm() {
  form.id = 0;
  form.categoryId = null;
  form.title = "";
  form.content = "";
  form.contactName = "";
  form.contactPhone = "";
  form.contactEmail = "";
  form.status = 0;
  form.replyContent = "";
  form.remark = "";
}

async function open(id) {
  resetForm();
  await loadCategories();
  isAdd.value = !id;
  visible.value = true;
  await nextTick();
  formRef.value?.clearValidate?.();
  if (id) {
    loading.value = true;
    try {
      const res = await getComplaintDetail(id);
      if (res?.code !== 200 || !res.data) {
        ElMessage.error(res?.msg || "加载失败");
        visible.value = false;
        return;
      }
      const d = res.data;
      form.id = d.id;
      form.categoryId = d.categoryId;
      form.title = d.title || "";
      form.content = d.content || "";
      form.contactName = d.contactName || "";
      form.contactPhone = d.contactPhone || "";
      form.contactEmail = d.contactEmail || "";
      form.status = d.status ?? 0;
      form.replyContent = d.replyContent || "";
      form.remark = d.remark || "";
    } finally {
      loading.value = false;
    }
  }
}

function onClosed() {
  resetForm();
}

async function submit() {
  if (!formRef.value) return;
  try {
    await formRef.value.validate();
  } catch {
    return;
  }

  saving.value = true;
  try {
    if (isAdd.value) {
      const res = await createComplaint({
        categoryId: form.categoryId,
        title: form.title,
        content: form.content,
        contactName: form.contactName || undefined,
        contactPhone: form.contactPhone || undefined,
        contactEmail: form.contactEmail || undefined,
      });
      if (res?.code === 200) {
        ElMessage.success("已创建");
        visible.value = false;
        emit("saved");
      } else {
        ElMessage.error(res?.msg || "失败");
      }
    } else {
      const res = await updateComplaint(form.id, {
        categoryId: form.categoryId,
        status: form.status,
        replyContent: form.replyContent,
        remark: form.remark || undefined,
      });
      if (res?.code === 200) {
        ElMessage.success("已保存");
        visible.value = false;
        emit("saved");
      } else {
        ElMessage.error(res?.msg || "失败");
      }
    }
  } finally {
    saving.value = false;
  }
}

defineExpose({ open });
</script>
