<template>
  <div class="page-container">
    <el-card shadow="never" class="table-card">
      <template #header>
        <div class="card-header">
          <span class="title">订单列表</span>
          <div class="right-panel">
            <ServiceTypeSelector v-model="filters.service" :options="serviceOptions" @change="handleSearch" />
            <el-input v-model="filters.content" placeholder="订单号/商户/宠主/手机号" class="search-input" prefix-icon="Search"
              clearable @clear="handleSearch" @keyup.enter="handleSearch" />
            <el-cascader v-model="filterCascaderValue" :options="areaTreeOptions"
              :props="{ checkStrictly: true, value: 'id', label: 'name' }" placeholder="所属站点" clearable
              style="width: 350px; margin-left: 10px;" @change="handleFilterCascaderChange" />
            <el-button type="primary" icon="Search" @click="handleSearch">查询</el-button>
            <el-button v-hasPermi="['order:management:export']" type="success" icon="Download"
              @click="handleExport">导出Excel</el-button>
          </div>
        </div>

        <el-tabs v-model="filters.status" class="status-tabs" @tab-change="handleStatusTabChange">
          <el-tab-pane label="全部订单" name="" />
          <el-tab-pane label="待派单" name="0" />
          <el-tab-pane label="待接单" name="1" />
          <el-tab-pane label="待服务" name="2" />
          <el-tab-pane label="服务中" name="3" />
          <el-tab-pane label="已完成" name="4" />
          <el-tab-pane label="已取消" name="5" />
          <el-tab-pane label="已拒绝" name="6" />
          <el-tab-pane label="已关闭" name="7" />
        </el-tabs>
      </template>

      <el-table :data="tableData" style="width: 100%" v-loading="loading"
        :header-cell-style="{ background: '#f5f7fa' }">
        <el-table-column prop="code" label="订单号" width="170" fixed="left" />

        <el-table-column label="服务类型" width="190">
          <template #default="{ row }">
            <div class="service-type-cell">
              <el-tag>{{ getServiceName(row.service) }}</el-tag>
              <el-tag v-if="getServiceModeTag(row)" class="sub-tag" type="warning" effect="plain">{{
                getServiceModeTag(row) }}</el-tag>
              <el-tag v-if="getServiceOrderTypeTag(row)" class="sub-tag" :type="getServiceOrderTypeTag(row).type"
                effect="dark">{{
                  getServiceOrderTypeTag(row).label
                }}</el-tag>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="宠物信息" min-width="150">
          <template #default="{ row }">
            <div class="pet-info" style="cursor: pointer" @click="handlePetDetail(row)">
              <el-avatar :size="30" class="avatar-type">{{ row.petName?.charAt(0) }}</el-avatar>
              <div class="pet-detail">
                <div class="pet-name">
                  {{ row.petName }}
                </div>
                <div class="pet-breed">{{ row.petBreed }}</div>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="所属用户" width="120" prop="customerName">
          <template #default="{ row }">
            <span style="font-weight: 500">{{ row.customerName }}</span>
          </template>
        </el-table-column>

        <el-table-column label="城市/区域" width="140">
          <template #default="{ row }">
            <div>{{ getCityDistrictText(row).city || '-' }}</div>
            <div class="sub-text">{{ getCityDistrictText(row).district || '-' }}</div>
          </template>
        </el-table-column>

        <el-table-column label="商户/下单人" min-width="160">
          <template #default="{ row }">
            <div class="merchant-info">
              <div>{{ row.storeName }}</div>
              <div class="sub-text" v-if="row.placerUsername">{{ row.placerUsername }}</div>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="createTime" label="下单时间" width="165" sortable>
          <template #default="{ row }">
            <span class="time-text">{{ row.createTime }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="createTime" label="预约服务时间" width="165" sortable>
          <template #default="{ row }">
            <span class="time-text">{{ row.serviceTime }}</span>
          </template>
        </el-table-column>

        <el-table-column label="订单状态" width="100">
          <template #default="{ row }">
            <div class="status-cell">
              <div class="status-dot" :class="getStatusClass(row.status)"></div>
              <span>{{ getStatusName(row.status) }}</span>
            </div>
          </template>
        </el-table-column>



        <el-table-column label="订单佣金" width="100">
          <template #default="{ row }">
            <span v-if="row.orderCommission !== null && row.orderCommission !== undefined"
              style="color: #f56c6c; font-weight: bold">¥{{ row.orderCommission / 100.0 }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>

        <el-table-column label="履约者" width="120">
          <template #default="{ row }">
            <div v-if="row.fulfillerName" class="fulfiller-info">
              <span class="fulfiller-name">{{ row.fulfillerName }}</span>
            </div>
            <span v-else class="text-gray">暂未指派</span>
          </template>
        </el-table-column>


        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <div class="op-cell">
              <el-button link type="primary" size="small" @click="handleDetail(row)">详情</el-button>
              <!--              <el-button v-if="row.status === 0" link type="success" size="small" @click="openDispatchDialog(row)">派单</el-button>-->
              <!--              <el-button v-if="![0, 4].includes(row.status)" link type="warning" size="small" @click="openDispatchDialog(row)">重新派单</el-button>-->
              <el-button v-if="[0, 1].includes(row.status)" link type="danger" size="small"
                @click="handleCancel(row)">取消</el-button>
              <el-button v-if="row.fulfiller && [3, 4, 5].includes(row.status)" link type="warning" size="small"
                @click="openComplaintDialog(row)">投诉</el-button>

              <el-dropdown v-if="[3, 4].includes(row.status)" trigger="click"
                @command="(cmd) => handleCommand(cmd, row)">
                <span class="el-dropdown-link">
                  更多<el-icon class="el-icon--right">
                    <ArrowDown />
                  </el-icon>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <!--                    <el-dropdown-item v-if="row.status === 3" command="complete">确认完成</el-dropdown-item>-->
                    <el-dropdown-item v-if="row.status === 4 && getServiceMode(row.service) == 0" command="care_summary"
                      v-hasPermi="['order:management:nursingSummary']">护理小结</el-dropdown-item>

                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination v-model:current-page="pagination.current" v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 组件 -->
    <OrderDetailDrawer v-model:visible="detailVisible" :order="currentOrder" @dispatch="openDispatchDialog"
      @cancel="handleCancel" @command="handleCommand" @care-summary="openCareSummary" />

    <DispatchDialog v-model:visible="dispatchDialogVisible" :order="currentDispatchOrder"
      @submit="handleDispatchSubmit" />

    <CareSummaryDrawer v-model:visible="careSummaryVisible" :order="careSummaryOrder" @submit="saveCareSummary" />

    <PetDetailDrawer v-model:visible="petDetailVisible" :pet-id="currentPetId" />

    <!-- 投诉/评价弹窗 -->
    <el-dialog v-model="complaintDialogVisible" :title="complaintForm.praiseFlag ? '评价' : '投诉'" width="460px">
      <el-form :model="complaintForm" label-width="80px">
        <el-form-item label="评价类型">
          <el-radio-group v-model="complaintForm.praiseFlag">
            <el-radio :label="false">投诉/差评</el-radio>
            <el-radio :label="true">好评</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="complaintForm.praiseFlag ? '评价内容' : '投诉原因'" required>
          <el-input v-model="complaintForm.reason" type="textarea" :rows="4"
            :placeholder="complaintForm.praiseFlag ? '请输入评价内容' : '请输入投诉原因'" />
        </el-form-item>
        <el-form-item label="凭证图片">
          <image-upload v-model="complaintForm.photos" :limit="6" />
          <div class="form-tip">最多上传6张</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="complaintDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitComplaint">确认提交</el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onUnmounted, nextTick, getCurrentInstance, toRefs } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import OrderDetailDrawer from './components/OrderDetailDrawer.vue';
import DispatchDialog from './components/DispatchDialog.vue';
import CareSummaryDrawer from './components/CareSummaryDrawer.vue';

import PetDetailDrawer from '@/components/PetDetailDrawer/index.vue';
import ServiceTypeSelector from '@/components/ServiceTypeSelector/index.vue';
import { listAllService } from '@/api/service/list/index';
import { listSubOrder, dispatchSubOrder, getSubOrderInfo, cancelSubOrder, remarkSubOrder, confirmSubOrder, nursingSummarySubOrder, exportSubOrder } from '@/api/order/subOrder/index';
import { listAreaStation } from '@/api/system/areaStation';
import { getStore } from '@/api/system/store';
import { reward } from '@/api/fulfiller/pool';
import { getPet } from '@/api/archieves/pet';
import { getCustomer } from '@/api/archieves/customer';
import { addComplaint } from '@/api/fulfiller/complaint/index';

const { proxy } = getCurrentInstance();
const { sys_house_type, sys_entry_method } = toRefs(
  proxy?.useDict('sys_house_type', 'sys_entry_method')
);

const loading = ref(false);

const filters = reactive({
  service: '',
  status: '',
  content: '',
  site: undefined
});

const pagination = reactive({
  current: 1,
  size: 10,
  total: 100
});

const tableData = ref([]);
const serviceOptions = ref([]);
const areaStationList = ref([]);
const areaStationMap = ref({});
const areaTreeOptions = computed(() => {
  const buildTree = (data: any[], parentId: any): any[] => {
    return data
      .filter(item => String(item.parentId) === String(parentId))
      .map(item => {
        const children = buildTree(data, item.id);
        const res: any = { id: item.id, name: item.name };
        if (children && children.length > 0) res.children = children;
        return res;
      });
  };
  return buildTree(areaStationList.value, 0);
});
const filterCascaderValue = ref<any[]>([]);
const storeMap = ref({});

let timer = null;

onMounted(() => {
  getServiceList();
  getAreaStationList();
  handleSearch();

  timer = setInterval(() => {
    listSubOrder({
      pageNum: pagination.current,
      pageSize: pagination.size,
      service: filters.service !== '' ? filters.service : undefined,
      status: filters.status !== '' ? Number(filters.status) : undefined,
      content: filters.content || undefined,
      site: filters.site || undefined
    }).then((res) => {
      tableData.value = res.rows || [];
      pagination.total = res.total || 0;
      loadStoresForRows(tableData.value);
    }).catch(() => { });
  }, 5000);
});

onUnmounted(() => {
  if (timer) {
    clearInterval(timer);
    timer = null;
  }
});

const getServiceList = () => {
  listAllService().then((res) => {
    serviceOptions.value = res.data || [];
  });
};

const getAreaStationList = () => {
  listAreaStation().then((res) => {
    const list = res.data || [];
    areaStationList.value = list;
    const map = {};
    for (const item of list) {
      if (item && item.id !== undefined && item.id !== null) map[item.id] = item;
    }
    areaStationMap.value = map;
  });
};

const getCityDistrictText = (row) => {
  if (!row) return { city: '', district: '' };
  const map = areaStationMap.value || {};
  let stationId = row.site;
  if (!map[stationId] && row.store) {
    const store = (storeMap.value || {})[row.store];
    if (store?.site) stationId = store.site;
  }
  if (!stationId) return { city: '', district: '' };

  const station = map[stationId];
  if (!station) return { city: '', district: '' };

  const parent = station.parentId ? map[station.parentId] : undefined;
  if (!parent) return { city: station.name || '', district: '' };

  if (parent.type === 0) return { city: parent.name || '', district: '' };
  if (parent.type === 1) {
    const city = parent.parentId ? map[parent.parentId] : undefined;
    return { city: city?.name || '', district: parent.name || '' };
  }

  return { city: '', district: parent.name || '' };
};

const handleStatusTabChange = async () => {
  pagination.current = 1;
  await nextTick();
  handleSearch();
};

const handleFilterCascaderChange = (val: any[]) => {
  if (val && val.length > 0) {
    const lastId = val[val.length - 1];
    const node = areaStationList.value.find((item: any) => item.id === lastId);
    if (node && node.type === 2) {
      filters.site = lastId;
    } else {
      filters.site = undefined;
    }
  } else {
    filters.site = undefined;
  }
  handleSearch();
};

const handleSearch = () => {
  loading.value = true;
  listSubOrder({
    pageNum: pagination.current,
    pageSize: pagination.size,
    service: filters.service !== '' ? filters.service : undefined,
    status: filters.status !== '' ? Number(filters.status) : undefined,
    content: filters.content || undefined,
    site: filters.site || undefined
  })
    .then((res) => {
      tableData.value = res.rows || [];
      pagination.total = res.total || 0;
      loadStoresForRows(tableData.value);
      loading.value = false;
    })
    .catch(() => {
      loading.value = false;
    });
};

const loadStoresForRows = async (rows) => {
  const map = storeMap.value || {};
  const ids = Array.from(new Set((rows || []).map((r) => r?.store).filter(Boolean)));
  const missing = ids.filter((id) => map[id] === undefined);
  if (missing.length === 0) return;
  await Promise.all(
    missing.map(async (id) => {
      try {
        const res = await getStore(id);
        if (res?.data) map[id] = res.data;
      } catch {
        map[id] = null;
      }
    })
  );
  storeMap.value = { ...map };
};

const handleSizeChange = (val) => {
  pagination.size = val;
  handleSearch();
};
const handleCurrentChange = (val) => {
  pagination.current = val;
  handleSearch();
};

const getServiceName = (serviceId) => {
  const item = serviceOptions.value.find((i) => i.id === serviceId);
  return item ? item.name : '未知服务';
};

const getServiceMode = (serviceId) => {
  const item = serviceOptions.value.find((i) => i.id === serviceId);
  return item ? item.mode : null;
};

const getServiceModeTag = (row) => {
  if (getServiceMode(row.service) !== 1 && getServiceMode(row.service) !== '1') return '';
  const t = row?.type;
  if (t === 0 || t === '0' || t === 1 || t === '1') return '往返';
  return '';
};

const getServiceOrderTypeTag = (row) => {
  if (getServiceMode(row.service) !== 1 && getServiceMode(row.service) !== '1') return null;
  const t = row?.type;
  if (t === 0 || t === '0') return { label: '接', type: 'primary' };
  if (t === 1 || t === '1') return { label: '送', type: 'success' };
  if (t === 2 || t === '2') return { label: '单程接', type: 'primary' };
  if (t === 3 || t === '3') return { label: '单程送', type: 'success' };
  return null;
};

const getStatusName = (status) => {
  const map = { 0: '待派单', 1: '待接单', 2: '待服务', 3: '服务中', 4: '已完成', 5: '已取消', 6: '已拒绝', 7: '已关闭' };
  return map[status] || '未知';
};

const getStatusClass = (status) => {
  const map = { 0: 'pending_dispatch', 1: 'pending_accept', 2: 'pending_service', 3: 'in_service', 4: 'completed', 5: 'cancelled', 6: 'rejected', 7: 'closed' };
  return map[status] || 'pending_dispatch';
};

const getFulfillerStatusText = (status) => {
  const statusMap = {
    resting: '休息',
    busy: '接单中',
    disabled: '禁用'
  };
  return statusMap[status] || '未知状态';
};

const getFulfillerStatusType = (status) => {
  const typeMap = {
    resting: 'info',
    busy: 'success',
    disabled: 'danger'
  };
  return typeMap[status] || 'info';
};

// 弹窗状态管理
const detailVisible = ref(false);
const currentOrder = ref(null);

const dispatchDialogVisible = ref(false);
const currentDispatchOrder = ref(null);

const careSummaryVisible = ref(false);
const careSummaryOrder = ref(null);

const rewardDialogVisible = ref(false);
const remarkDialogVisible = ref(false);
const currentOperateRow = ref(null);

const complaintDialogVisible = ref(false);
const complaintForm = reactive({
  reason: '',
  photos: '',
  praiseFlag: false
});
const currentComplaintOrder = ref(null);

const petDetailVisible = ref(false);
const currentPetId = ref(null);

// 详情
const handleDetail = async (row) => {
  const typeName = getServiceName(row?.service);
  const isTransport = row?.mode === 1 || row?.mode === '1';
  const typeCode = isTransport ? 'transport' : typeName?.includes('喂') || typeName?.includes('遛') ? 'feeding' : 'washing';
  currentOrder.value = {
    ...row,
    orderNo: row?.code || row?.orderCode || row?.orderNo || row?.orderNumber || row?.no || '',
    type: row?.typeCode || row?.type || typeCode,
    serviceItem: getServiceName(row?.service) || row?.serviceName || row?.service || '',
    userAvatar: row?.userAvatar || '',
    address: row?.address || '',
    groupBuyPackage: '',
    transportType: row?.splitType || row?.transportType,
    detail: {
      ...row?.detail,
      pickTime: row?.detail?.pickTime || '',
      pickAddr: row?.detail?.pickAddr || '',
      pickContact: row?.detail?.pickContact || '',
      pickPhone: row?.detail?.pickPhone || '',
      dropTime: row?.detail?.dropTime || '',
      dropAddr: row?.detail?.dropAddr || '',
      dropContact: row?.detail?.dropContact || '',
      dropPhone: row?.detail?.dropPhone || '',
      packageName: row?.detail?.packageName || '',
      petStatus: row?.detail?.petStatus || '',
      area: row?.detail?.area || ''
    },
    petGender: '',
    petAge: '',
    petWeight: '',
    petVaccine: '',
    petSterilized: undefined,
    petCharacter: '',
    petHealth: '',
    fulfillerAvatar: '',
    fulfillerPhone: '',
    fulfillerStation: '',
    orderLogs: []
  };

  try {
    const res = await getSubOrderInfo(row?.id);
    const info = res?.data?.data || res?.data;
    if (info) {
      currentOrder.value = {
        ...(currentOrder.value || {}),
        id: info.id,
        orderNo: info.code || currentOrder.value?.orderNo,
        code: info.code,
        subOrderType: info.type,
        status: info.status ?? currentOrder.value?.status,
        mode: info.mode ?? currentOrder.value?.mode,
        type: info.mode === 1 || info.mode === '1' ? 'transport' : currentOrder.value?.type,
        transportType: info.mode === 1 || info.mode === '1' ? 'round' : currentOrder.value?.transportType,
        serviceTime: info.serviceTime || currentOrder.value?.serviceTime,
        endServiceTime: info.endServiceTime || currentOrder.value?.endServiceTime,
        contact: info.contact || currentOrder.value?.contact,
        contactPhoneNumber: info.contactPhoneNumber || currentOrder.value?.contactPhoneNumber,
        toAddress: info.toAddress || currentOrder.value?.toAddress,
        address:
          info.mode === 1 || info.mode === '1'
            ? info.toAddress || currentOrder.value?.address
            : info.address || info.toAddress || currentOrder.value?.address,
        fulfillmentCommission: info.fulfillmentCommission ?? currentOrder.value?.fulfillmentCommission,
        orderCommission: info.orderCommission ?? currentOrder.value?.orderCommission,
        fulfillerFee: info.fulfillmentCommission ?? currentOrder.value?.fulfillerFee,
        merchantName: info.storeName || currentOrder.value?.merchantName,
        platformId: info.platformId ?? currentOrder.value?.platformId,
        groupBuyPackage: info.groupPurchasePackageName || currentOrder.value?.groupBuyPackage,
        fulfiller: info.fulfiller ?? currentOrder.value?.fulfiller,
        remark: info.remark ?? currentOrder.value?.remark,
        detail: {
          ...(currentOrder.value?.detail || {}),
          pickTime: info.serviceTime || currentOrder.value?.detail?.pickTime,
          pickAddr: info.fromAddress || currentOrder.value?.detail?.pickAddr,
          pickContact: info.contact || currentOrder.value?.detail?.pickContact,
          pickPhone: info.contactPhoneNumber || currentOrder.value?.detail?.pickPhone,
          dropTime: info.endServiceTime || currentOrder.value?.detail?.dropTime,
          dropAddr: info.toAddress || currentOrder.value?.detail?.dropAddr,
          dropContact: info.contact || currentOrder.value?.detail?.dropContact,
          dropPhone: info.contactPhoneNumber || currentOrder.value?.detail?.dropPhone,
          fromAddress: info.fromAddress || currentOrder.value?.detail?.fromAddress,
          toAddress: info.toAddress || currentOrder.value?.detail?.toAddress,
          area: info.area || info.address || info.toAddress || currentOrder.value?.detail?.area,
          packageName: info.packageName || info.servicePackageName || info.package || currentOrder.value?.detail?.packageName,
          petStatus: info.petStatus || info.specialRequirement || info.requirement || currentOrder.value?.detail?.petStatus,
          fromCode: info.fromCode || currentOrder.value?.detail?.fromCode,
          toCode: info.toCode || currentOrder.value?.detail?.toCode
        }
      };
    }
  } catch { }
  detailVisible.value = true;
};

// 宠物详情
const handlePetDetail = (row) => {
  currentPetId.value = row.pet || row.petId;
  petDetailVisible.value = true;
};

// 取消订单
const handleCancel = (row) => {
  ElMessageBox.prompt('请输入取消订单的原因', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /\S+/,
    inputErrorMessage: '取消原因不能为空',
    inputPlaceholder: '必填，请输入取消原因',
    type: 'warning'
  }).then(({ value }) => {
    cancelSubOrder({ orderId: row?.id, reason: value }).then(() => {
      ElMessage.success('订单已取消');
      handleSearch();
    });
  }).catch(() => { });
};

