import ProTable from '@ant-design/pro-table';
import { PageContainer } from '@ant-design/pro-layout';
import { PlusOutlined } from '@ant-design/icons';
import { Button, Modal, Form, Input, Select, Card, message, Popconfirm } from 'antd';
import React, { useRef, useState, useEffect } from 'react';
import appletAPI from "../service";
import styles from "./index.less";

const pageManage = () => {
    const actionRef = useRef();
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [pageForm] = Form.useForm();
    const [storeList, setStoreList] = useState([]);
    const [currentPage, setCurrentPage] = useState(1);
    const [pageSize, setPageSize] = useState(10);
    const [total, setTotal] = useState(0);
    const [selectedStore, setSelectedStore] = useState('');

    const columns = [
        {
            title: '页面名称',
            dataIndex: 'pageName',
            ellipsis: true,
        },
        {
            title: '页面路径',
            dataIndex: 'pageRoute',
            ellipsis: true,
        },
        {
            title: '所属门店',
            dataIndex: 'storeId',
            ellipsis: true,
        },
        {
            title: '操作',
            valueType: 'option',
            key: 'option',
            render: (_, record) => [
                <a onClick={() => {
                    pageForm.setFieldsValue(record);
                    setIsModalVisible(true);
                }}>
                    编辑
                </a>,
                <Popconfirm
                    title="确定要删除此页面吗？"
                    onConfirm={() => onDeletePage(record)}
                    okText="确定"
                    cancelText="取消"
                >
                    <a href="#">删除</a>
                </Popconfirm>
            ],
        }
    ];

    const onBeforeCreate = () => {
        setIsModalVisible(true);
        pageForm.resetFields();
    }

    /**
     * 添加/修改页面信息
     */
    const onFinishPage = async (values) => {
        if (values.id) {
            const response = await appletAPI.MiniPageUpdate(values);
            if (response.statusCode === 200) {
                message.success('修改成功');
                setIsModalVisible(false);
                actionRef.current.reloadAndRest();
            } else {
                message.error(response.errors);
            }
        } else {
            const response = await appletAPI.MiniPageAdd(values);
            if (response.statusCode === 200) {
                message.success('添加成功');
                setIsModalVisible(false);
                actionRef.current.reloadAndRest();
            } else {
                message.error(response.errors);
            }
        }
    }

    /**
     * 删除页面
     * @param {*} record 
     */
    const onDeletePage = async (record) => {
        const response = await appletAPI.MiniPageDelete(record.id);
        if (response.statusCode === 200) {
            message.success('删除成功');
            actionRef.current.reloadAndRest();
        } else {
            message.error(response.errors);
        }
    }

    /**
     * 获取店铺列表
     */
    const onFetchStoreList = async () => {
        const response = await appletAPI.GetAllStore();
        if (response.statusCode==200) {
            setStoreList(response.data);
            setSelectedStore(response.data[0].id);
        } else {
            message.error(response.msg || '获取店铺列表失败');
        }
    }

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

    useEffect(() => {
        actionRef.current.reloadAndRest();
    }, [selectedStore]);

    return <PageContainer>
        <Card style={{ marginBottom: '10px' }}>
            <div className={styles.table_search_item}>
                <div>
                    归属场景：
                </div>
                <Select style={{ width: 300 }} value={selectedStore} onChange={(value) => {
                    setSelectedStore(value);
                }}>
                    {
                        storeList.map(item => {
                            return <Option value={item.id} key={item.id}>{item.name}</Option>
                        })
                    }
                </Select>
            </div>
        </Card>
        <ProTable
            columns={columns}
            actionRef={actionRef}
            cardBordered
            editable={{
                type: 'multiple',
            }}
            request={async () => {
                if (!selectedStore) return;
                const jsonData = { 
                    "current": currentPage,
                    "pageSize": pageSize,
                    "storeId": selectedStore
                }
                const response = await appletAPI.MiniPageList(jsonData);
                return {
                    data: response.data.items,
                    success: true,
                    total: response.data.totalCount,
                }
            }}
            rowKey="id"
            search={false}
            pagination={{
                pageSize: 5,
                onChange: (page) => console.log(page),
            }}
            dateFormatter="string"
            headerTitle="页面管理"
            toolBarRender={() => [
                <Button key="button" icon={<PlusOutlined />} type="primary" onClick={onBeforeCreate}>
                    新建
                </Button>
            ]}
        />
        <Modal title="编辑页面" footer={false} visible={isModalVisible} onOk={() => setIsModalVisible(false)} onCancel={() => setIsModalVisible(false)} bodyStyle={{ padding: '32px 40px 1px 48px' }}>
            <Form
                name="basic"
                form={pageForm}
                onFinish={onFinishPage}
            >
                <Form.Item
                    name="id"
                    hidden={true}
                >
                    <Input />
                </Form.Item>
                <Form.Item
                    label="页面名称"
                    name="pageName"
                    rules={[
                        {
                            required: true,
                            message: '请输入页面名称！',
                        },
                    ]}
                >
                    <Input />
                </Form.Item>

                <Form.Item
                    label="页面路径"
                    name="pageRoute"
                    rules={[
                        {
                            required: true,
                            message: '请输入页面路径！',
                        },
                    ]}
                >
                    <Input />
                </Form.Item>

                <Form.Item
                    label="所属门店"
                    name="storeId"
                    rules={[
                        {
                            required: true,
                            message: '请选择门店！',
                        },
                    ]}
                >
                    <Select allowClear placeholder="请选择门店" style={{ width: '100%' }}>
                        {
                            storeList.map(item => {
                                return <Option value={item.id} key={item.id}>{item.store_Name}</Option>
                            })
                        }
                    </Select>
                </Form.Item>

                <Form.Item>
                <Button  htmlType="button" style={{float:'right',left:10}} onClick={() => setIsModalVisible(false)}>
                        取消
                    </Button>
        <Button type="primary" htmlType="submit" style={{float:'right'}} >
                        保存
                    </Button>
                    
                </Form.Item>
            </Form>
        </Modal>
    </PageContainer>
}

export default pageManage;