<template>
  <div class="page-container">
    <div class="create-layout">

      <!-- 左侧：下单填写区 -->
      <div class="form-container">
        <!-- 1. 服务类型选择 -->
        <div class="type-selection">
          <div
            v-for="item in serviceList"
            :key="item.type"
            class="type-card"
            :class="[item.type, { active: form.type === item.type }]"
            @click="handleTypeChange(item.type)"
          >
            <div class="icon-box"><el-icon><component :is="item.icon" /></el-icon></div>
            <div class="text">
              <div class="type-name">{{ item.name }}</div>
              <div class="type-desc">{{ item.desc }}</div>
            </div>
          </div>
        </div>

        <!-- 2. 基础信息：门店与宠主 -->
        <el-card shadow="never" class="section-card">
          <template #header>
            <div class="card-title">
              <span class="step-num">02</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>
                    <template #label>
                      <div style="display:flex; align-items:center; height: 24px;">
                        <span>服务门店 (平台代下单)</span>
                      </div>
                    </template>
                    <el-select v-model="form.merchantId" placeholder="请选择商户门店" size="large" style="width: 100%" filterable>
                      <el-option v-for="m in merchants" :key="m.id" :label="m.name" :value="m.id" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item>
                    <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;">添加用户</el-button>
                      </div>
                    </template>
                    <el-select
                      v-model="form.userId"
                      placeholder="搜索手机号/姓名"
                      size="large"
                      style="width: 100%"
                      filterable
                      remote
                      :remote-method="searchUser"
                      :loading="userLoading"
                      @change="handleUserChange"
                    >
                      <el-option v-for="u in userOptions" :key="u.id" :label="u.name + ' - ' + u.phone" :value="u.id" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-form-item label="选择宠物" v-if="form.userId">
                <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.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">
                    <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>

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

          <div class="card-body">
            <!-- 服务套餐信息 -->
            <el-form-item label="团购套餐">
              <el-input v-model="form.groupBuyPackage" placeholder="请输入团购套餐名称 (选填)" clearable />
            </el-form-item>

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

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

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

            <!-- C. 上门洗护表单 -->
            <WashingForm v-show="form.type === 'washing'" :washing-data="form.washing" :pca-options="pcaOptions" @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">{{ getTypeName(form.type) }}</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">
              立即下单
            </el-button>
          </div>
        </div>
      </div>

    </div>

    <!-- Dialogs -->
    <!-- Add User Dialog -->
    <AddUserDialog v-model:visible="userDialogVisible" :pca-options="pcaOptions" @success="handleUserSuccess" />
    <AddPetDialog v-model:visible="petDialogVisible" :user-id="form.userId" :user-options="userOptions" @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 AddUserDialog from './components/AddUserDialog.vue'
import AddPetDialog from './components/AddPetDialog.vue'

// --- Mock Data ---
const merchants = ref([
  { id: 1, name: '萌它宠物三里屯店' },
  { id: 2, name: '宠爱国际动物医院' }
])
const userOptions = ref([
  { id: 101, name: '张三', phone: '13812345678' },
  { id: 102, name: '李四', phone: '13987654321' }
])
const mockPets = {
  101: [
    { id: 1, name: '旺财', breed: '金毛', avatar: '', region: ['北京市', '市辖区', '朝阳区'], address: '三里屯SOHO A座 1001' },
    { id: 2, name: '咪咪', breed: '布偶', avatar: '', region: ['北京市', '市辖区', '朝阳区'], address: '三里屯SOHO A座 1001' }
  ],
  102: [
    { id: 3, name: '奥利奥', breed: '边牧', avatar: '', region: ['上海市', '市辖区', '浦东新区'], address: '陆家嘴一号院 5-502' }
  ]
}

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: '包月接送套餐', price: 0 },
  { id: 11, type: 'feeding', name: '基础喂猫套餐', price: 0 },
  { id: 12, type: 'feeding', name: '深度陪玩套餐', price: 0 },
  { id: 13, type: 'washing', name: '精致洗护+美容', price: 0 },
  { id: 14, type: 'washing', name: '除菌药浴套餐', price: 0 },
]

// --- State ---
const userLoading = ref(false)
const currentPets = ref([])