// 派单
const openDispatchDialog = (row) => {
  const typeName = getServiceName(row?.service);
  const isTransport = row?.mode === 1 || row?.mode === '1';
  const typeCode = isTransport ? 'transport' : typeName?.includes('喂') || typeName?.includes('遛') ? 'feeding' : 'washing';

  const t = row?.subOrderType ?? row?.type;
  const transportType =
    t === 0 || t === '0' || t === 1 || t === '1'
      ? 'round'
      : t === 2 || t === '2'
        ? 'pick'
        : t === 3 || t === '3'
          ? 'drop'
          : row?.splitType || row?.transportType;

  const toAddress = row?.toAddress || '';
  const pickAddr = isTransport ? toAddress : '';
  const dropAddr = isTransport ? toAddress : '';
  const address = isTransport ? '' : toAddress;

  const orderObj = {
    id: row.id,
    typeCode,
    transportType,
    time: row.serviceTime || row.appointTime || row.createTime,
    status: row.status,
    address,
    pickAddr,
    dropAddr,
    service: row.service,
    fulfillmentCommission: row.fulfillmentCommission,
    orderCommission: row.orderCommission,
    riderId: row.riderId || row.fulfiller || null,
    riderGender: row.fulfillerGender
  };
  currentDispatchOrder.value = orderObj;
  dispatchDialogVisible.value = true;
};

