<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="投诉用户ID" prop="complainUserId">
              <el-input v-model="queryParams.complainUserId" placeholder="请输入投诉用户ID" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="被投诉用户ID" prop="targetUserId">
              <el-input v-model="queryParams.targetUserId" placeholder="请输入被投诉用户ID" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="补充说明" prop="reasonDesc">
              <el-input v-model="queryParams.reasonDesc" placeholder="请输入补充说明" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['physical:complaint:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['physical:complaint:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['physical:complaint:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['physical:complaint:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="complaintList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="编号" align="center" prop="id" v-if="true" />
        <el-table-column label="投诉用户ID" align="center" prop="complainUserId" />
        <el-table-column label="投诉用户姓名" align="center" prop="complainUserName" />
        <el-table-column label="投诉原因" align="center" prop="reason" />
        <el-table-column label="投诉内容" align="center" width="150">
          <template #default="{ row }">
            <span><el-link type="primary" @click="showReasonDesc(row.reasonDesc)">点击查看</el-link></span>
          </template>
        </el-table-column>
        <el-table-column label="被投诉用户ID" align="center" prop="targetUserId" />
        <el-table-column label="被投诉用户姓名" align="center" prop="targetUserName" />
        <el-table-column label="创建时间" align="center" prop="createTime" />
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 'pending'" type="warning" effect="dark"> 待处理 </el-tag>
            <el-tag v-else-if="scope.row.status === 'handled'" type="success" effect="dark"> 已处理 </el-tag>
            <el-tag v-else-if="scope.row.status === 'rejected'" type="danger" effect="dark"> 已拒绝 </el-tag>
            <el-tag v-else type="info" effect="dark">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="回复内容" align="center" width="150">
          <template #default="{ row }">
            <span><el-link type="primary" @click="showReasonDesc(row.replyContent)">点击查看</el-link></span>
          </template>
        </el-table-column>
        <el-table-column label="处理人" align="center" prop="handlerName" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="回复" placement="top" v-if="scope.row.status === 'pending'">
              <el-button link type="primary" icon="ChatLineRound" @click="handleReply(scope.row)" v-hasPermi="['physical:complaint:edit']">
                回复
              </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改用户投诉对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="complaintFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="投诉用户ID" prop="complainUserId">
          <el-input v-model="form.complainUserId" placeholder="请输入投诉用户ID" />
        </el-form-item>
        <el-form-item label="被投诉用户ID" prop="targetUserId">
          <el-input v-model="form.targetUserId" placeholder="请输入被投诉用户ID" />
        </el-form-item>
        <el-form-item label="补充说明" prop="reasonDesc">
          <el-input v-model="form.reasonDesc" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="客服回复内容">
          <editor v-model="form.replyContent" :min-height="192" />
        </el-form-item>
        <el-form-item label="处理人ID" prop="handlerId">
          <el-input v-model="form.handlerId" placeholder="请输入处理人ID" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 回复对话框 -->
    <el-dialog :title="replyDialog.title" v-model="replyDialog.visible" width="660px" append-to-body>
      <el-form ref="replyFormRef" :model="replyDialog.form" label-width="120px">
        <el-form-item label="处理结果" prop="status">
          <el-select v-model="replyDialog.form.status" placeholder="请选择" required>
            <el-option label="已处理" value="handled"></el-option>
            <el-option label="已拒绝" value="rejected"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="回复内容" prop="replyContent">
          <editor v-model="replyDialog.form.replyContent" :min-height="192" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="replyDialog.visible = false">取 消</el-button>
          <el-button type="primary" :loading="buttonLoading" @click="submitReply"> 提 交 </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 查看投诉内容对话框 -->
    <el-dialog :title="viewDialog.title" v-model="viewDialog.visible" width="600px" append-to-body>
      <div class="p-4">
        <div v-html="viewDialog.content" class="prose max-w-none"></div>
        <!-- 或直接用 div + v-html -->
        <!-- <div v-html="viewDialog.content" class="text-gray-700"></div> -->
      </div>
      <template #footer>
        <el-button @click="viewDialog.visible = false">关 闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Complaint" lang="ts">
import { listComplaint, getComplaint, delComplaint, addComplaint, updateComplaint } from '@/api/system/physical/complaint';
import { ComplaintVO, ComplaintQuery, ComplaintForm } from '@/api/system/physical/complaint/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const complaintList = ref<ComplaintVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const complaintFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: ComplaintForm = {
  id: undefined,
  complainUserId: undefined,
  targetUserId: undefined,
  reasonType: undefined,
  reasonDesc: undefined,
  status: undefined,
  replyContent: undefined,
  handlerId: undefined
};
const data = reactive<PageData<ComplaintForm, ComplaintQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    complainUserId: undefined,
    targetUserId: undefined,
    reasonType: undefined,
    reasonDesc: undefined,
    status: undefined,
    replyContent: undefined,
    handlerId: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '主键ID不能为空', trigger: 'blur' }],
    complainUserId: [{ required: true, message: '投诉用户ID不能为空', trigger: 'blur' }],
    targetUserId: [{ required: true, message: '被投诉用户ID不能为空', trigger: 'blur' }],
    reasonType: [
      { required: true, message: '投诉原因类型：spam=垃圾信息, abuse=辱骂, fraud=诈骗, cheating=作弊, other=其他不能为空', trigger: 'change' }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询用户投诉列表 */
const getList = async () => {
  loading.value = true;
  const res = await listComplaint(queryParams.value);
  complaintList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  complaintFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: ComplaintVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加用户投诉';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: ComplaintVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getComplaint(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改用户投诉';
};

/** 提交按钮 */
const submitForm = () => {
  complaintFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateComplaint(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addComplaint(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: ComplaintVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除用户投诉编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delComplaint(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'physical/complaint/export',
    {
      ...queryParams.value
    },
    `complaint_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
});

const replyDialog = reactive({
  visible: false,
  title: '回复投诉',
  row: null as ComplaintVO | null,
  form: {
    status: 'handled' as 'handled' | 'rejected',
    replyContent: ''
  }
});

const handleReply = (row: ComplaintVO) => {
  replyDialog.row = row;
  // 安全赋值：仅当 status 是允许值时才赋值，否则设为 undefined
  replyDialog.form.status = row.status === 'handled' || row.status === 'rejected' ? row.status : undefined;
  replyDialog.form.replyContent = row.replyContent || '';
  replyDialog.visible = true;
};

const replyFormRef = ref<ElFormInstance>();

const submitReply = () => {
  replyFormRef.value?.validate(async (valid: boolean) => {
    if (!valid) return;

    const { status, replyContent } = replyDialog.form;
    const row = replyDialog.row;
    if (!row) return;

    buttonLoading.value = true;
    try {
      await updateComplaint({
        id: row.id,
        status,
        replyContent
      });
      proxy?.$modal.msgSuccess('回复成功');
      replyDialog.visible = false;
      await getList();
    } finally {
      buttonLoading.value = false;
    }
  });
};
const viewDialog = reactive({
  visible: false,
  title: '内容',
  content: ''
});
const showReasonDesc = (content: string | undefined) => {
  viewDialog.content = content || '';
  viewDialog.visible = true;
};
</script>
