import React, { useState, useEffect } from 'react';
import { Form, Button, DatePicker, Modal, Table, Pagination, Radio, Icon, Typography } from 'antd';
import router from 'umi/router';
import moment from 'moment';
import BuildSelect from '../../../components/SelectButton/BuildSelect'
import apis from '../../../services/apis';
import request from '../../../utils/request'
import AuthButton from '../../../components/AuthButton';
import Prompt from 'umi/prompt';

/**
  @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,
        startDate: moment().subtract(radioVal, 'day').format('YYYYMMDD'),
        endDate: moment().format('YYYYMMDD'),
        buildingId: '',
        // asc: '',
        // desc: '',
    })

    // 获取初始化数据
    const [data, setData] = useState({})
    const [totalRow, setTotalRow] = useState({})
    const [loading, updataLoading] = useState(true)
    const [btnloading, updataBtnloading] = useState(false)
    const [visible, setVisible] = useState(false)

    useEffect(() => {
        if (localStorage.getItem("consultantPageParams")) {
            props.form.setFieldsValue(JSON.parse(localStorage.getItem("consultantPageParams")));
            const consultantPageParams = JSON.parse(localStorage.getItem("consultantPageParams"))
            updateRadioVal(moment(consultantPageParams.endDate).diff(moment(consultantPageParams.startDate), 'day'))
            updateFormData({
                ...formData,
                startDate: consultantPageParams.startDate,
                endDate: consultantPageParams.endDate,
                buildingId: consultantPageParams.buildingId,
                pageNum: consultantPageParams.pageNum
            })
            getList(JSON.parse(localStorage.getItem("consultantPageParams")))
        } else {
            getList(formData);
        }
    }, [])

    // 查询列表
    const getList = (params) => {
        updataLoading(true)
        localStorage.setItem("consultantPageParams", JSON.stringify(params));
        request({ ...apis.stats.consultantKPI, params: { ...params }, }).then((data) => {
            setData(data.paged)
            setTotalRow(data.total)
            updataLoading(false)
        }).catch(err => {
            updataLoading(false)
        })
    }

    //重置搜索
    function handleReset() {
        props.form.resetFields();
        updateFormData({
            pageNum: 1,
            pageSize: 10,
            startDate: moment().subtract(radioVal, 'day').format('YYYYMMDD'),
            endDate: moment().format('YYYYMMDD'),
            buildingId: '',
        })
        updateRadioVal(6)
        getList({
            pageNum: 1,
            pageSize: 10,
            startDate: moment().subtract(radioVal, 'day').format('YYYYMMDD'),
            endDate: moment().format('YYYYMMDD'),
            buildingId: '',
        });
    }

    // 提交事件
    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('YYYYMMDD'),
            endDate: moment().format('YYYYMMDD'),
        })
        getList({
            ...formData, startDate: moment().subtract(e.target.value, 'day').format('YYYYMMDD'),
            endDate: moment().format('YYYYMMDD'),
        });

    }
    // 选择日期
    const handleDateChange = (val) => {
        updateFormData({
            ...formData,
            startDate: val[0].format('YYYYMMDD'),
            endDate: val[1].format('YYYYMMDD'),
        })
    }
    // 选择项目
    const handleBuildingChange = e => {
        updateFormData({
            ...formData,
            buildingId: e,
        })
    }

    const clickCon = (val, record, type) => {
        if (val == 0) {
            return <><span>{val}</span></>
        }
        return <><span style={{ color: '#1D74D9', cursor: 'pointer' }} onClick={() => toDetail(record, type)} >{val}</span></>
    }

    // 分享详情
    function toDetail(record, type) {
        if (type === 'totalPersons') {
            router.push({
                pathname: '/statistical/consultant/table',
                query: {
                    // startDate: formData.startDate,
                    // endDate: formData.endDate,
                    buildingId: record.buildingId,
                    userId: record.userId,
                },
            });
        } else if (type === 'newPersons') {
            router.push({
                pathname: '/statistical/consultant/newPersons',
                query: {
                    startDate: formData.startDate,
                    endDate: formData.endDate,
                    buildingId: record.buildingId,
                    userId: record.userId,
                },
            });
        } else if (type === 'shareNum') {
            router.push({
                pathname: '/statistical/consultant/sharetable',
                query: {
                    startDate: formData.startDate,
                    endDate: formData.endDate,
                    buildingId: record.buildingId,
                    userId: record.userId,
                },
            });
        } else if (type === 'visitPersons') {
            router.push({
                pathname: '/statistical/consultant/visitPersons',
                query: {
                    startDate: formData.startDate,
                    endDate: formData.endDate,
                    buildingId: record.buildingId,
                    userId: record.userId,
                },
            });
        } else if (type === 'visitNum') {
            router.push({
                pathname: '/statistical/consultant/visitNum',
                query: {
                    startDate: formData.startDate,
                    endDate: formData.endDate,
                    buildingId: record.buildingId,
                    userId: record.userId,
                },
            });
        } else if (type === 'sharePersons') {
            router.push({
                pathname: '/statistical/consultant/sharePersons',
                query: {
                    startDate: formData.startDate,
                    endDate: formData.endDate,
                    buildingId: record.buildingId,
                    userId: record.userId,
                    type: 'sharePersons',
                },
            });
        } else if (type === 'homePagePersons') {
            router.push({
                pathname: '/statistical/consultant/homePagePersons',
                query: {
                    startDate: formData.startDate,
                    endDate: formData.endDate,
                    buildingId: record.buildingId,
                    userId: record.userId,
                },
            });
        } else if (type === 'homePageNums') {
            router.push({
                pathname: '/statistical/consultant/homepageNum',
                query: {
                    startDate: formData.startDate,
                    endDate: formData.endDate,
                    buildingId: record.buildingId,
                    userId: record.userId,
                    type: 'homePageNums',
                },
            });
        } else if (type === 'chatPersons') {
            router.push({
                pathname: '/statistical/consultant/chatPersons',
                query: {
                    startDate: formData.startDate,
                    endDate: formData.endDate,
                    buildingId: record.buildingId,
                    userId: record.userId,
                    type: 'chatPersons',
                },
            });
        } else if (type === 'favorNum') {
            router.push({
                pathname: '/statistical/consultant/favorNum',
                query: {
                    startDate: formData.startDate,
                    endDate: formData.endDate,
                    buildingId: record.buildingId,
                    userId: record.userId,
                    type: 'favorNum',
                },
            });
        }
    }
    //排序
    const handleChange = (pagination, filters, sorter) => {
        if (sorter.order == 'ascend') {
            getList({ ...formData, asc: sorter.columnKey, })
        } else if (sorter.order == 'descend') {
            getList({ ...formData, desc: sorter.columnKey, })
        } else {
            getList(formData);
        }
    };

    // 表格数据
    const columns = [

        {
            title: '项目',
            dataIndex: 'buildingName',
            key: 'buildingName',
            align: 'center',
            render: (txt, _, index) => index ? txt : <span>总计</span>,
        },

        {
            title: '置业顾问名称',
            dataIndex: 'userName',
            key: 'userName',
            align: 'center',
        },
        {
            title: '置业顾问电话',
            dataIndex: 'phone',
            key: 'phone',
            align: 'center',
        },
        {
            title: '客户总计',
            dataIndex: 'totalPersons',
            key: 'totalPersons',
            align: 'center',
            sorter: true,
            // render: (txt, record, index) => clickCon(txt, record, 'totalPersons'),
            render: (txt, record, index) => index ? clickCon(txt, record, 'totalPersons') : <strong>{txt}</strong>,
        },
        {
            title: '新增客户',
            dataIndex: 'newPersons',
            key: 'newPersons',
            align: 'center',
            sorter: true,
            // render: (txt, record, index) => clickCon(txt, record, 'newPersons'),
            render: (txt, record, index) => index ? clickCon(txt, record, 'newPersons') : <strong>{txt}</strong>,
        },
        {
            title: '分享次数',
            dataIndex: 'shareNum',
            key: 'shareNum',
            align: 'center',
            sorter: true,
            // render: (txt, record, index) => clickCon(txt, record, 'shareNum'),
            render: (txt, record, index) => index ? clickCon(txt, record, 'shareNum') : <strong>{txt}</strong>,
        },
        {
            title: '分享访问人数',
            dataIndex: 'visitPersons',
            key: 'visitPersons',
            align: 'center',
            sorter: true,
            // render: (txt, record, index) => clickCon(txt, record, 'visitPersons'),
            render: (txt, record, index) => index ? clickCon(txt, record, 'visitPersons') : <strong>{txt}</strong>,
        },
        {
            title: '分享访问次数',
            dataIndex: 'visitNum',
            key: 'visitNum',
            align: 'center',
            sorter: true,
            // render: (txt, record, index) => clickCon(txt, record, 'visitNum'),
            render: (txt, record, index) => index ? clickCon(txt, record, 'visitNum') : <strong>{txt}</strong>,
        },

        {
            title: '分享拓客',
            dataIndex: 'sharePersons',
            key: 'sharePersons',
            align: 'center',
            sorter: true,
            // render: (txt, record, index) => clickCon(txt, record, 'sharePersons'),
            render: (txt, record, index) => index ? clickCon(txt, record, 'sharePersons') : <strong>{txt}</strong>,
        },
        {
            title: '主页访问人数',
            dataIndex: 'homePagePersons',
            key: 'homePagePersons',
            align: 'center',
            sorter: true,
            // render: (txt, record, index) => clickCon(txt, record, 'homePagePersons'),
            render: (txt, record, index) => index ? clickCon(txt, record, 'homePagePersons') : <strong>{txt}</strong>,
        },
        {
            title: '主页访问次数',
            dataIndex: 'homePageNums',
            key: 'homePageNums',
            align: 'center',
            sorter: true,
            // render: (txt, record, index) => clickCon(txt, record, 'homePageNums'),
            render: (txt, record, index) => index ? clickCon(txt, record, 'homePageNums') : <strong>{txt}</strong>,
        },
        {
            title: '咨询数',
            dataIndex: 'chatPersons',
            key: 'chatPersons',
            align: 'center',
            sorter: true,
            // render: (txt, record, index) => clickCon(txt, record, 'chatPersons'),
            render: (txt, record, index) => index ? clickCon(txt, record, 'chatPersons') : <strong>{txt}</strong>,
        },
        {
            title: '点赞数',
            dataIndex: 'favorNum',
            key: 'favorNum',
            align: 'center',
            sorter: true,
            // render: (txt, record, index) => clickCon(txt, record, 'favorNum'),
            render: (txt, record, index) => index ? clickCon(txt, record, 'favorNum') : <strong>{txt}</strong>,
        },
    ];
    // 下载文档
    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', '置业顾问KPI.xlsx')
        document.body.append(link)
        link.click()
    }
    // 导出
    function exportRecord() {
        updataBtnloading(true)
        request({ ...apis.stats.exportConsultantKPI, responseType: 'blob', params: { startDate: formData.startDate, endDate: formData.endDate, buildingId: formData.buildingId } })
            .then(response => {
                download(response)
                updataBtnloading(false)
            }).catch(error => {
                updataBtnloading(false)
            })
    }
    // 默认日期
    const dateRange = [
        moment(formData.startDate),
        moment(formData.endDate),
    ]
    const list = data.records
    const _list = list && list.length > 0 ? [totalRow, ...list] : [];
    let row = 0
    return (

        <>

            <Modal
                title="指标说明（数据会存在一定时间延迟）"
                centered
                visible={visible}
                footer={null}
                onCancel={() => setVisible(false)}
            >
                <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>
                <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>
                <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">
                <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>
                        <BuildSelect value={formData.buildingId} onChange={handleBuildingChange} />
                    </Form.Item>
                    <Form.Item >
                        <Button type="primary" onClick={handleSubmit}>搜索</Button>
                        <Button style={{ marginLeft: 8 }} onClick={handleReset}>重置</Button>
                    </Form.Item>
                    <Icon type="question-circle" theme="filled" style={{ fontSize: '25px', color: '#F00' }} onClick={() => setVisible(true)} />
                </div>
            </Form>
            <AuthButton name="admin.statistical.consultant.export" noRight={null}>
                <Button type="primary" onClick={exportRecord} loading={btnloading} style={{ float: 'right', margin: '20px 23px 20px 0', zIndex: 1 }}>
                    导出
                </Button>
            </AuthButton>
            <Table rowKey={record => data.current * data.size + (row++)}
                style={{ marginTop: '30px' }}
                dataSource={_list}
                // dataSource={data.records}
                columns={columns}
                pagination={false}
                onChange={handleChange}
                loading={loading}
            />
            < div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: '30px' }}>
                <Pagination showQuickJumper defaultCurrent={1} total={data.total} onChange={changePageNum} current={data.current} />
            </div>
            <Prompt message={location =>
                location.pathname.startsWith("/statistical/consultant")
                    ? true
                    : localStorage.removeItem("consultantPageParams")} />
        </>
    )
}
const WrappedHeader = Form.create({ name: 'record' })(record);

export default WrappedHeader