const handleDispatchSubmit = (payload) => {
  if (!currentDispatchOrder.value) return;
  const fulfillmentCommissionFen = Math.round(Number(payload.fee || 0) * 100);
  dispatchSubOrder({
    orderId: currentDispatchOrder.value.id,
    fulfiller: payload.riderId,
    fulfillmentCommission: fulfillmentCommissionFen
  }).then(() => {
    ElMessage.success('派单成功');
    const row = tableData.value.find((r) => r.id === currentDispatchOrder.value.id);
    if (row) {
      row.status = 1;
      row.fulfillerName = payload.riderName || 'Unknown';
      row.price = payload.fee;
    }
    handleSearch();
  });
};

// 护理小结
const openCareSummary = async (row) => {
  const orderData = {
    ...row,
    careSummary: row.nursingSummary || undefined
  };

  // 获取宠物信息
  const petId = row?.pet || row?.petId;
  if (petId) {
    try {
      const petRes = await getPet(petId);
      const pet = petRes?.data;
      if (pet) {
        orderData.petAge = pet.age ? `${pet.age}岁` : '未知';
        orderData.petGender = pet.gender || 'male';
        orderData.petTags = pet.tags || [];
        orderData.petWeight = pet.weight ? `${pet.weight} kg` : '未知';
        orderData.petPersonality = pet.personality || '未知';
        orderData.healthStatus = pet.healthStatus || '未知';
        orderData.vaccineImg = pet.vaccineImg || '';
        orderData.allergy = pet.allergy || '无';
        orderData.petBreed = pet.breed || '未知';
      }
    } catch { }
  }

  // 获取客户信息（宠物主人）
  const customerId = row?.customer || row?.customerId;
  if (customerId) {
    try {
      const customerRes = await getCustomer(customerId);
      const customer = customerRes?.data;
      if (customer) {
        orderData.userName = customer.name || orderData.userName;
        orderData.homeTime = customer.homeTime || '未知';

        const houseTypeDict = sys_house_type.value?.find(d => d.value === customer.houseType);
        orderData.houseType = houseTypeDict?.label || customer.houseType || '未知';

        const entryMethodDict = sys_entry_method.value?.find(d => d.value === customer.entryMethod);
        orderData.entryMethod = entryMethodDict?.label || customer.entryMethod || '未知';

        orderData.entryDetail = customer.entryMethod === 'password'
          ? (customer.entryPassword ? `密码: ${customer.entryPassword}` : '未设置密码')
          : (customer.keyLocation || '未设置');
      }
    } catch { }
  }

  orderData.summaryTime = row.nursingSummaryTime || orderData.summaryTime;
  careSummaryOrder.value = orderData;
  careSummaryVisible.value = true;
};

