<template>
  <div class="page-container">
    <div class="page-header">
      <el-button type="warning" size="default" icon="Upload" @click="openImportDialog" style="margin-left: auto;">
        导入微信订单
      </el-button>
    </div>
    <div class="create-layout">

      <!-- 左侧：下单填写区 -->
      <div class="form-container">
        <!-- 1. 基础信息：门店与宠主 -->
        <el-card shadow="never" class="section-card">
          <template #header>
            <div class="card-title">
              <span class="step-num">01</span> 基础信息
            </div>
          </template>
          <div class="card-body">
            <el-form label-position="top" class="base-form">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item required>
                    <template #label>
                      <div style="display:flex; align-items:center; height: 24px;">
                        <span>服务门店 (平台代下单)</span>
                      </div>
                    </template>
                    <PageSelect v-model="form.merchantId" placeholder="请选择商户门店" size="large" style="width: 100%"
                      :options="merchantOptions" :total="storeTotal" :page-size="5" @page-change="handleStorePageChange"
                      @update:modelValue="handleStoreChange" @filter-method="handleStoreFilter"
                      @visible-change="handleStoreVisible" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item required>
                    <template #label>
                      <div
                        style="display:flex; justify-content:space-between; align-items:center; width:100%; height: 24px;">
                        <span>宠主用户</span>
                        <el-button type="primary" plain size="small" @click="openAddUser" icon="Plus"
                          style="margin-left: 15px;" v-hasPermi="['order:purchase:addCustomer']"
                          :disabled="!form.merchantId">添加用户</el-button>
                      </div>
                    </template>
                    <PageSelect v-model="form.userId" :placeholder="form.merchantId ? '搜索姓名/手机号' : '请先选择服务门店'"
                      size="large" style="width: 100%" :options="userSelectOptions" :total="userTotal" :page-size="5"
                      :filter-method="searchUser" :loading="userLoading"
                      :popper-class="!userQuery.content ? 'hide-search-popper' : ''" :disabled="!form.merchantId"
                      @page-change="handleUserPageChange" @visible-change="handleUserVisibleChange"
                      @update:modelValue="handleUserChange" />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-form-item label="选择宠物" v-if="form.userId" required>
                <div class="pet-select-row">
                  <div v-for="p in currentPets" :key="p.id" class="pet-card" :class="{ active: form.petId === p.id }"
                    @click="form.petId = p.id">
                    <el-avatar :size="48" :src="p.avatarUrl || p.avatar" shape="square" style="border-radius: 6px;">{{
                      p.name.charAt(0)
                    }}</el-avatar>
                    <div class="pet-info">
                      <div class="name">{{ p.name }}</div>
                      <div class="sub">{{ p.breed }}</div>
                    </div>
                    <div class="check-mark" v-if="form.petId === p.id"><el-icon>
                        <Check />
                      </el-icon></div>
                  </div>

                  <!-- Add Button Card (Last Item in Grid) -->
                  <div class="pet-card add-card" @click="openAddPet" v-hasPermi="['order:purchase:addPet']">
                    <el-icon :size="24">
                      <Plus />
                    </el-icon>
                    <span style="font-size: 15px; font-weight: bold;">新增宠物</span>
                  </div>
                </div>
              </el-form-item>
            </el-form>
          </div>
        </el-card>

        <!-- 2. 服务类型选择 -->
        <div class="type-selection" v-if="form.merchantId">
          <div v-for="item in availableServices" :key="item.id" class="type-card"
            :class="[getServiceType(item.name), { active: form.serviceId === item.id }]"
            @click="handleServiceChange(item)">
            <div class="icon-box">
              <img v-if="item.iconUrl" :src="item.iconUrl" class="service-icon-img" />
              <el-icon v-else>
                <component :is="getServiceIcon(item.name)" />
              </el-icon>
            </div>
            <div class="text">
              <div class="type-name">{{ item.name }}</div>
              <div class="type-desc">{{ item.remark }}</div>
            </div>
          </div>
          <div v-if="availableServices.length === 0"
            style="grid-column: 1 / -1; color: #909399; text-align: center; padding: 20px;">该门店暂无可选服务</div>
        </div>
        <div v-else
          style="color: #909399; margin: 20px 0; padding: 20px; text-align: center; background: #fff; border-radius: 8px;">
          请先在上一步中选择服务门店
        </div>

        <!-- 3. 业务详情表单 -->
        <el-card shadow="never" class="section-card form-card" v-if="form.type">
          <template #header>
            <div class="card-title">
              <span class="step-num">02</span>
              {{ getStepTitle(form.mode, form.type) }}
            </div>
          </template>

          <div class="card-body">
            <!-- 服务套餐信息 -->
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="团购套餐">
                  <el-input v-model="form.groupBuyPackage" placeholder="请输入团购套餐名称 (选填)" clearable />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="订单佣金 (元)" required>
                  <el-input-number v-model="form.orderCommission" :min="0" :precision="2" :step="1" placeholder="佣金金额"
                    style="width: 100%" />
                </el-form-item>
              </el-col>
            </el-row>

            <div class="divider"></div>

            <!-- A. 宠物接送表单 -->
            <TransportForm v-show="form.type === 'transport'" :transport-data="form.transport" @change="calcPrice" />

            <!-- B. 上门喂遛表单 -->
            <FeedingForm v-show="form.type === 'feeding'" :feeding-data="form.feeding" @change="calcPrice" />

            <!-- C. 上门洗护表单 -->
            <WashingForm v-show="form.type === 'washing'" :washing-data="form.washing" @change="calcPrice" />

          </div>
        </el-card>
      </div>

      <!-- 右侧：收银台概览 -->
      <div class="summary-sidebar">
        <div class="summary-panel">
          <div class="summary-header">订单概览</div>

          <div class="summary-content">
            <div class="row" v-if="selectedMerchantName">
              <span class="label">服务门店</span>
              <span class="value">{{ selectedMerchantName }}</span>
            </div>
            <div class="row" v-if="selectedUserName">
              <span class="label">客户</span>
              <span class="value">{{ selectedUserName }}</span>
            </div>
            <div class="row" v-if="selectedPetName">
              <span class="label">服务对象</span>
              <span class="value action-text">{{ selectedPetName }} ({{ selectedPetBreed }})</span>
            </div>
            <div class="divider"></div>

            <div class="service-preview" v-if="form.type">
              <div class="preview-title">{{ selectedServiceName }}</div>

              <!-- 套餐显示 -->
              <div class="preview-detail" v-if="selectedPkgName">
                <div style="font-weight:bold; color:#409eff">{{ selectedPkgName }}</div>
              </div>
              <div class="preview-detail" v-else>
                <div style="color:#e6a23c">非服务套餐 (单次)</div>
              </div>

              <!-- 接送预览 -->
              <div v-if="form.type === 'transport'" class="preview-detail">
                <div>{{ form.transport.subType === 'round' ? '往返接送' : (form.transport.subType === 'pick' ? '单程接' :
                  '单程送') }}
                </div>
                <div class="minor">接: {{ form.transport.pickTime ? formatTime(form.transport.pickTime) : '未选时间' }}</div>
                <div class="minor" v-if="form.transport.subType !== 'pick'">送: {{ form.transport.dropTime ?
                  formatTime(form.transport.dropTime) : '未选' }}</div>
              </div>
            </div>

          </div>

          <div class="summary-footer">
            <el-button type="primary" size="large" class="submit-btn" :disabled="!canSubmit" @click="handleSubmit"
              v-hasPermi="['order:purchase:create']">
              立即下单
            </el-button>
          </div>
        </div>
      </div>

    </div>

    <!-- Import WeChat Order Dialog -->
    <el-dialog v-model="importDialogVisible" title="导入微信订单" width="600px" :close-on-click-modal="false"
      destroy-on-close>
      <el-alert type="info" :closable="false" show-icon style="margin-bottom: 15px;">
        <template #title>
          请将微信订单消息复制到下方文本框<br /><br />
          <b>【接送单模板】</b><br />
          门店：zj测试门店<br />
          宠物用户：13888888889<br />
          宠物：张晓蔷的狗<br />
          选择服务：宠物接送<br />
          接送类型：接送<br />
          时间：接[2026年5月28日18点]，送[2026年5月28日18点]<br />
          备注：测试微信订单<br />
          团购套餐：测试套餐<br /><br />
          <b>【服务单模板】</b><br />
          门店：zj测试门店<br />
          宠物用户：13888888889<br />
          宠物：张晓蔷的狗<br />
          选择服务：上门洗护<br />
          时间：2026年5月28日18点、2026年5月28日19点<br />
          备注：测试微信订单<br />
          团购套餐：测试套餐
        </template>
      </el-alert>
      <el-input v-model="importText" type="textarea" :rows="10" placeholder="请粘贴微信订单文本..."
        style="margin-bottom: 15px;" />
      <template #footer>
        <el-button @click="importDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="importLoading" @click="handleImportWechatOrder">
          解析并填充
        </el-button>
      </template>
    </el-dialog>

    <!-- Dialogs -->
    <!-- Add User Dialog -->
    <AddCustomerDialog v-model:visible="userDialogVisible" :tenant-id="currentTenantId" :station-id="currentStationId"
      :order-mode="true" @success="handleUserSuccess" />
    <AddPetDialog v-model:visible="petDialogVisible" :user-id="form.userId" :user-options="userOptions"
      :locked-owner="true" @success="handlePetSuccess" />

  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import TransportForm from './components/TransportForm.vue'
