import React from 'react';
import { BetaSchemaForm } from '@ant-design/pro-components';
import { notification } from 'antd';
import { brandInfoColumn } from '../staticData.js';
import { layout } from '@/utils/bll';
import { apiBrandDetail, apiCreateBrand, apiEditBrand, apiAppendQualifyBrand } from '../services';
import { transformVOToFormData, transformFormDataToDTO } from '../bll.js';

/**
 * 品牌信息组件
 */
const BrandInfo = props => {
  const refForm = React.useRef();
  const { actionStatus, brandId } = props;
  const closeModal = v => {
    refForm.current?.resetFields();
    !v && props.onClose(false);
  };
  const getAPI = () => {
    switch (actionStatus) {
      case 'edit':
        return apiEditBrand;
      case 'supplement':
        return apiAppendQualifyBrand;
      default:
        return apiCreateBrand;
    }
  };
  const submitForm = async values => {
    const params = transformFormDataToDTO(values);
    params.brandId = brandId;
    params.id = brandId;
    const api = getAPI();
    const res = await api(params);
    if (res?.success) {
      notification.success({
        message: '提交成功',
      });
      props.onClose(true);
    }
  };

  const getInfo = () =>
    new Promise(resolve => {
      setTimeout(async () => {
        if (brandId) {
          const res = await apiBrandDetail({ brandId });
          if (res?.data) {
            const data = transformVOToFormData(res.data);
            resolve(data);
          }
        }
        resolve({});
      }, 200);
    });

  const config = { actionStatus };

  return (
    props.visible && (
      <BetaSchemaForm
        layoutType="ModalForm"
        title="品牌信息"
        open={props.visible}
        width="600px"
        modalProps={{
          maskClosable: true,
          destroyOnClose: true,
        }}
        request={getInfo}
        formRef={refForm}
        onOpenChange={closeModal}
        layout="horizontal"
        {...layout}
        onFinish={submitForm}
        columns={brandInfoColumn(config)}
      />
    )
  );
};

export default BrandInfo;
