<script lang="ts" setup>
import { onMounted, ref } from 'vue';

import { Page } from '@vben/common-ui';

import { Button, Card, Input, InputNumber, message, Radio, Switch, Tabs } from 'ant-design-vue';

import FormAvatar from '#/components/form/components/avatar.vue';

import { getSystemConfigList, saveSystemConfig } from '#/views/system/system-config/api';

defineOptions({ name: 'SpecialPrescriptionDisplayConfig' });

const TAB_STORAGE_KEY = 'special_prescription_config_active_tab';

const loading = ref(false);
const saving = ref(false);
const activeKey = ref('global');

const specialPrescriptionEnabled = ref(true);
const specialPrescriptionTitleImage = ref('');
const specialPrescriptionMascotImage = ref('');
const specialPrescriptionSubtitle = ref('精选时令养生茶饮');
const specialPrescriptionHomeLimit = ref(4);

const specialPrescriptionListLayout = ref<'sidebar' | 'tabs'>('sidebar');
const specialPrescriptionListHeaderStyle = ref<'simple' | 'card'>('simple');
const specialPrescriptionListSort = ref<'id_desc' | 'sales_desc'>('id_desc');
const specialPrescriptionListTitleImage = ref('');
const specialPrescriptionListMascotImage = ref('');
const specialPrescriptionListSubtitle = ref('精选时令养生茶饮');

function readStoredTab() {
  const stored = localStorage.getItem(TAB_STORAGE_KEY);
  if (stored === 'global' || stored === 'home' || stored === 'list') {
    activeKey.value = stored;
  }
}

function handleTabChange(key: string | number) {
  activeKey.value = String(key);
  localStorage.setItem(TAB_STORAGE_KEY, String(key));
}

async function load() {
  loading.value = true;
  try {
    const list = await getSystemConfigList();
    const rows = Array.isArray(list) ? list : list?.data || [];
    for (const row of rows) {
      if (row.config_key === 'special_prescription_enabled') {
        specialPrescriptionEnabled.value =
          row.config_value === '1' || row.config_value === true || row.config_value === 'true';
      }
      if (row.config_key === 'special_prescription_title_image') {
        specialPrescriptionTitleImage.value = String(row.config_value || '');
      }
      if (row.config_key === 'special_prescription_mascot_image') {
        specialPrescriptionMascotImage.value = String(row.config_value || '');
      }
      if (row.config_key === 'special_prescription_subtitle') {
        specialPrescriptionSubtitle.value = String(row.config_value || '精选时令养生茶饮');
      }
      if (row.config_key === 'special_prescription_home_limit') {
        specialPrescriptionHomeLimit.value = Math.max(1, Number(row.config_value) || 4);
      }
      if (row.config_key === 'special_prescription_list_layout') {
        specialPrescriptionListLayout.value = row.config_value === 'tabs' ? 'tabs' : 'sidebar';
      }
      if (row.config_key === 'special_prescription_list_header_style') {
        specialPrescriptionListHeaderStyle.value = row.config_value === 'card' ? 'card' : 'simple';
      }
      if (row.config_key === 'special_prescription_list_sort') {
        specialPrescriptionListSort.value = row.config_value === 'sales_desc' ? 'sales_desc' : 'id_desc';
      }
      if (row.config_key === 'special_prescription_list_title_image') {
        specialPrescriptionListTitleImage.value = String(row.config_value || '');
      }
      if (row.config_key === 'special_prescription_list_mascot_image') {
        specialPrescriptionListMascotImage.value = String(row.config_value || '');
      }
      if (row.config_key === 'special_prescription_list_subtitle') {
        specialPrescriptionListSubtitle.value = String(row.config_value || '精选时令养生茶饮');
      }
    }
  } finally {
    loading.value = false;
  }
}

