<!-- @Author: Antigravity -->
<template>
  <div class="complaint-page">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="search">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="85px">
          <el-form-item label="反馈类型" prop="feedbackType">
            <el-select v-model="queryParams.feedbackType" placeholder="请选择反馈类型" clearable>
              <el-option v-for="dict in sys_complaint_type" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="员工姓名" prop="employeeName">
            <el-input v-model="queryParams.employeeName" 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>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:complaint:remove']" type="danger" plain icon="Delete" :disabled="multiple"
              @click="handleDelete()">删除</el-button>
          </el-col>
          <right-toolbar v-model:show-search="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="complaintList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" align="center" width="70" type="index" />
        <el-table-column label="类型" align="center" prop="feedbackType" width="100">
          <template #default="scope">
            <dict-tag :options="sys_complaint_type" :value="scope.row.feedbackType" />
          </template>
        </el-table-column>
        <el-table-column label="投诉内容" align="center" prop="content" min-width="160" :show-overflow-tooltip="true" />
        <el-table-column label="图片" align="center" width="130">
          <template #default="scope">
            <div v-if="scope.row.imageUrls" class="image-cell">
              <el-image v-for="(url, idx) in getShowImages(scope.row.imageUrls)" :key="idx" :src="url"
                :preview-src-list="scope.row.imageUrls.split(',')" :initial-index="idx" fit="cover"
                style="width:36px;height:36px;border-radius:4px" preview-teleported />
              <span v-if="getImageCount(scope.row.imageUrls) > 2" class="image-ellipsis">…</span>
            </div>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" width="90">
          <template #default="scope">
            <el-tag :type="scope.row.status === '0' ? 'warning' : 'success'">
              {{ scope.row.status === '0' ? '待处理' : '已处理' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="用户姓名" align="center" prop="employeeName" width="120" />
        <el-table-column label="用户手机" align="center" prop="employeePhone" width="130" />
        <el-table-column label="提交时间" align="center" prop="createTime" width="170" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="160">
          <template #default="scope">
            <div class="action-btns">
              <el-button v-hasPermi="['complaint:complaint:query']" link type="primary"
                @click="handleDetail(scope.row)">详情</el-button>
              <el-button v-if="scope.row.status !== '1'" v-hasPermi="['complaint:complaint:deal']" link type="warning"
                @click="handleDeal(scope.row)">处理</el-button>
              <el-button v-hasPermi="['system:complaint:remove']" link type="danger"
                @click="handleDelete(scope.row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
        :total="total" @pagination="getList" />
    </el-card>

    <!-- 投诉详情对话框 -->
    <el-dialog v-model="detailDialog.visible" width="620px" :close-on-click-modal="false" append-to-body
      class="detail-dialog">
      <template #header>
        <div class="detail-dialog-title">
          <el-icon :size="20" class="title-icon">
            <Document />
          </el-icon>
          <span>投诉详情</span>
        </div>
      </template>

      <template v-if="detailDialog.data">
        <div class="detail-card">
          <div class="detail-card__user">
            <el-avatar :size="52" class="detail-avatar">
              <el-icon :size="24">
                <UserFilled />
              </el-icon>
            </el-avatar>
            <div class="detail-card__meta">
              <div class="detail-card__name">{{ detailDialog.data.employeeName }}</div>
              <div class="detail-card__phone">{{ detailDialog.data.employeePhone || '-' }}</div>
            </div>
            <div class="detail-card__badge">
              <span class="status-dot"
                :class="detailDialog.data.status === '0' ? 'status-pending' : 'status-done'"></span>
              {{ detailDialog.data.status === '0' ? '待处理' : '已处理' }}
            </div>
          </div>
        </div>

        <div class="detail-section">
          <div class="detail-section__head">
            <el-icon :size="16">
              <InfoFilled />
            </el-icon>
            <span>基本信息</span>
          </div>
          <div class="detail-grid">
            <div class="detail-item">
              <span class="detail-label">投诉编号</span>
              <span class="detail-value">{{ detailDialog.data.id }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">反馈类型</span>
              <dict-tag :options="sys_complaint_type" :value="detailDialog.data.feedbackType" />
            </div>
            <div class="detail-item">
              <span class="detail-label">提交时间</span>
              <span class="detail-value">{{ detailDialog.data.createTime }}</span>
            </div>
          </div>
        </div>

        <div class="detail-section">
          <div class="detail-section__head">
            <el-icon :size="16">
              <ChatLineSquare />
            </el-icon>
            <span>投诉内容</span>
          </div>
          <div class="detail-content-text">{{ detailDialog.data.content }}</div>
        </div>

        <div class="detail-section" v-if="detailDialog.data.imageUrls">
          <div class="detail-section__head">
            <el-icon :size="16">
              <PictureFilled />
            </el-icon>
            <span>投诉图片</span>
          </div>
          <div class="detail-images">
            <div class="detail-image-item" v-for="(url, idx) in detailDialog.data.imageUrls.split(',')" :key="idx">
              <el-image :src="url" :preview-src-list="detailDialog.data.imageUrls.split(',')"
                :initial-index="(idx as number)" fit="cover" preview-teleported />
            </div>
          </div>
        </div>

        <template v-if="detailDialog.data.status === '1'">
          <div class="detail-divider"></div>

          <div class="detail-section">
            <div class="detail-section__head highlight">
              <el-icon :size="16">
                <CircleCheckFilled />
              </el-icon>
              <span>处理结果</span>
            </div>
            <div class="detail-content-text deal-text">{{ detailDialog.data.dealResult }}</div>
          </div>

          <div class="detail-section" v-if="detailDialog.data.dealImageUrls">
            <div class="detail-section__head">
              <el-icon :size="16">
                <PictureFilled />
              </el-icon>
              <span>处理凭证</span>
            </div>
            <div class="detail-images">
              <div class="detail-image-item" v-for="(url, idx) in detailDialog.data.dealImageUrls.split(',')"
                :key="idx">
                <el-image :src="url" :preview-src-list="detailDialog.data.dealImageUrls.split(',')"
                  :initial-index="(idx as number)" fit="cover" preview-teleported />
              </div>
            </div>
          </div>
        </template>
      </template>
    </el-dialog>

    <!-- 处理投诉对话框 -->
    <el-dialog v-model="dealDialog.visible" title="处理投诉" width="600px" append-to-body @close="resetDealForm">
      <el-form ref="dealFormRef" :model="dealForm" :rules="dealRules" label-width="80px">
        <el-form-item label="投诉内容">
          <div class="deal-content-text">{{ dealDialog.complaintContent }}</div>
        </el-form-item>
        <el-form-item label="处理结果" prop="dealResult">
          <el-input v-model="dealForm.dealResult" type="textarea" :rows="4" placeholder="请输入处理结果" maxlength="2000"
            show-word-limit />
        </el-form-item>
        <el-form-item label="上传凭证">
          <ImageUpload v-model="dealForm.dealImages" :limit="9" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="dealLoading" type="primary" icon="Check" @click="submitDeal">确 定</el-button>
          <el-button icon="Close" @click="dealDialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Complaint" lang="ts">
import { Document, UserFilled, InfoFilled, ChatLineSquare, PictureFilled, CircleCheckFilled } from '@element-plus/icons-vue';
import { listComplaint, getComplaintDetail, dealComplaint, delComplaint } from '@/api/system/complaint';
import { ComplaintVO, ComplaintQuery, ComplaintDealForm } from '@/api/system/complaint/types';

/** @Author: Antigravity */

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_complaint_type } = toRefs<any>(proxy?.useDict('sys_complaint_type'));

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

const queryFormRef = ref<ElFormInstance>();

const data = reactive<PageData<object, ComplaintQuery>>({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    feedbackType: undefined,
    employeeName: undefined
  },
  rules: {}
});

const { queryParams } = toRefs(data);

// 详情对话框
const detailDialog = reactive({
  visible: false,
  data: null as ComplaintVO | null
});

// 处理对话框
const dealDialog = reactive({
  visible: false,
  complaintId: undefined as string | number | undefined,
  complaintContent: ''
});
const dealLoading = ref(false);
const dealFormRef = ref<ElFormInstance>();
const dealForm = reactive<ComplaintDealForm>({
  id: '',
  dealResult: '',
  dealImages: ''
});
const dealRules = {
  dealResult: [{ required: true, message: '请输入处理结果', trigger: 'blur' }]
};

/**
 * 获取展示的图片列表（最多2张）
 */
const getShowImages = (imageUrls: string) => {
  const urls = imageUrls.split(',');
  return urls.slice(0, 2);
};

/**
 * 获取图片总数
 */
const getImageCount = (imageUrls: string) => {
  return imageUrls.split(',').length;
};

const getList = async () => {
  loading.value = true;
  const res = await listComplaint(queryParams.value);
  complaintList.value = (res as any).rows || [];
  total.value = (res as any).total || 0;
  loading.value = false;
};

const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

const handleSelectionChange = (selection: ComplaintVO[]) => {
  ids.value = selection.map((item) => item.id);
  multiple.value = !selection.length;
};

/** 查看详情 */
const handleDetail = async (row: ComplaintVO) => {
  detailDialog.visible = true;
  detailDialog.data = null;
  try {
    const res = await getComplaintDetail(row.id);
    detailDialog.data = res.data as ComplaintVO;
  } catch (e) {
    proxy?.$modal.msgError('获取投诉详情失败');
    detailDialog.visible = false;
  }
};

/** 打开处理弹窗 */
const handleDeal = (row: ComplaintVO) => {
  dealDialog.visible = true;
  dealDialog.complaintId = row.id;
  dealDialog.complaintContent = row.content;
  dealForm.id = row.id;
  dealForm.dealResult = '';
  dealForm.dealImages = '';
};

/** 重置处理表单 */
const resetDealForm = () => {
  dealFormRef.value?.resetFields();
  dealForm.dealImages = '';
};

/** 提交处理 */
const submitDeal = async () => {
  const valid = await dealFormRef.value?.validate().catch(() => false);
  if (!valid) return;
  dealLoading.value = true;
  try {
    await dealComplaint({ ...dealForm });
    proxy?.$modal.msgSuccess('处理成功');
    dealDialog.visible = false;
    getList();
  } catch (e: any) {
    proxy?.$modal.msgError(e?.msg || '处理失败');
  } finally {
    dealLoading.value = false;
  }
};

/** 删除 */
const handleDelete = async (row?: ComplaintVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除所选投诉建议数据？');
  loading.value = true;
  await delComplaint(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

onMounted(() => {
  getList();
});
</script>

<style scoped lang="scss">
@use '@/assets/styles/page-common.scss' as *;

/* 操作按钮一行显示 */
.action-btns {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-wrap: nowrap;
  white-space: nowrap;
}

/* 列表中图片展示 */
.image-cell {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
}

.image-ellipsis {
  font-size: 16px;
  font-weight: 600;
  color: #999;
  margin-left: 2px;
}

/* ==================== 详情弹窗优化 ==================== */
.detail-dialog :deep(.el-dialog) {
  border-radius: 14px;
  overflow: hidden;
}

.detail-dialog :deep(.el-dialog__header) {
  padding: 18px 24px 16px;
  margin-right: 0;
  border-bottom: 1px solid #eef1f6;
}

.detail-dialog-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 700;
  color: #1a202c;
}

.detail-dialog-title .title-icon {
  color: #4f46e5;
}

.detail-dialog :deep(.el-dialog__body) {
  padding: 24px;
}

/* 用户信息卡片 */
.detail-card {
  background: linear-gradient(135deg, #f8fafc 0%, #eef2ff 100%);
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 24px;
}

.detail-card__user {
  display: flex;
  align-items: center;
  gap: 16px;
}

.detail-avatar {
  background: linear-gradient(135deg, #4f46e5, #7c3aed) !important;
  flex-shrink: 0;
}

.detail-card__meta {
  flex: 1;
  min-width: 0;
}

.detail-card__name {
  font-size: 17px;
  font-weight: 700;
  color: #1a202c;
  line-height: 1.3;
}

.detail-card__phone {
  font-size: 13px;
  color: #718096;
  margin-top: 3px;
}

.detail-card__badge {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 13px;
  font-weight: 600;
  color: #4a5568;
  background: #fff;
  padding: 6px 14px 6px 10px;
  border-radius: 20px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  white-space: nowrap;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  flex-shrink: 0;
}

.status-pending {
  background: #f59e0b;
  box-shadow: 0 0 0 3px rgba(245, 158, 11, 0.15);
}

.status-done {
  background: #10b981;
  box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.15);
}

/* 分区 */
.detail-section {
  margin-bottom: 22px;
}

.detail-section:last-child {
  margin-bottom: 0;
}

.detail-section__head {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  font-weight: 600;
  color: #4a5568;
  margin-bottom: 12px;
  padding-left: 2px;
}

.detail-section__head .el-icon {
  color: #4f46e5;
}

.detail-section__head.highlight {
  color: #059669;
}

.detail-section__head.highlight .el-icon {
  color: #10b981;
}

/* 信息网格 */
.detail-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 14px;
  background: #f8fafc;
  border-radius: 10px;
  padding: 16px 18px;
}

.detail-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.detail-label {
  font-size: 12px;
  font-weight: 500;
  color: #a0aec0;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.detail-value {
  font-size: 14px;
  font-weight: 500;
  color: #1a202c;
}

/* 内容文本 */
.detail-content-text {
  background: #f8fafc;
  border: 1px solid #eef1f6;
  border-radius: 10px;
  padding: 14px 16px;
  font-size: 14px;
  color: #4a5568;
  line-height: 1.7;
  white-space: pre-wrap;
  word-break: break-word;
}

.deal-text {
  background: #ecfdf5;
  border-color: #a7f3d0;
  color: #065f46;
}

/* 图片展示 */
.detail-images {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.detail-image-item {
  width: 80px;
  height: 80px;
  border-radius: 10px;
  overflow: hidden;
  cursor: pointer;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.06);
  transition: transform 0.2s, box-shadow 0.2s;
}

.detail-image-item:hover {
  transform: scale(1.05);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.detail-image-item .el-image {
  width: 100%;
  height: 100%;
  display: block;
}

/* 已处理分隔线 */
.detail-divider {
  height: 1px;
  background: linear-gradient(90deg, #e2e8f0 0%, transparent 100%);
  margin: 28px 0 24px;
}

/* 处理弹窗 */
.deal-content-text {
  padding: 10px 12px;
  background: #f5f7fa;
  border-radius: 6px;
  color: #606266;
  font-size: 13px;
  line-height: 1.6;
  max-height: 120px;
  overflow-y: auto;
}

.complaint-page {
  @include page-common-list;
}
</style>