const saveCareSummary = async (text) => {
  if (!careSummaryOrder.value?.id) {
    ElMessage.warning('订单信息不存在');
    return;
  }
  try {
    await nursingSummarySubOrder({
      orderId: careSummaryOrder.value.id,
      content: text
    });
    if (careSummaryOrder.value) {
      careSummaryOrder.value.careSummary = text;
      careSummaryOrder.value.nursingSummary = text;
    }
    ElMessage.success('护理小结已保存');
    handleSearch();
  } catch {
    // Error handled by interceptor
  }
};

// 奖惩
const openRewardDialog = (row) => {
  const typeName = getServiceName(row?.service)
  const isTransport = row?.mode === 1 || row?.mode === '1'
  const typeCode = isTransport ? 'transport' : typeName?.includes('喂') || typeName?.includes('遛') ? 'feeding' : 'washing'

  const t = row?.subOrderType ?? row?.type
  const transportType =
    typeof t === 'number' ? (t === 0 ? 'pick' : t === 1 ? 'drop' : t === 2 ? 'round' : undefined) :
      (t === 'pick' || t === 'drop' || t === 'round' ? t : undefined)

  currentOperateRow.value = {
    ...row,
    orderNo: row?.code || row?.orderNo,
    type: typeCode,
    transportType,
    splitType: row?.splitType
  }
  rewardDialogVisible.value = true
}

