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


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

/**
 * 助力者弹框
 */
class InviteTable extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      dataSource: { records: [] },
      visibleData: { visible: false, helpId: '', realtyConsultant: '' },
    }
  }

  // 挂载之后
  componentDidMount () {
    const { helpId } = this.state.visibleData
    this.getList({ helpRecordInitiateId: helpId, pageNumber: 1, pageSize: 5 })
  }

  componentDidUpdate (preProps, preState) {
    const { helpId } = this.state.visibleData
    if (this.props.visibleData.visible !== preState.visibleData.visible) {
      this.getList({ helpRecordInitiateId: helpId, pageNumber: 1, pageSize: 5 })
      this.setState({ visibleData: this.props.visibleData });
    }
  }

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

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

  getList (params) {
    if (params.helpRecordInitiateId === '') {
      return
    }
    request({ ...apis.helpActivity.helpPeopleDetails, 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
      />
    })
  }

  // eslint-disable-next-line class-methods-use-this
  exportHelp() {
    request({ ...apis.helpActivity.gethelpRecordExport, responseType: 'blob', params: { helpRecordInitiateId: this.state.visibleData.helpId } })
      .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(() => {

      })
  }


  // 分页
  // eslint-disable-next-line react/sort-comp
  onChange (pageNum) {
    this.getList({ pageNumber: pageNum, pageSize: 5 })
  }

  render () {
    const columns = [
      {
        title: '用户姓名',
        dataIndex: 'name',
        key: 'name',
        align: 'center',
      },
      {
        title: '手机号',
        dataIndex: 'phone',
        key: 'phone',
        align: 'center',
        render: text => <a>{text}</a>,
      },
      {
        title: '助力时间',
        dataIndex: 'createDate',
        key: 'createDate',
        align: 'center',
        render: (x, row) => <><span>{`${moment(row.createDate).format('YYYY-MM-DD HH:mm:ss')}`}</span></>,
      },
    ]
    return (
      <>
        <Modal
          title="助力者"
          destroyOnClose="true"
          width={900}
          footer={null}
          visible={this.state.visibleData.visible}
          // onOk={() => this.handleOk()}
          onCancel={e => this.handleCancel(e)}
        >

      <Button name="admin.HelpInitiateRecordSucceed.export.get" noRight={null} type="primary" onClick={() => this.exportHelp()} style={{ float: 'right', margin: '20px 0', zIndex: 1 }}>
        导出
      </Button>
          <Table rowKey="independent" dataSource={this.state.dataSource.records} columns={columns} pagination={{ total: this.state.dataSource.total, onChange: e => this.onChange(e) }} />
        </Modal>
      </>
    );
  }
}


/**
 * 核销弹框
 */
class Verifier extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      verification: { verificationCode: '' },
      visibleData: { visible: false, helpId: '', helpActivityId: '', helpRecordInitiateId: '', verificationCode: '' },
    }
  }

  // 挂载之后
  componentDidMount () {
    const { helpId } = this.state.visibleData
  }

  componentDidUpdate (preProps, preState) {
    const { helpId } = this.state.visibleData
    if (this.props.visibleData.visible !== preState.visibleData.visible) {
      // eslint-disable-next-line react/no-did-update-set-state
      this.setState({ visibleData: { ...this.props.visibleData } })
    }
  }

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

  // 弹框取消按钮
  handleCancel () {
    console.log('核销关闭');
    // this.setState({ visibleData: { visible: false, helpId: '', helpRecordInitiateId: '', verificationCode: '' } })
    this.props.onCancel()
  }

  // eslint-disable-next-line class-methods-use-this
  audit (params) {
    request({ ...apis.helpActivity.verification, params: { ...params } }).then(res => {
      // eslint-disable-next-line no-undef
      message.info('核销成功')
      this.props.onSuccess({ pageNumber: 1, pageSize: 10, helpActivityId: this.props.visibleData.helpActivityId, status: 'helpSucceed' })
    }).catch(err => {
      // eslint-disable-next-line no-unused-expressions
      <Alert
        style={{
          marginBottom: 24,
        }}
        message={err}
        type="error"
        showIcon
      />
    })
  }

  // eslint-disable-next-line class-methods-use-this
  verify(e) {
    this.setState({ visibleData: { visible: true, helpId: this.props.visibleData.helpId, verificationCode: e.target.value } })
  }

  // eslint-disable-next-line class-methods-use-this
  verification(e) {
    this.audit({ helpRecordInitiateId: this.state.visibleData.helpId, verifyCode: this.state.visibleData.verificationCode })
  }

  render () {
    return (
      <>
        <Modal
          title="核销"
          destroyOnClose="true"
          width={300}
          footer={null}
          visible={this.state.visibleData.visible}
          // onOk={() => this.handleOk()}
          onCancel={e => this.handleCancel(e)}
        >
          <div><span>核销码:<input style={{marginLeft: '10px'}} onChange={this.verify.bind(this)}/></span>
           <Button name="admin.helpInitiateRecordVerify.post" noRight={null} onClick={e => this.verification(e)} style={{ marginLeft: '80px', marginTop:'10px', backgroundColor:'red' }}><span style={{color:'white'}}>立即核销</span></Button>
          </div>
        </Modal>
      </>
    );
  }
}

