<template>
  <view class="app-container detail-page pb-24">
    <TopBar :title="isEdit ? '编辑合同' : '新增合同'" show-back />

    <view v-if="loading" class="py-20 text-center">
      <text class="text-gray-400">加载中...</text>
    </view>

    <view v-else class="px-4 py-4 gap-y-4">
      <!-- 基本信息 -->
      <view class="card p-4">
        <view class="detail-section-title mb-4">
          <view class="w-8 h-8 rounded-lg bg-green-100 flex items-center justify-center mr-3">
            <text class="uni-icons uniui-file-text-filled text-green-500"></text>
          </view>
          <text>基本信息</text>
        </view>

        <view class="gap-y-4">
          <view>
            <text class="form-label">合同编号<text class="text-red-500">*</text></text>
            <uni-easyinput class="form-input" placeholder="请输入合同编号" v-model="form.contractNo" @blur="validateField('contractNo')" />
            <text v-if="errors.contractNo" class="text-red-500 text-xs mt-1">{{ errors.contractNo }}</text>
          </view>

          <view>
            <text class="form-label">合同名称<text class="text-red-500">*</text></text>
            <uni-easyinput class="form-input" placeholder="请输入合同名称" v-model="form.contractName" @blur="validateField('contractName')" />
            <text v-if="errors.contractName" class="text-red-500 text-xs mt-1">{{ errors.contractName }}</text>
          </view>

          <view>
            <text class="form-label">关联客户<text class="text-red-500">*</text></text>
            <picker mode="selector" :range="customerLabels" :value="customerIndex" @change="onCustomerChange">
              <view class="form-select flex items-center" :class="{ 'text-gray-400': !form.customerId }">
                <text class="uni-icons uniui-arrowdown text-gray-400 mr-2"></text>
                {{ currentCustomerLabel }}
              </view>
            </picker>
            <text v-if="errors.customerId" class="text-red-500 text-xs mt-1">{{ errors.customerId }}</text>
          </view>

          <view>
            <text class="form-label">合同金额（元）<text class="text-red-500">*</text></text>
            <uni-easyinput class="form-input" placeholder="请输入合同金额" v-model="form.contractAmount" type="digit" @blur="validateField('contractAmount')" />
            <text v-if="errors.contractAmount" class="text-red-500 text-xs mt-1">{{ errors.contractAmount }}</text>
          </view>

          <view>
            <text class="form-label">付款方式<text class="text-red-500">*</text></text>
            <picker mode="selector" :range="paymentLabels" :value="paymentIndex" @change="onPaymentChange">
              <view class="form-select flex items-center">
                <text class="uni-icons uniui-arrowdown text-gray-400 mr-2"></text>
                {{ currentPaymentLabel }}
              </view>
            </picker>
          </view>

          <view>
            <text class="form-label">合同状态</text>
            <picker mode="selector" :range="statusLabels" :value="statusIndex" @change="onStatusChange">
              <view class="form-select flex items-center">
                <text class="uni-icons uniui-arrowdown text-gray-400 mr-2"></text>
                {{ currentStatusLabel }}
              </view>
            </picker>
          </view>
        </view>
      </view>

      <!-- 日期 -->
      <view class="card p-4">
        <view class="detail-section-title mb-4">
          <view class="w-8 h-8 rounded-lg bg-blue-100 flex items-center justify-center mr-3">
            <text class="uni-icons uniui-calendar text-primary"></text>
          </view>
          <text>日期</text>
        </view>

        <view class="gap-y-4">
          <view>
            <text class="form-label">签订日期</text>
            <picker mode="date" :value="form.signDate" @change="onSignDateChange">
              <view class="form-select flex items-center text-gray-700">
                <text class="uni-icons uniui-calendar text-gray-400 mr-2"></text>
                {{ form.signDate || '选择日期' }}
              </view>
            </picker>
          </view>

          <view class="grid grid-cols-2 gap-3">
            <view>
              <text class="form-label">服务开始</text>
              <picker mode="date" :value="form.serviceStart" @change="onServiceStartChange">
                <view class="form-select flex items-center text-gray-700">
                  <text class="uni-icons uniui-calendar text-gray-400 mr-2"></text>
                  {{ form.serviceStart || '选择' }}
                </view>
              </picker>
            </view>
            <view>
              <text class="form-label">服务结束</text>
              <picker mode="date" :value="form.serviceEnd" @change="onServiceEndChange">
                <view class="form-select flex items-center text-gray-700">
                  <text class="uni-icons uniui-calendar text-gray-400 mr-2"></text>
                  {{ form.serviceEnd || '选择' }}
                </view>
              </picker>
            </view>
          </view>
        </view>
      </view>

      <!-- 备注 -->
      <view class="card p-4">
        <view class="detail-section-title mb-4">
          <view class="w-8 h-8 rounded-lg bg-gray-100 flex items-center justify-center mr-3">
            <text class="uni-icons uniui-compose text-gray-500"></text>
          </view>
          <text>备注</text>
        </view>
        <textarea
          v-model="form.remark"
          class="w-full p-3 bg-surface rounded-xl text-sm text-gray-700"
          placeholder="请输入备注..."
          :maxlength="1000"
        />
      </view>

      <!-- 提交 -->
      <view class="px-4 pt-2 pb-6">
        <button
          class="w-full py-4 btn-primary rounded-2xl text-base font-semibold flex items-center justify-center"
          @click="submitForm"
          :disabled="submitting"
        >
          <text v-if="submitting" class="uni-icons uniui-spinner-cycle mr-2 animate-spin"></text>
          <text v-else class="uni-icons uniui-checkmarkempty mr-2"></text>
          {{ submitting ? '提交中...' : isEdit ? '保存修改' : '新增合同' }}
        </button>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import type { ContractStatus, Customer, PaymentMethod } from '../../types'
