import { Modal } from 'antd';
import React, { useState } from 'react';
import ProTable from '@ant-design/pro-table';
import { GetGoodsByMenuIdPage } from '../service';
let allCheckKeys=[];
const CreateForm = (props) => {

  const [selectedRowsState, setSelectedRows] = useState([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);

  if(props.Data){
    allCheckKeys = props.Data.map(obj => {
      return obj.id;
   });
  }

  const columns = [
    {
      title: '商品id',
      dataIndex: 'id',
      tip: '规则名称是唯一的 key',
      hideInSearch: true,
      hideInTable: true,
    },
    {
      title: '商品名称',
      dataIndex: 'name',
    },
  ];
  return (
    <Modal
      width={700}
      bodyStyle={{ padding: '32px 40px 48px' }}
      destroyOnClose
      title="选择商品"
      visible={props.modalVisible}
      onCancel={() => {
        allCheckKeys = [];
        props.onCancel();
      }}
      onOk={() => {
        var submitData = [...selectedRowKeys];//[...allCheckKeys];
        allCheckKeys = [];
        props.onSubmit(submitData);
      }}
      maskClosable={false}
    >
      <ProTable
        headerTitle="商品信息"
        rowKey="id"
        pagination={{ defaultPageSize: 20 }}
        search={false}
        toolBarRender={false}
        params={{
          FoodMenuId: props.values,
        }}
        //数据绑定
        request={async (params) => {
          var Data = [];
          var total = 0;
          await GetGoodsByMenuIdPage(params).then((r) => {
            Data = r.data.data;
            total = r.data.total;
          });
          setSelectedRowKeys(allCheckKeys);
          return {
            data: Data,
            success: true,
            total: total,
          };
        }}
        columns={columns}
        defaultSelectedRowKeys={allCheckKeys}
        rowSelection={{ // 主要是这里的多选处理
          selectedRowKeys,
          defaultSelectedRowKeys:allCheckKeys,
          onChange: (_, selectedRows) => {
           setSelectedRows(selectedRows);
          },
          onSelect: (record, selected) => {
            if (selected) { // 如果选中,加入selectedRowKeys
              allCheckKeys = Array.from(new Set([...selectedRowKeys, record.id]));
            } else { // 如果未选中,删除这一项数据
              allCheckKeys = selectedRowKeys.filter(item => {
                return item !== record.id
              })
            }
            setSelectedRowKeys(allCheckKeys);
          }
        }}
      />
    </Modal>
  );
};

export default CreateForm;