/**
 *主体列表
 *
 * @param {*} props
 * @returns
 */
function body(props) {
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const [gInviteData, setGInviteData] = useState({ visible: false, helpId: '', realtyConsultant: '' })

  // 核销码弹框
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const [gVerifierData, setVerifierData] = useState({ visible: false, helpId: '', helpActivityId: '', helpRecordInitiateId: '', verificationCode: '' })

  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
  // const [columns, setColumns] = useState(privateColumns)

  // 默认成功
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const [customerType, setCustomerType] = useState('helpSucceed')

  // 调整归属 ============  start
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const [gVisibleData, setGVisibleData] = useState({ visible: false, helpId: '', realtyConsultant: '' })


  // 变更状态 ============= end

  // eslint-disable-next-line react-hooks/rules-of-hooks
  const { helpActivityId } = props.location.query
  useEffect(() => {
    console.log('customerType', customerType)
    getList({ pageNumber: 1, pageSize: 10, status: customerType, helpActivityId })
  }, [])

  function getList(params) {
    // 网路请求
    request({ ...apis.helpActivity.record, 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 displayNone() {
    setGVisibleData({ visible: false, helpId: '', realtyConsultant: '' })
  }

  // 提交事件
  function handleSubmit(e) {
    // displayNone()


    e.preventDefault();
    props.form.validateFields((err, values) => {
      if (!err) {
        getList({ pageNum: 1, pageSize: 10, status: customerType, ...values, helpActivityId })
      }
    });
  }

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

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

  // 助力成功/进行中/助力失败
  function radioButtonHandleSizeChange(e) {
    setGInviteData({ visible: false, helpId: '', realtyConsultant: '' })
    setVerifierData({ visible: false, helpId: '', helpRecordInitiateId: '', verificationCode: '' })
    // displayNone()

    const { value } = e.target
    setCustomerType(value)
    // setColumns(value === 'helpSucceed' ? privateColumns : publicColumns)
    getList({ pageNumber: 1, pageSize: 10, status: value, helpActivityId })
  }

  function handleReset() {
    props.form.resetFields();
    getList({ pageNum: 1, pageSize: 10, status: customerType, helpActivityId })
  }

  function toCustomerDateil(record) {
    router.push({
      pathname: '/customer/customerlist/customerDetail',
      query: {
        id: record.customerId,
      },
    });
  }

  function exportCustomer () {
    const fieldsValue = getFieldsValue()
    request({ ...apis.helpActivity.HelpInitiateRecordSucceed, responseType: 'blob', params: { ...fieldsValue, customerType, helpActivityId, condition: customerType } })
      .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()
  }

// 助力记录弹框
function helpRecord(row) {
  setVerifierData({ visible: false, helpId: row.helpRecordInitiateId, elpRecordInitiateId: '', verificationCode: '' })
  setGInviteData({ visible: true, helpId: row.helpRecordInitiateId, realtyConsultant: row.realtyConsultant })
}
 // 核销
 function helpInitiateRecordVerify(row) {
// 关闭助力记录弹框
  setGInviteData({ visible: false, helpId: row.helpRecordInitiateId, realtyConsultant: row.realtyConsultant })

  // 核销
  setVerifierData({ visible: true, helpId: row.helpRecordInitiateId, helpActivityId: row.helpActivityId, elpRecordInitiateId: '', verificationCode: '' })
 }
 // 核销回调
 function onSuccess(e) {
   console.log('回调：', e)
   getList(e)
    
   // 关闭
   onCancel()
 }

 function onCancel(e) {
  // 核销
  setVerifierData({ visible: false, helpId: '', helpActivityId: '', elpRecordInitiateId: '', verificationCode: '' })
  // 助力者
  setGInviteData({ visible: false, helpId: '', realtyConsultant: '' })
 }

 // 返回到首页
 function returList(params) {
  router.push({
      pathname: '/activity/helpActivity/list',
    });
}

  const publicColumns = [
    {
      title: '发起者',
      dataIndex: 'name',
      key: 'name',
      align: 'center',
      width: '15%',
    },
    {
      title: '发起者手机号',
      dataIndex: 'phone',
      key: 'phone',
      align: 'center',
      width: '10%',
    },
    {
      title: '发起时间',
      dataIndex: 'createDate',
      key: 'createDate',
      align: 'center',
      width: '15%',
      render: (x, row) => <><span>{`${moment(row.createDate).format('YYYY-MM-DD HH:mm:ss')}`}</span></>,
    },
    {
      title: '助力者',
      dataIndex: 'helpCount',
      key: 'helpCount',
      align: 'center',
      width: '15%',
      render: (text, record) => <a style={ { color: '#66B3FF' } } onClick={() => helpRecord(record)}>{record.helpCount}/{record.persionNumCount}</a>,
    },
  ]

  const privateColumns = [
    {
      title: '发起者',
      dataIndex: 'name',
      key: 'name',
      align: 'center',
      width: '15%',
      // render: (_, record) => <Avatar shape="square" src={customerType === 'helpSucceed' ? record.picture : record.avatarurl} size={64} icon="user" />,
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone',
      align: 'center',
      width: '10%',
      // eslint-disable-next-line no-nested-ternary
      // render: (_, record) => <><span>{customerType === 'helpSucceed' ? record.name : record.nickname}</span></>,
    },
    {
      title: '发起时间',
      dataIndex: 'createDate',
      key: 'createDate',
      align: 'center',
      width: '10%',
      render: (x, row) => <><span>{`${moment(row.createDate).format('YYYY-MM-DD HH:mm:ss')}`}</span></>,
      // eslint-disable-next-line no-nested-ternary
    },
    {
      title: '助力者',
      dataIndex: 'helpCount',
      key: 'helpCount',
      align: 'center',
      width: '15%',
      render: (text, record) => <a style={ { color: '#66B3FF' } } onClick={() => helpRecord(record)}>{record.helpCount}人</a>,
    },
    {
      title: '核销状态',
      dataIndex: 'reportRecommendStatus',
      key: 'reportRecommendStatus',
      align: 'center',
      width: '10%',
      // eslint-disable-next-line no-nested-ternary
      render: (text, records) => {
        if (records.verificationStatus === 0 || records.verificationStatus === null) { return '未核销' }
        if (records.verificationStatus === 1) { return '已核销' }
      },
    },
    {
      title: '操作',
      align: 'center',
      width: '25%',
      render: (x, row) => (
        <>
          {row.verificationStatus === 0 &&
          <AuthButton name="admin.help.writeOff" noRight={null}>
           <span style={{ color: '#1990FF', cursor: 'pointer' }} onClick={() => helpInitiateRecordVerify(row)}>核销</span>
          </AuthButton>
        }
        </>
      ),
    },
  ]

  return (
    <>
    {console.log('customerType', customerType)}
      <Form layout="inline" onSubmit={e => handleSubmit(e, props)}>
        <Form.Item>
          {getFieldDecorator('tel')(
            <Input
              prefix={<Icon type="text" style={{ color: 'rgba(0,0,0,.25)' }} />}
              placeholder="电话"
            />,
          )}
        </Form.Item>
        <Form.Item>
            <Button type="primary" htmlType="submit" >
              搜索
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={handleReset}>
              重置
            </Button>
        </Form.Item>
        <Button style={{ float: 'right' }} onClick={returList}>
          返回
        </Button>
      </Form>
      <Button name="admin.helpRecord.export.get" noRight={null} type="primary" onClick={() => exportCustomer()} style={{ float: 'right', margin: '20px 0', zIndex: 1 }}>
        导出
      </Button>

      <div style={{ margin: '20px 0' }}>
          <Radio.Group value={customerType} onChange={radioButtonHandleSizeChange} buttonStyle="solid">
            <Radio.Button value="helpSucceed">助力成功</Radio.Button>
            <Radio.Button value="helpUnderway">进行中</Radio.Button>
            <Radio.Button value="helpUnfinished">助力失败</Radio.Button>
          </Radio.Group>
      </div>
      {customerType === 'helpSucceed' ?
        <Table dataSource={dataSource.list} columns={privateColumns} pagination={{ total: dataSource.total, onChange }} rowKey="customerList" /> :
        <Table dataSource={dataSource.list} columns={publicColumns} pagination={{ total: dataSource.total, onChange }} rowKey="customerList" />
      }
        <Verifier visibleData={gVerifierData} onSuccess={e => onSuccess(e)} onCancel={(e) => onCancel(e)} />
       <InviteTable visibleData={gInviteData} onSuccess={e => onSuccess(e)} onCancel={(e) => onCancel(e)}/>
    </>
  );
}

const WrappedBody = Form.create({ name: 'body' })(body);

export default WrappedBody