import { getContractDetail, createContract, updateContract } from '../../api/contract'
import { getCustomerList } from '../../api/customer'
import TopBar from '../../components/common/TopBar.vue'

const paymentOptions: { label: string; value: PaymentMethod }[] = [
  { label: '一次性', value: 'lump_sum' },
  { label: '分期', value: 'installment' }
]
const paymentLabels = paymentOptions.map(p => p.label)

const statusOptions: { label: string; value: ContractStatus }[] = [
  { label: '草稿', value: 'draft' },
  { label: '待生效', value: 'pending' },
  { label: '生效中', value: 'active' },
  { label: '已过期', value: 'expired' },
  { label: '已终止', value: 'terminated' }
]
const statusLabels = statusOptions.map(s => s.label)

const isEdit = ref(false)
const editId = ref<number | string>('')
const loading = ref(false)
const submitting = ref(false)

const customers = ref<Customer[]>([])
const customerLabels = computed(() => customers.value.map(c => c.customerName))

const form = ref({
  contractNo: '',
  contractName: '',
  customerId: '' as number | string,
  customerName: '',
  contractAmount: '' as number | string,
  paymentMethod: 'lump_sum' as PaymentMethod,
  status: 'draft' as ContractStatus,
  signDate: '',
  serviceStart: '',
  serviceEnd: '',
  remark: ''
})

const errors = reactive<Record<string, string>>({
  contractNo: '',
  contractName: '',
  customerId: '',
  contractAmount: ''
})

const customerIndex = computed(() => {
  const idx = customers.value.findIndex(c => String(c.id) === String(form.value.customerId))
  return idx < 0 ? 0 : idx
})
const currentCustomerLabel = computed(() => {
  if (!form.value.customerId) return '请选择客户'
  return customers.value[customerIndex.value]?.customerName || form.value.customerName || '请选择客户'
})
const paymentIndex = computed(() => {
  const idx = paymentOptions.findIndex(p => p.value === form.value.paymentMethod)
  return idx < 0 ? 0 : idx
})
const currentPaymentLabel = computed(() => paymentOptions[paymentIndex.value].label)
const statusIndex = computed(() => {
  const idx = statusOptions.findIndex(s => s.value === form.value.status)
  return idx < 0 ? 0 : idx
})
const currentStatusLabel = computed(() => statusOptions[statusIndex.value].label)

function onCustomerChange(e: any) {
  const c = customers.value[Number(e.detail.value)]
  if (c) {
    form.value.customerId = c.id
    form.value.customerName = c.customerName
    errors.customerId = ''
  }
}
function onPaymentChange(e: any) {
  form.value.paymentMethod = paymentOptions[Number(e.detail.value)].value
}
function onStatusChange(e: any) {
  form.value.status = statusOptions[Number(e.detail.value)].value
}
function onSignDateChange(e: any) {
  form.value.signDate = e.detail.value
}
function onServiceStartChange(e: any) {
  form.value.serviceStart = e.detail.value
}
function onServiceEndChange(e: any) {
  form.value.serviceEnd = e.detail.value
}

