<template>
  <div class="min-h-screen bg-gray-100 dark:bg-gray-900">
    <!-- 顶部导航 -->
    <div class="bg-white dark:bg-gray-800 shadow">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4">
        <div class="flex justify-between items-center">
          <h1 class="text-2xl font-bold text-gray-900 dark:text-white">合同管理</h1>
          <div class="flex space-x-4">
            <button @click="showAddContractModal = true" class="bg-blue-600 text-white px-4 py-2 rounded-md hover:bg-blue-700">
              新增合同
            </button>
            <button @click="showApprovalModal = true" class="bg-yellow-600 text-white px-4 py-2 rounded-md hover:bg-yellow-700">
              合同审批
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <!-- 合同统计卡片 -->
      <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
          <div class="text-sm font-medium text-gray-500 dark:text-gray-400">总合同数</div>
          <div class="mt-2 text-3xl font-bold text-gray-900 dark:text-white">{{ totalContracts }}</div>
        </div>
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
          <div class="text-sm font-medium text-gray-500 dark:text-gray-400">待审批</div>
          <div class="mt-2 text-3xl font-bold text-yellow-600 dark:text-yellow-400">{{ pendingApproval }}</div>
        </div>
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
          <div class="text-sm font-medium text-gray-500 dark:text-gray-400">即将到期</div>
          <div class="mt-2 text-3xl font-bold text-red-600 dark:text-red-400">{{ expiringSoon }}</div>
        </div>
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
          <div class="text-sm font-medium text-gray-500 dark:text-gray-400">已到期</div>
          <div class="mt-2 text-3xl font-bold text-gray-600 dark:text-gray-400">{{ expired }}</div>
        </div>
      </div>

      <!-- 搜索和筛选 -->
      <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6 mb-6">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
          <div>
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">搜索</label>
            <input type="text" v-model="searchText" placeholder="合同编号/名称" class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">合同类型</label>
            <select v-model="filters.type" class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
              <option value="">所有类型</option>
              <option v-for="type in contractTypes" :key="type.id" :value="type.id">{{ type.name }}</option>
            </select>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">状态</label>
            <select v-model="filters.status" class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
              <option value="">所有状态</option>
              <option v-for="status in contractStatus" :key="status.id" :value="status.id">{{ status.name }}</option>
            </select>
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">部门</label>
            <select v-model="filters.department" class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
              <option value="">所有部门</option>
              <option v-for="dept in departments" :key="dept.id" :value="dept.id">{{ dept.name }}</option>
            </select>
          </div>
        </div>
      </div>

      <!-- 合同列表 -->
      <div class="bg-white dark:bg-gray-800 rounded-lg shadow overflow-hidden mb-6">
        <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
          <thead class="bg-gray-50 dark:bg-gray-700">
            <tr>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">合同信息</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">类型</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">金额</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">状态</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">操作</th>
            </tr>
          </thead>
          <tbody class="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
            <tr v-for="contract in filteredContracts" :key="contract.id">
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="text-sm font-medium text-gray-900 dark:text-white">{{ contract.contractNumber }}</div>
                <div class="text-sm text-gray-500 dark:text-gray-400">{{ contract.name }}</div>
                <div class="text-xs text-gray-500 dark:text-gray-400">
                  有效期: {{ formatDate(contract.startDate) }} - {{ formatDate(contract.endDate) }}
                </div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="text-sm text-gray-900 dark:text-white">{{ getContractTypeName(contract.type) }}</div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="text-sm text-gray-900 dark:text-white">¥{{ contract.amount }}</div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span :class="getStatusClass(contract.status)" class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full">
                  {{ getStatusName(contract.status) }}
                </span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                <button @click="viewContract(contract)" class="text-blue-600 hover:text-blue-900 dark:text-blue-400 dark:hover:text-blue-300 mr-3">查看</button>
                <button @click="editContract(contract)" class="text-yellow-600 hover:text-yellow-900 dark:text-yellow-400 dark:hover:text-yellow-300 mr-3">编辑</button>
                <button @click="deleteContract(contract)" class="text-red-600 hover:text-red-900 dark:text-red-400 dark:hover:text-red-300">删除</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <!-- 审批记录列表 -->
      <div class="bg-white dark:bg-gray-800 rounded-lg shadow overflow-hidden">
        <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
          <thead class="bg-gray-50 dark:bg-gray-700">
            <tr>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">审批信息</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">合同</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">审批人</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">状态</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">操作</th>
            </tr>
          </thead>
          <tbody class="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
            <tr v-for="approval in filteredApprovals" :key="approval.id">
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="text-sm font-medium text-gray-900 dark:text-white">{{ approval.approvalNumber }}</div>
                <div class="text-sm text-gray-500 dark:text-gray-400">
                  {{ formatDate(approval.date) }}
                </div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="text-sm text-gray-900 dark:text-white">{{ getContractName(approval.contractId) }}</div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="text-sm text-gray-900 dark:text-white">{{ approval.approver }}</div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span :class="getApprovalStatusClass(approval.status)" class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full">
                  {{ getApprovalStatusName(approval.status) }}
                </span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                <button @click="viewApproval(approval)" class="text-blue-600 hover:text-blue-900 dark:text-blue-400 dark:hover:text-blue-300 mr-3">查看</button>
                <button @click="editApproval(approval)" class="text-yellow-600 hover:text-yellow-900 dark:text-yellow-400 dark:hover:text-yellow-300 mr-3">编辑</button>
                <button @click="deleteApproval(approval)" class="text-red-600 hover:text-red-900 dark:text-red-400 dark:hover:text-red-300">删除</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 新增合同模态框 -->
    <div v-if="showAddContractModal" class="fixed inset-0 bg-gray-500 bg-opacity-75 flex items-center justify-center">
      <div class="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-md w-full p-6">
        <h2 class="text-xl font-bold mb-4 text-gray-900 dark:text-white">新增合同</h2>
        <form @submit.prevent="addContract">
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">合同编号</label>
            <input type="text" v-model="newContract.contractNumber" required class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
          </div>
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">合同名称</label>
            <input type="text" v-model="newContract.name" required class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
          </div>
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">合同类型</label>
            <select v-model="newContract.type" required class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
              <option v-for="type in contractTypes" :key="type.id" :value="type.id">{{ type.name }}</option>
            </select>
          </div>
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">合同金额</label>
            <input type="number" v-model="newContract.amount" required class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
          </div>
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">开始日期</label>
            <input type="date" v-model="newContract.startDate" required class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
          </div>
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">结束日期</label>
            <input type="date" v-model="newContract.endDate" required class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
          </div>
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">部门</label>
            <select v-model="newContract.department" required class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
              <option v-for="dept in departments" :key="dept.id" :value="dept.id">{{ dept.name }}</option>
            </select>
          </div>
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">备注</label>
            <textarea v-model="newContract.remarks" class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white"></textarea>
          </div>
          <div class="flex justify-end space-x-3">
            <button type="button" @click="showAddContractModal = false" class="px-4 py-2 border border-gray-300 rounded-md text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700">
              取消
            </button>
            <button type="submit" class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700">
              创建
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- 合同审批模态框 -->
    <div v-if="showApprovalModal" class="fixed inset-0 bg-gray-500 bg-opacity-75 flex items-center justify-center">
      <div class="bg-white dark:bg-gray-800 rounded-lg shadow-xl max-w-md w-full p-6">
        <h2 class="text-xl font-bold mb-4 text-gray-900 dark:text-white">合同审批</h2>
        <form @submit.prevent="addApproval">
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">审批编号</label>
            <input type="text" v-model="newApproval.approvalNumber" required class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
          </div>
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">合同</label>
            <select v-model="newApproval.contractId" required class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
              <option v-for="contract in contractList" :key="contract.id" :value="contract.id">{{ contract.name }}</option>
            </select>
          </div>
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">审批人</label>
            <input type="text" v-model="newApproval.approver" required class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white">
          </div>
          <div class="mb-4">
            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">审批意见</label>
            <textarea v-model="newApproval.comments" required class="w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600 dark:text-white"></textarea>
          </div>
          <div class="flex justify-end space-x-3">
            <button type="button" @click="showApprovalModal = false" class="px-4 py-2 border border-gray-300 rounded-md text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700">
              取消
            </button>
            <button type="submit" class="px-4 py-2 bg-yellow-600 text-white rounded-md hover:bg-yellow-700">
              提交
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'

