import React, { useState, useEffect } from 'react';
import { Form, Icon, Input, Button, DatePicker, Select, Card, Row, Col, Pagination, Alert, Table, Avatar, notification, Modal } 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 ChannelSelect from '@/components/SelectButton/channelSelect';

const { Option } = Select;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { Meta } = Card;
/**
 * 推荐客户
 */
class ModalTable extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      dataSource: { records: [] },
      visibleData: { visible: false, customerId: '', realtyConsultant: '' },
    }
  }

  // 挂载之后
  componentDidMount() {
    this.getList({ pageNumber: 1, pageSize: 5 })
  }

  componentDidUpdate(preProps, preState) {
    if (this.props.visibleData.customerId !== preState.visibleData.customerId) {
      this.getList({ pageNumber: 1, pageSize: 5 })
      this.setState({ visibleData: this.props.visibleData });
    }
  }

  // 弹框确定按钮
  // eslint-disable-next-line react/sort-comp
  handleOk() {
    this.setState({ visibleData: { visible: false, customerId: '', realtyConsultant: '' } })
  }

  // 弹框取消按钮
  handleCancel() {
    this.setState({ visibleData: { visible: false, customerId: '', realtyConsultant: '' } })
    this.props.onCancel()
  }

  getList(params) {
    // eslint-disable-next-line no-console
    console.log('this.state.visibleData', this.state.visibleData)
    const { customerId } = this.state.visibleData
    if (customerId === '' || customerId === undefined) {
      return
    }
    // 网路请求
    // 网路请求
    request({ ...apis.customer.recommend, urlData: { id: customerId }, params: { ...params } }).then(res => {
      this.setState({ dataSource: res })
    }).catch(err => {
      // eslint-disable-next-line no-unused-expressions
      <Alert
        style={{
          marginBottom: 24,
        }}
        message={err}
        type="error"
        showIcon
      />
    })
  }

  // 分页
  onChange(pageNum) {

    this.getList({ pageNumber: pageNum, pageSize: 5, })

  }

  render() {
    const columns = [
      {
        title: '头像',
        // eslint-disable-next-line jsx-a11y/alt-text
        render: (text, record) => <Avatar shape="square" src={record.picture} size={64} icon="user" />,
        // render: (text, records) => <img src={records.picture} width={50} height={50} />,
      },
      {
        title: '用户名',
        dataIndex: 'name',
        key: 'name',
        // render: (row) => <><span>{console.log(row, 'row')}{row.name || row.nickname}</span></>,
      },
      {
        title: '电话',
        dataIndex: 'phone',
        key: 'phone',
      },
      {
        title: '性别',
        dataIndex: 'sex',
        key: 'sex',
        render: (text, records) => <span>{records.sex === 1 ? '男' : '女'}</span>,
      },
      {
        title: '意向项目',
        dataIndex: 'intention',
        key: 'intention',
      },
      {
        title: '推荐时间',
        dataIndex: 'createDate',
        key: 'createDate',
        render: (_, record) => <><span>{record.createDate && moment(record.createDate).format('YYYY-MM-DD HH:mm:ss')}</span></>,
      },
      {
        title: '状态',
        // eslint-disable-next-line consistent-return
        render: (text, records) => {
          console.log("retrun", records)
          //     if (records.status === 1) { return '报备' }
          // if (records.status === 2) { return '推荐' }
          // if (records.status === 3) { return '认购' }
          // if (records.status === 4) { return '签约' }
          // if (records.verifyStatus === 1) { return '待审核' }
          // if (records.verifyStatus === 2) { return '审核同意' }
          // if (records.verifyStatus === 3) { return '签约' }
          // if (records.status === 1) { if(records.reportRecommendStatus === 1) {return '报备'} if(records.reportRecommendStatus === 2) {return '推荐'}  }
          // if (records.status === 2) { return '到访' }
          // if (records.status === 3) { return '认购' }
          // if (records.status === 4) { return '签约' }
          // if (records.verifyStatus === 1) { return '待审核' }
          // if (records.verifyStatus === 2) { return '审核同意' }
          // if (records.verifyStatus === 3) { return '签约' }
          if (records.status === 1) {
            if (records.verifyStatus === 0) { return '待审核' }
            if (records.verifyStatus === 1) { return '报备' }
            // if (records.reportRecommendStatus === 1) { return '报备' }
            // if (records.reportRecommendStatus === 2) { return '推荐' }}
            if (records.verifyStatus === 2) { return '审核驳回' }
           }
          if (records.status === 2) { return '到访' }
          if (records.status === 3) { return '认购' }
          if (records.status === 4) { return '签约' }
          // reportRecommendStatus
        },
      },
    ]
    return (
      <>
        <Modal
          title="推荐客户"
          destroyOnClose="true"
          width={900}
          footer={null}
          visible={this.state.visibleData.visible}
          // onOk={() => this.handleOk()}
          onCancel={(e) => this.handleCancel(e)}
        >
          <Table rowKey="independentList" dataSource={this.state.dataSource.records} columns={columns} pagination={{ current: this.state.dataSource.current, pageSize: this.state.dataSource.size, total: this.state.dataSource.total, onChange: e => this.onChange(e) }} />
        </Modal>
      </>
    );
  }
}
// defaultCurrent={1} total={dataSource.total} pageSize={6} onChange={onChange} current={dataSource.current}

