<script lang="ts" setup>
import { ref, computed } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import type { IGoodsTemplate } from '@/api/types/appointment'
import { createAppointment, getInvitationDetail, getVisitTypes, getVisitorAreas } from '@/api/appointment'
import { TMPL_CANCEL, TMPL_VISIT, TMPL_RESULT } from '@/utils/constants'

definePage({
  style: { navigationBarTitleText: '访客预约' },
})

const inviteCode = ref('')
const submitting = ref(false)

onLoad(async () => {
  try {
    const [typesRes, areasRes] = await Promise.all([
      getVisitTypes().catch(() => null),
      getVisitorAreas().catch(() => null),
    ])
    const types: any[] = (typesRes as any)?.data || typesRes || []
    visitTypes.value = types.map((t: any) => t.name || t)
    const areas: any[] = (areasRes as any)?.data || areasRes || []
    visitorAreaOptions.value = areas.map((a: any) => ({ label: a.name, value: a.name }))
  } catch {}
})

// ==================== 公司接待人员（当前页面填写） ====================
const employeeName = ref('')
const employeePhone = ref('')

// ==================== 外部来访人员（独立页管理） ====================
interface VisitorItem {
  id?: number
  company: string
  name: string
  phone: string
  gender: number
  id_type: string
  id_number: string
  license_plate: string
}

const visitors = ref<VisitorItem[]>([])

const visitorSummary = computed(() => {
  if (visitors.value.length === 0) return '请选择'
  const names = visitors.value.map(v => v.name).filter(Boolean)
  if (names.length === 0) return `待填写 ${visitors.value.length} 人`
  return `${names.join('、')} 等 ${visitors.value.length} 人`
})

function goVisitorSelect() {
  const data = encodeURIComponent(JSON.stringify(visitors.value))
  uni.navigateTo({ url: `/subpackages/appointment/visitor-select?visitors=${data}` })
}

// ==================== 预约信息 ====================
const visitorAreaOptions = ref<{ label: string; value: string }[]>([])
const visitTypes = ref<string[]>([])
const selectedAreas = ref<string[]>([])
const remark = ref('')
const visitPurpose = ref('')
const startDateIdx = ref(0)
const now = new Date()
const startHourIdx = ref(now.getHours())
const startMinuteIdx = ref(Math.min(Math.ceil(now.getMinutes() / 5) * 5, 55))
const endDateIdx = ref(0)
const endHourIdx = ref(23)
const endMinuteIdx = ref(59)
const hasVehicle = ref(false)
const vehiclePlates = ref<string[]>([''])

function addVehiclePlate() {
  vehiclePlates.value.push('')
}
function removeVehiclePlate(index: number) {
  vehiclePlates.value.splice(index, 1)
}

const WEEKDAY_CN = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']

// 开始时间日期选项（当天起 6 个月）
interface DateOption { label: string; val: string }
const dateOptions = computed<DateOption[]>(() => {
  const dates: DateOption[] = []
  const start = new Date()
  const end = new Date()
  end.setMonth(end.getMonth() + 6)
  const cur = new Date(start)
  while (cur <= end) {
    const m = cur.getMonth() + 1
    const d = cur.getDate()
    const w = WEEKDAY_CN[cur.getDay()]
    dates.push({
      label: `${m}月${d}日 ${w}`,
      val: `${cur.getFullYear()}-${String(m).padStart(2, '0')}-${String(d).padStart(2, '0')}`,
    })
    cur.setDate(cur.getDate() + 1)
  }
  return dates
})

// 结束时间可选日期（仅开始时间选中的那一天）
const endDateOptions = computed<DateOption[]>(() => {
  if (!dateOptions.value.length) return []
  return [dateOptions.value[startDateIdx.value]]
})

// 时间选项
const hourOptions = Array.from({ length: 24 }, (_, i) => ({ label: `${String(i).padStart(2, '0')}时` }))
const minuteOptions = Array.from({ length: 60 }, (_, i) => ({ label: `${String(i).padStart(2, '0')}分` }))

