<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="orderAutoConfirmDays">
        <a-input-number
          v-model:value="form.orderAutoConfirmDays"
          :min="1"
          :max="365"
          placeholder="请输入天数"
          style="width: 200px"
        />
        <span style="margin-left: 8px; color: #888">天</span>
      </a-form-item>
      <a-form-item label="未付款自动关闭" name="orderAutoCloseMins">
        <a-input-number
          v-model:value="form.orderAutoCloseMins"
          :min="1"
          :max="10080"
          placeholder="请输入分钟数"
          style="width: 200px"
        />
        <span style="margin-left: 8px; color: #888">分钟</span>
      </a-form-item>
      <a-form-item label="自动好评天数" name="orderAutoCommentDays">
        <a-input-number
          v-model:value="form.orderAutoCommentDays"
          :min="1"
          :max="365"
          placeholder="请输入天数"
          style="width: 200px"
        />
        <span style="margin-left: 8px; color: #888">天</span>
      </a-form-item>
      <a-form-item label="免运费金额" name="orderFreightFreeAmount">
        <a-input-number
          v-model:value="form.orderFreightFreeAmount"
          :min="0"
          :precision="2"
          placeholder="0 表示不免运费"
          style="width: 200px"
        />
        <span style="margin-left: 8px; color: #888">元（0 表示不免运费）</span>
      </a-form-item>
      <a-form-item label="允许退款" name="orderRefundEnabled">
        <a-switch
          v-model:checked="form.orderRefundEnabled"
          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 { 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';

const category = 'order';

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

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

const { form, assignFields } = useFormData<ShopSetting>({
  orderAutoConfirmDays: 7,
  orderAutoCloseMins: 30,
  orderAutoCommentDays: 15,
  orderFreightFreeAmount: 0,
  orderRefundEnabled: true
});

const rules = reactive({
  orderAutoConfirmDays: [
    {
      required: true,
      message: '请输入自动确认收货天数',
      type: 'number',
      trigger: 'blur'
    }
  ],
  orderAutoCloseMins: [
    {
      required: true,
      message: '请输入未付款自动关闭分钟数',
      type: 'number',
      trigger: 'blur'
    }
  ],
  orderAutoCommentDays: [
    {
      required: true,
      message: '请输入自动好评天数',
      type: 'number',
      trigger: 'blur'
    }
  ]
});

const load = async () => {
  try {
    const values = await getShopSettingCategoryValues(category);
    if (values && Object.keys(values).length > 0) {
      assignFields(values);
      // 布尔值转换
      const raw = (values as any).orderRefundEnabled;
      form.orderRefundEnabled = raw === true || raw === 'true' || raw === '1' || raw === 1;
      // 数值字段转换（后端返回字符串时）
      if (values.orderAutoConfirmDays !== undefined) {
        form.orderAutoConfirmDays = Number(values.orderAutoConfirmDays);
      }
      if (values.orderAutoCloseMins !== undefined) {
        form.orderAutoCloseMins = Number(values.orderAutoCloseMins);
      }
      if (values.orderAutoCommentDays !== undefined) {
        form.orderAutoCommentDays = Number(values.orderAutoCommentDays);
      }
      if (values.orderFreightFreeAmount !== undefined) {
        form.orderFreightFreeAmount = Number(values.orderFreightFreeAmount);
      }
    }
  } 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>