import FeedingForm from './components/FeedingForm.vue'
import WashingForm from './components/WashingForm.vue'
import AddCustomerDialog from '@/components/AddCustomerDialog/index.vue'
import AddPetDialog from '@/components/AddPetDialog/index.vue'
import PageSelect from '@/components/PageSelect/index.vue'
import { listStoreOnOrder } from '@/api/system/store'
import { listAllService } from '@/api/service/list'
import { listCustomerOnOrder } from '@/api/archieves/customer'
import { listPetByUser } from '@/api/archieves/pet'
import { createOrder } from '@/api/order/order'

// --- State ---
const userOptions = ref([])
const userTotal = ref(0)
const userQuery = reactive({ pageNum: 1, pageSize: 5, content: '', tenantId: undefined, stationId: undefined })
const userLoading = ref(false)

const serviceList = [
  { type: 'transport', name: '宠物接送', icon: 'Van', desc: '专车接送 · 全程监护', basePrice: 35 },
  { type: 'feeding', name: '上门喂遛', icon: 'Food', desc: '喂食添水 · 陪玩遛狗', basePrice: 68 },
  { type: 'washing', name: '上门洗护', icon: 'Soap', desc: '专业设备 · 深度清洁', basePrice: 88 }
]

const allPackages = [
  { id: 10, type: 'transport', name: '包月接送套餐', fulfillmentCommission: 0 },
  { id: 11, type: 'feeding', name: '基础喂猫套餐', fulfillmentCommission: 0 },
  { id: 12, type: 'feeding', name: '深度陪玩套餐', fulfillmentCommission: 0 },
  { id: 13, type: 'washing', name: '精致洗护+美容', fulfillmentCommission: 0 },
  { id: 14, type: 'washing', name: '除菌药浴套餐', fulfillmentCommission: 0 },
]

