<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Icon } from '@iconify/vue'
import { serviceExecutionApi } from '@/api/service.js'

const tableData = ref([])
const total = ref(0)
const loading = ref(false)
const dialogVisible = ref(false)
const submitLoading = ref(false)

const today = new Date().toISOString().slice(0, 10)

const searchForm = reactive({ order_id: '', technician_id: '', status: '', date: today })
const pagination = reactive({ page: 1, per_page: 20 })

const formRef = ref(null)
const form = reactive({
  order_id: '', service_item_name: '', technician_id: '', technician_name: '', scheduled_at: '', notes: ''
})

const statusMap = {
  scheduled: '待执行',
  in_progress: '执行中',
  completed: '已完成',
  cancelled: '已取消'
}
const statusTagType = {
  scheduled: 'warning',
  in_progress: 'primary',
  completed: 'success',
  cancelled: 'info'
}

const formRules = {
  order_id: [{ required: true, message: '请输入关联订单ID', trigger: 'blur' }],
  service_item_name: [{ required: true, message: '请输入服务项目名称', trigger: 'blur' }],
  scheduled_at: [{ required: true, message: '请选择计划执行时间', trigger: 'change' }]
}

// 今日待执行行高亮
function getRowClass({ row }) {
  const scheduledDate = row.scheduled_at ? row.scheduled_at.slice(0, 10) : ''
  if (scheduledDate === today && row.status === 'scheduled') return 'row-today-highlight'
  return ''
}

const todayCount = computed(() =>
  tableData.value.filter(r => {
    const d = r.scheduled_at ? r.scheduled_at.slice(0, 10) : ''
    return d === today && r.status === 'scheduled'
  }).length
)

async function fetchList() {
  loading.value = true
  try {
    const res = await serviceExecutionApi.getList({ ...searchForm, ...pagination })
    tableData.value = res.data?.list || res.data?.data || []
    total.value = res.data?.total || 0
  } catch {
    ElMessage.error('加载失败')
  } finally {
    loading.value = false
  }
}

function handleSearch() { pagination.page = 1; fetchList() }
function handleReset() {
  Object.assign(searchForm, { order_id: '', technician_id: '', status: '', date: today })
  handleSearch()
}

function handleAdd() {
  Object.assign(form, { order_id: '', service_item_name: '', technician_id: '', technician_name: '', scheduled_at: '', notes: '' })
  dialogVisible.value = true
}

async function handleComplete(row) {
  await ElMessageBox.confirm(`确认「${row.service_item_name}」已执行完成？`, '标记完成', {
    type: 'success',
    confirmButtonText: '确认完成'
  })
  try {
    await serviceExecutionApi.finish(row.id)
    ElMessage.success('已标记完成')
    fetchList()
  } catch {
    ElMessage.error('操作失败')
  }
}

async function handleSubmit() {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    submitLoading.value = true
    try {
      await serviceExecutionApi.create(form)
      ElMessage.success('创建成功')
      dialogVisible.value = false
      fetchList()
    } catch {
      ElMessage.error('创建失败')
    } finally {
      submitLoading.value = false
    }
  })
}

function handlePageChange(val) { pagination.page = val; fetchList() }
function handleSizeChange(val) { pagination.per_page = val; pagination.page = 1; fetchList() }

onMounted(() => fetchList())
</script>