/**
 * 邀请客户
 */
class InviteTable extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      dataSource: { records: [] },
      visibleData: { visible: false, customerId: '', realtyConsultant: '' },
    }
  }

  // 挂载之后
  componentDidMount() {

  }

  componentDidUpdate(preProps, preState) {
    const { customerId } = this.props.visibleData

    if (this.props.visibleData.visible !== preState.visibleData.visible) {
      this.getList({ id: customerId, pageNumber: 1, pageSize: 5 })
      this.setState({ visibleData: this.props.visibleData });
    }
  }

  // 弹框确定按钮
  // eslint-disable-next-line react/sort-comp
  handleOk() {
    this.setState({ dataSource: { records: [] } })
    this.props.onCancel()
  }

  // 弹框取消按钮
  handleCancel() {
    console.log('345')
    this.setState({ dataSource: { records: [] } })
    this.props.onCancel()
  }

  getList(params) {
    const { id } = params
    console.log(id)
    if (id === '' || id === undefined) {
      return
    }
    request({ ...apis.customer.InviteClientsList, params: { ...params } }).then(res => {
      this.setState({ dataSource: res })
    }).catch(err => {
      // eslint-disable-next-line no-unused-expressions

    })
  }

  // 分页
  onChange(pageNum) {
    this.getList({ pageNumber: pageNum, pageSize: 5 })
  }

  render() {
    const columns = [
      {
        title: '头像',
        dataIndex: 'img',
        key: 'img',
        align: 'center',
        render: (text, record) => <img src={record.avatarurl} width={50} height={50} />,
      },
      {
        title: '用户姓名',
        dataIndex: 'nickname',
        key: 'nickname',
        align: 'center',
        render: (row) => <><span>{console.log(row, 'row')}{row.name || row.nickname}</span></>,
      },
      {
        title: '电话',
        dataIndex: 'phone',
        key: 'phone',
        align: 'center',
      },
      {
        title: '性别',
        dataIndex: 'sex',
        key: 'sex',
        align: 'center',
        render: (text, list) => <span>{list.sex === 1 ? '男' : '女'}</span>,
      },
    ]
    return (
      <>
        <Modal
          title="邀请经纪人"
          destroyOnClose="true"
          width={900}
          footer={null}
          visible={this.state.visibleData.visible}
          // onOk={() => this.handleOk()}
          onCancel={(e) => this.handleCancel(e)}
        >
          <Table rowKey="independent" dataSource={this.state.dataSource.records} columns={columns} pagination={{ total: this.state.dataSource.total, onChange: e => this.onChange(e) }} />
        </Modal>
      </>
    );
  }
}

/**
 *
 *主题列表
 * @param {*} props
 * @returns
 */