const currentPets = ref([])

const stores = ref([])
const storeTotal = ref(0)
const allServices = ref([])
const storeQuery = reactive({ pageNum: 1, pageSize: 5, name: '' })

const form = reactive({
  merchantId: '',
  userId: '',
  petId: '',
  serviceId: '',
  type: '',
  mode: undefined,
  groupBuyPackage: '',
  orderCommission: 0.00,

  // Sub Forms Data
  transport: {
    pkgId: '',
    fulfillmentCommission: 0,
    pickPrice: 35,
    dropPrice: 35,
    subType: 'round',
    pickStartRegion: [], pickStartDetail: '', pickEndRegion: [], pickEndDetail: '', pickContact: '', pickPhone: '', pickTime: '',
    dropStartRegion: [], dropStartDetail: '', dropEndRegion: [], dropEndDetail: '', dropContact: '', dropPhone: '', dropTime: '',
    other: ''
  },
  feeding: {
    pkgId: '', fulfillmentCommission: 68,
    appointments: [{ startTime: '', endTime: '' }],
    region: [], addressDetail: '',
    count: 1, dates: [], area: '', itemLoc: '', cleanLoc: '', foodAmount: '', other: ''
  },
  washing: {
    pkgId: '', fulfillmentCommission: 88,
    appointments: [{ startTime: '', endTime: '' }],
    region: [], addressDetail: '',
    time: '', petStatus: '', cleanLoc: '', toolLoc: '', other: ''
  }
})

// Address Autofill Watcher
watch([() => form.merchantId, () => form.userId, () => form.petId], () => {
  const store = stores.value.find(s => s.id === form.merchantId)
  const user = userOptions.value.find(u => u.id === form.userId)

  const storeRegion = store?.areaCode ? store.areaCode.split(',') : []
  const storeAddr = store?.address || ''

  const userRegion = user?.regionCode ? user.regionCode.split('/') : []
  const userAddr = user?.address || ''

  // Fill Transport Pick
  form.transport.pickStartRegion = userRegion
  form.transport.pickStartDetail = userAddr
  form.transport.pickEndRegion = storeRegion
  form.transport.pickEndDetail = storeAddr
  form.transport.pickContact = user?.name || ''
  form.transport.pickPhone = user?.phoneNumber || user?.phone || ''

  // Fill Transport Drop
  form.transport.dropStartRegion = storeRegion
  form.transport.dropStartDetail = storeAddr
  form.transport.dropEndRegion = userRegion
  form.transport.dropEndDetail = userAddr
  form.transport.dropContact = user?.name || ''
  form.transport.dropPhone = user?.phoneNumber || user?.phone || ''

  // Fill Feeding (上门服务)
  form.feeding.region = userRegion
  form.feeding.addressDetail = userAddr

  // Fill Washing (上门服务)
  form.washing.region = userRegion
  form.washing.addressDetail = userAddr
})

// Current Active Data Helper
const activeData = computed(() => {
  return form[form.type]
})

// --- Logic ---
const fetchStores = () => {
  listStoreOnOrder(storeQuery).then(res => {
    stores.value = res.rows || []
    storeTotal.value = res.total || 0
  })
}

const handleStorePageChange = (page) => {
  storeQuery.pageNum = page
  fetchStores()
}

const handleStoreFilter = (query) => {
  storeQuery.name = query || ''
  storeQuery.pageNum = 1
  fetchStores()
}

const handleStoreVisible = (visible) => {
  if (visible) {
    storeQuery.name = ''
    storeQuery.pageNum = 1
    fetchStores()
  }
}

const handleStoreChange = (val) => {
  // 切换门店时强制清空已选客户和宠物
  form.userId = ''
  form.petId = ''
  currentPets.value = []
  userOptions.value = []
  userTotal.value = 0

  const store = stores.value.find(s => s.id === val)
  if (store && store.services) {
    if (!store.services.includes(form.serviceId)) {
      form.serviceId = ''
      form.type = ''
      form.mode = undefined
    }
  } else {
    form.serviceId = ''
    form.type = ''
    form.mode = undefined
  }
}

const getServiceType = (name) => {
  if (!name) return 'feeding'
  if (name.includes('喂') || name.includes('遛')) return 'feeding'
  if (name.includes('洗护') || name.includes('美容')) return 'washing'
  if (name.includes('接送')) return 'transport'
  return 'feeding'
}

const getServiceIcon = (name) => {
  const type = getServiceType(name)
  const map = { transport: 'Van', feeding: 'Food', washing: 'Soap' }
  return map[type] || 'Menu'
}

const handleServiceChange = (item) => {
  form.serviceId = item.id
  form.mode = item.mode
  const isRouteMode = item.mode === 1 || item.mode === '1'

  if (isRouteMode) {
    form.type = 'transport'
  } else {
    const t = getServiceType(item.name)
    // 如果 mode=0 但识别为 transport，强制改为 feeding 作为兜底服务单
    form.type = t === 'transport' ? 'feeding' : t
  }

  calcPrice(form.type)
}

const currentPackages = computed(() => {
  return allPackages.filter(p => p.type === form.type)
})

const handlePkgSelect = (id) => {
  activeData.value.pkgId = id
  // Price calculation should remain same (base price), just payable changes
  calcPrice(form.type)
}

