<script setup lang="ts">
import type { MemberDaySettingDto } from '#/api/member';

import { reactive, watch } from 'vue';

import { Button, InputNumber, Select, Switch } from 'ant-design-vue';

interface Props {
  canManage: boolean;
  loading: boolean;
  value: MemberDaySettingDto | null;
}

const props = defineProps<Props>();

const emit = defineEmits<{
  (event: 'save', value: MemberDaySettingDto): void;
}>();

const state = reactive<MemberDaySettingDto>({
  isEnabled: true,
  weekday: 2,
  extraDiscountRate: 9,
});

const weekdayOptions = [
  { label: '每周一', value: 1 },
  { label: '每周二', value: 2 },
  { label: '每周三', value: 3 },
  { label: '每周四', value: 4 },
  { label: '每周五', value: 5 },
  { label: '每周六', value: 6 },
  { label: '每周日', value: 7 },
];

watch(
  () => props.value,
  (value) => {
    if (!value) {
      return;
    }

    state.isEnabled = value.isEnabled;
    state.weekday = value.weekday;
    state.extraDiscountRate = value.extraDiscountRate;
  },
  { immediate: true },
);

function submit() {
  emit('save', {
    isEnabled: state.isEnabled,
    weekday: Number(state.weekday || 2),
    extraDiscountRate: Number(state.extraDiscountRate || 9),
  });
}
</script>

<template>
  <div class="mm-member-day">
    <div class="mm-section-title">会员日设置</div>

    <div class="mm-day-card">
      <div class="mm-day-row">
        <span class="mm-day-label">启用会员日</span>
        <Switch
          :checked="state.isEnabled"
          :disabled="!props.canManage"
          @update:checked="(value) => (state.isEnabled = !!value)"
        />
      </div>

      <div class="mm-day-row">
        <span class="mm-day-label">会员日</span>
        <Select
          :value="state.weekday"
          class="mm-day-select"
          :options="weekdayOptions"
          :disabled="!props.canManage"
          @update:value="(value) => (state.weekday = Number(value || 2))"
        />
      </div>

      <div class="mm-day-row">
        <span class="mm-day-label">会员日权益</span>
        <div class="mm-day-benefit">
          <span>额外</span>
          <InputNumber
            :value="state.extraDiscountRate"
            :min="0.1"
            :max="10"
            :step="0.1"
            :precision="1"
            :disabled="!props.canManage"
            @update:value="
              (value) =>
                (state.extraDiscountRate = Number(
                  value || state.extraDiscountRate,
                ))
            "
          />
          <span>折优惠</span>
        </div>
      </div>

      <div class="mm-day-actions">
        <Button
          type="primary"
          :disabled="!props.canManage"
          :loading="props.loading"
          @click="submit"
        >
          保存会员日设置
        </Button>
      </div>
    </div>
  </div>
</template>
