<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { approvalApi, approvalTemplateApi } from '@/api/office.js'

const tableData = ref([])
const total = ref(0)
const loading = ref(false)
const dialogVisible = ref(false)
const detailVisible = ref(false)
const rejectDialogVisible = ref(false)
const submitLoading = ref(false)

const searchForm = reactive({ status: '' })
const pagination = reactive({ page: 1, per_page: 20 })

const formRef = ref(null)
const form = reactive({ title: '', template_id: '', form_data: '' })
const templates = ref([])

const currentDetail = ref(null)
const rejectForm = reactive({ comment: '' })
const rejectTargetRow = ref(null)

const statusMap = { 0: '待审批', 1: '审批中', 2: '已通过', 3: '已驳回', 4: '已撤回' }
const statusType = { 0: 'warning', 1: 'primary', 2: 'success', 3: 'danger', 4: 'info' }
const nodeActionMap = { 0: '待处理', 1: '已通过', 2: '已驳回' }

const formRules = {
  title: [{ required: true, message: '请输入审批标题', trigger: 'blur' }]
}

async function fetchList() {
  loading.value = true
  try {
    const res = await approvalApi.getList({ ...searchForm, ...pagination })
    tableData.value = res.data?.list || res.data?.data || []
    total.value = res.data?.total || 0
  } finally { loading.value = false }
}

async function fetchTemplates() {
  try {
    const res = await approvalTemplateApi.getList({ per_page: 100, status: 1 })
    templates.value = res.data?.list || res.data?.data || []
  } catch { /* ignore */ }
}

function handleSearch() { pagination.page = 1; fetchList() }
function handleReset() {
  Object.assign(searchForm, { status: '' })
  handleSearch()
}

function handleAdd() {
  Object.assign(form, { title: '', template_id: '', form_data: '' })
  dialogVisible.value = true
}

async function handleSubmit() {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    submitLoading.value = true
    try {
      const payload = { ...form }
      if (payload.form_data) {
        try { payload.form_data = JSON.parse(payload.form_data) } catch { /* keep string */ }
      }
      if (!payload.template_id) delete payload.template_id
      await approvalApi.create(payload)
      ElMessage.success('提交成功，审批节点已自动创建')
      dialogVisible.value = false
      fetchList()
    } finally { submitLoading.value = false }
  })
}

async function handleShowDetail(row) {
  try {
    const res = await approvalApi.getDetail(row.id)
    currentDetail.value = res.data
    detailVisible.value = true
  } catch {
    ElMessage.error('加载详情失败')
  }
}

async function handleApprove(row) {
  await ElMessageBox.confirm('确定通过该审批节点吗？', '审批确认', { type: 'warning' })
  await approvalApi.approve(row.id, {})
  ElMessage.success('审批已通过')
  fetchList()
}

function handleRejectOpen(row) {
  rejectTargetRow.value = row
  rejectForm.comment = ''
  rejectDialogVisible.value = true
}

async function handleRejectSubmit() {
  if (!rejectTargetRow.value) return
  await approvalApi.reject(rejectTargetRow.value.id, { comment: rejectForm.comment })
  ElMessage.success('审批已驳回')
  rejectDialogVisible.value = false
  fetchList()
}

async function handleWithdraw(row) {
  await ElMessageBox.confirm('确定撤回该审批吗？', '撤回确认', { type: 'warning' })
  await approvalApi.withdraw(row.id)
  ElMessage.success('审批已撤回')
  fetchList()
}

function getStepStatus(node, currentNode) {
  if (node.node_order < currentNode) {
    return node.action === 2 ? 'error' : 'finish'
  }
  if (node.node_order === currentNode) {
    return node.action === 0 ? 'process' : node.action === 1 ? 'finish' : 'error'
  }
  return 'wait'
}

function sortedNodes(nodes) {
  return [...(nodes || [])].sort((a, b) => a.node_order - b.node_order)
}

function handlePageChange(val) { pagination.page = val; fetchList() }
function handleSizeChange(val) { pagination.per_page = val; pagination.page = 1; fetchList() }

onMounted(() => { fetchList(); fetchTemplates() })
</script>

