import { PlusOutlined } from '@ant-design/icons';
import { Button, message, Input, Drawer, Tag, Modal, Card, Avatar } from 'antd';

const { Meta } = Card;
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import CreateForm from './components/CreateForm';
import { Page, Add, GetStoreInfoPageAsync, DeleteDesktopNumber } from "./services"
import QRCode from 'qrcode.react';

const key = 'message';


const storeDesktopNumber = () => {
    /** 新建/更新窗口的弹窗 */
    const [modalVisible, handleModalVisible] = useState(false);
    const actionRef = useRef();
    const [currentRow, setCurrentRow] = useState();
    const [storeInfoList, setStoreInfoList] = useState();

    useEffect(() => {
        var data = GetStoreInfoPageAsync({ current: 1, pageSize: 99999 }).then((data) => {
            var list = [];
            data.data.data.forEach((item) => {
                list[item.id] = { text: item.name };
                setStoreInfoList(list);
            });
        });

    }, [])

    const showQRCode = (record) => {
        var config = {
            title: `${record.storeName} ${record.desktopNumber}号桌`,
            okText: '下载',
            cancelText: '取消',
            onOk() {
                changeCanvasToPic(`${record.storeName} ${record.desktopNumber}号桌`);
            },
            content: (
                // <QRCode
                //     id="qrCode"
                //     value={`https://black-pa.com:5443/lead?StoreId=${store.id}&number=${number}`}
                //     size={200} // 二维码的大小
                //     fgColor="#000000" // 二维码的颜色
                //     style={{ margin: 'auto' }}
                // />

                <Card
                    style={{ width: 300, height: 450, backgroundImage: 'url(http://bpic.588ku.com/back_pic/05/42/90/125a6c515c035ab.jpg%21r650/fw/800)', backgroundSize: 'cover' }}
                    title={(<h2 style={{ fontWeight: 600 }}>{`${record.storeName}`}</h2>)}
                    headStyle={{ border: '0px', textAlign: 'center' }}
                    cover={
                        <QRCode
                            id="qrCode"
                            // value={`https://www.black-pa.com:5500?number=${number}`}
                            value={`${record.host}?storeId=${record.storeId}&number=${record.desktopNumber}`}
                            size={174} // 二维码的大小
                            fgColor="#000000" // 二维码的颜色
                            style={{ margin: 'auto', marginTop: '60px' }}

                        />
                    }>
                    <div style={{ textAlign: 'center' }}>
                        <h2 style={{ fontWeight: 600 }}>{`${record.desktopNumber}号桌`}</h2>
                    </div>
                </Card>
            ),
        };
        Modal.confirm(config);
    }

    const changeCanvasToPic = (name) => {
        const canvasImg = document.getElementById('qrCode'); // 获取canvas类型的二维码
        const img = new Image();
        img.src = canvasImg.toDataURL('image/png'); // 将canvas对象转换为图片的data url
        const linkNode = document.createElement('a');
        linkNode.download = name; //a标签的download属性规定下载文件的名称
        linkNode.style.display = 'none';
        linkNode.href = img.src; //生成一个Blob URL
        document.body.appendChild(linkNode);
        linkNode.click();  //模拟在按钮上的一次鼠标单击
        URL.revokeObjectURL(linkNode.href); // 释放URL 对象
        document.body.removeChild(linkNode);
    };


    const columns = [{
        title: '主键',
        dataIndex: 'id',
        hideInSearch: true,
        hideInTable: true,
        tip: '规则名称是唯一的 key'
    },
    {
        title: '桌号',
        dataIndex: 'desktopNumber',
        align: 'center',
        search: false,
        render: item => (
            <>
                <Button type="primary" shape="circle">
                    {item}
                </Button>
            </>
        ),
    },
    {
        title: '适用店铺',
        align: 'center',
        dataIndex: 'storeName',
        // render: tags => (
        //     <>
        //         {return (
        //                 <Tag color={'green'} key={tag.storeId}>
        //                     {tag.storeName}
        //                 </Tag>
        //             );}
        //     </>
        // ),
    }, {
        title: '创建时间',
        dataIndex: 'createAt',
        hideInForm: true,
        search: false,
    }, {
        title: '二维码',
        dataIndex: 'option',
        valueType: 'option',
        render: (_, record) => [
            <a onClick={() => { showQRCode(record) }} type="link">{record.storeName}</a>,
            <a onClick={() => {
                DeleteDesktopNumber([record.id]).then((r) => {
                    if (r.data) {
                      message.success('删除成功');
                      actionRef.current.reload();
                      return true;
                    } else {
                      message.error('删除失败');
                      actionRef.current.reload();
                      return false;
                    }
                  });

            }} type="link">删除</a>
        ]
    }];



    return (
        <PageContainer>
            <ProTable
                headerTitle="店铺类型"
                actionRef={actionRef}
                rowKey="id"
                search={{
                    labelWidth: 120,
                }}
                toolBarRender={() => [
                    <Button
                        type="primary"
                        key="primary"
                        onClick={() => {
                            handleModalVisible(true);
                        }} >
                        <PlusOutlined /> 编辑
                    </Button>,
                ]}
                request={async (params) => {
                    var data = [];
                    var total = 0;
                    await Page(params).then((r) => {
                        data = r.data.data;
                        total = r.data.total;
                    });
                    return {
                        data: data,
                        success: true,
                        total: total,
                    };
                }}
                columns={columns}
            />
            <CreateForm
                onFinish={async (value) => {
                    var success = false;
                    value.startNumber = value.numbers[0];
                    value.endNumber = value.numbers[1];
                    if (value.id) {
                    } else {
                        success = Add(value);
                    }
                    if (success) {
                        handleModalVisible(false);
                        actionRef.current.reload();
                    }
                }}
                onCancel={() => {
                    handleModalVisible(false);
                }}
                modalVisible={modalVisible}
                storeInfoList={storeInfoList}
                values={currentRow || {}}
            />

        </PageContainer>
    );
};

export default storeDesktopNumber;