async function handleSave() {
  saving.value = true;
  try {
    await saveSystemConfig([
      {
        config_key: 'special_prescription_enabled',
        config_value: specialPrescriptionEnabled.value ? '1' : '0',
      },
      {
        config_key: 'special_prescription_title_image',
        config_value: specialPrescriptionTitleImage.value,
      },
      {
        config_key: 'special_prescription_mascot_image',
        config_value: specialPrescriptionMascotImage.value,
      },
      {
        config_key: 'special_prescription_subtitle',
        config_value: specialPrescriptionSubtitle.value,
      },
      {
        config_key: 'special_prescription_home_limit',
        config_value: String(specialPrescriptionHomeLimit.value),
      },
      {
        config_key: 'special_prescription_list_layout',
        config_value: specialPrescriptionListLayout.value,
      },
      {
        config_key: 'special_prescription_list_header_style',
        config_value: specialPrescriptionListHeaderStyle.value,
      },
      {
        config_key: 'special_prescription_list_sort',
        config_value: specialPrescriptionListSort.value,
      },
      {
        config_key: 'special_prescription_list_title_image',
        config_value: specialPrescriptionListTitleImage.value,
      },
      {
        config_key: 'special_prescription_list_mascot_image',
        config_value: specialPrescriptionListMascotImage.value,
      },
      {
        config_key: 'special_prescription_list_subtitle',
        config_value: specialPrescriptionListSubtitle.value,
      },
    ]);
    message.success('保存成功');
  } finally {
    saving.value = false;
  }
}

onMounted(() => {
  readStoredTab();
  load();
});
</script>

<template>
  <Page auto-content-height title="特色方展示配置">
    <Card :loading="loading">
      <Tabs :active-key="activeKey" @change="handleTabChange">
        <Tabs.TabPane key="global" tab="全局">
          <div class="py-4">
          <div class="mb-2 font-medium">特色方功能开关</div>
          <Switch
            v-model:checked="specialPrescriptionEnabled"
            checked-children="开启"
            un-checked-children="关闭"
          />
        </div>
      </Tabs.TabPane>

      <Tabs.TabPane key="home" tab="首页">
        <div class="py-4">
          <div class="mb-4">
            <div class="mb-2 font-medium">首页标题图</div>
            <FormAvatar v-model:value="specialPrescriptionTitleImage" />
          </div>

          <div class="mb-4">
            <div class="mb-2 font-medium">吉祥物图</div>
            <FormAvatar v-model:value="specialPrescriptionMascotImage" />
          </div>

          <div class="mb-4">
            <div class="mb-2 font-medium">副标题</div>
            <Input
              v-model:value="specialPrescriptionSubtitle"
              placeholder="如：精选时令养生茶饮"
              allow-clear
            />
          </div>

          <div class="mb-4">
            <div class="mb-2 font-medium">首页展示数量</div>
            <InputNumber v-model:value="specialPrescriptionHomeLimit" :min="1" :max="20" />
          </div>
        </div>
      </Tabs.TabPane>

      <Tabs.TabPane key="list" tab="列表页">
        <div class="py-4">
          <div class="mb-4">
            <div class="mb-2 font-medium">列表筛选布局</div>
            <Radio.Group v-model:value="specialPrescriptionListLayout">
              <Radio value="sidebar">左侧分类（默认）</Radio>
              <Radio value="tabs">顶部标签</Radio>
            </Radio.Group>
          </div>

          <div class="mb-4">
            <div class="mb-2 font-medium">头部样式</div>
            <Radio.Group v-model:value="specialPrescriptionListHeaderStyle">
              <Radio value="simple">简洁横幅（默认）</Radio>
              <Radio value="card">异形卡片</Radio>
            </Radio.Group>
          </div>

          <div class="mb-4">
            <div class="mb-2 font-medium">列表排序</div>
            <Radio.Group v-model:value="specialPrescriptionListSort">
              <Radio value="id_desc">按 ID 倒序（默认）</Radio>
              <Radio value="sales_desc">按销量倒序</Radio>
            </Radio.Group>
          </div>

          <div class="mb-4">
            <div class="mb-2 font-medium">列表页标题图</div>
            <FormAvatar v-model:value="specialPrescriptionListTitleImage" />
          </div>

          <div class="mb-4">
            <div class="mb-2 font-medium">列表页 IP 图</div>
            <FormAvatar v-model:value="specialPrescriptionListMascotImage" />
          </div>

          <div class="mb-4">
            <div class="mb-2 font-medium">列表页副标题</div>
            <Input
              v-model:value="specialPrescriptionListSubtitle"
              placeholder="如：精选时令养生茶饮"
              allow-clear
            />
          </div>
        </div>
      </Tabs.TabPane>
      </Tabs>

      <div class="mt-4">
        <Button type="primary" :loading="saving" @click="handleSave">保存配置</Button>
      </div>
    </Card>
  </Page>
</template>