const calcPrice = (type) => {
  const data = form[type]
  const base = serviceList.find(s => s.type === type)?.basePrice || 0

  // Always use Base Logic for "Order Value", regardless of package
  if (type === 'transport') {
    if (data.subType === 'round') {
      data.pickPrice = base
      data.dropPrice = base
    } else if (data.subType === 'pick') {
      data.pickPrice = base
      data.dropPrice = 0
    } else if (data.subType === 'drop') {
      data.pickPrice = 0
      data.dropPrice = base
    }
  } else if (type === 'feeding') {
    data.fulfillmentCommission = base * data.count
  } else if (type === 'washing') {
    data.fulfillmentCommission = base
  }
}

// Add User Logic
const userDialogVisible = ref(false)
const openAddUser = () => { userDialogVisible.value = true }
const handleUserSuccess = (newUser) => {
  // 重新获取列表
  userQuery.pageNum = 1
  fetchUsers()

  if (newUser && newUser.id) {
    // 后端如果直接返回了用户信息或主键，尝试将其加入列表中并选中
    const exists = userOptions.value.find(u => u.id === newUser.id)
    if (!exists) {
      userOptions.value.unshift(newUser)
    }
    form.userId = newUser.id
    currentPets.value = []
    form.petId = ''
    ElMessage.success('用户添加成功并已自动选中')
  } else {
    // 未返回具体信息情况，清空当前选中项让用户重选
    form.userId = ''
    currentPets.value = []
    form.petId = ''
    ElMessage.success('用户添加成功')
  }
}

// Add Pet Logic
const petDialogVisible = ref(false)
const openAddPet = () => { petDialogVisible.value = true }

// --- Import WeChat Order ---
const importDialogVisible = ref(false)
const importText = ref('')
const importLoading = ref(false)

const openImportDialog = () => {
  importText.value = ''
  importDialogVisible.value = true
}

const parseWechatOrderText = (text) => {
  const result = {}
  const lines = text.split('\n').map(l => l.trim()).filter(l => l)

  for (const line of lines) {
    const match = line.match(/^(.+?)[：:]\s*(.*)/)
    if (!match) continue
    const key = match[1].trim()
    const value = match[2].trim()
    if (key.includes('门店')) result.storeName = value
    else if (key.includes('宠物用户')) result.customerPhone = value
    else if (key.includes('宠物')) result.petName = value
    else if (key.includes('服务') || key.includes('选择服务')) result.serviceName = value
    else if (key.includes('接送类型')) result.transportType = value
    else if (key.includes('时间')) result.serviceTime = value
    else if (key.includes('团购套餐')) result.groupBuyPackage = value
    else if (key.includes('备注')) result.remark = value
  }

  return result
}

/**
 * 解析时间字符串为 yyyy-MM-dd HH:mm:ss 格式
 */
const resolveTimeString = (timeStr) => {
  if (!timeStr) return ''
  const match = timeStr.match(/(\d{4})\s*年\s*(\d{1,2})\s*月\s*(\d{1,2})\s*日\s*(\d{1,2})\s*点/)
  if (match) {
    return `${match[1]}-${match[2].padStart(2, '0')}-${match[3].padStart(2, '0')} ${match[4].padStart(2, '0')}:00`
  }
  return timeStr
}

/**
 * 解析接送单时间行
 * 单程: "2026年5月28日18点" → { pickTime }
 * 双程: "接[2026年5月28日18点]，送[2026年5月28日18点]" → { pickTime, dropTime }
 */
const parseTransportTime = (timeStr) => {
  const result = { pickTime: '', dropTime: '' }
  const roundMatch = timeStr.match(/接\s*[\[【]\s*(.*?)\s*[\]】]\s*[,，]\s*送\s*[\[【]\s*(.*?)\s*[\]】]/)
  if (roundMatch) {
    result.pickTime = resolveTimeString(roundMatch[1])
    result.dropTime = resolveTimeString(roundMatch[2])
  } else {
    result.pickTime = resolveTimeString(timeStr)
  }
  return result
}

/**
 * 解析服务单时间行
 * "2026年5月28日18点、2026年5月28日19点" → ['2026-05-28 18:00:00', '2026-05-28 19:00:00']
 */
const parseServiceTimes = (timeStr) => {
  if (!timeStr) return []
  return timeStr.split(/[,，、]/).map(t => resolveTimeString(t.trim())).filter(Boolean)
}

