import { addDish, getDishById } from '@/services/dish';
import { getStoreList } 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, useState } from 'react';

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

  const formRef = useRef();
  useEffect(() => {
    getStoreList({ isDish: 1, pageSize: 9999 }).then((res) => {
      setFoodDict(
        res?.records?.map((x) => ({
          label: x.name,
          value: x.id,
        })),
      );
    });
  }, [id]);

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

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

    addDish({ ...values, id }).then((res) => {
      message.success('添加成功');
      navigate(-1);
    });

    return false;
  };

  return (
    <PageContainer>
      <Card>
        <ProForm
          formRef={formRef}
          layout={'horizontal'}
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          onFinish={onFinish}
          initialValues={{ type: '1', state: '1' }}
          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="请输入菜肴名称"
            rules={[{ required: true, message: '请输入菜肴名称' }]}
            width={460}
          />
          <ProFormText
            name="unit"
            label="菜肴单位"
            placeholder="请输入菜肴单位"
            rules={[{ required: true, message: '请输入菜肴单位' }]}
            width={460}
          />
          <ProFormSelect
            mode="multiple"
            name="ingredientsIdList"
            label="包含食材"
            placeholder="请选择包含食材"
            rules={[{ required: true, message: '请选择包含食材' }]}
            width={460}
            options={foodDict}
          />
        </ProForm>
      </Card>
    </PageContainer>
  );
};
