import React, { useState, useRef } from 'react';
import { Button, Modal, Form, Input, Select, Divider, Space, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { EditableProTable } from '@ant-design/pro-table';
import { AddBomType } from '../services';

const App = (props) => {

  const inputRef = useRef(null);
  const [typename, settypename] = useState('');
  const [dataSource, setDataSource] = useState([]);
  const [editableKeys, setEditableRowKeys] = useState([]);

  const onNameChange = (event) => {
    settypename(event.target.value);
  }

  const columns = [
    {
      title: '物料名称',
      dataIndex: 'batchingId',
      formItemProps: (form, { rowIndex }) => {
        return {
          rules:
            rowIndex > 1 ? [{ required: true, message: '此项为必填项' }] : [],
        };
      },
      valueType: 'select',
      fieldProps: {
        showSearch: true,
        options: props.matedata.map((item, index) => { return { label: item.name, value: item.id } })
      },
      width: '25%',
    },
    {
      title: '用量',
      dataIndex: 'dosage',
      valueType: 'digit',
      width: '15%',
    },
    {
      title: '操作',
      valueType: 'option',
      width: '15%',
      render: () => {
        return null;
      },
    },
  ]


  const addItem = (e) => {
    e.preventDefault();
    if (typename.length == 0) {
      message.error("请输入名称");
    } else {
      var parm = { name: typename }
      AddBomType(parm).then((r) => {
        if (r.succeeded) {
          message.success('添加成功');
          props.initTypeList();
          settypename('');
        } else {
          message.error(r.errors);
        }
      })
    }

  }

  const headleOk = () => {
    props.form.validateFields().then((values) => {
      var check = true;
      var data = values;
      debugger
      if (dataSource.length == 0) {
        check = false;
        message.error("请选择物料")
      } else {
        data.mate = dataSource.map(x => { return { batchingId: x.batchingId, dosage: x.dosage } });
      }
      if (check) {
        props.form.resetFields();
        props.onFinish(data);
        setDataSource([])
      }

    }).catch((info) => {
        message.error("请填写必填信息")
      });
  }

  return (
    <>

      <Modal title="新增菜谱"
        width={600}
        onCancel={props.onCancel}
        open={props.modalVisible}
        okText="确认"
        cancelText="取消"
        onOk={headleOk}>
        <Form layout="horizontal" preserve={false} form={props.form}  >

          <Form.Item name="bomName" label="配方名称" rules={[{ required: true, message: '配方名称' }]}>
            <Input placeholder="请输入配方名称" />
          </Form.Item>

          <Form.Item name="bomTypeList" rules={[{ required: true, message: '配方分类' }]} label="配方分类" >
            <Select
              style={{ width: '100%' }}
              mode="tags"
              placeholder="请选配方分类"
              options={props.bomTypeData}
              dropdownRender={(menu) => (
                <>
                  {menu}
                  <Divider style={{ margin: '8px 0' }} />
                  <Space style={{ padding: '0 8px 4px' }}>
                    <Input
                      placeholder="请输入配方分类"
                      ref={inputRef}
                      value={typename}
                      onChange={onNameChange}
                      onKeyDown={(e) => e.stopPropagation()}
                    />
                    <Button type="text" icon={<PlusOutlined />} onClick={addItem}>
                      新增
                    </Button>
                  </Space>
                </>
              )}
            />
          </Form.Item>
        </Form>
        <EditableProTable
          headerTitle={<span><span style={{ color: 'red', marginRight: 3 }}>*</span>配方详情</span>}
          columns={columns}
          rowKey="id"
          value={dataSource}
          onChange={setDataSource}
          recordCreatorProps={{
            newRecordType: 'dataSource',
            record: () => ({
              id: Date.now(),
            }),
          }}

          editable={{
            type: 'multiple',
            editableKeys,
            actionRender: (row, config, defaultDoms) => {
              return [defaultDoms.delete, defaultDoms.Button];
            },
            onValuesChange: (record, recordList) => {
              setDataSource(recordList);
            },
            onDelete: async (key, row) => {
              console.log(key)
              console.log(row)

            },
            onChange: setEditableRowKeys,
          }} />

      </Modal>
    </>
  );
};
export default App;