import React, { useState, useEffect, useRef } from 'react';
import ProTable from '@ant-design/pro-table';
import { Form, Input, message, Button, Modal, Radio } from 'antd';
import quickAPI from "../../service";
import styles from "./index.less";
import indexStyles from "../../index.less";
import { PlusOutlined } from '@ant-design/icons';
import { nanoid } from 'nanoid'
const key = 'message';

const FoodMenuConfig = (props) => {

    //表单实例
    const [editFoodMenuForm] = Form.useForm();

    /**
    * 提交表单
    */
    const onFinishSubmit = async (formValues) => {
        if (formValues.id) {
            try {
                message.loading('正在修改', key);
                await quickAPI.UpdateFoodMenu(formValues).then((r) => {
                    message.destroy(key);
                    if (r.data) {
                        message.success('修改成功');
                        setIsShowModal(false);
                        actionRef.current.reload();
                    } else {
                        message.error('修改失败');
                    }
                });
            } catch (error) {
                message.destroy(key);
                message.error('修改失败请重试！');
            }
        } else {
            try {
                message.loading('正在添加', key);
                await quickAPI.AddFoodMenu(formValues).then((r) => {
                    message.destroy(key);
                    if (r.data) {
                        message.success('添加成功');
                        setIsShowModal(false);
                        actionRef.current.reload();
                    } else {
                        message.error('添加失败');
                    }
                });
            } catch (error) {
                message.destroy(key);
                message.error('添加失败请重试！');
            }
        }
    }

    //当前操作的菜谱对象
    const [currentOption, setCurrentOption] = useState({ id: '' });

    //是否显示 新增/编辑 菜谱弹窗
    const [isShowModal, setIsShowModal] = useState(false);

    //表格实例
    const actionRef = useRef();
    const [currentPage, setCurrentPage] = useState(1);
    const [pageSize, setPageSize] = useState(10);

    const [selectedRowKeys, setSelectRowKeys] = useState([]);

    const columns = [
        {
            title: '主键',
            dataIndex: 'id',
            hideInSearch: true,
            hideInTable: true,
            tip: '规则名称是唯一的 key'
        },
        {
            title: '菜谱编码',
            dataIndex: 'code',
            valueType: 'textarea',
        },
        {
            title: '菜谱名称',
            dataIndex: 'name',
            valueType: 'textarea',
        },
        {
            title: '操作',
            dataIndex: 'option',
            valueType: 'option',
            render: (_, record) => [
                <a
                    key="config"
                    onClick={() => {
                        setCurrentOption(record);
                        setIsShowModal(true);
                        editFoodMenuForm.setFieldsValue(record);
                    }}>更新</a>
            ]
        }
    ]

    /**
     * 回显 选中的菜谱
     */
    const onSetSelectedState = () => {
        if (props.foodMenuConfig.length > 0) {
            const selected = [];
            props.foodMenuConfig.forEach(item => {
                selected.push(item.id);
            });
            setSelectRowKeys(selected);
        }
    }

    useEffect(() => {
        onSetSelectedState();
    }, []);

    return <>
        <ProTable
            style={{ width: '100%' }}
            headerTitle="菜谱列表"
            actionRef={actionRef}
            rowKey="id"
            search={false}
            pagination={{
                current: currentPage,
                pageSize: pageSize,
                onChange: (page, pageSize) => {
                    setCurrentPage(page);
                    setPageSize(pageSize);
                }
            }}
            request={async (params) => {
                let data = [];
                let total = 0;
                await quickAPI.GetFoodMenuInfoPage(params).then((r) => {
                    data = r.data.data;
                    total = r.data.total;
                });
                return {
                    data: data,
                    success: true,
                    total: total,
                };
            }}
            columns={columns}
            rowSelection={{
                type: 'checkbox',
                onChange: (selectedRowKeys, selectedRows) => {
                    setSelectRowKeys(selectedRowKeys);
                    props.onSelectedChange('foodMenuConfig', selectedRows);
                },
                selectedRowKeys: selectedRowKeys
            }}
            toolBarRender={() => [
                <Button key="button" icon={<PlusOutlined />} type="primary" onClick={() => {
                    editFoodMenuForm.resetFields();
                    const temp = editFoodMenuForm.getFieldsValue();
                    temp.code = nanoid().substring(0, 20);
                    editFoodMenuForm.setFieldsValue(temp);
                    setCurrentOption({ id: '' });
                    setIsShowModal(true);
                }}>
                    新建
                </Button>
            ]}
        />


        <Modal width={600} title={currentOption.id ? '编辑菜谱' : '新增菜谱'} visible={isShowModal} footer={false} onCancel={() => setIsShowModal(false)}>
            <Form
                form={editFoodMenuForm}
                layout="Horizontal"
                preserve={false}
                onFinish={onFinishSubmit}
                style={{ width: '100%' }}
            >
                <Form.Item name="id" hidden={true}>
                    <Input />
                </Form.Item>

                <Form.Item label={"菜谱编码"} name="code" rules={[{ required: true, max: 50 }]}>
                    <Input disabled />
                </Form.Item>

                <Form.Item label={"菜谱名称"} name="name" rules={[{ required: true, max: 20 }]} >
                    <Input />
                </Form.Item>

                <Form.Item>
                    <Button type="primary" htmlType="submit">
                        确定
                    </Button>
                </Form.Item>
            </Form>
        </Modal>
    </>
}

export default FoodMenuConfig;