const handleImportWechatOrder = async () => {
  if (!importText.value.trim()) {
    ElMessage.warning('请粘贴微信订单文本')
    return
  }

  const parsed = parseWechatOrderText(importText.value)
  if (!parsed.storeName) {
    ElMessage.warning('未能解析到门店名称，请检查文本格式')
    return
  }
  if (!parsed.customerPhone) {
    ElMessage.warning('未能解析到宠物用户手机号，请检查文本格式')
    return
  }
  if (!parsed.petName) {
    ElMessage.warning('未能解析到宠物名，请检查文本格式')
    return
  }
  if (!parsed.serviceName) {
    ElMessage.warning('未能解析到服务名，请检查文本格式')
    return
  }

  importLoading.value = true
  try {
    // ① 查询门店
    const storeRes = await listStoreOnOrder({ name: parsed.storeName, pageNum: 1, pageSize: 10 })
    const storeList = storeRes?.data?.rows || storeRes?.rows || []
    if (storeList.length === 0) {
      ElMessage.warning(`未找到门店："${parsed.storeName}"`)
      return
    }
    const store = storeList[0]

    // 刷新门店列表到 stores 中
    stores.value = storeList
    storeTotal.value = storeRes?.data?.total || storeRes?.total || 1

    // ② 设置门店 → 触发 handleStoreChange 清空下游
    form.merchantId = store.id
    form.userId = ''
    form.petId = ''
    form.serviceId = ''
    form.type = ''
    form.mode = undefined
    currentPets.value = []

    // ③ 查询宠物用户（需要 tenantId + stationId）
    const customerRes = await listCustomerOnOrder({
      content: parsed.customerPhone,
      tenantId: store.tenantId,
      stationId: store.site
    })
    const customerList = customerRes?.data?.rows || customerRes?.rows || []
    if (customerList.length === 0) {
      ElMessage.warning(`门店"${parsed.storeName}"下未找到手机号："${parsed.customerPhone}"对应客户`)
      return
    }
    const customer = customerList[0]

    // 填充用户选项
    userOptions.value = customerList.map(c => ({
      id: c.id, name: c.name,
      phoneNumber: c.phoneNumber || c.phone,
      regionCode: c.regionCode, address: c.address
    }))
    userTotal.value = customerRes?.data?.total || customerRes?.total || customerList.length

    form.userId = customer.id

    // ④ 查询宠物
    const petRes = await listPetByUser(customer.id)
    const petList = petRes?.data || petRes?.rows || []
    if (petList.length === 0) {
      ElMessage.warning(`用户"${customer.name}"名下没有宠物`)
      return
    }
    const matchedPet = petList.find(p => p.name === parsed.petName)
    if (!matchedPet) {
      ElMessage.warning(`未找到宠物"${parsed.petName}"，用户"${customer.name}"名下有：${petList.map(p => p.name).join('、')}`)
      return
    }
    currentPets.value = petList
    form.petId = matchedPet.id

    // ⑤ 匹配服务
    const matchedService = allServices.value.find(s => s.name === parsed.serviceName)
    if (!matchedService) {
      const available = store.services
        ? allServices.value.filter(s => store.services.includes(s.id)).map(s => s.name)
        : allServices.value.map(s => s.name)
      ElMessage.warning(`未找到服务"${parsed.serviceName}"，该门店可选服务：${available.join('、')}`)
      return
    }

    if (store.services && !store.services.includes(matchedService.id)) {
      ElMessage.warning(`服务"${parsed.serviceName}"在该门店不可用`)
      return
    }

    handleServiceChange(matchedService)

    const isTransportOrder = form.type === 'transport'

    // ⑥ 显式填充地址、联系人（不依赖 watcher，避免异步时序导致红框）
    const storeRegion = store?.areaCode ? store.areaCode.split(',') : []
    const storeAddr = store?.address || ''
    const userRegion = customer?.regionCode ? customer.regionCode.split('/') : []
    const userAddr = customer?.address || ''
    const contactName = customer.name || ''
    const contactPhone = customer.phoneNumber || customer.phone || ''

    if (isTransportOrder) {
      form.transport.pickStartRegion = userRegion
      form.transport.pickStartDetail = userAddr
      form.transport.pickEndRegion = storeRegion
      form.transport.pickEndDetail = storeAddr
      form.transport.pickContact = contactName
      form.transport.pickPhone = contactPhone
      form.transport.dropStartRegion = storeRegion
      form.transport.dropStartDetail = storeAddr
      form.transport.dropEndRegion = userRegion
      form.transport.dropEndDetail = userAddr
      form.transport.dropContact = contactName
      form.transport.dropPhone = contactPhone
    } else {
      form[form.type].region = userRegion
      form[form.type].addressDetail = userAddr
    }

    // ⑦ 接送类型（仅接送单）
    if (isTransportOrder && parsed.transportType) {
      const typeMap = { '接送': 'round', '接': 'pick', '送': 'drop' }
      const subType = typeMap[parsed.transportType]
      if (subType) {
        form.transport.subType = subType
      }
    }

    // ⑧ 设置时间
    if (parsed.serviceTime) {
      const data = form[form.type]
      if (data) {
        if (isTransportOrder) {
          const times = parseTransportTime(parsed.serviceTime)
          if (times.pickTime) {
            data.pickTime = times.pickTime
          }
          if (times.dropTime) {
            data.dropTime = times.dropTime
          }
        } else {
          const times = parseServiceTimes(parsed.serviceTime)
          if (times.length > 0) {
            data.appointments = times.map(t => ({ startTime: t, endTime: t }))
          }
        }
      }
    }

    // ⑨ 团购套餐
    if (parsed.groupBuyPackage) {
      form.groupBuyPackage = parsed.groupBuyPackage
    }

    // ⑩ 备注
    if (parsed.remark) {
      const data = form[form.type]
      if (data) {
        data.other = parsed.remark
      }
    }

    importDialogVisible.value = false
    ElMessage.success('微信订单解析成功，已填充至表单，请核对后下单')
  } catch (err) {
    console.error('导入微信订单失败:', err)
    ElMessage.error(err?.msg || err?.message || '导入失败，请稍后重试')
  } finally {
    importLoading.value = false
  }
}
// --- End Import WeChat Order ---
const handlePetSuccess = (newPet) => {
  if (form.userId) {
    listPetByUser(form.userId).then(res => {
      currentPets.value = res.data || res.rows || []
      if (newPet && newPet.id) {
        form.petId = newPet.id
        ElMessage.success('宠物添加成功并已自动选中')
      } else {
        form.petId = ''
        ElMessage.success('宠物添加成功')
      }
    })
  } else {
    ElMessage.success('宠物添加成功')
  }
}


