import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Icon, message, Table, Pagination, Modal } from 'antd';
import router from 'umi/router';
import moment from 'moment';
import AuthButton from '@/components/AuthButton';
import withActions from '@/components/ActionList';
import EditIcon from '@/components/EditIcon';
import QrcodeType from '@/components/SelectButton/QrcodeType'
import { ConfirmButton } from '@/components/ModalButton';
import BuildSelect from '@/components/SelectButton/BuildSelect'
import ChannelSelect from '@/components/SelectButton/channelSelect'
import apis from '../../../services/apis';
import request from '../../../utils/request';

// import RaiseHelpDoc from '../edit/components/RaiseHelpDoc';
// eslint-disable-next-line consistent-return
const typeName = targetType => {
    // eslint-disable-next-line default-case
    switch (targetType) {
        case 'project': return '项目';
        case 'activity': return '报名活动';
        case 'help': return '助力活动';
        case 'group': return '拼团活动';
        case 'h5': return 'H5活动';
        case 'live': return '直播活动';
        case 'news': return '资讯';
        case 'salesBatch': return '在线选房';
    }
}

const qrcodelist = props => {
    const [data, setData] = useState([])
    const [showHelp, setShowHelp] = useState(false)
    const [qrcodeList, setQrcodeList] = useState([])
    const [beforeCheck, setBeforeCheck] = useState('请至少选择一条数据')

    // eslint-disable-next-line react-hooks/rules-of-hooks
    useEffect(() => {
        // eslint-disable-next-line @typescript-eslint/no-use-before-define
        // eslint-disable-next-line no-use-before-define
        getList({ pageNum: 1, pageSize: 10 });
    }, [])

    // 查询列表
    const getList = params => {
        request({ ...apis.qrcode.list, params: { ...params } }).then(data => {
            console.log(data)
            setData(data)
        })
    }

    const batchDelete = () => {
        request({ ...apis.qrcode.batchDelete, data: qrcodeList }).then(() => {
            message.info('操作成功')
            setBeforeCheck('请至少选择一条数据')
            getList({ pageNum: 1, pageSize: 10 });
        }).catch(() => {
            // message.info(err.msg)
        })
    }


    const toAdd = () => {
        router.push({
            pathname: '/qrcode/qrcodelist/add',
        });
    }

    const toDataRecord = id => {
        // eslint-disable-next-line no-console
        console.log(id)
        router.push({
            pathname: '/qrcode/qrcodelist/dataRecord',
            query: { id },
        });
    }

    const downloadQrcode = row => {
        const x = new XMLHttpRequest();
        const resourceUrl = row.qrCodeUrl
        // const name = `${row.targetName}二维码.png`
        console.log(resourceUrl);
        x.open('GET', resourceUrl, true);
        x.responseType = 'blob';
        x.onload = function (e) {
            const url = window.URL.createObjectURL(x.response)
            const a = document.createElement('a');
            a.href = url;
            a.style.display = 'none'
            a.download = `${row.targetName}二维码.png`
            a.click();
        }
        x.send();
    }

    /**
     *
     *
     * @param {*} props
     * @returns
     */
    const columns = [
        {
            title: '二维码',
            dataIndex: 'qrCodeUrl',
            key: 'qrCodeUrl',
            align: 'center',
            render: (x, row) => <img src={row.qrCodeUrl} alt="" width="100px"></img >,
        },
        {
            title: '二维码内容',
            dataIndex: 'targetName',
            key: 'targetName',
            align: 'center',

        },
        {
            title: '二维码类型',
            dataIndex: 'targetType',
            key: 'targetType',
            align: 'center',
            render: (x, row) => <span >{typeName(row.targetType)}</span>,
        },
        {
            title: '关联项目',
            dataIndex: 'buildingName',
            key: 'buildingName',
            align: 'center',
            render: x => <span >{x || '暂无'}</span>,

        },
        {
            title: '关联渠道',
            dataIndex: 'channelName',
            key: 'channelName',
            align: 'center',
            render: x => <span >{x || '暂无'}</span>,
        },
        {
            title: '创建时间',
            dataIndex: 'createDate',
            key: 'createDate',
            align: 'center',
            render: (x, row) => <><span>{`${moment(row.createDate).format('YYYY-MM-DD HH:mm:ss')}`}</span></>,
        },
        {
            title: '操作',
            dataIndex: '',
            key: '',
            align: 'center',
            render: withActions((text, row) => [
                <AuthButton name="admin.qrcode.download" noRight={null}>
                    <EditIcon type="download" text="下载二维码" onClick={() => downloadQrcode(row)}> </EditIcon>
                </AuthButton>,
                <AuthButton name="admin.qrcode.dataRecord" noRight={null}>
                    <EditIcon type="data" text="数据" onClick={() => toDataRecord(row.qrCodeId)} ></EditIcon>
                </AuthButton>,


            ]),
        },
    ];


    const changePageNum = pageNumber => {
        getList({ pageNum: pageNumber, pageSize: 10, ...props.form.getFieldsValue() })
    }


    const rowSelection = {
        onChange: (selectedRowKeys, selectedRows) => {
            console.log('selectedRowKeys:', selectedRowKeys, 'selectedRows: ', selectedRows);
            setQrcodeList(selectedRows)
            if (selectedRowKeys.length <= 0) {
                setBeforeCheck('请至少选择一条数据')
            } else {
                setBeforeCheck('')
            }
        },
    };

    //   // 提交事件
    const handleSubmit = e => {
        e.preventDefault();
        props.form.validateFields((err, values) => {
            if (!err) {
                getList({ pageNum: 1, pageSize: 10, ...values })
            }
        });
    }

    //   // 重置搜索
    function handleReset() {
        props.form.resetFields();
        // setTime('')
        getList({ pageNum: 1, pageSize: 10 })
    }


    const { getFieldDecorator } = props.form
    return (

        <>
            <Form layout="inline" style={{ marginBottom: '10px' }} onSubmit={e => handleSubmit(e)}>
                <Form.Item>
                    {getFieldDecorator('targetType')(
                        <QrcodeType all visible />,
                    )}
                </Form.Item>
                <Form.Item>
                    {getFieldDecorator('targetName')(
                        <Input
                            placeholder="二维码内容"
                        />,
                    )}
                </Form.Item>
                <Form.Item>
                    {getFieldDecorator('channelId')(
                        <ChannelSelect all />,
                    )}
                </Form.Item>
                <Form.Item>
                    {getFieldDecorator('buildingId')(
                        <BuildSelect on />,
                    )}
                </Form.Item>
                <Form.Item>
                    <Button type="primary" htmlType="submit">搜索</Button>
                    <Button style={{ marginLeft: 8 }} onClick={handleReset}>重置</Button>
                </Form.Item>
            </Form>
            {/* title="确认删除？" */}

            <AuthButton name="admin.qrcode.add" noRight={null}>
                <Button type="danger" onClick={() => toAdd()}>新增</Button>
            </AuthButton>
            <AuthButton name="admin.qrcode.delete" noRight={null}>
                <ConfirmButton type="link" title="确认删除选中数据？" beforeCheck={beforeCheck} onClick={() => batchDelete()} style={{ marginLeft: '30px' }}>
                    <Button type="primary" >删除</Button>
                </ConfirmButton>
            </AuthButton>
            <Icon type="question-circle" theme="filled" style={{ fontSize: '25px', color: '#F00', marginLeft: '30px' }} onClick={() => setShowHelp(true)} />
            <Modal
                title="相关说明"
                centereds
                visible={showHelp}
                footer={null}
                onCancel={() => setShowHelp(false)}
                width="700px"
            >
                <p style={{ fontSize: '0.106rem', color: '#333', marginBottom: '8px' }}>1、支持为小程序中的项目、活动、资讯生成单独的二维码，用于渠道投放；</p>
                <p style={{ fontSize: '0.106rem', color: '#333', marginBottom: '8px' }}>2、同一个活动需要投放多个渠道时，需要生成多个二维码；</p>
                <p style={{ fontSize: '0.106rem', color: '#333', marginBottom: '8px' }}>3、点击每个二维码列表的“数据记录”可查看对应的获客记录。</p>


            </Modal>

            <Table rowSelection={rowSelection}
                dataSource={data.records} columns={columns} pagination={false} rowKey={r => r.qrCodeId} style={{ marginTop: '20px' }} />
            <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: '30px' }}>
                <Pagination
                    showQuickJumper
                    defaultCurrent={1}
                    total={data.total} onChange={e => changePageNum(e)} current={data.current} />
            </div>
        </>
    )
}
const WrappedQrcodelist = Form.create({ name: 'qrcodelist' })(qrcodelist);

export default WrappedQrcodelist