function body(props) {
  const { getFieldDecorator, getFieldsValue } = 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 openNotificationWithIcon(type, message) {
    notification[type]({
      message,
      description:
        '',
    });
  }

  function getList(params) {
    // 网路请求
    request({ ...apis.customer.agents, params: { ...params } }).then(res => {
      setDataSource(res)
    }).catch(err => {
      openNotificationWithIcon('error', err)
    })
  }

  // 提交事件
  function handleSubmit(e) {
    e.preventDefault();
    props.form.validateFields((err, values) => {
      if (!err) {
        getList({ pageNum: 1, pageSize: 10, ...values })
      }
    });
  }
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const [gVisibleData, setGVisibleData] = useState({ visible: false, customerId: '', realtyConsultant: '' })
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const [gInviteData, setGInviteData] = useState({ visible: false, customerId: '', realtyConsultant: '' })
  // Change 事件
  function handleSelectChange(e) {
    // eslint-disable-next-line no-console
    console.log(e)
  }
  function gM(row) {
    setGVisibleData({ visible: true, customerId: row.personId, realtyConsultant: row.realtyConsultant })

    setGInviteData({ visible: false })
  }

  function Invite(row) {
    setGInviteData({ visible: true, customerId: row.personId, realtyConsultant: row.realtyConsultant })

    setGVisibleData({ visible: false })
  }

  // 分页
  function onChange(pageNum) {
    // eslint-disable-next-line react-hooks/rules-of-hooks
    getList({ pageNumber: pageNum, pageSize: 10 })
  }

  /**
    * 重置搜索
    */
  function handleReset() {
    props.form.resetFields();
    getList({ pageNumber: 1, pageSize: 10 })
  }

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

  function exportIndependen() {
    const fieldsValue = getFieldsValue()
    console.log('fieldsValue', fieldsValue)
    request({ ...apis.customer.customerRecommendAgentsExport, responseType: 'blob', params: { ...fieldsValue } })
      .then(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: 'avatarurl',
      key: 'avatarurl',
      render: (_, record) => <Avatar shape="square" src={record.avatarurl} size={64} icon="user" />,
    },
    {
      title: '姓名',
      dataIndex: 'nickname',
      key: 'nickname',
      render: (_, record) => <><span>{record.name || record.nickname}</span></>,
    },
    {
      title: '电话',
      dataIndex: 'phone',
      key: 'phone',
    },
    {
      title: '性别',
      dataIndex: 'gender',
      key: 'gender',
      // eslint-disable-next-line no-nested-ternary
      render: (_, record) => <><span>{record.gender === '1' ? '男' : record.gender === '2' ? '女' : '未知'}</span></>,
    },
    {
      title: '类型',
      dataIndex: 'personType',
      key: 'personType',
      render: (_, record) => <><span>{record.personType === 'channel agent' ? '专业经纪人' : '专业经纪人'}</span></>,
    },
    {
      title: '所属渠道',
      dataIndex: 'channelName',
      key: 'channelName',
      render: (_, record) => <><span>{record.channelName}</span></>,
    },
    {
      title: '操作',
      dataIndex: 'customerId',
      key: 'customerId',
      render: (_, record) => (
        <>
          {
            <>
              {/* <span style={{ color: 'rgba(239,39,58,1)' }}>查看详细</span> */}
              {/* <AuthButton name="admin.channel.InviteClientsList.get" noRight={null}>
                <a style={{ color: 'rgba(239,39,58,1)' }} onClick={() => Invite(record)}>邀请经纪人</a>
              </AuthButton> */}
              {/* &nbsp;&nbsp;&nbsp;&nbsp; */}
              <AuthButton name="admin.customer.recommend.id.get" noRight={null}>
                <a style={{ color: 'rgba(239,39,58,1)' }} onClick={() => gM(record)}>推荐客户</a>
              </AuthButton>
            </>
          }
        </>
      ),
    },
  ]

  // <div>
  //         <span className={channels.selectName}>渠道名称</span>
  //         <Select defaultValue="请选择" style={{ width: 180 }} onChange={handleChange}>
  //           <option value="">全部</option>
  //           {data.channelNmae.map(Item =>
  //             <Option value={Item.channelId}> {Item.channelName} </Option>,
  //           )}
  //           {/* {listItems} */}
  //         </Select>
  //       </div>
  //       <div ></div>

  return (
    <>
      <Form layout="inline" onSubmit={e => handleSubmit(e, props)} style={{ display: 'flex', alignItems: 'center' }}>
        <Form.Item>
          {getFieldDecorator('channelId')(
            <ChannelSelect />
            //   <Select defaultValue="渠道名称" style={{ width: 180 }} onChange={handleChange}>
            //   <option value="">全部</option>
            //   {data.channelNmae.map(Item =>
            //     <Option value={Item.channelId}> {Item.channelName} </Option>,
            //   )}

            // </Select>,
          )}
        </Form.Item>
        <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 style={{ position: 'absolute', right: '38px' }} >
          <AuthButton name="admin.major.search" noRight={null}>
            <Button type="primary" htmlType="submit" >
              搜索
            </Button>
          </AuthButton>
          <Button style={{ marginLeft: 8 }} onClick={handleReset}>
            重置
          </Button>
        </Form.Item>
      </Form>
      <AuthButton name="admin.major.import" noRight={null}>
        <Button type="primary" onClick={() => exportIndependen()} style={{ float: 'right', margin: '20px 0', zIndex: 1 }}>
          导出
        </Button>
      </AuthButton>
      <Table rowKey="independentIndex" dataSource={dataSource.records} columns={columns} pagination={{ total: dataSource.total, onChange }} />
      {/* 推荐客户 */}
      <ModalTable visibleData={gVisibleData} onCancel={() => setGVisibleData({ visible: false, customerId: '', realtyConsultant: '' })}/>

      {/* 邀请经纪人 */}
      <InviteTable visibleData={gInviteData} onCancel={() => setGInviteData({ visible: false, customerId: '', realtyConsultant: '' })} />
    </>
  );
}
const WrappedBody = Form.create({ name: 'body' })(body);

export default WrappedBody