// 合同数据
const contractList = ref([
  {
    id: 1,
    contractNumber: 'CT202403150001',
    name: '办公用品采购合同',
    type: 1,
    amount: 50000,
    startDate: '2024-03-15',
    endDate: '2025-03-14',
    department: 1,
    status: 1,
    remarks: '正常执行中'
  },
  {
    id: 2,
    contractNumber: 'CT202403150002',
    name: '设备维护服务合同',
    type: 2,
    amount: 30000,
    startDate: '2024-03-15',
    endDate: '2024-09-14',
    department: 2,
    status: 2,
    remarks: '待审批'
  }
])

// 审批记录数据
const approvalRecords = ref([
  {
    id: 1,
    approvalNumber: 'AP202403150001',
    contractId: 1,
    approver: '张三',
    date: '2024-03-15',
    status: 1,
    comments: '同意'
  },
  {
    id: 2,
    approvalNumber: 'AP202403150002',
    contractId: 2,
    approver: '李四',
    date: '2024-03-15',
    status: 2,
    comments: '待审核'
  }
])

// 合同类型
const contractTypes = ref([
  { id: 1, name: '采购合同' },
  { id: 2, name: '服务合同' },
  { id: 3, name: '租赁合同' }
])

// 合同状态
const contractStatus = ref([
  { id: 1, name: '执行中' },
  { id: 2, name: '待审批' },
  { id: 3, name: '已到期' }
])