// --- Computed Helpers ---
const merchantOptions = computed(() => {
  return stores.value.map(m => ({ label: m.name, value: m.id }))
})
const availableServices = computed(() => {
  const store = stores.value.find(s => s.id === form.merchantId)
  if (!store || !store.services) return []
  return allServices.value.filter(srv => store.services.includes(srv.id))
})
const userSelectOptions = computed(() => {
  return userOptions.value.map(u => ({ label: `${u.name} - ${u.phoneNumber || u.phone}`, value: u.id }))
})
const selectedMerchantName = computed(() => stores.value.find(m => m.id === form.merchantId)?.name)
const selectedUserName = computed(() => userOptions.value.find(u => u.id === form.userId)?.name)
const selectedPet = computed(() => currentPets.value.find(p => p.id === form.petId))
const selectedPetName = computed(() => selectedPet.value?.name)
const selectedPetBreed = computed(() => selectedPet.value?.breed)
const selectedServiceName = computed(() => {
  return availableServices.value.find(s => s.id === form.serviceId)?.name || getTypeName(form.type)
})

const selectedPkgName = computed(() => {
  const pkgId = activeData.value?.pkgId
  return allPackages.find(p => p.id === pkgId)?.name || ''
})



const canSubmit = computed(() => {
  if (!form.merchantId || !form.userId || !form.petId || !form.serviceId) return false
  return true
})

const currentTenantId = computed(() => {
  const store = stores.value.find(s => s.id === form.merchantId)
  return store ? store.tenantId : undefined
})

const currentStationId = computed(() => {
  const store = stores.value.find(s => s.id === form.merchantId)
  return store ? store.site : undefined
})

// --- Methods ---
const fetchUsers = () => {
  if (!form.merchantId) return
  userLoading.value = true

  // 关联当前选中门店的租户ID和站点ID
  const store = stores.value.find(s => s.id === form.merchantId)
  userQuery.tenantId = store ? store.tenantId : undefined
  userQuery.stationId = store ? store.site : undefined

  listCustomerOnOrder(userQuery).then(res => {
    userOptions.value = res.rows || []
    userTotal.value = res.total || 0
  }).finally(() => {
    userLoading.value = false
  })
}

const handleUserPageChange = (page) => {
  userQuery.pageNum = page
  fetchUsers()
}

const searchUser = (query) => {
  userQuery.content = query || ''
  userQuery.pageNum = 1
  fetchUsers()
}

const handleUserVisibleChange = (visible) => {
  if (visible && form.merchantId) {
    userQuery.pageNum = 1
    fetchUsers()
  }
}

const handleUserChange = (val) => {
  form.petId = ''
  currentPets.value = []
  if (!val) return
  listPetByUser(val).then(res => {
    currentPets.value = res.data || res.rows || []
  })
}
const getStepTitle = (mode, type) => {
  if (mode === 1 || mode === '1') return '填写接送路线与时间'
  return '选择套餐与服务的细则'
}
const getTypeName = (type) => {
  const map = { transport: '宠物接送', feeding: '上门喂遛', washing: '上门洗护' }
  return map[type]
}
const formatTime = (time) => {
  if (!time) return ''
  const d = new Date(time)
  return `${d.getMonth() + 1}-${d.getDate()} ${d.getHours()}:${d.getMinutes() < 10 ? '0' + d.getMinutes() : d.getMinutes()}`
}

const resetForm = () => {
  form.merchantId = ''
  form.userId = ''
  form.petId = ''
  form.serviceId = ''
  form.type = ''
  form.mode = undefined
  form.groupBuyPackage = ''
  form.orderCommission = 0.00

  form.transport = {
    pkgId: '',
    fulfillmentCommission: 0,
    pickPrice: 35,
    dropPrice: 35,
    subType: 'round',
    pickStartRegion: [], pickStartDetail: '', pickEndRegion: [], pickEndDetail: '', pickContact: '', pickPhone: '', pickTime: '',
    dropStartRegion: [], dropStartDetail: '', dropEndRegion: [], dropEndDetail: '', dropContact: '', dropPhone: '', dropTime: '',
    other: ''
  }
  form.feeding = {
    pkgId: '', fulfillmentCommission: 68,
    appointments: [{ startTime: '', endTime: '' }],
    region: [], addressDetail: '',
    count: 1, dates: [], area: '', itemLoc: '', cleanLoc: '', foodAmount: '', other: ''
  }
  form.washing = {
    pkgId: '', fulfillmentCommission: 88,
    appointments: [{ startTime: '', endTime: '' }],
    region: [], addressDetail: '',
    time: '', petStatus: '', cleanLoc: '', toolLoc: '', other: ''
  }
  currentPets.value = []
}

