<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-blue-100 flex items-center justify-center mr-3">
            <text class="uni-icons uniui-person-filled text-primary"></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.customerName" @blur="validateField('customerName')" />
            <text v-if="errors.customerName" class="text-red-500 text-xs mt-1">{{ errors.customerName }}</text>
          </view>

          <view>
            <text class="form-label">客户状态<text class="text-red-500">*</text></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-purple-100 flex items-center justify-center mr-3">
            <text class="uni-icons uniui-phone-filled text-purple-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.contactName" @blur="validateField('contactName')" />
            <text v-if="errors.contactName" class="text-red-500 text-xs mt-1">{{ errors.contactName }}</text>
          </view>

          <view>
            <text class="form-label">联系电话<text class="text-red-500">*</text></text>
            <input
              class="form-input"
              placeholder="请输入联系电话"
              v-model="form.phone"
              type="number"
              maxlength="11"
              @blur="validateField('phone')"
            />
            <text v-if="errors.phone" class="text-red-500 text-xs mt-1">{{ errors.phone }}</text>
          </view>
        </view>
      </view>

      <!-- 地址 -->
      <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-location-filled text-green-500"></text>
          </view>
          <text>地址信息</text>
        </view>

        <view class="gap-y-4">
          <view class="grid grid-cols-3 gap-3">
            <view>
              <text class="form-label">省</text>
              <uni-easyinput class="form-input" placeholder="省" v-model="form.province" />
            </view>
            <view>
              <text class="form-label">市</text>
              <uni-easyinput class="form-input" placeholder="市" v-model="form.city" />
            </view>
            <view>
              <text class="form-label">区/县</text>
              <uni-easyinput class="form-input" placeholder="区/县" v-model="form.district" />
            </view>
          </view>

          <view>
            <text class="form-label">街道</text>
            <uni-easyinput class="form-input" placeholder="街道（选填）" v-model="form.street" />
          </view>

          <view>
            <text class="form-label">详细地址<text class="text-red-500">*</text></text>
            <uni-easyinput class="form-input" placeholder="请输入详细地址" v-model="form.detailAddress" @blur="validateField('detailAddress')" />
            <text v-if="errors.detailAddress" class="text-red-500 text-xs mt-1">{{ errors.detailAddress }}</text>
          </view>

          <view class="grid grid-cols-2 gap-3">
            <view>
              <text class="form-label">纬度</text>
              <uni-easyinput class="form-input" placeholder="选填" v-model="form.latitude" type="digit" />
            </view>
            <view>
              <text class="form-label">经度</text>
              <uni-easyinput class="form-input" placeholder="选填" v-model="form.longitude" type="digit" />
            </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="500"
        />
      </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 { CustomerStatus } from '../../types'
import { getCustomerDetail, createCustomer, updateCustomer } from '../../api/customer'
import TopBar from '../../components/common/TopBar.vue'

const statusOptions: { label: string; value: CustomerStatus }[] = [
  { label: '合作中', value: 1 },
  { label: '潜在客户', value: 2 },
  { label: '已停用', value: 0 }
]
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 form = ref({
  customerName: '',
  contactName: '',
  phone: '',
  province: '',
  city: '',
  district: '',
  street: '',
  detailAddress: '',
  latitude: '',
  longitude: '',
  status: 1 as CustomerStatus,
  remark: ''
})

const errors = reactive<Record<string, string>>({
  customerName: '',
  contactName: '',
  phone: '',
  detailAddress: ''
})

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 onStatusChange(e: any) {
  form.value.status = statusOptions[Number(e.detail.value)].value
}

function validateField(field: string) {
  const value = (form.value as any)[field] as string
  errors[field] = ''
  if (!value || !value.toString().trim()) {
    const names: Record<string, string> = {
      customerName: '客户名称',
      contactName: '联系人',
      phone: '联系电话',
      detailAddress: '详细地址'
    }
    errors[field] = `请输入${names[field] || field}`
    return false
  }
  if (field === 'phone') {
    const re = /^1(3[0-9]|4[5-9]|5[0-3,5-9]|6[6-7]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/
    if (!re.test(value)) {
      errors[field] = '请输入正确的手机号'
      return false
    }
  }
  return true
}

function validateForm() {
  let ok = true
  for (const f of ['customerName', 'contactName', 'phone', 'detailAddress']) {
    if (!validateField(f)) ok = false
  }
  return ok
}

async function loadDetail(id: number | string) {
  loading.value = true
  try {
    const c = await getCustomerDetail(id)
    form.value = {
      customerName: c.customerName || '',
      contactName: c.contactName || '',
      phone: c.phone || '',
      province: c.province || '',
      city: c.city || '',
      district: c.district || '',
      street: c.street || '',
      detailAddress: c.detailAddress || '',
      latitude: c.latitude || '',
      longitude: c.longitude || '',
      status: (Number(c.status) as CustomerStatus) ?? 1,
      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 payload = {
      customerName: form.value.customerName.trim(),
      contactName: form.value.contactName.trim(),
      phone: form.value.phone.trim(),
      province: form.value.province || undefined,
      city: form.value.city || undefined,
      district: form.value.district || undefined,
      street: form.value.street || undefined,
      detailAddress: form.value.detailAddress.trim(),
      latitude: form.value.latitude || undefined,
      longitude: form.value.longitude || undefined,
      status: form.value.status,
      remark: form.value.remark || undefined
    }
    if (isEdit.value) {
      await updateCustomer({ ...payload, id: editId.value })
    } else {
      await createCustomer(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((options) => {
  const id = options?.id
  if (id) {
    isEdit.value = true
    editId.value = id
    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>
