<template>
  <div class="page-container">
    <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>
                    <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>
                    <template #label>
                      <div
                        style="display: flex; justify-content: space-between; align-items: center; width: 100%; height: 24px">
                        <span>宠主用户</span>
                        <el-button v-hasPermi="['order:purchase:addCustomer']" type="primary" plain size="small"
                          @click="openAddUser" icon="Plus" style="margin-left: 15px">添加用户</el-button>
                      </div>
                    </template>
                    <PageSelect v-model="form.userId" placeholder="搜索姓名/手机号" size="large" style="width: 100%"
                      :options="userSelectOptions" :total="userTotal" :page-size="5" :filter-method="searchUser"
                      @page-change="handleUserPageChange" @update:modelValue="handleUserChange" />
                  </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.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 v-hasPermi="['order:purchase:addPet']" 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>

        <!-- 2. 服务类型选择 -->
        <div class="type-selection" v-if="form.merchantId">
          <div v-for="item in availableServices" :key="item.id" class="type-card"
            :class="[getServiceType(item), { 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-if="typeof item.icon === 'string' && isNaN(Number(item.icon))">
                <component :is="item.icon" />
              </el-icon>
              <el-icon v-else>
                <component :is="getServiceIcon(item)" />
              </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 v-hasPermi="['order:purchase:create']" type="primary" size="large" class="submit-btn"
              :disabled="!canSubmit" @click="handleSubmit"> 立即下单 </el-button>
          </div>
        </div>
      </div>
    </div>

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

<script setup lang="ts">
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 EditCustomerDialog from '@/components/EditCustomerDialog/index.vue';
import EditPetDialog from '@/components/EditPetDialog/index.vue';
import PageSelect from '@/components/PageSelect/index.vue';
import { listStoreOnOrder } from '@/api/system/store';
import { listAllService } from '@/api/service/list/index';
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: '', 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,

  // 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 = (item) => {
  if (!item) return 'transport';
  // 1. 如果是接送单模式 (mode=1)，强制为 transport
  if (item.mode === 1 || item.mode === '1') return 'transport';

  // 2. 如果是服务单模式 (mode=0)，根据名称区分喂遛还是洗护
  const name = typeof item === 'string' ? item : (item.name || '');
  if (name.includes('喂') || name.includes('遛')) return 'feeding';
  if (name.includes('洗护') || name.includes('美容')) return 'washing';

  return 'feeding'; // 默认服务类型
};

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

const handleServiceChange = (item) => {
  form.serviceId = item.id;
  form.mode = item.mode;
  form.type = getServiceType(item);
  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 fulfillmentCommission), 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) => {
  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;
};
const handlePetSuccess = (newPet) => {
  if (newPet && newPet.id) {
    const exists = currentPets.value.find(p => p.id === newPet.id)
    if (!exists) {
      currentPets.value.unshift(newPet)
    }
    form.petId = newPet.id
    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 currentStationId = computed(() => {
  const store = stores.value.find((s) => s.id === form.merchantId)
  return store ? store.site : undefined
})
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;
});

// --- Methods ---
const fetchUsers = () => {
  if (!userQuery.content) {
    userOptions.value = [];
    userTotal.value = 0;
    return;
  }

  // 关联当前选中门店的站点ID，仅显示同站点用户
  const store = stores.value.find((s) => s.id === form.merchantId);
  userQuery.stationId = store ? store.site : undefined;

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

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

const searchUser = (query) => {
  userQuery.content = query || '';
  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;

  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 = () => {
  if (!form.merchantId) return '请选择服务门店';
  if (!form.userId) return '请选择宠主用户';
  if (!form.petId) return '请选择宠物';
  if (!form.serviceId) return '请选择服务项目';
  if (!form.orderCommission || form.orderCommission <= 0) return '请填写订单佣金且不能为0';

  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 || 0;

    // 获取默认客户联系方式
    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,
      orderCommission: Math.round(Number(form.orderCommission || 0) * 100),
      remark: form[form.type] && form[form.type].other ? form[form.type].other : "",
      tenantId: storeObj.tenantId || '',
      subOrders: subOrders
    };

    const res = await createOrder(payload);
    if (res && res.code === 200) {
      ElMessage.success('下单成功');
      resetForm();
    } else {
      // 如果没有抛异常，走这里
      ElMessage.success('下单成功');
      resetForm();
    }
  } catch (error) {
    console.error('Create order error: ', error);
  }
};

// Initialize
onMounted(() => {
  fetchStores();
  listAllService().then((res) => {
    allServices.value = res.data || [];
  });
});
</script>

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

.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-fulfillmentCommission {
  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>