function validateField(field: string) {
  errors[field] = ''
  if (field === 'customerId') {
    if (!form.value.customerId) {
      errors.customerId = '请选择关联客户'
      return false
    }
    return true
  }
  const value = (form.value as any)[field]
  if (value === undefined || value === null || value === '') {
    const names: Record<string, string> = { contractNo: '合同编号', contractName: '合同名称', contractAmount: '合同金额' }
    errors[field] = `请输入${names[field] || field}`
    return false
  }
  if (field === 'contractAmount') {
    const num = Number(value)
    if (isNaN(num) || num < 0) {
      errors.contractAmount = '请输入有效的金额'
      return false
    }
  }
  return true
}

function validateForm() {
  let ok = true
  for (const f of ['contractNo', 'contractName', 'customerId', 'contractAmount']) {
    if (!validateField(f)) ok = false
  }
  return ok
}

async function loadCustomers() {
  try {
    const res = await getCustomerList(1, 1000)
    customers.value = res.rows || []
  } catch (e) {
    customers.value = []
  }
}

function parseServicePeriod(sp?: string) {
  if (!sp) return { start: '', end: '' }
  const parts = sp.split(' 至 ')
  return { start: parts[0] || '', end: parts[1] || '' }
}

async function loadDetail(id: number | string) {
  loading.value = true
  try {
    const c = await getContractDetail(id)
    const sp = parseServicePeriod(c.servicePeriod)
    form.value = {
      contractNo: c.contractNo || '',
      contractName: c.contractName || '',
      customerId: c.customerId || '',
      customerName: c.customerName || '',
      contractAmount: c.contractAmount ?? '',
      paymentMethod: c.paymentMethod || 'lump_sum',
      status: c.status || 'draft',
      signDate: c.signDate || '',
      serviceStart: sp.start,
      serviceEnd: sp.end,
      remark: c.remark || ''
    }
  } catch (e) {
    uni.showToast({ title: '加载失败', icon: 'none' })
  } finally {
    loading.value = false
  }
}

async function submitForm() {
  if (!validateForm()) {
    uni.showToast({ title: '请完善表单信息', icon: 'none' })
    return
  }
  submitting.value = true
  try {
    const servicePeriod =
      form.value.serviceStart && form.value.serviceEnd
        ? `${form.value.serviceStart} 至 ${form.value.serviceEnd}`
        : undefined
    const payload = {
      contractNo: form.value.contractNo.trim(),
      contractName: form.value.contractName.trim() || undefined,
      customerId: form.value.customerId,
      customerName: form.value.customerName || undefined,
      contractAmount: Number(form.value.contractAmount),
      paymentMethod: form.value.paymentMethod,
      status: form.value.status,
      signDate: form.value.signDate || undefined,
      servicePeriod,
      remark: form.value.remark || undefined
    }
    if (isEdit.value) {
      await updateContract({ ...payload, id: editId.value })
    } else {
      await createContract(payload)
    }
    uni.showToast({ title: isEdit.value ? '保存成功' : '创建成功', icon: 'success' })
    setTimeout(() => uni.navigateBack(), 900)
  } catch (e) {
    uni.showToast({ title: isEdit.value ? '保存失败' : '创建失败', icon: 'none' })
  } finally {
    submitting.value = false
  }
}

onLoad(async (options) => {
  await loadCustomers()
  const id = options?.id
  if (id) {
    isEdit.value = true
    editId.value = id
    await loadDetail(id)
  }
})
</script>

<style scoped>
.detail-page {
  background-color: #f6fbf9;
}

.card {
  border-radius: 20px;
  margin-bottom: 0;
  border: 1px solid rgba(164, 216, 152, 0.28);
  box-shadow: 0 14px 34px -18px rgba(54, 143, 111, 0.35);
}

/* 区块标题与图标块统一青山绿水 */
.detail-section-title {
  padding: 0;
  border-bottom: none;
}
.detail-section-title .w-8 {
  background-color: rgba(164, 216, 152, 0.2) !important;
}
.detail-section-title .uni-icons {
  color: #368f6f !important;
}

/* 主按钮 */
.btn-primary {
  background: linear-gradient(135deg, #368f6f 0%, #5ab8d0 100%);
  box-shadow: 0 10px 22px -10px rgba(54, 143, 111, 0.55);
}

/* 输入聚焦态 */
.form-input :deep(.uni-easyinput__content.focus) {
  border-color: #368f6f !important;
}

/* 备注框白底 */
.bg-surface {
  background-color: #ffffff;
  border: 1px solid #e5e7eb;
}
</style>
