
import { addStore, getStoreTypeList,getStoreById,updataStore } from '@/services/stock';
import { queryDict } from '@/utils/request';
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 formRef = useRef();
  const navigate = useNavigate();

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

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

    if (id) {
      // 修改
      updataStore(id, { ...values }).then((res) => {
        message.success('修改成功');
        navigate(-1);
      });
    } else {
      // 新增
      addStore({ ...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}
          // 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>
              );
            },
          }}
        >
          <ProFormSelect
            name="typeId"
            label="分类"
            placeholder="请选择分类"
            request={() => queryDict(getStoreTypeList)()}
            rules={[{ required: true, message: '请选择分类' }]}
            allowClear={false}
            width={460}
          />
          <ProFormText
            name="name"
            label="名称"
            placeholder="请输入名称"
            rules={[{ required: true, message: '请输入名称' }]}
            allowClear={false}
            width={460}
          />
          <ProFormText
            name="unit"
            label="单位"
            placeholder="请输入单位"
            rules={[{ required: true, message: '请输入单位' }]}
            allowClear={false}
            width={460}
          />
          <ProFormText
            name="amount"
            label="库存"
            disabled={true}
            placeholder="请输入库存"
            allowClear={false}
            width={460}
          />
        </ProForm>
      </Card>
    </PageContainer>
  );
};
