<template>
  <el-dialog v-model="visible" title="派单调度" width="900px" top="5vh" destroy-on-close append-to-body>
    <div class="dispatch-dialog-content">
      <!-- Top: Order Info -->
      <div class="dispatch-order-info box-card" v-if="order">
        <div class="list-card order-card" style="margin: 0; box-shadow: none; cursor: default; border: none">
          <div class="card-left">
            <div class="type-tag" :class="order.typeCode">
              {{ getShortType(order.typeCode) }}
            </div>
          </div>
          <div class="card-main">
            <template v-if="order.typeCode === 'transport'">
              <div class="row-addr" :title="order.pickAddr">
                <span class="tag pick">取</span> {{ order.pickAddr }}
              </div>
              <div class="row-addr" :title="order.dropAddr">
                <span class="tag drop">送</span> {{ order.dropAddr }}
              </div>
            </template>
            <template v-else>
              <div class="row-addr" :title="order.address"><span class="tag home">址</span> {{ order.address }}</div>
            </template>
            <div class="row-time" style="margin-top: 4px">
              <el-icon><Clock /></el-icon> {{ order.time }}
              <span class="days-tag" v-if="order.daysLater">{{ order.daysLater }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- Current Rider Info (For Re-dispatch) -->
      <div class="current-rider-section" v-if="currentRider">
        <div class="select-header" style="margin-bottom: 8px">
          <span class="tit">当前派单履约者</span>
        </div>
        <div class="list-card rider-card" style="margin-bottom: 20px; border: 1px solid #e4e7ed; background: #fafafa; cursor: default">
          <div class="card-left relative">
            <el-avatar :src="currentRider.avatar" :size="40" />
            <div class="dot" :class="currentRider.status"></div>
          </div>
          <div class="card-main">
            <div class="row-1" style="justify-content: space-between; align-items: flex-start">
              <div style="display: flex; align-items: baseline; gap: 8px">
                <span class="r-name">{{ currentRider.name }}</span>
                <span class="r-phone">{{ currentRider.maskPhone }}</span>
              </div>
              <div class="status-right">
                <span class="status-badge" :class="currentRider.status">{{ getRiderStatusText(currentRider.status) }}</span>
              </div>
            </div>

            <div class="row-2 categories-row" style="margin-top: 6px; display: flex; gap: 4px; flex-wrap: wrap">
              <span v-for="cat in currentRider.categories" :key="cat" class="cat-tag" :class="getCategoryClass(cat)">{{ cat }}</span>
            </div>

            <div class="row-3 time-row" style="margin-top: 4px">
              <span class="last-time"
                >下一单: {{ currentRider.status === 'offline' || currentRider.status === 'disabled' ? '--' : currentRider.lastServiceTime }}</span
              >
            </div>
          </div>
        </div>
      </div>

      <!-- Middle: Rider Selection -->
      <div class="dispatch-rider-select">
        <div class="select-header">
          <span class="tit">选择履约者 (下一单时间由近及远排序)</span>
          <el-input v-model="searchQuery" placeholder="搜索履约者姓名/手机号" prefix-icon="Search" clearable style="width: 240px" />
        </div>

        <div class="rider-grid-wrapper">
          <el-scrollbar height="400px">
            <div class="rider-grid">
              <div
                v-for="rider in filteredRiders"
                :key="rider.id"
                class="list-card rider-card select-card"
                :class="{ active: selectedId === rider.id }"
                @click="selectedId = rider.id"
              >
                <div class="card-left relative">
                  <el-avatar :src="rider.avatar" :size="40" />
                  <div class="dot" :class="rider.status"></div>
                </div>
                <div class="card-main">
                  <div class="row-1" style="justify-content: space-between; align-items: flex-start">
                    <div style="display: flex; align-items: baseline; gap: 8px">
                      <span class="r-name">{{ rider.name }}</span>
                      <span class="r-phone">{{ rider.maskPhone }}</span>
                    </div>
                    <div class="status-right">
                      <span class="status-badge" :class="rider.status">{{ getRiderStatusText(rider.status) }}</span>
                    </div>
                  </div>

                  <div class="row-2 categories-row" style="margin-top: 6px; display: flex; gap: 4px; flex-wrap: wrap">
                    <span v-for="cat in rider.categories" :key="cat" class="cat-tag" :class="getCategoryClass(cat)">{{ cat }}</span>
                  </div>

                  <div class="row-3 time-row" style="margin-top: 4px">
                    <span class="last-time"
                      >下一单: {{ rider.status === 'offline' || rider.status === 'disabled' ? '--' : rider.lastServiceTime }}</span
                    >
                  </div>
                </div>

                <!-- Selected Check -->
                <div class="selected-mark" v-if="selectedId === rider.id">
                  <el-icon><Check /></el-icon>
                </div>
              </div>

              <div v-if="filteredRiders.length === 0" class="empty-text">暂无符合条件的履约者</div>
            </div>
          </el-scrollbar>
        </div>
      </div>

      <!-- Bottom: Fee & Submit -->
      <div class="dispatch-footer">
        <div class="fee-input">
          <span class="label">服务费用：</span>
          <el-input-number v-model="fee" :min="0" :precision="2" :step="10" placeholder="请输入" style="width: 140px" />
          <span class="unit">元</span>
        </div>
        <div class="btns">
          <el-button @click="visible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确认派单</el-button>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { Check, Clock, Search } from '@element-plus/icons-vue';

const props = defineProps({
  modelValue: { type: Boolean, default: false },
  order: { type: Object, default: () => null },
  currentRider: { type: Object, default: () => null },
  ridersList: { type: Array, default: () => [] }
});

const emit = defineEmits(['update:modelValue', 'submit']);

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
});