// 审批状态
const approvalStatus = ref([
  { id: 1, name: '已通过' },
  { id: 2, name: '待审核' },
  { id: 3, name: '已拒绝' }
])

// 部门
const departments = ref([
  { id: 1, name: '行政部' },
  { id: 2, name: '生产部' },
  { id: 3, name: '销售部' }
])

// 筛选条件
const searchText = ref('')
const filters = ref({
  type: '',
  status: '',
  department: ''
})

// 模态框状态
const showAddContractModal = ref(false)
const showApprovalModal = ref(false)

// 新合同表单
const newContract = ref({
  contractNumber: '',
  name: '',
  type: '',
  amount: '',
  startDate: '',
  endDate: '',
  department: '',
  remarks: ''
})

// 新审批记录表单
const newApproval = ref({
  approvalNumber: '',
  contractId: '',
  approver: '',
  comments: ''
})

// 计算属性
const filteredContracts = computed(() => {
  return contractList.value.filter(item => {
    const matchesSearch = !searchText.value || 
      item.contractNumber.toLowerCase().includes(searchText.value.toLowerCase()) ||
      item.name.toLowerCase().includes(searchText.value.toLowerCase())
    const matchesType = !filters.value.type || item.type === filters.value.type
    const matchesStatus = !filters.value.status || item.status === filters.value.status
    const matchesDepartment = !filters.value.department || item.department === filters.value.department
    return matchesSearch && matchesType && matchesStatus && matchesDepartment
  })
})

const filteredApprovals = computed(() => {
  return approvalRecords.value.filter(item => {
    const contract = contractList.value.find(c => c.id === item.contractId)
    const matchesSearch = !searchText.value || 
      item.approvalNumber.toLowerCase().includes(searchText.value.toLowerCase()) ||
      (contract && contract.name.toLowerCase().includes(searchText.value.toLowerCase()))
    return matchesSearch
  })
})

const totalContracts = computed(() => contractList.value.length)
const pendingApproval = computed(() => contractList.value.filter(item => item.status === 2).length)
const expiringSoon = computed(() => {
  const today = new Date()
  const thirtyDaysLater = new Date(today)
  thirtyDaysLater.setDate(today.getDate() + 30)
  return contractList.value.filter(item => {
    const endDate = new Date(item.endDate)
    return endDate > today && endDate <= thirtyDaysLater
  }).length
})
const expired = computed(() => {
  const today = new Date()
  return contractList.value.filter(item => new Date(item.endDate) < today).length
})

