<template>
  <div class="change-request-list">
    <el-card shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-title">
            <el-icon class="title-icon" :size="22"><Document /></el-icon>
            <span>消耗记录删改申请</span>
          </div>
          <el-radio-group v-model="viewMode" size="small">
            <el-radio-button value="pending">待处理</el-radio-button>
            <el-radio-button value="processed">已处理</el-radio-button>
            <el-radio-button value="my">我的申请</el-radio-button>
          </el-radio-group>
        </div>
      </template>

      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="6" animated />
      </div>

      <template v-else>
        <!-- 待处理申请列表（上级查看下级的） -->
        <div v-if="viewMode === 'pending'">
          <el-empty v-if="pendingRequests.length === 0" description="暂无待处理的申请" />
          <el-table v-else :data="pendingRequests" stripe>
            <el-table-column label="申请时间" width="170" align="center">
              <template #default="{ row }">
                {{ formatDate(row.requestedAt) }}
              </template>
            </el-table-column>
            <el-table-column label="申请单位" width="120" align="center">
              <template #default="{ row }">
                {{ row.requestedByUnitName }}
              </template>
            </el-table-column>
            <el-table-column label="申请类型" width="100" align="center">
              <template #default="{ row }">
                <el-tag :type="row.requestType === 'Delete' ? 'danger' : 'warning'" size="small">
                  {{ row.requestType === 'Delete' ? '删除' : '修改' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="物资名称" width="120">
              <template #default="{ row }">
                {{ row.consumptionReport?.materialName || '-' }}
              </template>
            </el-table-column>
            <el-table-column label="上报数量" width="100" align="center">
              <template #default="{ row }">
                {{ row.consumptionReport?.reportedAmount }} {{ row.consumptionReport?.unit }}
              </template>
            </el-table-column>
            <el-table-column label="申请原因" min-width="150">
              <template #default="{ row }">
                {{ row.reason }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" align="center" fixed="right">
              <template #default="{ row }">
                <el-button type="success" size="small" @click="handleApprove(row)">
                  同意
                </el-button>
                <el-button type="danger" size="small" @click="handleReject(row)">
                  拒绝
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 已处理申请列表（上级已处理的下级申请） -->
        <div v-else-if="viewMode === 'processed'">
          <el-empty v-if="processedRequests.length === 0" description="暂无已处理的申请" />
          <el-table v-else :data="processedRequests" stripe>
            <el-table-column label="申请时间" width="170" align="center">
              <template #default="{ row }">
                {{ formatDate(row.requestedAt) }}
              </template>
            </el-table-column>
            <el-table-column label="申请单位" width="120" align="center">
              <template #default="{ row }">
                {{ row.requestedByUnitName }}
              </template>
            </el-table-column>
            <el-table-column label="申请类型" width="100" align="center">
              <template #default="{ row }">
                <el-tag :type="row.requestType === 'Delete' ? 'danger' : 'warning'" size="small">
                  {{ row.requestType === 'Delete' ? '删除' : '修改' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="物资名称" width="120">
              <template #default="{ row }">
                {{ row.consumptionReport?.materialName || '-' }}
              </template>
            </el-table-column>
            <el-table-column label="申请原因" min-width="120">
              <template #default="{ row }">
                {{ row.reason }}
              </template>
            </el-table-column>
            <el-table-column label="处理结果" width="100" align="center">
              <template #default="{ row }">
                <el-tag :type="getStatusTagType(row.status)" size="small">
                  {{ getStatusText(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="处理时间" width="170" align="center">
              <template #default="{ row }">
                {{ row.processedAt ? formatDate(row.processedAt) : '-' }}
              </template>
            </el-table-column>
            <el-table-column label="处理意见" min-width="120">
              <template #default="{ row }">
                {{ row.processComments || '-' }}
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 我的申请列表 -->
        <div v-else>
          <el-empty v-if="myRequests.length === 0" description="暂无申请记录" />
          <el-table v-else :data="myRequests" stripe>
            <el-table-column label="申请时间" width="170" align="center">
              <template #default="{ row }">
                {{ formatDate(row.requestedAt) }}
              </template>
            </el-table-column>
            <el-table-column label="申请类型" width="100" align="center">
              <template #default="{ row }">
                <el-tag :type="row.requestType === 'Delete' ? 'danger' : 'warning'" size="small">
                  {{ row.requestType === 'Delete' ? '删除' : '修改' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="申请原因" min-width="150">
              <template #default="{ row }">
                {{ row.reason }}
              </template>
            </el-table-column>
            <el-table-column label="状态" width="100" align="center">
              <template #default="{ row }">
                <el-tag :type="getStatusTagType(row.status)" size="small">
                  {{ getStatusText(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="处理时间" width="170" align="center">
              <template #default="{ row }">
                {{ row.processedAt ? formatDate(row.processedAt) : '-' }}
              </template>
            </el-table-column>
            <el-table-column label="处理单位" width="120" align="center">
              <template #default="{ row }">
                {{ row.processedByUnitName || '-' }}
              </template>
            </el-table-column>
            <el-table-column label="处理意见" min-width="150">
              <template #default="{ row }">
                {{ row.processComments || '-' }}
              </template>
            </el-table-column>
          </el-table>
        </div>
      </template>
    </el-card>

    <!-- 拒绝原因对话框 -->
    <el-dialog v-model="rejectDialogVisible" title="拒绝申请" width="400px">
      <el-form :model="rejectForm" label-width="80px">
        <el-form-item label="拒绝原因">
          <el-input
            v-model="rejectForm.comments"
            type="textarea"
            :rows="3"
            placeholder="请输入拒绝原因（可选）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="rejectDialogVisible = false">取消</el-button>
        <el-button type="danger" :loading="processing" @click="confirmReject">
          确认拒绝
        </el-button>
      </template>
    </el-dialog>

    <!-- 修改数据对话框 -->
    <el-dialog v-model="modifyDialogVisible" title="修改消耗记录" width="500px">
      <div v-if="selectedRequest?.consumptionReport" class="modify-info">
        <el-descriptions :column="1" border size="small">
          <el-descriptions-item label="物资名称">
            {{ selectedRequest.consumptionReport.materialName }}
          </el-descriptions-item>
          <el-descriptions-item label="原上报数量">
            {{ selectedRequest.consumptionReport.reportedAmount }} {{ selectedRequest.consumptionReport.unit }}
          </el-descriptions-item>
          <el-descriptions-item label="原备注">
            {{ selectedRequest.consumptionReport.remarks || '-' }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <el-form :model="modifyForm" label-width="100px" style="margin-top: 20px">
        <el-form-item label="新数量" required>
          <el-input-number
            v-model="modifyForm.newAmount"
            :min="0"
            :precision="2"
            style="width: 200px"
          />
          <span style="margin-left: 8px">{{ selectedRequest?.consumptionReport?.unit }}</span>
        </el-form-item>
        <el-form-item label="新备注">
          <el-input
            v-model="modifyForm.newRemarks"
            type="textarea"
            :rows="2"
            placeholder="请输入新备注（可选）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="modifyDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="processing" @click="confirmModify">
          确认修改
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Document } from '@element-plus/icons-vue'
import { changeRequestsApi, type ChangeRequest } from '@/api'

const loading = ref(false)
const processing = ref(false)
const viewMode = ref<'pending' | 'processed' | 'my'>('pending')
const pendingRequests = ref<ChangeRequest[]>([])
const processedRequests = ref<ChangeRequest[]>([])
const myRequests = ref<ChangeRequest[]>([])

const rejectDialogVisible = ref(false)
const modifyDialogVisible = ref(false)
const selectedRequest = ref<ChangeRequest | null>(null)
const rejectForm = reactive({ comments: '' })
const modifyForm = reactive({ newAmount: 0, newRemarks: '' })

function formatDate(dateStr: string): string {
  return new Date(dateStr).toLocaleString('zh-CN')
}

function getStatusTagType(status: string): 'success' | 'warning' | 'danger' | 'info' {
  switch (status) {
    case 'Approved': return 'success'
    case 'Rejected': return 'danger'
    case 'Pending': return 'warning'
    default: return 'info'
  }
}

function getStatusText(status: string): string {
  switch (status) {
    case 'Approved': return '已同意'
    case 'Rejected': return '已拒绝'
    case 'Pending': return '待处理'
    default: return status
  }
}

async function loadPendingRequests() {
  try {
    pendingRequests.value = await changeRequestsApi.getPending()
  } catch (error: any) {
    console.error('加载待处理申请失败', error)
  }
}

async function loadProcessedRequests() {
  try {
    processedRequests.value = await changeRequestsApi.getProcessed()
  } catch (error: any) {
    console.error('加载已处理申请失败', error)
  }
}

async function loadMyRequests() {
  try {
    myRequests.value = await changeRequestsApi.getMy()
  } catch (error: any) {
    console.error('加载我的申请失败', error)
  }
}

async function loadData() {
  loading.value = true
  try {
    await Promise.all([loadPendingRequests(), loadProcessedRequests(), loadMyRequests()])
  } finally {
    loading.value = false
  }
}

async function handleApprove(request: ChangeRequest) {
  if (request.requestType === 'Delete') {
    // 删除类型直接确认
    try {
      await ElMessageBox.confirm(
        '同意后将自动删除该消耗记录，确定同意吗？',
        '确认同意',
        { type: 'warning' }
      )
      processing.value = true
      await changeRequestsApi.process(request.id, { approved: true })
      ElMessage.success('已同意删除申请')
      await loadData()
    } catch (error: any) {
      if (error !== 'cancel') {
        ElMessage.error(error.response?.data?.message || '操作失败')
      }
    } finally {
      processing.value = false
    }
  } else {
    // 修改类型需要填写新数据
    selectedRequest.value = request
    modifyForm.newAmount = request.consumptionReport?.reportedAmount || 0
    modifyForm.newRemarks = request.consumptionReport?.remarks || ''
    modifyDialogVisible.value = true
  }
}

function handleReject(request: ChangeRequest) {
  selectedRequest.value = request
  rejectForm.comments = ''
  rejectDialogVisible.value = true
}

async function confirmReject() {
  if (!selectedRequest.value) return
  
  processing.value = true
  try {
    await changeRequestsApi.process(selectedRequest.value.id, {
      approved: false,
      comments: rejectForm.comments
    })
    ElMessage.success('已拒绝申请')
    rejectDialogVisible.value = false
    await loadData()
  } catch (error: any) {
    ElMessage.error(error.response?.data?.message || '操作失败')
  } finally {
    processing.value = false
  }
}

async function confirmModify() {
  if (!selectedRequest.value) return
  
  if (modifyForm.newAmount <= 0) {
    ElMessage.warning('新数量必须大于0')
    return
  }
  
  processing.value = true
  try {
    // 先同意申请
    await changeRequestsApi.process(selectedRequest.value.id, { approved: true })
    // 再执行修改
    await changeRequestsApi.modify(selectedRequest.value.id, {
      newAmount: modifyForm.newAmount,
      newRemarks: modifyForm.newRemarks
    })
    ElMessage.success('修改成功')
    modifyDialogVisible.value = false
    await loadData()
  } catch (error: any) {
    ElMessage.error(error.response?.data?.message || '操作失败')
  } finally {
    processing.value = false
  }
}

watch(viewMode, () => {
  // 切换视图时不需要重新加载，数据已经加载
})

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.change-request-list {
  padding: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.title-icon {
  margin-right: 8px;
  color: #409EFF;
}

.loading-container {
  padding: 20px;
}

.modify-info {
  margin-bottom: 16px;
}
</style>