<template>
  <div class="p-6 space-y-4">
    <!-- 搜索栏 -->
    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm p-4 flex items-center flex-wrap gap-3">
      <el-input v-model="searchForm.order_id" placeholder="订单ID" clearable style="width:140px" />
      <el-input v-model="searchForm.technician_id" placeholder="技师ID" clearable style="width:140px" />
      <el-select v-model="searchForm.status" placeholder="执行状态" clearable style="width:130px">
        <el-option v-for="(v, k) in statusMap" :key="k" :label="v" :value="k" />
      </el-select>
      <el-date-picker v-model="searchForm.date" type="date" value-format="YYYY-MM-DD" placeholder="执行日期" style="width:160px" />
      <el-button type="primary" @click="handleSearch">
        <Icon icon="solar:magnifer-bold-duotone" class="mr-1" />查询
      </el-button>
      <el-button @click="handleReset">重置</el-button>
    </div>

    <!-- 今日待执行提示 -->
    <div v-if="todayCount > 0" class="bg-rose-50 border border-rose-200 rounded-xl px-4 py-3 flex items-center gap-2">
      <Icon icon="solar:bell-bing-bold-duotone" class="text-rose-500 text-xl flex-shrink-0" />
      <span class="text-rose-600 text-sm font-medium">
        今日共有 <span class="text-rose-700 font-bold">{{ todayCount }}</span> 条待执行服务，已高亮显示。
      </span>
    </div>

    <!-- 表格区 -->
    <div class="bg-white rounded-2xl border border-gray-100 shadow-sm">
      <div class="flex items-center justify-between px-5 py-4 border-b border-gray-50">
        <div class="flex items-center gap-2">
          <span class="w-1 h-5 bg-rose-500 rounded-full inline-block"></span>
          <span class="font-semibold text-gray-700">服务执行记录</span>
        </div>
        <el-button type="primary" @click="handleAdd">
          <Icon icon="solar:add-circle-bold-duotone" class="mr-1" />新建执行记录
        </el-button>
      </div>
      <div class="px-2">
        <el-table v-loading="loading" :data="tableData" style="width:100%" :row-class-name="getRowClass">
          <el-table-column prop="service_item_name" label="服务项目" min-width="140" />
          <el-table-column label="客户" min-width="100">
            <template #default="{ row }">{{ row.customer_name || '-' }}</template>
          </el-table-column>
          <el-table-column label="执行技师" min-width="100">
            <template #default="{ row }">{{ row.technician_name || '-' }}</template>
          </el-table-column>
          <el-table-column prop="scheduled_at" label="计划时间" min-width="160" />
          <el-table-column prop="completed_at" label="完成时间" min-width="160">
            <template #default="{ row }">{{ row.completed_at || '—' }}</template>
          </el-table-column>
          <el-table-column label="客户评分" width="90" align="center">
            <template #default="{ row }">
              <span v-if="row.customer_rating" class="text-amber-500 font-medium">{{ row.customer_rating }} ★</span>
              <span v-else class="text-gray-300">—</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" width="90" align="center">
            <template #default="{ row }">
              <el-tag :type="statusTagType[row.status]" size="small">{{ statusMap[row.status] || '-' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" fixed="right" align="center">
            <template #default="{ row }">
              <el-button
                v-if="row.status === 'scheduled' || row.status === 'in_progress'"
                size="small"
                type="success"
                text
                @click="handleComplete(row)"
              >
                标记完成
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="px-5 py-3 border-t border-gray-50">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.per_page"
          :total="total"
          :page-sizes="[10, 20, 50]"
          layout="total,sizes,prev,pager,next,jumper"
          background
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>

    <!-- 新建执行记录弹窗 -->
    <el-dialog v-model="dialogVisible" title="新建执行记录" width="540px" destroy-on-close>
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="100px">
        <el-form-item label="关联订单ID" prop="order_id">
          <el-input v-model="form.order_id" placeholder="请输入服务订单ID" />
        </el-form-item>
        <el-form-item label="服务项目" prop="service_item_name">
          <el-input v-model="form.service_item_name" placeholder="服务项目名称" />
        </el-form-item>
        <el-form-item label="执行技师">
          <el-input v-model="form.technician_name" placeholder="技师姓名（可选）" />
        </el-form-item>
        <el-form-item label="计划时间" prop="scheduled_at">
          <el-date-picker
            v-model="form.scheduled_at"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择计划执行时间"
            style="width:100%"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.notes" type="textarea" :rows="2" placeholder="执行备注（可选）" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
:deep(.row-today-highlight) {
  background-color: #fff1f2 !important;
}
:deep(.row-today-highlight:hover > td) {
  background-color: #ffe4e6 !important;
}
</style>