const handleRewardSubmit = async (form) => {
  if (!currentOperateRow.value?.fulfiller) {
    ElMessage.warning('当前订单未指派履约者，无法执行奖惩操作')
    return
  }
  try {
    const bizType = form.type === 'add' ? 'order_reward' : 'order_punish'
    // 如果调整项目是金额(balance)，则将元转换为分
    const amount = form.item === 'balance' ? Math.round(form.value * 100) : form.value
    await reward({
      fulfillerId: currentOperateRow.value.fulfiller,
      type: form.type,
      target: form.item,
      amount: amount,
      reason: form.reason,
      bizType: bizType,
      orderId: currentOperateRow.value.id
    })
    ElMessage.success(`操作成功：${form.type === 'add' ? '奖励' : '惩罚'}已执行`)
    handleSearch()
  } catch {
    // Error handled by interceptor
  }
}

// 备注
const openRemarkDialog = (row) => {
  currentOperateRow.value = {
    ...row,
    orderNo: row?.code || row?.orderNo
  }
  remarkDialogVisible.value = true
}

const handleRemarkSubmit = async (text) => {
  if (!currentOperateRow.value?.id) {
    ElMessage.warning('订单信息不存在')
    return
  }
  try {
    await remarkSubOrder({
      orderId: currentOperateRow.value.id,
      remark: text
    })
    if (currentOperateRow.value) {
      currentOperateRow.value.remark = text
    }
    ElMessage.success('备注已保存')
    handleSearch()
  } catch {
    // Error handled by interceptor
  }
}