const validateForm = () => {
  // 1. 基础信息校验
  if (!form.merchantId) return '请选择服务门店';
  if (!form.userId) return '请选择宠主用户';
  if (!form.petId) return '请选择宠物';
  if (!form.serviceId) return '请选择服务项目';
  if (!form.orderCommission || form.orderCommission <= 0) return '请填写订单佣金且不能为0';

  // 2. 业务详情校验
  if (form.type === 'transport') {
    const td = form.transport;
    if (['round', 'pick'].includes(td.subType)) {
      if (!td.pickStartRegion || td.pickStartRegion.length === 0) return '请选择接宠起点区域';
      if (!td.pickStartDetail) return '请填写接宠起点详细地址';
      if (!td.pickEndRegion || td.pickEndRegion.length === 0) return '请选择接宠终点区域';
      if (!td.pickEndDetail) return '请填写接宠终点详细地址';
      if (!td.pickContact) return '请填写接宠联系人';
      if (!td.pickPhone) return '请填写接宠电话';
      if (!td.pickTime) return '请选择接宠时间';
    }
    if (['round', 'drop'].includes(td.subType)) {
      if (!td.dropStartRegion || td.dropStartRegion.length === 0) return '请选择送宠起点区域';
      if (!td.dropStartDetail) return '请填写送宠起点详细地址';
      if (!td.dropEndRegion || td.dropEndRegion.length === 0) return '请选择送宠终点区域';
      if (!td.dropEndDetail) return '请填写送宠终点详细地址';
      if (!td.dropContact) return '请填写送宠联系人';
      if (!td.dropPhone) return '请填写送宠电话';
      if (!td.dropTime) return '请选择预计送回时间';
    }
  } else if (form.type === 'feeding' || form.type === 'washing') {
    const data = form[form.type];
    if (!data.region || data.region.length === 0) return '请选择服务区域';
    if (!data.addressDetail) return '请填写服务详细地址';
    if (!data.appointments || data.appointments.length === 0) return '请至少添加一个预约时间';

    for (let i = 0; i < data.appointments.length; i++) {
      if (!data.appointments[i].startTime) {
        return `请选择第 ${i + 1} 个预约的开始时间`;
      }
      if (!data.appointments[i].endTime) {
        return `请选择第 ${i + 1} 个预约的结束时间`;
      }
    }
  }

  return null;
};

const handleSubmit = async () => {
  // 执行校验
  const errorMsg = validateForm();
  if (errorMsg) {
    ElMessage.warning(errorMsg);
    return;
  }

  try {
    const storeObj = stores.value.find(s => s.id === form.merchantId)
    if (!storeObj) {
      ElMessage.warning('请选择门店')
      return
    }

    let subOrders = []
    const baseMode = form.mode

    // 获取默认客户联系方式
    const userObj = userOptions.value.find(u => u.id === form.userId)
    const defaultContact = userObj?.name || ''
    const defaultPhone = userObj?.phoneNumber || userObj?.phone || ''

    if (form.type === 'transport') {
      const td = form.transport
      const createTransportSubOrder = (orderType, time, startRegion, startDetail, endRegion, endDetail, contact, phone) => {
        return {
          mode: baseMode,
          type: orderType,
          contact: contact || defaultContact,
          contactPhoneNumber: phone || defaultPhone,
          serviceTime: time || '',
          endServiceTime: time || '',
          fromCode: startRegion && startRegion.length > 0 ? startRegion[startRegion.length - 1] : '',
          fromAddress: startDetail || '',
          toCode: endRegion && endRegion.length > 0 ? endRegion[endRegion.length - 1] : '',
          toAddress: endDetail || ''
        }
      }

      // 接送单：往返算两个，接/送分别算一个
      if (td.subType === 'round' || td.subType === 'pick') {
        subOrders.push(createTransportSubOrder(
          td.subType === 'round' ? 0 : 2,
          td.pickTime, td.pickStartRegion, td.pickStartDetail, td.pickEndRegion, td.pickEndDetail, td.pickContact, td.pickPhone
        ))
      }

      if (td.subType === 'round' || td.subType === 'drop') {
        subOrders.push(createTransportSubOrder(
          td.subType === 'round' ? 1 : 3,
          td.dropTime, td.dropStartRegion, td.dropStartDetail, td.dropEndRegion, td.dropEndDetail, td.dropContact, td.dropPhone
        ))
      }
    } else {
      // 上门喂遛或洗护：一个服务时间一个子订单
      const hd = form[form.type]
      let code = hd.region && hd.region.length > 0 ? hd.region[hd.region.length - 1] : ''
      let address = hd.addressDetail || ''

      const createHomeSubOrder = (startTime, endTime) => {
        return {
          mode: baseMode,
          contact: defaultContact,
          contactPhoneNumber: defaultPhone,
          serviceTime: startTime || hd.time || '',
          endServiceTime: endTime || startTime || hd.time || '',
          fromCode: code,
          fromAddress: address,
          toCode: code,
          toAddress: address
        }
      }

      if (hd.appointments && hd.appointments.length > 0) {
        hd.appointments.forEach(appt => {
          subOrders.push(createHomeSubOrder(appt.startTime, appt.endTime))
        })
      } else if (hd.time) { // 兼容没有appointments只有time的情况
        subOrders.push(createHomeSubOrder(hd.time, hd.time))
      }
    }

    const payload = {
      store: form.merchantId,
      storeSite: storeObj.site,
      customer: form.userId,
      pet: form.petId,
      groupPurchasePackageName: form.groupBuyPackage || '',
      service: form.serviceId,
      remark: form[form.type] && form[form.type].other ? form[form.type].other : "",
      tenantId: storeObj.tenantId || "",
      orderCommission: Math.round((form.orderCommission || 0) * 100), // 订单佣金，单位：分
      subOrders: subOrders
    }

    const res = await createOrder(payload)
    if (res && res.code === 200) {
      ElMessage.success('下单成功')
      resetForm()
    }
  } catch (error) {
    console.error('Create order error: ', error)
  }
}

// Initialize
onMounted(() => {
  fetchStores()
  // fetchUsers() // 移除初始加载，改为输入后触发
  listAllService().then(res => {
    allServices.value = res.data || []
  })
})
</script>

<style scoped>
.page-container {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.create-layout {
  display: flex;
  align-items: flex-start;
  width: 100%;
  margin: 0;
}

/* Left Content */
.form-container {
  width: 70%;
  padding-right: 20px;
  min-width: 0;
  display: flex;
  flex-direction: column;
  gap: 20px;
  box-sizing: border-box;
}

.section-card {
  border-radius: 8px;
  border: none;
}

.card-title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 10px;
}