const searchQuery = ref('');
const selectedId = ref(null);
const fee = ref(0);

// Reset form when dialog opens
watch(visible, (val) => {
  if (val) {
    searchQuery.value = '';
    selectedId.value = null;
    fee.value = 0;
  }
});

const filteredRiders = computed(() => {
  let result = props.ridersList.filter((r) => r.status === 'online' || r.status === 'busy');

  if (searchQuery.value) {
    const q = searchQuery.value.toLowerCase();
    result = result.filter((r) => r.name.includes(q) || r.phone.includes(q));
  }

  result.sort((a, b) => {
    return a.lastServiceTime.localeCompare(b.lastServiceTime);
  });
  return result;
});

const handleSubmit = () => {
  if (!selectedId.value) {
    ElMessage.warning('请选择履约者');
    return;
  }
  if (!fee.value) {
    ElMessage.warning('请输入服务费用');
    return;
  }
  emit('submit', { order: props.order, riderId: selectedId.value, fee: fee.value });
};

// Helpers
const getShortType = (code) => {
  const map = { 'transport': '接送', 'feeding': '喂遛', 'washing': '洗护' };
  return map[code] || '订单';
};
const getRiderStatusText = (status) => {
  const map = { 'online': '接单中', 'busy': '接单中', 'offline': '休息中', 'disabled': '禁用' };
  return map[status];
};
const getCategoryClass = (cat) => {
  const map = { '接送': 'cat-transport', '喂遛': 'cat-feeding', '洗护': 'cat-washing' };
  return map[cat] || '';
};
</script>

<style scoped>
.list-card {
  background: #fff;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  padding: 12px;
  margin-bottom: 10px;
  display: flex;
  align-items: stretch;
  gap: 12px;
  transition: all 0.2s;
}

.card-left {
  flex-shrink: 0;
  display: flex;
  align-items: center;
}
.order-card .type-tag {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: bold;
}
.type-tag.transport {
  background: #e6a23c;
}
.type-tag.feeding {
  background: #67c23a;
}
.type-tag.washing {
  background: #409eff;
}

