import { addStoreType, getStoreTypeById, updataStoreType } from '@/services/stock';
import { PageContainer, ProForm, ProFormSelect, ProFormText } from '@ant-design/pro-components';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { Card, Col, message, Row, Space } from 'antd';
import { useEffect, useRef } from 'react';

export default (props) => {
  const [searchParams, setSearchParams] = useSearchParams();
  const id = searchParams.get('id');
  const navigate = useNavigate();

  const formRef = useRef();
  useEffect(() => {
    if (id) {
      getStoreTypeById(id).then((res) => {
        formRef.current.setFieldsValue(res);
      });
    }
  }, [id]);

  const onFinish = async (values) => {
    console.log(values);

    if (id) {
      // 修改
      updataStoreType(id, { ...values }).then((res) => {
        message.success('修改成功');
        navigate(-1);
      });
    } else {
      // 新增;
      addStoreType({ ...values }).then((res) => {
        message.success('添加成功');
        navigate(-1);
      });
    }

    return false;
  };

  return (
    <PageContainer>
      <Card>
        <ProForm
          formRef={formRef}
          layout={'horizontal'}
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          onFinish={onFinish}
          submitter={{
            searchConfig: {
              resetText: '返回',
            },
            onReset: () => navigate(-1),
            render: (props, doms) => {
              return (
                <Row>
                  <Col span={8} offset={8}>
                    <Space>{doms}</Space>
                  </Col>
                </Row>
              );
            },
          }}
        >
          <ProFormText
            name="name"
            label="名称"
            placeholder="请输入名称"
            width={460}
            allowClear={false}
            rules={[{ required: true, message: '请输入名称' }]}
          />
          <ProFormSelect
            name="isFood"
            label="食材"
            options={[
              { label: '是', value: 1 },
              { label: '否', value: 0 },
            ]}
            placeholder="请选择"
            width={460}
            allowClear={false}
            rules={[{ required: true, message: '请选择是否食材' }]}
          />
        </ProForm>
      </Card>
    </PageContainer>
  );
};
