<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm">
      <template #avatar>
        <CropperAvatar
          :uploadApi="uploadApi"
          :value="avatar"
          btnText="更换头像"
          :btnProps="{ preIcon: 'ant-design:cloud-upload-outlined' }"
          @change="updateAvatar"
          width="150"
        />
      </template>
    </BasicForm>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form';
  import { accountFormSchema } from './account.data';
  import { addAccount } from '@/api/demo/system';
  import { useMessage } from '@/hooks/web/useMessage';
  import md5 from 'js-md5';
  import { CropperAvatar } from '@/components/Cropper';
  import { uploadApi } from '@/api/sys/upload';
  import { getAppEnvConfig } from '@/utils/env';

  const { VITE_GLOB_UPLOAD_URL } = getAppEnvConfig();

  const avatar = ref('');
  const headIcon = ref('');
  const { createMessage } = useMessage();
  defineOptions({ name: 'AccountModal' });

  const emit = defineEmits(['success', 'register']);

  const isUpdate = ref(true);
  const rowId = ref('');

  const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
    labelWidth: 100,
    baseColProps: { span: 24 },
    schemas: accountFormSchema,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 23,
    },
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    avatar.value = '';
    headIcon.value = '';
    if (unref(isUpdate)) {
      rowId.value = data.record.id;
      avatar.value = VITE_GLOB_UPLOAD_URL + '/' + data.record.headicon || '';
      data.record.headIcon = data.record.headicon || '';
      headIcon.value = data.record.headicon || '';
      setFieldsValue({
        ...data.record,
      });
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增账号' : '编辑账号'));

  async function handleSubmit() {
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });
      if (values.password) {
        values.password = md5(values.password);
      }
      // 头像
      values.headIcon = headIcon.value;
      const data = await addAccount(values);
      if (data) {
        // TODO custom api
        closeModal();
        emit('success', { isUpdate: unref(isUpdate), values: { ...values, id: rowId.value } });
        return createMessage.success('成功');
      } else {
        return createMessage.error('失败');
      }
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
  function updateAvatar(value) {
    avatar.value = VITE_GLOB_UPLOAD_URL + '/' + value.data.filePath;
    headIcon.value = value.data.filePath;
  }
</script>
