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

/**
 * 刷卡机管理
 * @returns
 */
const Machine = () => {
    const actionRef = useRef();
    const [modalForm] = Form.useForm();
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [currentOption, setCurrentOption] = useState({ id: '' });
    const [storeList, setStoreList] = useState([]);
    const [selectedStore, setSelectedStore] = useState('');
    const [gateList, setGateList] = useState([]);
    const [selectedGate, setSelectedGate] = useState('');
    const [current, setCurrent] = useState(1);
    const [pageSize, setPageSize] = useState(10);

    /**
     * 点击编辑按钮
     * @param {*} record
     */
    const onEditTableRow = (record) => {
        setCurrentOption(record);
        setIsModalOpen(true);
        modalForm.setFieldsValue(record);
    }

    /**
     * 点击新建
     */
    const onCreateTableRow = () => {
        setIsModalOpen(true);
        modalForm.resetFields();
        modalForm.setFieldValue('sleepTime', 10);
        modalForm.setFieldValue('status', 1);
    }

    /**
     * 删除数据
     * @param {*} record
     */
    const onDeleteTableRow = (record) => {
        console.log('删除', record)
    }

    /**
     * 提交表单
     */
    const onFinish = async (values) => {
        if (values.id) {
            const response = await cardAPI.UpdatePayCardInfo(values);
            if (response.statusCode === 200) {
                setIsModalOpen(false);
                message.success('更新成功！');
                actionRef.current.reload();
            } else {
                message.error(response.error || '更新设备失败');
            }
        } else {
            const response = await cardAPI.PayCardAdd(values);
            if (response.statusCode === 200) {
                setIsModalOpen(false);
                message.success('新增成功！');
                actionRef.current.reload();
            } else {
                message.error(response.error || '新增设备失败');
            }
        }
    }

    const columns = [
        {
            title: '设备名称',
            dataIndex: 'name',
            ellipsis: true,
        },
        {
            title: '归属档口',
            dataIndex: 'gateId',
            render: (_, record) => {
                const findGate = gateList.find(item => item.id === record.gateId);
                return <div>
                    {findGate ? findGate.name : '默认档口'}
                </div>
            }
        },
        {
            title: '设备地址',
            dataIndex: 'address',
            ellipsis: true,
        },
        {
            title: '状态',
            dataIndex: 'status',
            valueType: 'select',
            valueEnum: {
                0: {
                    text: '正常',
                    status: 'Success',
                },
                1: {
                    text: '禁用',
                    status: 'Error',
                },
                2: {
                    text: '删除',
                    status: 'Error',
                }
            },
        },
        {
            title: '间隔时间',
            dataIndex: 'sleepTime',
        },
        {
            title: '操作',
            valueType: 'option',
            key: 'option',
            render: (text, record, _, action) => [
                <a onClick={() => onEditTableRow(record)}>编辑</a>,
            ],
        },
    ];

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

    /**
     * 根据门店ID获取档口列表
     */
    const onFetchGateList = async (storeId) => {
        const response = await cardAPI.GetGateListByStoreList(storeId);
        if (response.statusCode === 200) {
          if(response.data.length>0)
          {setGateList(response.data);
            setSelectedGate(response.data[0].id);
          }

            actionRef.current.reload();
        } else {
            message.error(response.error || '获取档口列表失败');
        }
    }

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


    return (
        <PageContainer>
            <div className={styles.member_card_container}>
                <ProTable
                    columns={columns}
                    actionRef={actionRef}
                    request={
                        async () => {
                            console.log('selectedGate', selectedGate);
                            if (selectedGate) {
                                const response = await cardAPI.PayCardByGateId(selectedGate, current, pageSize);
                                if (response.statusCode === 200) {
                                    return {
                                        data: response.data.data,
                                        success: true,
                                        total: response.data.total,
                                    }
                                }
                            }
                        }
                    }
                    cardBordered
                    editable={{
                        type: 'multiple',
                    }}
                    rowKey="id"
                    search={false}
                    options={{
                        setting: {
                            listsHeight: 400,
                        },
                    }}
                    pagination={{
                        pageSize: pageSize,
                        onChange: (page) => setCurrent(page)
                    }}
                    dateFormatter="string"
                    headerTitle="刷卡机管理"
                    toolBarRender={() => [
                        <div className={styles.table_search_item}>
                            <div>
                                当前门店：
                            </div>
                            <Select style={{ width: 300 }} value={selectedStore} onChange={(value) => {
                                setSelectedStore(value);
                                onFetchGateList(value);
                                setSelectedGate({});
                            }}>
                                {
                                    storeList.map(item => {
                                        return <Option value={item.id} key={item.id}>{item.store_Name}</Option>
                                    })
                                }
                            </Select>
                        </div>,
                        <div className={styles.table_search_item}>
                            <div>
                                当前档口：
                            </div>
                            <Select style={{ width: 300 }} value={selectedGate} onChange={(value) => {
                                setSelectedGate(value);
                                actionRef.current.reload();
                            }}>
                                {
                                    gateList.map(item => {
                                        return <Option value={item.id} key={item.id}>{item.name}</Option>
                                    })
                                }
                            </Select>
                        </div>,
                        <Button key="button" icon={<PlusOutlined />} type="primary" onClick={onCreateTableRow}>
                            新建
                        </Button>
                    ]}
                />
                <Modal width={600} title={currentOption.id ? '编辑刷卡机' : '添加刷卡机'} visible={isModalOpen} footer={false} onCancel={() => setIsModalOpen(false)}>
                    <Form
                        name="basic"
                        onFinish={onFinish}
                        form={modalForm}
                        labelCol={{ span: 4 }}
                    >

                        <Form.Item
                            label="id"
                            name="id"
                            hidden={true}
                        >
                            <Input />
                        </Form.Item>


                        <Form.Item
                            label="设备名称"
                            name="name"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入档口名称！',
                                },
                            ]}
                        >
                            <Input />
                        </Form.Item>

                        <Form.Item
                            label="归属档口"
                            name="gateId"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入归属门店！',
                                },
                            ]}
                        >
                            <Select>
                                {
                                    gateList.map(item => {
                                        return (
                                            <Select.Option key={item.id} value={item.id}>
                                                {item.name}
                                            </Select.Option>
                                        )
                                    })
                                }
                            </Select>
                        </Form.Item>

                        <Form.Item
                            label="状态"
                            name="status"
                        >
                            <Select size="large" defaultValue={1}>
                                        <Option value={0}>正常</Option>
                                        <Option value={1}>禁用</Option>
                                    </Select>
                        </Form.Item>

                        <Form.Item
                            label="间隔时间"
                            name="sleepTime"

                        >
                            <InputNumber min={0} />
                        </Form.Item>

                        <Form.Item
                            label="设备地址"
                            name="address"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入档口名称！',
                                },
                                {
                                    pattern: new RegExp(/[0-9A-Fa-f]{2}/, 'g'),
                                    message: '请输入16进制！'
                                }
                            ]}
                        >
                            <Input />
                        </Form.Item>

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

export default Machine;