.card-main {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  gap: 4px;
}
.row-1 {
  display: flex;
  align-items: center;
}
.o-type {
  font-weight: bold;
  font-size: 14px;
  color: #303133;
}
.row-2 {
  font-size: 12px;
  color: #606266;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.row-3 {
  font-size: 12px;
  color: #909399;
  display: flex;
  align-items: center;
  gap: 4px;
}

.card-right {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  justify-content: center;
  gap: 8px;
  margin-left: 8px;
  flex-shrink: 0;
}
.card-right .actions {
  display: flex;
  align-items: center;
  gap: 4px;
}

.rider-card .card-left .dot {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  border: 2px solid #fff;
}
.dot.online {
  background: #67c23a;
}
.dot.busy {
  background: #409eff;
}
.dot.offline {
  background: #909399;
}

.r-name {
  font-size: 14px;
  font-weight: bold;
  color: #303133;
}
.r-phone {
  font-size: 12px;
  color: #909399;
}

.cat-tag {
  background: #f4f4f5;
  color: #909399;
  font-size: 10px;
  padding: 1px 4px;
  border-radius: 2px;
}
.cat-tag.cat-transport {
  background: #e6f7ff;
  color: #1890ff;
  border: 1px solid #91d5ff;
}
.cat-tag.cat-feeding {
  background: #f6ffed;
  color: #52c41a;
  border: 1px solid #b7eb8f;
}
.cat-tag.cat-washing {
  background: #fff0f6;
  color: #eb2f96;
  border: 1px solid #ffadd2;
}

.status-badge {
  font-size: 11px;
  padding: 2px 6px;
  border-radius: 4px;
  display: inline-block;
  font-weight: bold;
}
.status-badge.online {
  background: #f0f9eb;
  color: #67c23a;
}
.status-badge.busy {
  background: #ecf5ff;
  color: #409eff;
}
.status-badge.offline {
  background: #f4f4f5;
  color: #909399;
}
.status-badge.disabled {
  background: #fef0f0;
  color: #f56c6c;
}

.last-time {
  font-size: 11px;
  color: #999;
}

.dispatch-order-info {
  background: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
  margin-bottom: 20px;
  border: 1px solid #e4e7ed;
}
.dispatch-rider-select .select-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}
.dispatch-rider-select .tit {
  font-weight: bold;
  font-size: 14px;
}

.rider-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
  padding-right: 10px;
}
.rider-card.select-card {
  cursor: pointer;
  border: 1px solid #dcdfe6;
  position: relative;
  transition: all 0.2s;
  margin-bottom: 0;
}
.rider-card.select-card:hover {
  border-color: #409eff;
}
.rider-card.select-card.active {
  border-color: #409eff;
  background-color: #ecf5ff;
}
.selected-mark {
  position: absolute;
  top: 0;
  right: 0;
  background: #409eff;
  color: #fff;
  border-bottom-left-radius: 6px;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
}

.dispatch-footer {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.dispatch-footer .fee-input {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}
.empty-text {
  text-align: center;
  color: #909399;
  padding: 20px;
  width: 100%;
  grid-column: span 2;
}

/* Order Card New Layout */
.row-addr {
  font-size: 13px;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.5;
}
.row-addr .tag {
  font-size: 11px;
  color: #fff;
  padding: 1px 4px;
  border-radius: 4px;
  flex-shrink: 0;
  transform: scale(0.9);
}
.tag.pick {
  background: #409eff;
}
.tag.drop {
  background: #e6a23c;
}
.tag.home {
  background: #67c23a;
}
.row-time {
  font-size: 12px;
  color: #909399;
  display: flex;
  align-items: center;
  gap: 4px;
}
.days-tag {
  color: #f56c6c;
  background: #fef0f0;
  padding: 0 4px;
  border-radius: 4px;
  font-size: 11px;
  border: 1px solid #fde2e2;
  transform: scale(0.95);
}
</style>
