<script setup lang="ts">
/**
 * 文件职责：时段规则编辑抽屉。
 */
import type { ScheduleEditorForm, ScheduleProductChip } from '../types';

import { onBeforeUnmount, watch } from 'vue';

import { IconifyIcon } from '@vben/icons';

import { WEEK_DAY_OPTIONS } from '../composables/schedule-page/constants';

const props = defineProps<{
  form: ScheduleEditorForm;
  open: boolean;
  selectedProducts: ScheduleProductChip[];
  submitText: string;
  submitting: boolean;
  title: string;
}>();

const emit = defineEmits<{
  close: [];
  openProductPicker: [];
  removeProduct: [productId: string];
  selectAllDays: [];
  selectWeekdays: [];
  selectWeekend: [];
  setEndTime: [value: string];
  setName: [value: string];
  setStartTime: [value: string];
  submit: [];
  toggleStatus: [];
  toggleWeekDay: [day: number];
}>();

function closeDrawer() {
  emit('close');
}

function submit() {
  if (props.submitting) return;
  emit('submit');
}

function isWeekDayActive(day: number) {
  return props.form.weekDays.includes(day);
}

function setBodyLock(locked: boolean) {
  if (typeof document === 'undefined') return;
  document.body.style.overflow = locked ? 'hidden' : '';
}

watch(
  () => props.open,
  (open) => {
    setBodyLock(open);
  },
  { immediate: true },
);

onBeforeUnmount(() => {
  setBodyLock(false);
});
</script>

<template>
  <Teleport to="body">
    <div class="g-drawer-mask" :class="{ open }" @click="closeDrawer"></div>

    <div
      class="g-drawer ptm-editor-drawer"
      :class="{ open }"
      style="width: 520px"
    >
      <div class="g-drawer-hd">
        <span class="g-drawer-title">{{ title }}</span>
        <button type="button" class="g-drawer-close" @click="closeDrawer">
          <IconifyIcon icon="lucide:x" />
        </button>
      </div>

      <div class="g-drawer-bd">
        <div class="g-form-group">
          <label class="g-form-label required">规则名称</label>
          <input
            type="text"
            class="g-input"
            :value="form.name"
            maxlength="30"
            placeholder="请输入规则名称，如：早餐供应、午市套餐"
            @input="
              (event) =>
                emit('setName', (event.target as HTMLInputElement).value)
            "
          />
        </div>

        <div class="g-form-group">
          <label class="g-form-label required">时间范围</label>
          <div class="ptm-fg-row">
            <input
              type="time"
              class="g-input"
              :value="form.startTime"
              @input="
                (event) =>
                  emit('setStartTime', (event.target as HTMLInputElement).value)
              "
            />
            <span class="ptm-fg-sep">~</span>
            <input
              type="time"
              class="g-input"
              :value="form.endTime"
              @input="
                (event) =>
                  emit('setEndTime', (event.target as HTMLInputElement).value)
              "
            />
          </div>
          <div class="g-hint">
            结束时间小于开始时间时视为跨天（如 21:00 ~ 02:00）
          </div>
        </div>

        <div class="g-form-group">
          <label class="g-form-label required">适用星期</label>
          <div class="ptm-day-sel">
            <button
              v-for="day in WEEK_DAY_OPTIONS"
              :key="day.value"
              type="button"
              class="ptm-day"
              :class="{ active: isWeekDayActive(day.value) }"
              @click="emit('toggleWeekDay', day.value)"
            >
              {{ day.label }}
            </button>
          </div>
          <div class="ptm-day-quick">
            <button
              type="button"
              class="g-btn g-btn-sm"
              @click="emit('selectAllDays')"
            >
              全选
            </button>
            <button
              type="button"
              class="g-btn g-btn-sm"
              @click="emit('selectWeekdays')"
            >
              工作日
            </button>
            <button
              type="button"
              class="g-btn g-btn-sm"
              @click="emit('selectWeekend')"
            >
              周末
            </button>
          </div>
        </div>

        <div class="g-form-group">
          <label class="g-form-label required">关联商品</label>
          <div class="ptm-prod-search">
            <input
              type="text"
              class="g-input"
              readonly
              placeholder="搜索并选择要关联的商品…"
              @click="emit('openProductPicker')"
            />
          </div>

          <div class="ptm-prod-selected">
            <span
              v-for="product in selectedProducts"
              :key="product.id"
              class="ptm-prod-chip"
            >
              {{ product.name }}
              <button
                type="button"
                class="ptm-prod-chip-x"
                @click="emit('removeProduct', product.id)"
              >
                <IconifyIcon icon="lucide:x" />
              </button>
            </span>
            <span v-if="selectedProducts.length === 0" class="ptm-prod-empty">
              暂未关联商品
            </span>
          </div>
        </div>

        <div class="g-form-group">
          <label class="g-form-label">启用状态</label>
          <div class="ptm-toggle-row">
            <button
              type="button"
              class="g-toggle"
              :class="{ on: form.status === 'enabled' }"
              @click="emit('toggleStatus')"
            ></button>
            <span class="g-toggle-label">{{
              form.status === 'enabled' ? '启用' : '停用'
            }}</span>
          </div>
        </div>
      </div>

      <div class="g-drawer-ft">
        <button type="button" class="g-btn" @click="closeDrawer">取消</button>
        <button
          type="button"
          class="g-btn g-btn-primary"
          :disabled="submitting"
          @click="submit"
        >
          {{ submitText }}
        </button>
      </div>
    </div>
  </Teleport>
</template>