const startDisplay = computed(() => {
  if (!dateOptions.value.length) return '请选择'
  const d = dateOptions.value[startDateIdx.value]
  return `${d.label} ${String(startHourIdx.value).padStart(2, '0')}时 ${String(startMinuteIdx.value).padStart(2, '0')}分`
})
const endDisplay = computed(() => {
  if (!endDateOptions.value.length) return '请选择'
  const d = endDateOptions.value[endDateIdx.value]
  return `${d.label} ${String(endHourIdx.value).padStart(2, '0')}时 ${String(endMinuteIdx.value).padStart(2, '0')}分`
})

function onStartChange(e: any) {
  const [di, hi, mi] = e.detail.value as number[]
  startDateIdx.value = di
  startHourIdx.value = hi
  startMinuteIdx.value = mi
}
function onEndChange(e: any) {
  const [di, hi, mi] = e.detail.value as number[]
  endDateIdx.value = di
  endHourIdx.value = hi
  endMinuteIdx.value = mi
}

// 到访区域切换
function toggleArea(area: string) {
  const idx = selectedAreas.value.indexOf(area)
  if (idx > -1) selectedAreas.value.splice(idx, 1)
  else selectedAreas.value.push(area)
}

// ==================== 携带物品 ====================
const selectedGoods = ref<IGoodsTemplate[]>([])

const goodsSummary = computed(() => {
  if (selectedGoods.value.length === 0) return '请选择'
  return `已选 ${selectedGoods.value.length} 项`
})

function goToGoodsSelect() {
  const goodsStr = encodeURIComponent(JSON.stringify(selectedGoods.value))
  uni.navigateTo({ url: `/subpackages/appointment/goods-select?selected=${goodsStr}` })
}

// ==================== 页面通讯接收 ====================
onShow(() => {
  const pages = getCurrentPages()
  const cp = pages[pages.length - 1] as any

  // 外部来访人员回显
  if (cp.visitorResult) {
    visitors.value = cp.visitorResult
    cp.visitorResult = null
  }

  // 携带物品回显
  if (cp.goodsResult) {
    selectedGoods.value = cp.goodsResult
    cp.goodsResult = null
  }
})

