import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Icon, Select, message, Table, Divider, Tag, Pagination, Modal, Radio, DatePicker, notification } 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 Navigate from '@/components/Navigate';
import styles from '../../style/GoodsList.less';
import BuildSelect from '@/components/SelectButton/BuildSelect'
import QrcodeType from '@/components/SelectButton/QrcodeType1'
import ChannelSelect from '@/components/SelectButton/channelSelect'
import apis from '../../../services/apis';
import request from '../../../utils/request';

// import RaiseHelpDoc from '../edit/components/RaiseHelpDoc';

// function getDayBegin(dt) {
//     return moment(dt, 'day').hours(0).minutes(0).seconds(0).milliseconds(0).format('YYYY-MM-DDTHH:mm:ss')+'.000Z';
//   }


//   function getDayEnd(dt) {
//     return moment(dt, 'day').hours(23).minutes(59).seconds(59).milliseconds(999).format('YYYY-MM-DDTHH:mm:ss')+'.999Z';
//   }
const { RangePicker } = DatePicker

const qrcodelist = props => {
    const { id, name, customerNum } = props.location.query
    const [data, setData] = useState([])
    const [showHelp, setShowHelp] = useState(false)
    const [endDate, setEndDate] = useState(new Date())
    const [startDate, setStartDate] = useState(moment().subtract(7, 'day').toDate())

    // setEndDate(`${moment(dateStrings[1]).format('YYYY-MM-DDT00:00:00.000')}Z`)
    // setStartDate(`${moment(dateStrings[0]).format('YYYY-MM-DDT00:00:00.000')}Z`)
    // 查询列表
    const getList = params => {
        request({ ...apis.channelList.getIntroductionList, params: { ...params, channelId: id } }).then(data => {
            console.log(data)
            setData(data)
        })
    }
    const formatDate = (start, end) => {
        const tempStartDate = `${moment(start).format('YYYY-MM-DDT00:00:00.000')}Z`
        const tempEndDate = `${moment(end).format('YYYY-MM-DDT23:59:59.999')}Z`
        return { startDate: tempStartDate, endDate: tempEndDate }
    }
    // eslint-disable-next-line react-hooks/rules-of-hooks
    useEffect(() => {
        setEndDate(new Date())
        setStartDate(moment().subtract(7, 'day').toDate())
        getList({ pageNum: 1, pageSize: 10, ...formatDate(startDate, endDate) });
    }, [])


    const toNewuser = (record) => {
        router.push({
            pathname: '/channel/newCustomer/dataRecord',
            query: {
                channelId: record.channelId,
                targetName: record.targetName,
                targetId: record.targetId,
                targetType: record.targetType,
                buildingId: record.buildingId,
                newCustomers: record.newCustomers,
                ...formatDate(startDate, endDate)
            },
        });
    }

    const toVisitNum = (record) => {
        router.push({
            pathname: '/channel/newCustomer/visitNum',
            query: {
                channelId: record.channelId,
                targetName: record.targetName,
                targetId: record.targetId,
                targetType: record.targetType,
                buildingId: record.buildingId,
                visitNum: record.visitNum,
                ...formatDate(startDate, endDate)
            },
        });
    }

    const toPersonNum = (record) => {
        router.push({
            pathname: '/channel/newCustomer/personNum',
            query: {
                channelId: record.channelId,
                targetName: record.targetName,
                targetId: record.targetId,
                targetType: record.targetType,
                buildingId: record.buildingId,
                visitPersons: record.visitPersons,
                ...formatDate(startDate, endDate)
            },
        });
    }

    /**
     * 导出
     */
    const exportExcel = () => {
        // console.log('fieldsValue', ...props.form.getFieldsValue())
        request({ ...apis.channelList.getIntroductionListExport, params: { channelId: id, ...props.form.getFieldsValue(), ...formatDate(startDate, endDate) } })
            .then(data => {
                if (!data) {
                    return
                }
                const url = window.URL.createObjectURL(new Blob([data]))
                const link = document.createElement('a')
                link.style.display = 'none'
                link.href = url
                link.setAttribute('download', '引进注册用户.xlsx')
                document.body.append(link)
                link.click()
            }).catch(() => {

            })
    }

    // 排序
    const handleTableChange = (pagination, filters, sorter) => {
        console.log(pagination, filters, sorter)
        // if (sorter.order === 'ascend') { 
        //     getList({ pageNum: 1, pageSize: 10, ...props.form.getFieldsValue(), startDate, endDate, asc: sorter.columnKey })
        // } else if (sorter.order === 'descend') {
        //     getList({ pageNum: 1, pageSize: 10, ...props.form.getFieldsValue(), startDate, endDate, desc: sorter.columnKey })
        // } else {
        //     getList({ pageNum: 1, pageSize: 10, ...props.form.getFieldsValue(), startDate, endDate });
        // }
        // sortField, sortOrder
        // getList({ pageNum: 1, pageSize: 10, ...props.form.getFieldsValue(), startDate, endDate, sorter.columnKey, sorter.order })
        getList({ channelId: id, ...props.form.getFieldsValue(), ...formatDate(startDate, endDate), sortField: sorter.columnKey, sortOrder: sorter.order })
    };

    /**
     *
     *
     * @param {*} props
     * @returns
     */
    const columns = [
        {
            title: '类型',
            dataIndex: 'targetType',
            key: 'targetType',
            align: 'center',
            render: (text, record) => <span>{text == 'building' ? '项目' : text == 'activity' ? '报名活动' : text == 'help' ? '助力活动' : text == 'group' ? '拼团活动'
                : text == 'h5' ? 'H5活动' : text == 'live' ? '直播活动' : text == 'news' ? '资讯' : text == 'house' ? '在线选房' : ''}</span>,
        },
        {
            title: '内容',
            dataIndex: 'targetName',
            key: 'targetName',
            align: 'center',

        },
        {
            title: '关联项目',
            dataIndex: 'buildingName',
            key: 'buildingName',
            align: 'center',

        },
        {
            title: '注册用户',
            dataIndex: 'newCustomers',
            key: 'new_customers',
            align: 'center',
            sorter: true,
            render: (text, record) => <Navigate onClick={() => toNewuser(record)}>{text}</Navigate>,

        },
        {
            title: '访问人数',
            dataIndex: 'visitPersons',
            key: 'visit_persons',
            align: 'center',
            sorter: true,
            render: (text, record) => <Navigate onClick={() => toPersonNum(record)}>{text}</Navigate>,

        },
        {
            title: '访问次数',
            dataIndex: 'visitNum',
            key: 'visit_num',
            align: 'center',
            sorter: true,
            render: (text, record) => <Navigate onClick={() => toVisitNum(record)}>{text}</Navigate>,
        },
    ];


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


    // 提交事件
    const handleSubmit = e => {
        e.preventDefault();

        props.form.validateFields((err, values) => {
            if (!err) {
                console.log(values, 'values')
                getList({ pageNum: 1, pageSize: 10, ...values, ...formatDate(startDate, endDate) })
            }
        });
    }

    //   // 重置搜索
    function handleReset() {
        props.form.resetFields();
        setEndDate(new Date())
        setStartDate(moment().subtract(7, 'day').toDate())
        getList({ pageNum: 1, pageSize: 10, ...formatDate(moment().subtract(7, 'day').toDate(), new Date()) })
    }

    function onChangetime(dates, dateStrings) {
        setEndDate(`${moment(dateStrings[1]).format('YYYY-MM-DDT00:00:00.000')}Z`)
        setStartDate(`${moment(dateStrings[0]).format('YYYY-MM-DDT00:00:00.000')}Z`)
        // daterange[1] = `${moment(dateStrings[1]).format('YYYY-MM-DDT00:00:00.000')}Z`
        // daterange[0] = `${moment(dateStrings[0]).format('YYYY-MM-DDT00:00:00.000')}Z`

    }

    const getDataOf = days => {

        setEndDate(new Date())
        setStartDate(moment().subtract(days, 'day').toDate())

        getList({ pageNum: 1, pageSize: 10, ...formatDate(moment().subtract(days, 'day').toDate(), new Date()) })
        // userResource({ startDate: moment().subtract(days, 'day').toDate(), endDate: new Date() })
    }

    const dateRange = [moment(startDate), moment(endDate)]

    const { getFieldDecorator } = props.form
    return (

        <>
            <div style={{ marginBottom: '20px' }}>
                <span> 渠道{name}总计引进{customerNum}个注册用户</span>
                <Icon type="question-circle" theme="filled" style={{ fontSize: '25px', color: '#F00', marginLeft: '30px' }} onClick={() => setShowHelp(true)} />
                <Button style={{ float: 'right', zIndex: 1 }} onClick={() => router.go(-1)}>
                    返回
               </Button>
            </div>
            <Modal
                title="相关说明"
                centereds
                visible={showHelp}
                footer={null}
                onCancel={() => setShowHelp(false)}
            // width="700px"
            >
                <p style={{ fontSize: '0.106rem', color: '#333', marginBottom: '8px' }}>新增注册用户：</p>
                <p style={{ fontSize: '0.106rem', color: '#999', marginBottom: '8px' }}>通过关联当前渠道的二维码授权手机号的总人数</p>
                <p style={{ fontSize: '0.106rem', color: '#333', marginBottom: '8px' }}>访问人数：</p>
                <p style={{ fontSize: '0.106rem', color: '#999', marginBottom: '8px' }}>通过关联当前渠道的二维码访问小程序的总人数</p>
                <p style={{ fontSize: '0.106rem', color: '#333', marginBottom: '8px' }}>访问次数：</p>
                <p style={{ fontSize: '0.106rem', color: '#999', marginBottom: '8px' }}>通过关联当前渠道的二维码访问小程序的总次数</p>


            </Modal>
            <Form layout="inline" style={{ marginBottom: '10px' }} onSubmit={e => handleSubmit(e)}>
                <Form.Item>
                    {getFieldDecorator('state', {
                        initialValue: 'a'
                    })(
                        <Radio.Group buttonStyle="solid" defaultValue="a" >
                            <Radio.Button value="a" onClick={() => getDataOf(7)}>最近7天</Radio.Button>
                            <Radio.Button value="b" onClick={() => getDataOf(30)}>最近1月</Radio.Button>
                        </Radio.Group>,
                    )}

                </Form.Item>
                {/* <Form.Item>
                        <RangePicker value={dateRange} onChange={handleDateChange} placeholder={['开始日期', '结束日期']} />
                    </Form.Item> */}
                <Form.Item>

                    <RangePicker
                        ranges={{
                            Today: [moment(), moment()],
                            'This Month': [moment().startOf('month'), moment().endOf('month')],
                        }}
                        value={dateRange}
                        onChange={(_dates, dateStrings) => onChangetime(_dates, dateStrings)}
                        allowClear={false}
                    />

                </Form.Item>
                <Form.Item>
                    {getFieldDecorator('buildingId')(
                        <BuildSelect style={{ width: '200px' }} />,
                    )}
                </Form.Item>
                <Form.Item>
                    {getFieldDecorator('targetType')(
                        <QrcodeType all visible />,
                    )}
                </Form.Item>
                <Form.Item>
                    <Button type="primary" htmlType="submit" className={styles.searchBtn}>搜索</Button>
                    <Button style={{ marginLeft: 8 }} onClick={handleReset}>重置</Button>
                </Form.Item>
            </Form>
            <Button type="primary" style={{ float: 'right', marginBottom: '20px', zIndex: 1 }} onClick={exportExcel}>导出</Button>
            <Table dataSource={data.records} columns={columns} pagination={false} rowKey={r => r.serialNo} onChange={handleTableChange} />
            <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: '30px' }}>
                <Pagination showQuickJumper defaultCurrent={1} total={data.total} onChange={e => changePageNum(e)} current={data.current} scroll={{ y: 500 }} />
            </div>
        </>
    )
}
const WrappedQrcodelist = Form.create({ name: 'qrcodelist' })(qrcodelist);

export default WrappedQrcodelist