// 投诉
const openComplaintDialog = (row) => {
  currentComplaintOrder.value = row;
  complaintForm.reason = '';
  complaintForm.photos = '';
  complaintForm.praiseFlag = false;
  complaintDialogVisible.value = true;
};

const submitComplaint = async () => {
  if (!complaintForm.reason.trim()) {
    ElMessage.warning(complaintForm.praiseFlag ? '请输入评价内容' : '请输入投诉原因');
    return;
  }
  if (!currentComplaintOrder.value?.id || !currentComplaintOrder.value?.fulfiller) {
    ElMessage.warning('订单信息不完整');
    return;
  }
  try {
    await addComplaint({
      orderId: currentComplaintOrder.value.id,
      fulfiller: currentComplaintOrder.value.fulfiller,
      reason: complaintForm.reason,
      photos: complaintForm.photos,
      praiseFlag: complaintForm.praiseFlag
    });
    ElMessage.success('提交成功');
    complaintDialogVisible.value = false;
    handleSearch();
  } catch { /* handled by interceptor */ }
};

// 更多操作
const handleCommand = (cmd, row) => {
  if (cmd === 'reward') openRewardDialog(row);
  if (cmd === 'remark') openRemarkDialog(row);
  if (cmd === 'care_summary') openCareSummary(row);
  if (cmd === 'complete') {
    ElMessageBox.confirm('确认将该订单手动标记为完成吗？', '提示', { type: 'warning' }).then(async () => {
      try {
        await confirmSubOrder({ id: row.id });
        ElMessage.success('订单已确认完成');
        handleSearch();
      } catch {
        // Error handled by interceptor
      }
    }).catch(() => { });
  }
  if (cmd === 'delete') {
    ElMessageBox.confirm('确认删除该订单吗？此操作不可恢复', '警告', { type: 'error' }).then(() => {
      tableData.value = tableData.value.filter((item) => item.id !== row.id);
      ElMessage.success('订单已删除');
    });
  }
};