// 格式化日期
const formatDate = (date) => {
  return new Date(date).toLocaleDateString('zh-CN')
}

// 获取合同类型名称
const getContractTypeName = (typeId) => {
  const type = contractTypes.value.find(t => t.id === typeId)
  return type ? type.name : '未知类型'
}

// 获取合同状态名称
const getStatusName = (statusId) => {
  const status = contractStatus.value.find(s => s.id === statusId)
  return status ? status.name : '未知状态'
}

// 获取审批状态名称
const getApprovalStatusName = (statusId) => {
  const status = approvalStatus.value.find(s => s.id === statusId)
  return status ? status.name : '未知状态'
}

// 获取部门名称
const getDepartmentName = (departmentId) => {
  const department = departments.value.find(d => d.id === departmentId)
  return department ? department.name : '未知部门'
}

// 获取合同名称
const getContractName = (contractId) => {
  const contract = contractList.value.find(c => c.id === contractId)
  return contract ? contract.name : '未知合同'
}

// 获取状态样式
const getStatusClass = (statusId) => {
  const classes = {
    1: 'bg-green-100 text-green-800 dark:bg-green-700 dark:text-green-300',
    2: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-700 dark:text-yellow-300',
    3: 'bg-red-100 text-red-800 dark:bg-red-700 dark:text-red-300'
  }
  return classes[statusId] || 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300'
}

// 获取审批状态样式
const getApprovalStatusClass = (statusId) => {
  const classes = {
    1: 'bg-green-100 text-green-800 dark:bg-green-700 dark:text-green-300',
    2: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-700 dark:text-yellow-300',
    3: 'bg-red-100 text-red-800 dark:bg-red-700 dark:text-red-300'
  }
  return classes[statusId] || 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-300'
}

// 添加合同
const addContract = () => {
  const item = {
    id: contractList.value.length + 1,
    ...newContract.value,
    status: 2 // 默认为待审批状态
  }
  contractList.value.push(item)
  showAddContractModal.value = false
  resetNewContract()
}

// 重置新合同表单
const resetNewContract = () => {
  newContract.value = {
    contractNumber: '',
    name: '',
    type: '',
    amount: '',
    startDate: '',
    endDate: '',
    department: '',
    remarks: ''
  }
}

// 添加审批记录
const addApproval = () => {
  const item = {
    id: approvalRecords.value.length + 1,
    ...newApproval.value,
    date: new Date().toISOString().split('T')[0],
    status: 2 // 默认为待审核状态
  }
  approvalRecords.value.push(item)
  showApprovalModal.value = false
  resetNewApproval()
}

// 重置新审批记录表单
const resetNewApproval = () => {
  newApproval.value = {
    approvalNumber: '',
    contractId: '',
    approver: '',
    comments: ''
  }
}

// 查看合同
const viewContract = (item) => {
  // 实现查看合同逻辑
  console.log('查看合同:', item)
}

// 编辑合同
const editContract = (item) => {
  // 实现编辑合同逻辑
  console.log('编辑合同:', item)
}

// 删除合同
const deleteContract = (item) => {
  if (confirm(`确定要删除合同 ${item.contractNumber} 吗？`)) {
    const index = contractList.value.findIndex(c => c.id === item.id)
    if (index !== -1) {
      contractList.value.splice(index, 1)
    }
  }
}

// 查看审批记录
const viewApproval = (item) => {
  // 实现查看审批记录逻辑
  console.log('查看审批记录:', item)
}

// 编辑审批记录
const editApproval = (item) => {
  // 实现编辑审批记录逻辑
  console.log('编辑审批记录:', item)
}

// 删除审批记录
const deleteApproval = (item) => {
  if (confirm(`确定要删除审批记录 ${item.approvalNumber} 吗？`)) {
    const index = approvalRecords.value.findIndex(a => a.id === item.id)
    if (index !== -1) {
      approvalRecords.value.splice(index, 1)
    }
  }
}
</script> 