const form = reactive({
  merchantId: '',
  userId: '',
  petId: '',
  type: 'transport',
  groupBuyPackage: '',

  // Sub Forms Data
  transport: {
    pkgId: '',
    price: 0,
    pickPrice: 35,
    dropPrice: 35,
    subType: 'round',
    pickRegion: [], pickDetail: '', pickContact: '', pickPhone: '', pickTime: '',
    dropRegion: [], dropDetail: '', dropContact: '', dropPhone: '', dropTime: ''
  },
  feeding: {
    pkgId: '', price: 68,
    appointments: [{ startTime: '', endTime: '' }],
    region: [], addressDetail: '',
    count: 1, dates: [], area: '', itemLoc: '', cleanLoc: '', foodAmount: '', other: ''
  },
  washing: {
    pkgId: '', price: 88,
    appointments: [{ startTime: '', endTime: '' }],
    region: [], addressDetail: '',
    time: '', petStatus: '', cleanLoc: '', toolLoc: '', other: ''
  }
})

// Address Autofill Watcher
watch(() => form.petId, (newId) => {
  if (!newId) return
  const pet = currentPets.value.find(p => p.id === newId)
  if (!pet) return

  const user = userOptions.value.find(u => u.id === form.userId)

  // Fill Transport
  form.transport.pickRegion = pet.region || []
  form.transport.pickDetail = pet.address || ''
  form.transport.pickContact = user?.name || ''
  form.transport.pickPhone = user?.phone || ''

  form.transport.dropRegion = pet.region || []
  form.transport.dropDetail = pet.address || ''
  form.transport.dropContact = user?.name || ''
  form.transport.dropPhone = user?.phone || ''

  // Fill Feeding
  form.feeding.region = pet.region || []
  form.feeding.addressDetail = pet.address || ''

  // Fill Washing
  form.washing.region = pet.region || []
  form.washing.addressDetail = pet.address || ''
})

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

// --- Logic ---

const handleTypeChange = (type) => {
  form.type = type
  calcPrice(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.price = base * data.count
  } else if (type === 'washing') {
    data.price = base
  }
}

// Add User Logic
const userDialogVisible = ref(false)
const openAddUser = () => { userDialogVisible.value = true }
const handleUserSuccess = (newUser) => {
  userOptions.value.push(newUser)
  form.userId = newUser.id
  currentPets.value = []
  form.petId = ''
  ElMessage.success('用户添加成功并已选中')
}

const pcaOptions = [
  {
    value: '北京市', label: '北京市',
    children: [
      { value: '市辖区', label: '市辖区', children: [ { value: '朝阳区', label: '朝阳区' }, { value: '海淀区', label: '海淀区' } ] }
    ]
  },
  {
    value: '上海市', label: '上海市',
    children: [
      { value: '市辖区', label: '市辖区', children: [ { value: '浦东新区', label: '浦东新区' }, { value: '徐汇区', label: '徐汇区' } ] }
    ]
  }
]

// Add Pet Logic
const petDialogVisible = ref(false)
const openAddPet = () => { petDialogVisible.value = true }
const handlePetSuccess = (newPet) => {
  if(!currentPets.value) currentPets.value = []
  currentPets.value.push(newPet)
  form.petId = newPet.id
  ElMessage.success('宠物添加成功')
}


// --- Computed Helpers ---
const selectedMerchantName = computed(() => merchants.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 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) return false
  return true
})

// --- Methods ---
const searchUser = (query) => { /* Mock */ }
const handleUserChange = (val) => {
  currentPets.value = mockPets[val] || []
  form.petId = ''
}
const getStepTitle = (type) => {
  const map = { transport: '填写接送路线与时间', feeding: '选择套餐与服务的细则', washing: '选择套餐与服务的细则' }
  return map[type]
}
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 handleSubmit = () => {
  ElMessage.success('下单成功！订单号：ORD20248888')
}

// Initialize
onMounted(() => {
  calcPrice('transport')
})
</script>

<style scoped>
.page-container { padding: 20px; background-color: #f0f2f5; min-height: 100vh; }
.create-layout { display: flex; gap: 20px; align-items: flex-start; max-width: 1400px; margin: 0 auto; }

/* Left Content */
.form-container { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 20px; }

.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; }
.type-price { font-size: 14px; color: #f56c6c; font-weight: bold; }

/* 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: 320px; flex-shrink: 0; }
.summary-panel { background: white; border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.05); position: sticky; top: 20px; }
.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>
