import React, { useState, useEffect } from 'react';
import { Form, Icon, Input, Button, DatePicker, Select, Card, Row, Col, Pagination, Alert, Table, Avatar } from 'antd';
import moment from 'moment';
import request from '../../../utils/request';
import apis from '../../../services/apis';
import Styles from './style.less';
import { router } from 'umi';
import AuthButton from '@/components/AuthButton';
import BuildingSelect from '@/components/SelectButton/BuildSelect';


const { Option } = Select;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { Meta } = Card;

/**
 *
 *
 * @param {*} props
 * @returns
 */
function body(props) {
  const { getFieldDecorator } = props.form

  // eslint-disable-next-line react-hooks/rules-of-hooks
  const [dataSource, setDataSource] = useState({ records: [] })

  // eslint-disable-next-line react-hooks/rules-of-hooks
  useEffect(() => {
    getList({ pageNumber: 1, pageSize: 10 })
  }, [])

  function getList(params) {
    // 网路请求
    request({ ...apis.customer.recommender, params: { ...params } }).then(res => {
      setDataSource(res)
    }).catch(err => {
      // eslint-disable-next-line no-unused-expressions
      <Alert
        style={{
          marginBottom: 24,
        }}
        message={err}
        type="error"
        showIcon
      />
    })
  }

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

  // Change 事件
  function handleSelectChange(e) {
    // eslint-disable-next-line no-console
    console.log(e)
  }

  // 分页
  function onChange(pageNum) {
    props.form.validateFields((err, values) => {
      if (!err) {
        getList({ pageNumber: pageNum, pageSize: 10, ...values })
      }
    });
  }

  function toAudit(cuurentId) {
    router.push({
      pathname: '/recommend/recommendCustomer/audit',
      query: {
        id: cuurentId,
      },
    })
  }


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

  /**
   *导出数据（推荐用户）
   *
   */
  function exportRecommendCustomer() {
    request({
      ...apis.customer.customerRecommendRecommenderExport,
      responseType: 'blob',
    }).then(response => {
      console.log('exportRecommendCustomer: ', response)
      download(response)
    }).catch(error => {

    })
  }

  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', '推荐客户.xlsx')
    document.body.append(link)
    link.click()
  }

  const columns = [
    {
      title: '头像',
      dataIndex: 'picture',
      key: 'picture',
      render: (_, record) => <Avatar shape="square" src={record.picture} size={64} icon="user" />,
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '电话',
      dataIndex: 'phone',
      key: 'phone',
    },
    {
      title: '性别',
      dataIndex: 'sex',
      key: 'sex',
      // eslint-disable-next-line no-nested-ternary
      render: (_, record) => <><span>{record.sex === 1 ? '男' : record.sex === 2 ? '女' : '未知'}</span></>,
    },
    {
      title: '意向项目',
      dataIndex: 'intention',
      key: 'intention',
    },
    {
      title: '推荐人',
      dataIndex: 'consultantName',
      key: 'consultantName',
      render: (_, record) => <><span>{(record.recommendName !== null ? record.recommendName : '') + " " + (record.recommendTel !== null ? record.recommendTel : '')}</span></>,
    },
    {
      title: '推荐时间',
      dataIndex: 'createDate',
      key: 'createDate',
      render: (_, record) => <><span>{record.createDate && moment(record.createDate).format('YYYY-MM-DD')}</span></>,
    },
    {
      title: '状态',
      dataIndex: 'verifyStatus',
      key: 'verifyStatus',
      render: (_, record) => <><span>{record.verifyStatus === 0 ? '待审核' : record.verifyStatus === 1 ? '已通过' : record.verifyStatus === 2 ? '已驳回' : ''}</span></>,
    },
    {
      title: '操作',
      dataIndex: 'customerId',
      key: 'customerId',
      render: (_, record) => (
        <>
          {
            <AuthButton name="admin.customer.recommend.verify.id.put" noRight={null}>
              {record.verifyStatus === 0 ? <span style={{ color: 'rgba(239,39,58,1)', cursor: 'pointer' }} onClick={() => toAudit(record.customerId)}>审核</span> : ''}
            </AuthButton>
          }
        </>
      ),
    },
  ]

  return (
    <>
      <Form layout="inline" onSubmit={e => handleSubmit(e, props)} style={{ display: 'flex' }}>
        <Form.Item>
          {getFieldDecorator('name')(
            <Input
              prefix={<Icon type="text" style={{ color: 'rgba(0,0,0,.25)' }} />}
              placeholder="姓名"
            />,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('tel')(
            <Input
              prefix={<Icon type="text" style={{ color: 'rgba(0,0,0,.25)' }} />}
              placeholder="电话"
            />,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('consultName')(
            <Input placeholder="推荐人" />,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('consultTel')(
            <Input placeholder="推荐人电话" />,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('verifyStatus')(
            <Select style={{ width: '180px' }} placeholder="状态" onChange={handleSelectChange}>
              <Option value={0}>未通过</Option>
              <Option value={1}>已通过</Option>
              <Option value={2}>已驳回</Option>
            </Select>,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('buildingId')(
            <BuildingSelect />,
          )}
        </Form.Item>
        <Form.Item>
          <AuthButton name="admin.recommend.search" noRight={null}>
            <Button type="primary" htmlType="submit" >
              搜索
              </Button>
          </AuthButton>
          <Button style={{ marginLeft: 8 }} onClick={handleReset}>
            重置
            </Button>
        </Form.Item>
      </Form>
      {/* style={{float:'right',margin:'20px 0'}} */}
      <div style={{ textAlign: 'right', padding: '10px 0' }}>
        <AuthButton name="admin.recommend.import" noRight={null} >
          <Button type="primary" onClick={() => exportRecommendCustomer()}>
            导出
        </Button>
        </AuthButton>
      </div>
      <Table rowKey="recommendCustomer" dataSource={dataSource.records} columns={columns} pagination={{ total: dataSource.total, onChange }} />
    </>
  );
}
const WrappedBody = Form.create({ name: 'body' })(body);

export default WrappedBody
