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

const tableData = ref([])
const total = ref(0)
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('新增合同')
const submitLoading = ref(false)
const auditVisible = ref(false)
const currentContract = ref(null)
const customers = ref([])

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

const formRef = ref(null)
const form = reactive({
  id: null, customer_id: '', contract_no: '', package_name: '',
  total_amount: 0, discount_amount: 0, actual_amount: 0,
  days: '', check_in_date: '', check_out_date: '', remark: ''
})
const isEdit = ref(false)
const formRules = {
  customer_id: [{ required: true, message: '请选择客户', trigger: 'change' }],
  contract_no: [{ required: true, message: '请输入合同编号', trigger: 'blur' }],
  total_amount: [{ required: true, message: '请输入总金额', trigger: 'blur' }],
  actual_amount: [{ required: true, message: '请输入实付金额', trigger: 'blur' }]
}

const auditForm = reactive({ status: 1, audit_remark: '' })
const statusMap = { 0: '待审核', 1: '已通过', 2: '无效', 3: '已退' }
const statusType = { 0: 'warning', 1: 'success', 2: 'danger', 3: 'info' }

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

async function fetchCustomers() {
  try {
    const res = await customerApi.getList({ per_page: 500 })
    customers.value = res.data?.list || res.data?.data || []
  } catch {}
}

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

function handleAdd() {
  isEdit.value = false; dialogTitle.value = '新增合同'
  Object.assign(form, { id: null, customer_id: '', contract_no: '', package_name: '', total_amount: 0, discount_amount: 0, actual_amount: 0, days: '', check_in_date: '', check_out_date: '', remark: '' })
  dialogVisible.value = true
}

async function handleEdit(row) {
  if (row.status !== 0) { ElMessage.warning('只能编辑待审核合同'); return }
  isEdit.value = true; dialogTitle.value = '编辑合同'
  const res = await contractApi.getDetail(row.id)
  const d = res.data
  Object.assign(form, { id: d.id, customer_id: d.customer_id, contract_no: d.contract_no, package_name: d.package_name || '', total_amount: d.total_amount, discount_amount: d.discount_amount, actual_amount: d.actual_amount, days: d.days || '', check_in_date: d.check_in_date || '', check_out_date: d.check_out_date || '', remark: d.remark || '' })
  dialogVisible.value = true
}

async function handleSubmit() {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    submitLoading.value = true
    try {
      if (isEdit.value) { await contractApi.update(form.id, form); ElMessage.success('更新成功') }
      else { await contractApi.create(form); ElMessage.success('创建成功') }
      dialogVisible.value = false; fetchList()
    } finally { submitLoading.value = false }
  })
}

async function handleDelete(row) {
  if (row.status !== 0) { ElMessage.warning('只能删除待审核合同'); return }
  await ElMessageBox.confirm('确定删除该合同吗？', '删除确认', { type: 'warning' })
  await contractApi.delete(row.id); ElMessage.success('删除成功'); fetchList()
}

function openAudit(row) {
  currentContract.value = row
  Object.assign(auditForm, { status: 1, audit_remark: '' })
  auditVisible.value = true
}

async function submitAudit() {
  await contractApi.audit(currentContract.value.id, auditForm)
  ElMessage.success('审核完成')
  auditVisible.value = false; fetchList()
}

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

onMounted(() => { fetchList(); fetchCustomers() })
</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-input v-model="searchForm.contract_no" placeholder="合同编号" style="width:180px" clearable @keydown.enter="handleSearch" />
      <el-select v-model="searchForm.customer_id" placeholder="选择客户" clearable filterable style="width:180px">
        <el-option v-for="c in customers" :key="c.id" :label="`${c.name} (${c.phone})`" :value="c.id" />
      </el-select>
      <el-select v-model="searchForm.status" placeholder="状态" clearable style="width:120px">
        <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">
        <div class="flex items-center gap-3">
          <span class="font-medium text-gray-700">合同列表</span>
        </div>
        <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 prop="contract_no" label="合同编号" min-width="150" />
          <el-table-column label="客户" min-width="100"><template #default="{ row }">{{ row.customer?.name || '-' }}</template></el-table-column>
          <el-table-column prop="package_name" label="套餐" min-width="120" />
          <el-table-column prop="actual_amount" label="实付金额" min-width="110" align="right" />
          <el-table-column prop="days" label="天数" width="70" align="center" />
          <el-table-column prop="check_in_date" label="入住日期" min-width="110" />
          <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 label="操作" width="200" fixed="right" align="center">
            <template #default="{ row }">
              <el-button v-if="row.status===0" size="small" type="success" text @click="openAudit(row)">审核</el-button>
              <el-button size="small" type="primary" text @click="handleEdit(row)">编辑</el-button>
              <el-button size="small" type="danger" text @click="handleDelete(row)">删除</el-button>
            </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>

    <!-- Add/Edit -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="700px" destroy-on-close>
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="90px">
        <el-row :gutter="16">
          <el-col :span="12"><el-form-item label="客户" prop="customer_id"><el-select v-model="form.customer_id" placeholder="选择客户" filterable style="width:100%"><el-option v-for="c in customers" :key="c.id" :label="`${c.name} (${c.phone})`" :value="c.id" /></el-select></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="合同编号" prop="contract_no"><el-input v-model="form.contract_no" /></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="套餐名称"><el-input v-model="form.package_name" /></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="天数"><el-input-number v-model="form.days" :min="1" style="width:100%" /></el-form-item></el-col>
          <el-col :span="8"><el-form-item label="总金额" prop="total_amount"><el-input-number v-model="form.total_amount" :min="0" :precision="2" style="width:100%" /></el-form-item></el-col>
          <el-col :span="8"><el-form-item label="优惠金额"><el-input-number v-model="form.discount_amount" :min="0" :precision="2" style="width:100%" /></el-form-item></el-col>
          <el-col :span="8"><el-form-item label="实付金额" prop="actual_amount"><el-input-number v-model="form.actual_amount" :min="0" :precision="2" style="width:100%" /></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="入住日期"><el-date-picker v-model="form.check_in_date" type="date" value-format="YYYY-MM-DD" style="width:100%" /></el-form-item></el-col>
          <el-col :span="12"><el-form-item label="退房日期"><el-date-picker v-model="form.check_out_date" type="date" value-format="YYYY-MM-DD" style="width:100%" /></el-form-item></el-col>
          <el-col :span="24"><el-form-item label="备注"><el-input v-model="form.remark" type="textarea" :rows="2" /></el-form-item></el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- Audit -->
    <el-dialog v-model="auditVisible" title="合同审核" width="450px" destroy-on-close>
      <el-form label-width="80px">
        <el-form-item label="审核结果">
          <el-radio-group v-model="auditForm.status">
            <el-radio :value="1">通过</el-radio>
            <el-radio :value="2">驳回</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核备注"><el-input v-model="auditForm.audit_remark" type="textarea" :rows="3" /></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="auditVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAudit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
