<template>
  <div>
    <BasicForm @register="registerForm" layout="vertical">
      <template #logo>
        <Upload
          name="file"
          :showUploadList="false"
          :beforeUpload="handleBeforeUpload"
          accept=".jpg,.jpeg,.gif,.png,.webp"
        >
          <img :src="logo" class="img-avatar" />
        </Upload>
      </template>
    </BasicForm>
    <a-button @click="handleReset">重置</a-button>
    <a-button type="primary" @click="handleSubmit">保存</a-button>
  </div>
</template>

<script lang="ts" setup>
  import { BasicForm, useForm } from '/@/components/Form';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { InformationFormSchema } from './data';
  import { Upload } from 'ant-design-vue';
  import { sysSettingEdit, sysSettingDetail, sysSettingDefault } from '/@/api/sys/sysSettingApi';
  import { onMounted, ref } from 'vue';
  import { fileToBase64 } from '/@/utils/file/base64Conver';

  onMounted(async () => {
    const res = await sysSettingDetail();
    logo.value = res.logo;
    await setFieldsValue({ ...res });
  });

  const { createMessage } = useMessage();
  const [registerForm, { setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: InformationFormSchema,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 23,
    },
    baseColProps: {
      span: 18,
    },
    wrapperCol: {
      span: 24,
    },
  });

  const logo = ref(null);

  // 提交按钮事件
  async function handleSubmit() {
    const values = await validate();
    console.log('abc', values);
    if (logo.value) {
      values.logo = logo.value;
    }
    await sysSettingEdit(values);
    createMessage.success('修改成功');
  }
  async function handleReset() {
    const res = await sysSettingDefault();

    await setFieldsValue(res);
  }
  async function handleBeforeUpload(file) {
    logo.value = await fileToBase64(file);
    return false;
  }
</script>

<style lang="less" scoped>
  .img-avatar {
    display: block;
    width: 60px;
    height: 60px;
  }
</style>
