import React, { useState, useEffect } from 'react';
import { Form, Button, DatePicker, Table, Pagination, Radio, Typography } from 'antd';
import sortBy from 'lodash/sortBy';
import router from 'umi/router';
import moment from 'moment';
import apis from '../../../services/apis';
import request from '../../../utils/request'
import AuthButton from '../../../components/AuthButton';
import echarts from 'echarts/lib/echarts';
import EChart from '../../../components/EchartsTest/EChart';
import Prompt from 'umi/prompt';
import Navigate from '@/components/Navigate';

/**
  @param {*} props
  @returns
 */
const { RangePicker } = DatePicker;
const { Text } = Typography;

function record(props) {
    const [radioVal, updateRadioVal] = useState(6)
    const [formData, updateFormData] = useState({
        pageNum: 1,
        pageSize: 10,
        ...props.location.query,
    })

    // 获取初始化数据
    const [data, setData] = useState([])
    const [chartsData, setChartsData] = useState([])
    const [loading, updataLoading] = useState(true)
    const [btnloading, updataBtnloading] = useState(false)

    useEffect(() => {
        getList(formData);
    }, [])

    // 查询列表
    const getList = (params) => {
        request({ ...apis.stats.activityDetail, params: { ...params }, }).then((data) => {
            setData((data || []).slice().reverse())
            setChartsData(data)
            updataLoading(false)
        }).catch(err => {
            updataLoading(false)
        })
    }

    //重置搜索
    function handleReset() {
        updateRadioVal(6)
        updateFormData({
            ...formData,
            startDate: moment().subtract(6, 'day').format('YYYY-MM-DD'),
            endDate: moment().format('YYYY-MM-DD'),
        })
        props.form.resetFields();
        getList({
            ...formData,
            startDate: moment().subtract(6, 'day').format('YYYY-MM-DD'),
            endDate: moment().format('YYYY-MM-DD'),
        });
    }

    // 提交事件
    const handleSubmit = (e) => {
        e.preventDefault();
        getList(formData);
    }
    // 更新页码
    const changePageNum = (pageNumber) => {
        props.form.validateFields((err, values) => {
            if (!err) {
                getList({ ...formData, pageNum: pageNumber });
            }
        });
    }

    // 切换日期 与picker联动
    function setFormData(e) {
        updateRadioVal(e.target.value)
        updateFormData({
            ...formData,
            startDate: moment().subtract(e.target.value, 'day').format('YYYY-MM-DD'),
            endDate: moment().format('YYYY-MM-DD'),
        })
        getList({
            ...formData, startDate: moment().subtract(e.target.value, 'day').format('YYYY-MM-DD'),
            endDate: moment().format('YYYY-MM-DD'),
        });

    }
    // 选择日期
    const handleDateChange = (val) => {
        updateFormData({
            ...formData,
            startDate: val[0].format('YYYY-MM-DD'),
            endDate: val[1].format('YYYY-MM-DD'),
        })
    }
    const clickCon = (val, record, type) => {
        if (val == 0) {
            return <><span>{val}</span></>
        }
        return <Navigate onClick={() => toDetail(record, type)}>{val}</Navigate>
    }

    //排序
    const handleChange = (pagination, filters, sorter) => {
        const keyValue = sorter.columnKey

        if (sorter.order == 'ascend') {
            setData(sortBy(data, function (item) {
                return item[keyValue];
            }))

        } else if (sorter.order == 'descend') {

            setData(sortBy(data, function (item) {
                return -item[keyValue];
            }))

        } else {
            setData(sortBy(data, function (item) {
                return item.statisDate;
            }))
        }
    };

    const toSharePersons = rowData => () => {
        console.log(rowData, 'rowData')
        if (rowData) {
            router.push({
                pathname: '/statistical/activity/sharePersonNum',
                query: {
                    queryDate: rowData.statisDate,
                    activityName: props.location.query.targetName,
                    buildingId: props.location.query.buildingId,
                    activityId: props.location.query.targetId,
                    activityType: props.location.query.targetType,

                },
            });
            return
        }
    }

    const toShareNum = rowData => () => {
        console.log(rowData, 'rowData')
        if (rowData) {
            router.push({
                pathname: '/statistical/activity/shareNum',
                query: {
                    queryDate: rowData.statisDate,
                    activityName: props.location.query.targetName,
                    buildingId: props.location.query.buildingId,
                    activityId: props.location.query.targetId,
                    activityType: props.location.query.targetType,
                },
            });
            return
        }
    }

    const toAddVisitNum = rowData => () => {
        console.log(rowData, 'statisDate')
        if (rowData) {
            router.push({
                pathname: '/statistical/activity/visitNum',
                query: {
                    queryDate: rowData.date,
                    activityName: props.location.query.targetName,
                    buildingId: props.location.query.buildingId,
                    activityId: props.location.query.targetId,
                    activityType: props.location.query.targetType,
                },
            });
            return
        }
    }

    const toAddVisitPersonNum = rowData => () => {
        console.log(rowData, 'rowData')
        if (rowData) {
            router.push({
                pathname: '/statistical/activity/visitPersonNum',
                query: {
                    queryDate: rowData.statisDate,
                    activityName: props.location.query.targetName,
                    buildingId: props.location.query.buildingId,
                    activityId: props.location.query.targetId,
                    activityType: props.location.query.targetType,
                },
            });
            return
        }
    }

    const toAddRegistNum = rowData => () => {
        console.log(rowData, 'rowData')
        if (rowData) {
            router.push({
                pathname: '/statistical/activity/addRegistNum',
                query: {
                    queryDate: rowData.statisDate,
                    activityName: props.location.query.targetName,
                    buildingId: props.location.query.buildingId,
                    activityId: props.location.query.targetId,
                    activityType: props.location.query.targetType,
                },
            });
            return
        }
    }

    // 表格数据
    const columns = [
        {
            title: '日期',
            dataIndex: 'statisDate',
            key: 'statisDate',
            align: 'center',
        },
        {
            title: '访问人数',
            dataIndex: 'visitPersons',
            key: 'visitPersons',
            sorter: true,
            align: 'center',
            render: (text, record) => (
                <Navigate onClick={toAddVisitPersonNum(record)}>{record.visitPersons}</Navigate>
                // <a style={{ color: '#66B3FF' }} onClick={toAddVisitPersonNum(record)}><span>{record.visitPersons}</span></a>
            ),
        },
        {
            title: '访问次数',
            dataIndex: 'visitNum',
            key: 'visitNum',
            sorter: true,
            align: 'center',
            render: (text, record) => (
                <Navigate onClick={toAddVisitNum(record)}>{record.visitNum}</Navigate>
                // <a style={{ color: '#66B3FF' }} onClick={toAddVisitNum(record)}><span>{record.visitNum}</span></a>
            ),
        },
        {
            title: '新增注册用户',
            dataIndex: 'newCustomers',
            key: 'newCustomers',
            sorter: true,
            align: 'center',
            render: (text, record) => (
                <Navigate onClick={toAddRegistNum(record)}>{record.newCustomers}</Navigate>
                // <a style={{ color: '#66B3FF' }} onClick={toAddRegistNum(record)}><span>{record.newCustomers}</span></a>
            ),
        },
        {
            title: '分享人数',
            dataIndex: 'sharePersons',
            key: 'sharePersons',
            sorter: true,
            align: 'center',
            render: (text, record) => (
                <Navigate onClick={toSharePersons(record)}>{record.sharePersons}</Navigate>
                // <a style={{ color: '#66B3FF' }} onClick={toSharePersons(record)}><span>{record.sharePersons}</span></a>
            ),
        },
        {
            title: '分享次数',
            dataIndex: 'shareNum',
            key: 'shareNum',
            sorter: true,
            align: 'center',
            render: (text, record) => (
                <Navigate onClick={toShareNum(record)}>{record.shareNum}</Navigate>
                // <a style={{ color: '#66B3FF' }} onClick={toShareNum(record)}><span>{record.shareNum}</span></a>
            ),
        },
    ];
    // 下载文档
    function download(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', `${props.location.query.targetName}.xlsx`)
        document.body.append(link)
        link.click()
    }
    // 导出
    function exportRecord() {
        updataBtnloading(true)
        request({ ...apis.stats.exportActivityDetail, responseType: 'blob', params: { ...props.location.query, startDate: formData.startDate, endDate: formData.endDate, } })
            .then(response => {
                download(response)
                updataBtnloading(false)
            }).catch(error => {
                updataBtnloading(false)
            })
    }
    // 默认日期
    const dateRange = [
        moment(formData.startDate),
        moment(formData.endDate),
    ]

    const dataZoom = props.dataZoom ? [
        {
            type: 'inside',
            start: 0,
            end: 100
        },
        {
            type: 'slider',
            start: 0,
            end: 100
        },
    ] : undefined
    const dataset = chartsData || []
    const options = {

        color: ["rgba(241,43,62,1)", "rgba(254,146,156,1)", "rgba(100,124,225,1)", "rgba(162,185,255,1)", "rgba(255,132,79,1)"],
        tooltip: {
            trigger: "axis"
        },
        icon: "rect",
        legend: {
            data: ["访问人数", "访问次数", "新增注册用户", "分享人数", "分享次数"]
        },
        toolbox: {},
        xAxis: {
            type: "category",
        },
        yAxis: {},
        dataZoom,
        series: [
            {
                name: "访问人数",
                type: "line",
            },
            {
                name: "访问次数",
                type: "line",
            },

            {
                name: "新增注册用户",
                type: "line",
            },
            {
                name: "分享人数",
                type: "line",
            },
            {
                name: "分享次数",
                type: "line",
            }
        ],
        dataset: {
            dimensions: ['statisDate', 'visitPersons', 'visitNum', 'newCustomers', 'sharePersons', 'shareNum'],
            source: dataset
        }
    }


    const piestyles = {
        width: '100%',
        height: '400px',
    }
    return (

        <>
            <div align="right" style={{ marginBottom: '16px' }}><Button onClick={() => router.go(-1)}>返回</Button></div>
            <Form layout="inline">
                <div style={{ display: 'flex', alignItems: 'center' }}>
                    <Radio.Group buttonStyle="solid" value={radioVal} onChange={setFormData} style={{ marginRight: '16px', }}>
                        <Radio.Button value={0}>今日</Radio.Button>
                        <Radio.Button value={6}>最近7天</Radio.Button>
                        <Radio.Button value={29}>最近1月</Radio.Button>
                    </Radio.Group>
                    <Form.Item>
                        <RangePicker value={dateRange} onChange={handleDateChange} placeholder={['开始日期', '结束日期']} />
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" onClick={handleSubmit}>搜索</Button>
                        <Button style={{ marginLeft: 8 }} onClick={handleReset}>重置</Button>
                    </Form.Item>
                </div>
            </Form>
            <div style={{ fontSize: '0.12rem', lineHeight: '2.6', fontWeight: '600' }}>趋势图：{props.location.query.targetName}</div>
            <div>
                <EChart options={options} style={piestyles} />
            </div>

            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <h4 style={{ fontSize: '0.12rem', fontWeight: '600' }}>详细数据</h4>
                <AuthButton name="admin.statistical.activity.content.export" noRight={null}>
                    <Button type="primary" onClick={exportRecord} loading={btnloading} style={{ zIndex: 1 }}>
                        导出
                </Button>
                </AuthButton>
            </div>

            <Table rowKey={(index => { index })}
                style={{ marginTop: '30px' }}
                dataSource={data}
                columns={columns}
                pagination={{ pageSize: 10 }}
                onChange={handleChange}
                loading={loading}
            />
            {/* < div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: '30px' }}>
                <Pagination size={2} showQuickJumper defaultCurrent={1}  total={data.total} onChange={changePageNum} current={data.current} />
            </div> */}
            <Prompt message={location =>
                location.pathname.startsWith("/statistical/activity")
                    ? true
                    : localStorage.removeItem("tabState")} />
        </>
    )
}
const WrappedHeader = Form.create({ name: 'record' })(record);

export default WrappedHeader