<template>
  <div class="p-6 space-y-4">
    <!-- 搜索栏 -->
    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm p-4 flex items-center flex-wrap gap-3">
      <el-select v-model="searchForm.status" placeholder="审批状态" clearable style="width:140px">
        <el-option v-for="(v, k) in statusMap" :key="k" :label="v" :value="Number(k)" />
      </el-select>
      <el-button type="primary" @click="handleSearch">查询</el-button>
      <el-button @click="handleReset">重置</el-button>
    </div>

    <!-- 列表 -->
    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm">
      <div class="flex items-center justify-between px-5 py-4 border-b border-gray-50">
        <span class="font-medium text-gray-700">审批列表</span>
        <el-button type="primary" @click="handleAdd">发起审批</el-button>
      </div>
      <div class="px-2">
        <el-table v-loading="loading" :data="tableData" style="width:100%">
          <el-table-column label="标题" min-width="200">
            <template #default="{ row }">
              <el-button type="primary" link @click="handleShowDetail(row)">{{ row.title }}</el-button>
            </template>
          </el-table-column>
          <el-table-column label="申请人" min-width="100">
            <template #default="{ row }">{{ row.applicant?.name || '-' }}</template>
          </el-table-column>
          <el-table-column label="审批模板" min-width="120">
            <template #default="{ row }">{{ row.template?.name || '无模板' }}</template>
          </el-table-column>
          <el-table-column label="当前节点" width="90" align="center">
            <template #default="{ row }">第 {{ row.current_node || 1 }} 级</template>
          </el-table-column>
          <el-table-column label="状态" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="statusType[row.status]" size="small">{{ statusMap[row.status] }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="created_at" label="创建时间" min-width="160" />
          <el-table-column label="操作" width="230" fixed="right" align="center">
            <template #default="{ row }">
              <el-button size="small" text @click="handleShowDetail(row)">详情</el-button>
              <template v-if="row.status <= 1">
                <el-button size="small" type="success" text @click="handleApprove(row)">通过</el-button>
                <el-button size="small" type="danger" text @click="handleRejectOpen(row)">驳回</el-button>
                <el-button size="small" type="warning" text @click="handleWithdraw(row)">撤回</el-button>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="px-5 py-3 border-t border-gray-50">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.per_page"
          :total="total"
          :page-sizes="[10,20,50]"
          layout="total,sizes,prev,pager,next,jumper"
          background
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>

    <!-- 发起审批弹窗 -->
    <el-dialog v-model="dialogVisible" title="发起审批" width="600px" destroy-on-close>
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="100px">
        <el-form-item label="审批标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入审批标题" />
        </el-form-item>
        <el-form-item label="审批模板">
          <el-select v-model="form.template_id" placeholder="请选择审批模板（可选，选择后自动生成多级审批节点）" clearable style="width:100%">
            <el-option v-for="t in templates" :key="t.id" :label="t.name" :value="t.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="表单数据">
          <el-input v-model="form.form_data" type="textarea" :rows="3" placeholder="JSON格式（可选）" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">提交</el-button>
      </template>
    </el-dialog>

    <!-- 审批详情弹窗（含多级节点进度） -->
    <el-dialog v-model="detailVisible" title="审批详情" width="700px" destroy-on-close>
      <template v-if="currentDetail">
        <el-descriptions :column="2" border class="mb-5">
          <el-descriptions-item label="审批标题" :span="2">{{ currentDetail.title }}</el-descriptions-item>
          <el-descriptions-item label="申请人">{{ currentDetail.applicant?.name || '-' }}</el-descriptions-item>
          <el-descriptions-item label="审批模板">{{ currentDetail.template?.name || '无模板' }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="statusType[currentDetail.status]" size="small">{{ statusMap[currentDetail.status] }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="当前节点">第 {{ currentDetail.current_node || 1 }} 级</el-descriptions-item>
          <el-descriptions-item label="创建时间" :span="2">{{ currentDetail.created_at }}</el-descriptions-item>
        </el-descriptions>

        <!-- 审批节点进度 -->
        <div class="font-medium text-gray-700 mb-3">审批流程进度</div>
        <div v-if="currentDetail.nodes && currentDetail.nodes.length">
          <el-steps
            direction="vertical"
            :active="currentDetail.current_node"
            space="80px"
          >
            <el-step
              v-for="node in sortedNodes(currentDetail.nodes)"
              :key="node.id"
              :title="node.node_label || `第${node.node_order}级审批`"
              :status="getStepStatus(node, currentDetail.current_node)"
            >
              <template #description>
                <div class="text-sm space-y-1 py-1 text-gray-500">
                  <div>审批人：<span class="text-gray-700">{{ node.approver?.name || (node.role ? `[${node.role}角色]` : '待指定') }}</span></div>
                  <div>
                    状态：
                    <el-tag size="small" :type="node.action === 1 ? 'success' : node.action === 2 ? 'danger' : 'info'">
                      {{ nodeActionMap[node.action] || '-' }}
                    </el-tag>
                  </div>
                  <div v-if="node.comment">意见：<span class="text-gray-700">{{ node.comment }}</span></div>
                  <div v-if="node.acted_at" class="text-xs text-gray-400">操作时间：{{ node.acted_at }}</div>
                </div>
              </template>
            </el-step>
          </el-steps>
        </div>
        <el-empty v-else description="暂无审批节点（提交后自动按模板生成）" :image-size="60" />
      </template>
      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 驳回意见弹窗 -->
    <el-dialog v-model="rejectDialogVisible" title="驳回审批" width="460px" destroy-on-close>
      <el-form label-width="80px">
        <el-form-item label="驳回意见">
          <el-input v-model="rejectForm.comment" type="textarea" :rows="3" placeholder="请输入驳回意见（可选）" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="rejectDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="handleRejectSubmit">确认驳回</el-button>
      </template>
    </el-dialog>
  </div>
</template>
