<template>
  <PageShell>
    <div class="post-page">
      <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
        <div v-show="showSearch" class="search-panel">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" class="search-form">
            <el-form-item prop="postName" class="search-form-item search-keyword-item">
              <el-input v-model="queryParams.postName" placeholder="请输入岗位" clearable @keyup.enter="handleQuery">
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item class="search-form-item search-action-item">
              <el-button type="primary" icon="Search" @click="handleQuery" />
            </el-form-item>
            <el-form-item prop="applyStatus" class="search-form-item search-select-item">
              <el-select v-model="queryParams.applyStatus" placeholder="审核状态" clearable>
                <el-option v-for="item in auditStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item prop="postType" class="search-form-item search-select-item">
              <el-select v-model="queryParams.postType" placeholder="岗位类型" clearable>
                <el-option v-for="item in postTypeOptions" :key="item" :label="item" :value="item" />
              </el-select>
            </el-form-item>
            <el-form-item prop="postLevel" class="search-form-item search-select-item">
              <el-select v-model="queryParams.postLevel" placeholder="岗位级别" clearable>
                <el-option v-for="item in postCategoryOptions" :key="item" :label="item" :value="item" />
              </el-select>
            </el-form-item>
          </el-form>
        </div>
      </transition>

      <div class="post-card">
        <div class="table-toolbar">
          <div class="page-title">岗位列表</div>
          <div class="toolbar-actions">
            <el-button v-hasPermi="['system:post:add']" type="primary" icon="Plus" @click="handleAdd">添加</el-button>
            <el-button v-hasPermi="['system:post:export']" icon="Download" @click="handleImportOpen">批量导入</el-button>
            <el-button v-hasPermi="['system:post:remove']" :disabled="multiple" icon="Delete" @click="handleDelete()">批量删除</el-button>
          </div>
        </div>

        <el-table v-loading="loading" border :data="postList" class="post-table" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="岗位名称" align="center" prop="postName" min-width="140" />
          <el-table-column label="岗位类型" align="center" prop="postType" min-width="120">
            <template #default="scope">
              <span>{{ scope.row.postType || '--' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="岗位级别" align="center" prop="postLevel" min-width="120">
            <template #default="scope">
              <span>{{ scope.row.postLevel || '--' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="审核状态" align="center" min-width="180">
            <template #default="scope">
              <div class="audit-status-cell">
                <el-tag
                  v-if="getAuditStatusMeta(getAuditStatusText(scope.row.applyStatus))"
                  :type="getAuditStatusMeta(getAuditStatusText(scope.row.applyStatus))?.type"
                  effect="dark"
                >
                  {{ getAuditStatusMeta(getAuditStatusText(scope.row.applyStatus))?.label }}
                </el-tag>
                <span v-else class="audit-status-empty"></span>
                <el-button
                  v-if="showAuditRemark(getAuditStatusText(scope.row.applyStatus))"
                  link
                  type="primary"
                  class="audit-remark-button"
                  @click="handleOpenAuditRemark(scope.row)"
                >
                  说明
                </el-button>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="岗位人数" align="center" min-width="100">
            <template #default="scope">
              <span>{{ scope.row.recruitNum ?? '--' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="报名人数" align="center" min-width="100">
            <template #default="scope">
              <el-button link type="primary" @click="handleOpenApplyList(scope.row)">0</el-button>
            </template>
          </el-table-column>
          <el-table-column label="发布状态" align="center" min-width="100">
            <template #default="scope">
              <el-switch
                :model-value="scope.row.status === '0'"
                inline-prompt
                active-text="开"
                inactive-text="关"
                :disabled="scope.row.applyStatus !== 2 || publishLoadingMap[String(scope.row.id)]"
                @change="handlePublishChange(scope.row, $event)"
              />
            </template>
          </el-table-column>
          <el-table-column label="添加时间" align="center" prop="createTime" min-width="180">
            <template #default="scope">
              <span>{{ proxy?.parseTime(scope.row.createTime) || '--' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="180" align="center">
            <template #default="scope">
              <el-button v-if="scope.row.applyStatus !== 0" link type="primary" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button v-hasPermi="['system:post:remove']" link type="primary" @click="handleDelete(scope.row)">删除</el-button>
            </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" />
      </div>

      <el-dialog v-model="auditRemarkDialog.visible" title="审核状态说明" width="520px" append-to-body>
        <div class="audit-remark-content">
          <div class="audit-remark-item">
            <span class="audit-remark-label">审核状态</span>
            <span class="audit-remark-value">{{ auditRemarkDialog.data.auditStatus || '--' }}</span>
          </div>
          <div class="audit-remark-item align-start">
            <span class="audit-remark-label">说明</span>
            <div class="audit-remark-value remark-text">{{ auditRemarkDialog.data.auditRemark || '暂无说明' }}</div>
          </div>
        </div>
      </el-dialog>

      <el-dialog v-model="importDialog.visible" :title="importDialog.title" width="420px" append-to-body>
        <div class="import-notice">
          <span class="import-notice-text">首次导入先下载导入模板。</span>
          <el-link type="primary" :underline="false" class="import-notice-link" @click="handleDownloadImportTemplate">立即下载</el-link>
        </div>
        <el-upload :limit="1" accept=".xlsx,.xls" :auto-upload="false" drag>
          <el-icon class="el-icon--upload">
            <i-ep-upload-filled />
          </el-icon>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <template #tip>
            <div class="el-upload__tip import-upload-tip">
              <span>仅允许导入 xls、xlsx 格式文件。</span>
            </div>
          </template>
        </el-upload>
        <template #footer>
          <div class="dialog-footer import-dialog-footer">
            <el-link type="primary" :underline="false" class="import-template-link" @click="handleDownloadImportTemplate">模板下载</el-link>
            <div class="import-dialog-actions">
              <el-button type="primary" @click="submitImportForm">确 定</el-button>
              <el-button @click="importDialog.visible = false">取 消</el-button>
            </div>
          </div>
        </template>
      </el-dialog>
    </div>
  </PageShell>
</template>

<script setup name="Post" lang="ts">
import { getCurrentInstance, onMounted, reactive, ref, type ComponentInternalInstance } from 'vue';
import { useRouter } from 'vue-router';
import { getMainAudit, listMainAudit } from '@/api/main/audit';
import PageShell from '@/components/PageShell/index.vue';
import { delPostManage, listPostManage, publishPostManage, unpublishPostManage } from '@/api/main/postManage';
import { MainPostApplyQuery, MainPostApplyVO } from '@/api/main/postManage/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const router = useRouter();
const modal = proxy?.$modal as any;

type AuditTagType = 'primary' | 'warning' | 'danger';
type PostAuditRemarkVO = {
  auditStatus?: string;
  auditRemark?: string;
};

const postList = ref<MainPostApplyVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<number | string>>([]);
const multiple = ref(true);
const total = ref(0);
const publishLoadingMap = reactive<Record<string, boolean>>({});
const postCategoryOptions = ref<string[]>([]);
const postTypeOptions = ref<string[]>([]);
const queryFormRef = ref<ElFormInstance>();
const auditStatusOptions = [
  { label: '待审核', value: 0 },
  { label: '审核中', value: 1 },
  { label: '审核通过', value: 2 },
  { label: '驳回', value: 3 }
];

const importDialog = reactive<DialogOption>({
  visible: false,
  title: '批量导入'
});

const auditRemarkDialog = reactive<{ visible: boolean; data: PostAuditRemarkVO }>({
  visible: false,
  data: {
    auditStatus: '',
    auditRemark: ''
  }
});

const auditStatusMap: Record<string, { label: string; type: AuditTagType }> = {
  pending: { label: '待审核', type: 'warning' },
  approved: { label: '审核通过', type: 'primary' },
  processing: { label: '审核中', type: 'warning' },
  rejected: { label: '驳回', type: 'danger' },
  '待审核': { label: '待审核', type: 'warning' },
  '审核通过': { label: '审核通过', type: 'primary' },
  '审核中': { label: '审核中', type: 'warning' },
  '驳回': { label: '驳回', type: 'danger' }
};

const queryParams = reactive<MainPostApplyQuery>({
  pageNum: 1,
  pageSize: 10,
  applyStatus: undefined,
  postName: '',
  postType: '',
  postLevel: ''
});

const normalizeAuditStatus = (status?: string) => (status || '').trim();

const getAuditStatusMeta = (status?: string) => {
  const normalizedStatus = normalizeAuditStatus(status);
  return normalizedStatus ? auditStatusMap[normalizedStatus] : undefined;
};

const getAuditStatusText = (status?: number) => {
  switch (status) {
    case 2:
      return '审核通过';
    case 3:
      return '驳回';
    case 1:
      return '审核中';
    case 0:
    default:
      return '待审核';
  }
};

const showAuditRemark = (status?: string) => {
  const normalizedStatus = normalizeAuditStatus(status);
  return normalizedStatus === '审核通过' || normalizedStatus === 'approved' || normalizedStatus === '驳回' || normalizedStatus === 'rejected';
};

/** 查询岗位列表 */
const getList = async () => {
  loading.value = true;
  try {
    const res = await listPostManage(queryParams);
    postList.value = res.rows;
    total.value = res.total;
    postTypeOptions.value = Array.from(new Set(res.rows.map((item) => item.postType).filter(Boolean) as string[]));
    postCategoryOptions.value = Array.from(new Set(res.rows.map((item) => item.postLevel).filter(Boolean) as string[]));
  } finally {
    loading.value = false;
  }
};

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields?.();
  queryParams.pageNum = 1;
  queryParams.applyStatus = undefined;
  queryParams.postName = '';
  queryParams.postType = '';
  queryParams.postLevel = '';
  handleQuery();
};

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

/** 新增按钮操作 */
const handleAdd = () => {
  router.push('/postManage/create');
};

const handleEdit = (row: MainPostApplyVO) => {
  router.push({
    path: '/postManage/create',
    query: {
      id: String(row.id)
    }
  });
};

const handleOpenApplyList = (row: MainPostApplyVO) => {
  router.push({
    path: '/postManage/apply-list',
    query: {
      postId: String(row.postId ?? row.id ?? ''),
      applyId: String(row.id ?? ''),
      postName: row.postName || ''
    }
  });
};

const handlePublishChange = async (row: MainPostApplyVO, value: boolean | string | number) => {
  const rowKey = String(row.id);
  try {
    publishLoadingMap[rowKey] = true;
    if (Boolean(value)) {
      await publishPostManage(row.id);
      modal?.msgSuccess('发布成功');
    } else {
      await unpublishPostManage(row.id);
      modal?.msgSuccess('取消发布成功');
    }
    await getList();
  } finally {
    publishLoadingMap[rowKey] = false;
  }
};

const handleOpenAuditRemark = async (row: MainPostApplyVO) => {
  let auditRemark = row.rejectReason || '';

  if (row.auditId) {
    const auditRes = await getMainAudit(row.auditId);
    auditRemark = auditRes.data?.auditRemark || auditRemark;
  } else if (row.id) {
    const auditListRes = await listMainAudit({
      pageNum: 1,
      pageSize: 1,
      auditType: 2,
      targetId: row.id
    });
    auditRemark = auditListRes.rows?.[0]?.auditRemark || auditRemark;
  }

  auditRemarkDialog.data = {
    auditStatus: getAuditStatusText(row.applyStatus),
    auditRemark
  };
  auditRemarkDialog.visible = true;
};

/** 删除按钮操作 */
const handleDelete = async (row?: MainPostApplyVO) => {
  const postIds = row?.id || ids.value;
  await modal?.confirm('是否确认删除岗位编号为"' + postIds + '"的数据项？');
  await delPostManage(postIds);
  await getList();
  modal?.msgSuccess('删除成功');
};

const handleImportOpen = () => {
  importDialog.visible = true;
};

const submitImportForm = () => {
  importDialog.visible = false;
};

const handleDownloadImportTemplate = () => {
  modal?.msgSuccess('待接入模板下载');
};

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

<style scoped>
.post-page {
  min-height: 100%;
}

.search-panel {
  margin-bottom: 14px;
}

.search-form {
  display: flex;
  align-items: center;
  gap: 6px;
  flex-wrap: wrap;
}

.search-form-item {
  margin-bottom: 0;
}

.search-keyword-item {
  width: 280px;
}

.search-keyword-item :deep(.el-input__wrapper) {
  border-radius: 4px 0 0 4px;
}

.search-select-item {
  width: 160px;
}

.search-action-item :deep(.el-button) {
  width: 40px;
  padding: 0;
  margin-left: -80px;
  border-radius: 0 4px 4px 0;
}

.post-card {
  display: flex;
  flex-direction: column;
  min-height: calc(100vh - 220px);
  padding: 12px 16px 16px;
  background: #fff;
  border-radius: 4px;
}

.table-toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  margin-bottom: 14px;
}

.page-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.toolbar-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.post-table :deep(.el-table__header th) {
  background: #f5f5f5;
  color: #303133;
  font-weight: 600;
}

.post-table :deep(.el-button.is-link) {
  padding: 0 6px;
}

.post-card :deep(.pagination-container) {
  display: flex;
  justify-content: center;
  margin-top: auto;
  padding-top: 16px;
}

.audit-status-cell {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  min-height: 24px;
}

.audit-status-empty {
  display: inline-block;
  width: 12px;
}

.audit-remark-button {
  padding: 0;
}

.audit-remark-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.audit-remark-item {
  display: flex;
  align-items: center;
  gap: 12px;
}

.audit-remark-item.align-start {
  align-items: flex-start;
}

.audit-remark-label {
  width: 72px;
  color: #606266;
  flex-shrink: 0;
}

.audit-remark-value {
  color: #303133;
}

.remark-text {
  white-space: pre-wrap;
  word-break: break-all;
  line-height: 22px;
}

.import-notice {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
  padding: 10px 12px;
  color: #1677ff;
  background: #edf5ff;
  border-radius: 6px;
  line-height: 20px;
  text-align: left;
}

.import-upload-tip {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 6px;
  margin-top: 8px;
  padding-left: 2px;
}

.import-template-link {
  font-size: 12px;
  line-height: 20px;
}

.import-dialog-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.import-dialog-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.import-notice-text {
  color: #1677ff;
}

.import-notice-link {
  font-size: 12px;
  flex-shrink: 0;
}
</style>