// ==================== 提交 ====================
async function handleSubmit() {
  if (!employeeName.value.trim()) { uni.showToast({ title: '请填写公司接待人员姓名', icon: 'none' }); return }
  if (!employeePhone.value.trim()) { uni.showToast({ title: '请填写公司接待人员手机号', icon: 'none' }); return }
  if (visitors.value.length === 0) { uni.showToast({ title: '请选择外部来访人员', icon: 'none' }); return }
  for (let i = 0; i < visitors.value.length; i++) {
    const v = visitors.value[i]
    if (!v.name.trim()) { uni.showToast({ title: `请输入第 ${i + 1} 位访客姓名`, icon: 'none' }); return }
    if (!/^1[3-9]\d{9}$/.test(v.phone)) { uni.showToast({ title: `第 ${i + 1} 位访客手机号不正确`, icon: 'none' }); return }
  }
  if (!visitPurpose.value) { uni.showToast({ title: '请选择来访目的', icon: 'none' }); return }
  if (selectedAreas.value.length === 0) { uni.showToast({ title: '请选择到访区域', icon: 'none' }); return }

  // 校验开始时间不能早于当前时间
  const startDate = new Date()
  startDate.setDate(startDate.getDate() + startDateIdx.value)
  startDate.setHours(startHourIdx.value, startMinuteIdx.value, 0, 0)
  if (startDate <= new Date()) {
    uni.showToast({ title: '开始时间必须晚于当前时间', icon: 'none' })
    return
  }

  // 校验结束时间不能早于开始时间
  const endDate = new Date(startDate)
  endDate.setHours(endHourIdx.value, endMinuteIdx.value, 0, 0)
  if (endDate <= startDate) {
    uni.showToast({ title: '结束时间必须晚于开始时间', icon: 'none' })
    return
  }

  submitting.value = true
  try {
    const d = new Date()
    d.setDate(d.getDate() + startDateIdx.value)
    d.setHours(startHourIdx.value, startMinuteIdx.value, 0, 0)
    const visitStartTime = d.toISOString()
    const e = new Date(d)
    e.setHours(endHourIdx.value, endMinuteIdx.value, 0, 0)
    const visitEndTime = e.toISOString()

    const res = await createAppointment({
      employee_name: employeeName.value.trim(),
      employee_phone: employeePhone.value.trim(),
      visitors: visitors.value.map(v => ({
        name: v.name,
        phone: v.phone,
        company: v.company || '',
        gender: v.gender,
        id_type: v.id_type || '',
        id_number: v.id_number || '',
      })),
      visit_purpose: visitPurpose.value,
      visit_start_time: visitStartTime,
      visit_end_time: visitEndTime,
      visit_areas: selectedAreas.value,
      has_vehicle: hasVehicle.value,
      license_plates: hasVehicle.value ? vehiclePlates.value.filter(p => p.trim()) : [],
      goods: selectedGoods.value.map(g => ({
        name: g.name, quantity: g.quantity, model: g.model || '', remark: g.remark || '',
      })),
      remark: remark.value,
      invite_code: inviteCode.value || undefined,
    })
    uni.showToast({ title: '预约成功', icon: 'success' })
    // 预约成功后提示订阅，请求完毕后再跳转
    await requestSubscribeAfterSubmit()
    uni.redirectTo({ url: `/subpackages/appointment/appointment-detail?id=${res.id}` })
  } catch {} finally { submitting.value = false }
}

/** 提交成功后引导用户再次订阅（攒消息发送次数） */
async function requestSubscribeAfterSubmit() {
  // #ifdef MP-WEIXIN
  try {
    await uni.requestSubscribeMessage({
      tmplIds: [TMPL_VISIT, TMPL_RESULT, TMPL_CANCEL],
    })
  } catch {
    // 用户拒绝或取消订阅，不影响流程
  }
  // #endif
}

// 接收 URL 参数（邀请码）
onLoad((options?: any) => {
  if (options?.invite_code) {
    inviteCode.value = options.invite_code
    getInvitationDetail(options.invite_code).then((res: any) => {
      if (res.employee_name) {
        employeeName.value = res.employee_name
        employeePhone.value = res.employee_phone || ''
      }
    }).catch(() => {
      uni.showToast({ title: '邀请码无效或已过期', icon: 'none' })
    })
  }
})
</script>

