import type { FormInstance } from '@ant-design/pro-components';
import { ProCard, ProForm, StepsForm } from '@ant-design/pro-components';
import { message } from 'antd';
import { useEffect } from 'react';
import ProdInfo from '@/pages/prod/list/components/prod-info';
import Sku from '@/pages/prod/list/components/sku';
import type { Prod, ProdDetail, SkuConfig } from '@/services/prod/prod-manager';

const waitTime = (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

const ProdDetailPage: React.FC<{
  data?: Prod;
  formRef?: React.RefObject<FormInstance<any>>;
}> = (props) => {
  const { data, formRef } = props;
  console.log(data, 'ProdDetailPage');
  useEffect(() => {
    if (data) {
      formRef?.current?.setFieldsValue(data);
    }
  }, [data]);
  return (
    <ProCard>
      {data?.prodId ? (
        <ProForm
          formRef={formRef}
          layout="horizontal"
          grid={true}
          submitter={false}
        >
          <ProdInfo />
        </ProForm>
      ) : (
        <StepsForm<ProdDetail>
          current={0}
          formRef={formRef}
          submitter={false}
          onFinish={async () => {
            await waitTime(1000);
            message.success('提交成功');
          }}
          formProps={{
            validateMessages: {
              required: '此项为必填项',
            },
          }}
        >
          <StepsForm.StepForm<ProdDetail>
            grid={true}
            layout="horizontal"
            name="info"
            title="填写商品信息"
            onFinish={async () => {
              try {
                await formRef?.current?.validateFields();
                console.log(formRef?.current?.getFieldsValue());
              } catch (error: any) {
                console.log(error);
                message.error(error.msg);
              }
              return true;
            }}
          >
            <ProdInfo data={data} />
          </StepsForm.StepForm>
          <StepsForm.StepForm<SkuConfig> name="sku" title="设置商品规格">
            <Sku />
          </StepsForm.StepForm>
          <StepsForm.StepForm<ProdDetail> name="prod" title="发布商品">
            提交
          </StepsForm.StepForm>
        </StepsForm>
      )}
    </ProCard>
  );
};

export default ProdDetailPage;
