<script lang="ts" setup>
/**
 * 门店挂号统一设置弹窗：默认可预约天数（医生排班「跟随门店」时生效）
 * 诊所管理员固定本店（后端强制）；平台管理员需先选门店再配置
 */
import { computed, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { useUserStore } from '@vben/stores';

import { InputNumber, message } from 'ant-design-vue';

import StorePicker from '#/components/form/components/store-picker.vue';

import {
  getStoreRegisterSettingApi,
  saveStoreRegisterSettingApi,
} from '../api/schedule';

const userStore = useUserStore();
/** 平台管理员（user_type=2）需要选门店；诊所管理员后端固定本店 */
const isPlatform = computed(
  () => Number(userStore.userInfo?.roles?.user_type) === 2,
);

const storeId = ref<number | undefined>(undefined);
const defaultBookDays = ref<number>(7);
const loaded = ref(false);

/**
 * 拉取指定门店（或本店）的统一设置
 */
async function fetchSetting() {
  loaded.value = false;
  try {
    const data = await getStoreRegisterSettingApi(storeId.value || undefined);
    defaultBookDays.value = Number(data?.default_book_days || 7);
    // 诊所管理员回显后端解析出的本店 id，避免再传 0
    if (!isPlatform.value && data?.store_id) {
      storeId.value = Number(data.store_id);
    }
    loaded.value = true;
  } catch {
    message.error('获取门店统一设置失败');
  }
}

/** 平台管理员切换门店后重新拉取 */
function onStoreChange(val: number | undefined) {
  storeId.value = val;
  if (val) fetchSetting();
}

/**
 * 保存统一可预约天数
 */
async function handleSave() {
  if (isPlatform.value && !storeId.value) {
    message.warning('请先选择门店');
    return;
  }
  if (!defaultBookDays.value || defaultBookDays.value < 1) {
    message.warning('可预约天数至少为 1 天');
    return;
  }
  ModalApi.lock();
  try {
    await saveStoreRegisterSettingApi({
      store_id: storeId.value || 0,
      default_book_days: defaultBookDays.value,
    });
    message.success('设置保存成功');
    ModalApi.close();
  } catch {
    // 错误提示由 requestClient 统一弹出
  } finally {
    ModalApi.unlock();
  }
}

const [Modal, ModalApi] = useVbenModal({
  onOpenChange(isOpen) {
    if (isOpen) {
      storeId.value = undefined;
      defaultBookDays.value = 7;
      // 诊所管理员直接拉本店；平台管理员等选店后拉取
      if (isPlatform.value) {
        loaded.value = false;
      } else {
        fetchSetting();
      }
    }
  },
  onConfirm: handleSave,
});

defineExpose({ ModalApi });
</script>

<template>
  <Modal class="w-[440px]" title="排班统一设置">
    <div class="store-setting">
      <div v-if="isPlatform" class="store-setting__item">
        <div class="store-setting__label">选择门店</div>
        <StorePicker :value="storeId" @update:value="onStoreChange" />
      </div>
      <div class="store-setting__item">
        <div class="store-setting__label">默认可预约天数（含当天）</div>
        <div class="store-setting__control">
          <InputNumber
            v-model:value="defaultBookDays"
            :disabled="isPlatform && !loaded"
            :max="30"
            :min="1"
            style="width: 120px"
          />
          <span class="store-setting__tip">
            医生排班「可预约天数」为 0（跟随门店）时使用本值，默认 7 天
          </span>
        </div>
      </div>
    </div>
  </Modal>
</template>

<style scoped>
.store-setting {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 4px 2px;
}

.store-setting__label {
  margin-bottom: 8px;
  font-size: 13px;
  font-weight: 600;
  color: hsl(var(--foreground));
}

.store-setting__control {
  display: flex;
  gap: 8px;
  align-items: center;
  flex-wrap: wrap;
}

.store-setting__tip {
  font-size: 12px;
  color: hsl(var(--muted-foreground));
}
</style>