/** 导出为Excel */
const handleExport = () => {
  proxy?.download(
    'order/subOrder/export',
    {
      status: filters.status !== '' ? Number(filters.status) : undefined,
      service: filters.service !== '' ? filters.service : undefined,
      content: filters.content || undefined
    },
    `订单列表.xlsx`
  );
};
</script>

<style scoped>
.page-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-weight: bold;
  font-size: 18px;
}

.right-panel {
  display: flex;
  gap: 10px;
  align-items: center;
}

.search-input {
  width: 220px;
}

.status-tabs {
  margin-top: 10px;
  margin-bottom: -10px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

/* Table Content Styles */
.service-type-cell {
  display: flex;
  flex-direction: row;
  gap: 4px;
  align-items: center;
}

.sub-tag {
  font-size: 11px;
  height: 20px;
  padding: 0 5px;
}

.pet-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.pet-info .el-avatar {
  background: #e0eaff;
  color: #409eff;
  font-weight: bold;
  flex-shrink: 0;
}

.pet-info .avatar-feeding {
  background: #fdf6ec;
  color: #e6a23c;
}

.pet-info .avatar-washing {
  background: #f0f9eb;
  color: #67c23a;
}

.pet-detail {
  display: flex;
  flex-direction: column;
  line-height: 1.4;
}

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

.pet-breed {
  color: #909399;
  font-weight: normal;
  font-size: 12px;
}

.merchant-info {
  display: flex;
  flex-direction: column;
  line-height: 1.4;
}

.sub-text {
  font-size: 12px;
  color: #999;
}

.text-gray {
  color: #ccc;
  font-style: italic;
}

.time-text {
  font-size: 13px;
  color: #606266;
}

.status-cell {
  display: flex;
  align-items: center;
}

.status-dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  margin-right: 6px;
  background-color: #909399;
}

.status-dot.pending_dispatch {
  background-color: #f56c6c;
  box-shadow: 0 0 4px rgba(245, 108, 108, 0.4);
}

.status-dot.pending_accept {
  background-color: #e6a23c;
}

.status-dot.pending_service {
  background-color: #49a3ff;
}

.status-dot.in_service {
  background-color: #49a3ff;
}

.status-dot.pending_confirm {
  background-color: #bf24e8;
}

.status-dot.completed {
  background-color: #67c23a;
}

.status-dot.cancelled {
  background-color: #909399;
}

.status-dot.rejected {
  background-color: #f56c6c;
}

.status-dot.closed {
  background-color: #909399;
}

.fulfiller-info {
  display: flex;
  flex-direction: column;
}

.fulfiller-name {
  font-weight: 500;
  color: #333;
}

.fulfiller-fee {
  font-size: 12px;
  color: #e6a23c;
}

.op-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
  font-size: 12px;
  display: flex;
  align-items: center;
  line-height: 1;
  height: 24px;
}
</style>