<template>
  <view class="form-page min-h-screen bg-[#f5f7fa]">
    <view class="px-3 pt-2 space-y-2">

      <!-- ═══ 公司接待人员（当前页面填写） ═══ -->
      <view class="card">
        <view class="card-header">
          <view class="flex items-center gap-2">
            <view class="w-1 h-4 bg-[#2979ff] rounded" />
            <text class="text-base font-semibold text-[#1a1a1a]">公司接待人员</text>
          </view>
          <text v-if="employeeName" class="text-xs text-green-500">已填写</text>
          <text v-else class="text-xs text-red-400">必填</text>
        </view>
        <view class="card-body">
          <view class="form-row">
            <view class="flex items-center gap-1.5">
              <text class="text-red-500">*</text>
              <text class="form-label">姓名</text>
            </view>
            <input v-model="employeeName" class="form-input text-sm" placeholder="请输入公司接待人员姓名" />
          </view>
          <view class="form-row">
            <view class="flex items-center gap-1.5">
              <text class="text-red-500">*</text>
              <text class="form-label">手机号</text>
            </view>
            <input v-model="employeePhone" class="form-input text-sm" placeholder="请输入手机号" type="number" :maxlength="11" />
          </view>
        </view>
      </view>

      <!-- ═══ 外部来访人员 ═══ -->
      <view class="card">
        <view class="card-header">
          <view class="flex items-center gap-2">
            <view class="w-1 h-4 bg-[#2979ff] rounded" />
            <text class="text-base font-semibold text-[#1a1a1a]">外部来访人员（请逐一填写）</text>
          </view>
          <text v-if="visitors.length" class="text-xs text-green-500">{{ visitors.length }} 人</text>
          <text v-else class="text-xs text-red-400">必填</text>
        </view>
        <view class="card-body">
          <view class="form-row" @click="goVisitorSelect">
            <view class="flex items-center gap-1.5">
              <text class="text-red-500">*</text>
              <text class="form-label">外部来访人员</text>
            </view>
            <view class="form-value">
              <text v-if="visitors.length" class="text-[#1a1a1a] font-medium">已选择{{ visitors.length }}人</text>
              <text v-else class="text-[#909399]">{{ visitorSummary }}</text>
              <wd-icon name="right" size="14px" color="#bbb" />
            </view>
          </view>
        </view>
      </view>

      <!-- ═══ 预约信息 ═══ -->
      <view class="card">
        <view class="card-header">
          <view class="flex items-center gap-2">
            <view class="w-1 h-4 bg-[#2979ff] rounded" />
            <text class="text-base font-semibold text-[#1a1a1a]">预约信息</text>
          </view>
        </view>
        <view class="card-body divide-y divide-[#f0f0f0]">
          <!-- 来访目的 -->
          <view class="form-row">
            <view class="flex items-center gap-1.5">
              <text class="text-red-500">*</text>
              <text class="form-label">来访目的</text>
            </view>
            <picker mode="selector" :range="visitTypes" @change="e => visitPurpose = visitTypes[e.detail.value]">
              <view class="form-value">
                <text :class="visitPurpose ? 'text-[#1a1a1a] font-medium' : 'text-[#909399]'">{{ visitPurpose || '请选择' }}</text>
                <wd-icon name="right" size="14px" color="#bbb" />
              </view>
            </picker>
          </view>
          <!-- 来访开始时间 -->
          <view class="form-row">
            <view class="flex items-center gap-1.5">
              <text class="text-red-500">*</text>
              <text class="form-label">来访开始时间</text>
            </view>
            <picker mode="multiSelector" :range="[dateOptions, hourOptions, minuteOptions]" range-key="label" :value="[startDateIdx, startHourIdx, startMinuteIdx]" @change="onStartChange">
              <view class="form-value">
                <text :class="'text-[#1a1a1a] font-medium'">{{ startDisplay }}</text>
                <wd-icon name="right" size="14px" color="#bbb" />
              </view>
            </picker>
          </view>
          <!-- 来访结束时间 -->
          <view class="form-row">
            <view class="flex items-center gap-1.5">
              <text class="text-red-500">*</text>
              <text class="form-label">来访结束时间</text>
            </view>
            <picker mode="multiSelector" :range="[endDateOptions, hourOptions, minuteOptions]" range-key="label" :value="[endDateIdx, endHourIdx, endMinuteIdx]" @change="onEndChange">
              <view class="form-value">
                <text :class="'text-[#1a1a1a] font-medium'">{{ endDisplay }}</text>
                <wd-icon name="right" size="14px" color="#bbb" />
              </view>
            </picker>
          </view>
        </view>
      </view>

      <!-- ═══ 到访区域 ═══ -->
      <view class="card">
        <view class="card-header">
          <view class="flex items-center gap-2">
            <view class="w-1 h-4 bg-[#2979ff] rounded" />
            <text class="text-base font-semibold text-[#1a1a1a]">到访区域</text>
          </view>
          <text v-if="selectedAreas.length" class="text-xs text-green-500">已选 {{ selectedAreas.length }} 个</text>
          <text v-else class="text-xs text-red-400">必填</text>
        </view>
        <view class="px-4 py-3">
          <view class="flex flex-wrap gap-2">
            <wd-tag
              v-for="area in visitorAreaOptions" :key="area.value"
              :type="selectedAreas.includes(area.value) ? 'primary' : 'info'"
              :plain="!selectedAreas.includes(area.value)"
              @click="toggleArea(area.value)"
            >
              {{ area.label }}
            </wd-tag>
          </view>
        </view>
      </view>

      <!-- ═══ 车辆信息 ═══ -->
      <view class="card">
        <view class="card-header">
          <view class="flex items-center gap-2">
            <view class="w-1 h-4 bg-[#2979ff] rounded" />
            <text class="text-base font-semibold text-[#1a1a1a]">车辆信息</text>
          </view>
        </view>
        <view class="card-body">
          <view class="form-row">
            <view class="flex items-center gap-1.5">
              <text class="form-label">有无车辆</text>
            </view>
            <switch :checked="hasVehicle" @change="hasVehicle = $event.detail.value" color="#2979ff" />
          </view>
          <view v-if="hasVehicle" class="px-4 pb-3">
            <view
              v-for="(plate, idx) in vehiclePlates" :key="idx"
              class="flex items-center gap-2 mb-2"
            >
              <text class="text-sm text-[#666] shrink-0">车牌{{ vehiclePlates.length > 1 ? idx + 1 : '' }}</text>
              <input v-model="vehiclePlates[idx]" class="flex-1 form-input-sm" placeholder="请输入车牌号" />
              <view v-if="vehiclePlates.length > 1" class="shrink-0 flex items-center justify-center w-8 h-8 rounded-full bg-[#fef0f0]" @click="removeVehiclePlate(idx)">
                <wd-icon name="delete" size="16px" color="#dd524d" />
              </view>
            </view>
            <view class="flex justify-center pt-1">
              <wd-button size="small" plain @click="addVehiclePlate">新增车牌号</wd-button>
            </view>
          </view>
        </view>
      </view>

      <!-- ═══ 备注 ═══ -->
      <view class="card">
        <view class="card-header">
          <view class="flex items-center gap-2">
            <view class="w-1 h-4 bg-[#2979ff] rounded" />
            <text class="text-base font-semibold text-[#1a1a1a]">备注</text>
          </view>
          <text v-if="remark" class="text-xs text-green-500">已填写</text>
        </view>
        <view class="card-body px-3 pb-3">
          <wd-textarea v-model="remark" placeholder="其他需要说明的信息（选填）" :maxlength="200" />
        </view>
      </view>

      <!-- 提交 -->
      <view class="px-0 pt-2 pb-8">
        <wd-button type="primary" size="large" block round :loading="submitting" @click="handleSubmit">
          提交预约
        </wd-button>
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.form-page {
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
}

.card {
  background: #fff;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.04);
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 16px 4px;
}

.card-body {
  padding: 2px 0;
}

.form-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 16px;
  min-height: 44px;
}

.form-input-sm {
  border: none;
  outline: none;
  background: #f5f7fa;
  color: #1a1a1a;
  font-size: 14px;
  padding: 8px 12px;
  border-radius: 6px;

  &::placeholder {
    color: #909399;
  }
}

.form-col {
  display: flex;
  flex-direction: column;
  padding: 10px 16px;
  gap: 8px;
}

.form-label {
  font-size: 16px;
  font-weight: 500;
  color: #1a1a1a;
}

.form-value {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 15px;
}

.form-input {
  flex: 1;
  text-align: right;
  border: none;
  outline: none;
  background: transparent;
  color: #1a1a1a;
  font-size: 15px;
  font-weight: 500;

  &::placeholder {
    color: #909399;
    font-weight: 400;
  }
}
</style>