.step-num {
  background: #e6f7ff;
  color: #1890ff;
  width: 28px;
  height: 28px;
  border-radius: 50%;
  text-align: center;
  line-height: 28px;
  font-family: Impact, sans-serif;
}

.base-form .el-form-item {
  margin-bottom: 18px;
}

/* Pet Selection */
/* Pet Selection */
.pet-select-row {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 15px;
  width: 100%;
}

.pet-card {
  border: 1px solid #8D9095;
  border-radius: 8px;
  padding: 12px 15px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 12px;
  position: relative;
  transition: all 0.2s ease-in-out;
  background: #fff;
  min-height: 70px;
}

.pet-card:hover {
  border-color: #303133;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.pet-card.active {
  border-color: #409eff;
  background-color: #fff;
  box-shadow: 0 0 0 1px #409eff inset;
}

.check-mark {
  position: absolute;
  right: 0;
  top: 0;
  background: #409eff;
  color: white;
  width: 28px;
  height: 18px;
  border-radius: 0 8px 0 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
}

.pet-info .name {
  font-weight: bold;
  font-size: 15px;
  color: #303133;
  margin-bottom: 2px;
}

.pet-info .sub {
  font-size: 12px;
  color: #606266;
  line-height: 1.2;
}

.pet-card.add-card {
  border: 1px solid #8D9095;
  justify-content: center;
  align-items: center;
  color: #303133;
  flex-direction: row;
  gap: 8px;
  background: #fff;
  box-shadow: none;
  height: auto;
  min-height: 70px;
}

.pet-card.add-card:hover {
  border-color: #303133;
  color: #303133;
  background: #f9f9f9;
  transform: translateY(-2px);
}

/* Type Selection */
.type-selection {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 15px;
}

.type-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  cursor: pointer;
  position: relative;
  display: flex;
  align-items: center;
  gap: 15px;
  transition: all 0.2s;
  border: 2px solid transparent;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.type-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.1);
}

.type-card.active {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.type-card .icon-box {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  background: #f2f3f5;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: #606266;
}

.type-card.active .icon-box {
  background: #409eff;
  color: white;
}

/* Colors */
.type-card.transport.active .icon-box {
  background: #409eff;
}

.type-card.transport.active {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.type-card.feeding.active .icon-box {
  background: #e6a23c;
}

.type-card.feeding.active {
  border-color: #e6a23c;
  background-color: #fdf6ec;
}

.type-card.washing.active .icon-box {
  background: #67c23a;
}

.type-card.washing.active {
  border-color: #67c23a;
  background-color: #f0f9eb;
}

.type-name {
  font-weight: bold;
  font-size: 16px;
  color: #303133;
  margin-bottom: 4px;
}

.type-desc {
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.type-price {
  font-size: 14px;
  color: #f56c6c;
  font-weight: bold;
}

/* Custom Backend Icon Img */
.service-icon-img {
  width: 28px;
  height: 28px;
  object-fit: cover;
  border-radius: 4px;
}

/* Package Selection Grid */
.form-section-title {
  font-weight: bold;
  margin-bottom: 12px;
  font-size: 14px;
}

.package-selection-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 12px;
  margin-bottom: 20px;
}

.pkg-select-card {
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  padding: 10px 15px;
  cursor: pointer;
  position: relative;
  background: #fff;
  transition: all 0.2s;
  min-height: 56px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.pkg-select-card:hover {
  border-color: #409eff;
}

.pkg-select-card.active {
  border-color: #409eff;
  background-color: #ecf5ff;
}

.pkg-select-card .pkg-name {
  font-weight: bold;
  font-size: 14px;
  color: #303133;
}

.pkg-select-card .pkg-desc {
  font-size: 12px;
  color: #909399;
  margin-top: 2px;
}

.divider {
  height: 1px;
  background: #EBEEF5;
  margin: 15px 0;
}

/* Sidebar */
.summary-sidebar {
  width: 30%;
  flex-shrink: 0;
}

.summary-panel {
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  position: fixed;
  top: 154px;
  right: 10px;
  width: 25%;
  z-index: 2000;
}

.summary-header {
  background: #304156;
  color: white;
  padding: 15px 20px;
  font-weight: bold;
  font-size: 16px;
  border-radius: 8px 8px 0 0;
}

.summary-content {
  padding: 20px;
}

.row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
  font-size: 14px;
}

.row .label {
  color: #909399;
}

.row .value {
  color: #303133;
  font-weight: 500;
}

.preview-title {
  font-weight: bold;
  margin-bottom: 8px;
  color: #333;
}

.preview-detail {
  background: #f8f9fa;
  padding: 10px;
  border-radius: 4px;
  font-size: 13px;
  margin-bottom: 8px;
}

.preview-detail .minor {
  color: #999;
  font-size: 12px;
  margin-top: 2px;
}

.placeholder {
  color: #C0C4CC;
  text-align: center;
  padding: 20px 0;
  font-size: 13px;
  font-style: italic;
}


.summary-footer {
  background: #f9f9fc;
  padding: 15px 20px;
  border-top: 1px solid #ebeef5;
  text-align: center;
  border-radius: 0 0 8px 8px;
}

.submit-btn {
  width: 100%;
  font-weight: bold;
  border-radius: 22px;
}
</style>

<style>
/* 全局样式：用于在搜索框无内容时强行隐藏 PageSelect 的下拉弹窗 */
.hide-search-popper {
  display: none !important;
}
</style>
