<template>
  <a-card :bordered="false">
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="styleResponsive ? { md: 3, sm: 5, xs: 24 } : { flex: '90px' }"
      :wrapper-col="styleResponsive ? { md: 9, sm: 19, xs: 24 } : { flex: '1' }"
    >
      <a-form-item label="商城名称" name="shopName">
        <a-input
          allow-clear
          :maxlength="50"
          placeholder="请输入商城名称"
          v-model:value="form.shopName"
        />
      </a-form-item>
      <a-form-item label="商城Logo" name="shopLogo">
        <a-image
          v-if="form.shopLogo"
          width="100px"
          height="100px"
          :src="form.shopLogo"
          style="margin-right: 10px; border-radius: 6px;"
        />
        <a-upload
          :show-upload-list="false"
          :customRequest="onUploadLogo"
        >
          <a-button class="ele-btn-icon">
            <template #icon>
              <UploadOutlined/>
            </template>
            <span>上传</span>
          </a-button>
        </a-upload>
        <div class="ele-text-placeholder" style="margin-top: 6px;">
          建议上传 400x400 像素的正方形 Logo，图片大小不超过 10MB。
        </div>
      </a-form-item>
      <a-form-item label="商城描述" name="shopDesc">
        <a-textarea
          :rows="4"
          :maxlength="500"
          placeholder="请输入商城描述"
          v-model:value="form.shopDesc"
        />
      </a-form-item>
      <a-form-item label="客服电话" name="shopPhone">
        <a-input
          allow-clear
          :maxlength="20"
          placeholder="请输入客服电话"
          v-model:value="form.shopPhone"
        />
      </a-form-item>
      <a-form-item label="商城地址" name="shopAddress">
        <a-input
          allow-clear
          :maxlength="200"
          placeholder="请输入商城地址"
          v-model:value="form.shopAddress"
        />
      </a-form-item>
      <a-form-item label="商城开关" name="shopEnabled">
        <a-switch v-model:checked="form.shopEnabled" checked-children="开" un-checked-children="关" />
      </a-form-item>
      <a-form-item label="保存">
        <a-button type="primary" :loading="loading" @click="save">保存</a-button>
      </a-form-item>
    </a-form>
  </a-card>
</template>

<script lang="ts" setup>
import { UploadOutlined } from '@ant-design/icons-vue';
import { reactive, ref, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { useThemeStore } from '@/store/modules/theme';
import { storeToRefs } from 'pinia';
import { FormInstance } from 'ant-design-vue/es/form';
import useFormData from '@/utils/use-form-data';
import { batchSaveShopSetting, getShopSettingCategoryValues } from '@/api/shop/shopSetting';
import type { ShopSetting } from '@/api/shop/shopSetting/model';
import { uploadOss } from '@/api/system/file';
import { messageLoading } from 'ele-admin-pro';

const category = 'basic';

const themeStore = useThemeStore();
const { styleResponsive } = storeToRefs(themeStore);

const loading = ref(false);
const formRef = ref<FormInstance | null>(null);

const { form, assignFields } = useFormData<ShopSetting>({
  shopName: '',
  shopLogo: '',
  shopDesc: '',
  shopPhone: '',
  shopAddress: '',
  shopEnabled: true
});

const rules = reactive({
  shopName: [
    {
      required: true,
      message: '请输入商城名称',
      type: 'string',
      trigger: 'blur'
    }
  ]
});

// 上传 Logo
const onUploadLogo = (item: any) => {
  const { file } = item;
  if (file.size / 1024 / 1024 > 10) {
    message.error('图片大小不能超过 10MB');
    return;
  }
  const hide = messageLoading({
    content: '上传中..',
    duration: 0,
    mask: true
  });
  uploadOss(file)
    .then((res) => {
      hide();
      form.shopLogo = res.path;
    })
    .catch((e) => {
      hide();
      message.error(e.message || '上传失败');
    });
};

const load = async () => {
  try {
    const values = await getShopSettingCategoryValues(category);
    if (values && Object.keys(values).length > 0) {
      assignFields(values);
      // 布尔值转换（后端可能返回字符串 '1'/'0'/'true'/'false'）
      const raw = (values as any).shopEnabled;
      form.shopEnabled = raw === true || raw === 'true' || raw === '1' || raw === 1;
    }
  } catch (e: any) {
    // 未配置时忽略
  }
};

const save = () => {
  if (!formRef.value) return;
  formRef.value
    .validate()
    .then(() => {
      loading.value = true;
      batchSaveShopSetting(category, form as Record<string, unknown>)
        .then(() => {
          message.success('保存成功');
        })
        .catch((e) => {
          message.error(e.message);
        })
        .finally(() => {
          loading.value = false;
        });
    })
    .catch(() => {});
};

onMounted(load);
</script>
