import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Icon, Select, DatePicker, Table, Pagination } from 'antd';
import { FormattedMessage } from 'umi-plugin-react/locale';
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 Navigate from '@/components/Navigate';

/**
  @param {*} props
  @returns
 */
const { Option } = Select;
const { MonthPicker, RangePicker, WeekPicker } = DatePicker;

function record(props) {
  const { getFieldDecorator } = props.form
  
  // 获取初始化数据
  const [ data, setData ] = useState({})

  useEffect(() => {
    getList({ pageNum: 1, pageSize: 10 });
  },[])

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

  //重置搜索
  function handleReset() {
    props.form.resetFields();
  }

    // 分享详情
    function shareCount(personId) {
        router.push({
        pathname: '/record/share/shareCountList',
        query: {
            id: personId,
        },
        });
    }
  
    // 点击人数详情
    function clickCount(personId) {
      console.log('123123123213',personId)
      router.push({
      pathname: '/record/share/clickCountList',
      query: {
          id: personId,
      },
      });
  }

  // 提交事件
  const handleSubmit = (e, props) => {
    e.preventDefault();
    props.form.validateFields((err, values) => {
      if (!err) {
        let {shareTime,receiveTime, ...submitValue} = values
        if(null != shareTime && shareTime.length > 0){
          const [startCreateDate, endCreateDate] = shareTime
          submitValue.startCreateDate = moment(startCreateDate).format('YYYY-MM-DD');
          submitValue.endCreateDate = moment(endCreateDate).format('YYYY-MM-DD');
        }else{
          submitValue.startCreateDate = null
          submitValue.endCreateDate = null
        }        
        console.log(submitValue)
        getList({ pageNum: 1, pageSize: 10, ...submitValue })
      }
    });
  }

  const changePageNum = (pageNumber) => {
    props.form.validateFields((err, values) => {
      if (!err) {
        let {shareTime,receiveTime, ...submitValue} = values
        if(null != shareTime && shareTime.length > 0){
          const [startCreateDate, endCreateDate] = shareTime
          submitValue.startCreateDate = moment(startCreateDate).format('YYYY-MM-DD');
          submitValue.endCreateDate = moment(endCreateDate).format('YYYY-MM-DD');
        }else{
          submitValue.startCreateDate = null
          submitValue.endCreateDate = null
        }        
        getList({ pageNum: pageNumber, pageSize: 10, ...submitValue })
      }
    });
  }

  function exportSales() {
    const fieldsValue = props.form.getFieldsValue()
    let {shareTime,receiveTime, ...submitValue} = fieldsValue
    if(null != shareTime && shareTime.length > 0){
      const [startCreateDate, endCreateDate] = shareTime
      submitValue.startCreateDate = moment(startCreateDate).format('YYYY-MM-DD');
      submitValue.endCreateDate = moment(endCreateDate).format('YYYY-MM-DD');
    }else{
      submitValue.startCreateDate = null
      submitValue.endCreateDate = null
    }   

    request({ ...apis.activity.exportSales, params: { ...submitValue} })
      .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 columns = [

    {
      title: '项目',
      dataIndex: 'buildingName',
      key: 'buildingName',
      align: 'center',
    },
    {
      title: '置业顾问',
      dataIndex: 'consultantName',
      key: 'consultantName',
      align: 'center',
    },
    {
      title: '分享次数',
      dataIndex: 'shareCount',
      key: 'shareCount',
      align: 'center',
      render: (_, record) => <Navigate onClick={() => shareCount(record.personId)}>{record.shareCount}</Navigate>,
    },
    {
      title: '点击人数',
      dataIndex: 'clickNum',
      key: 'clickNum',
      align: 'center',
      render: (_, record) => <Navigate onClick={() => clickCount(record.personId)}>{record.clickNum}</Navigate>,
    },
  ];

  return (

    <>
      <Form layout="inline" onSubmit={e => handleSubmit(e, props)}>
        <div style={{ display: 'flex' }}>
           <Form.Item>
            {getFieldDecorator('buildingId')(
              <BuildSelect />,
            )}
          </Form.Item>
          <Form.Item>
            <span style={{marginRight:'10px'}}>分享时间：</span>
                {getFieldDecorator('shareTime',{initialValue : [moment(),moment()],})(
                  <RangePicker placeholder={['开始时间','结束时间']}/>
                )}
          </Form.Item>
          <Form.Item style={{position:'absolute',right:'38px'}}>
            <AuthButton name="admin.taGoods.exchange" noRight={null}>
              <Button type="primary" htmlType="submit">
                搜索
              </Button>
            </AuthButton>
            <Button style={{ marginLeft: 8 }} onClick={handleReset}>
              重置
            </Button>
          </Form.Item>
        </div>
      </Form>
      <Button name="admin.activityDynamicEnlist.export.get" noRight={null} type="primary" onClick={exportSales}>导出</Button>
      <Table rowKey="exchangeRecords" style={{marginTop:'40px'}} dataSource={data.records} columns={columns} pagination={false} />
      <div style={{ display: 'flex', justifyContent: 'flex-end', marginTop: '30px' }}>
        <Pagination showQuickJumper defaultCurrent={1} total={data.total} onChange={changePageNum} current={data.current}/>
      </div>
    </>
  )
}
const WrappedHeader = Form.create({ name: 'record' })(record);

export default WrappedHeader
