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, groupActivityId: '', groupStatus: '' },
    }
  }

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

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

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

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

  getList(params) {
    console.log("params", params);
    request({ ...apis.groupActivity.shareChildList, 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 })
  }

  exportChildRecord(params) {
    request({ ...apis.groupActivity.exportShareChildRecord, responseType: 'blob', params: { ...params } })
      .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(() => {

      })
  }

  render() {
    const columns = [
      {
        title: '用户姓名',
        dataIndex: 'nickname',
        key: 'nickname',
        align: 'center',
      },
      {
        title: '手机号',
        dataIndex: 'phone',
        key: 'phone',
        align: 'center',
        render: text => <a>{text}</a>,
      },
      {
        title: '开团时间',
        dataIndex: 'createTime',
        key: 'createTime',
        align: 'center',
        render: (x, row) => <><span>{row.createTime ? `${moment(row.createTime).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 type="primary" name="admin.taShareChildRecord.export.get" noRight={null} onClick={() => this.exportChildRecord({ ...this.props.visibleData, pageNumber: 1, pageSize: 5 })} 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 = {
      groupActivityId: { id: '' },
      visibleData: { visible: false, groupActivityId: '', recordId: '' },
    }
  }

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

  componentDidUpdate(preProps, preState) {
    const { groupActivityId } = this.state.visibleData
    console.log('this.state.visibleData', this.state.visibleData)
    if (this.props.visibleData.visible !== preState.visibleData.visible) {
      this.setState({ visibleData: this.props.visibleData });
    }
  }

  // 弹框确定按钮
  handleOk() {
  }

  // 弹框取消按钮
  handleCancel() {
    this.props.onSuccess({ groupActivityId: this.props.visibleData.groupActivityId, groupStatus: 0 });
  }

  getVerCodeList(params) {
    request({ ...apis.groupActivity.verification, params: { ...params } }).then(res => {
      message.info('核销成功')
      this.props.onSuccess({ groupActivityId: this.state.visibleData.groupActivityId, groupStatus: 0 });
    }).catch(err => {
      <Alert
        style={{
          marginBottom: 24,
        }}
        message={err}
        type="error"
        showIcon
      />
    })
  }

  verify(e) {
    this.setState({ visibleData: { visible: true, groupActivityId: this.props.visibleData.groupActivityId, verificationCode: e.target.value, recordId: this.state.visibleData.recordId } })
  }

  // eslint-disable-next-line class-methods-use-this
  verification(e) {
    console.log("asdasdasdasd", this.state.visibleData);
    this.getVerCodeList({ groupActivityId: this.state.visibleData.groupActivityId, verifyCode: this.state.visibleData.verificationCode, recordId: this.state.visibleData.recordId })
  }

  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.taShareRecord.verificate.put" noRight={null} style={{ marginLeft: '80px', marginTop: '10px', backgroundColor: 'red' }} onClick={() => this.verification()}><span style={{ color: 'white' }}>立即核销</span></Button>
          </div>
        </Modal>
      </>
    );
  }
}

/**
 *主体列表
 *
 * @param {*} props
 * @returns
 */
function body(props) {
  const [gInviteData, setGInviteData] = useState({ visible: false, groupActivityId: '', recordId: '', groupStatus: '' })

  const [gVerifierData, setVerifierData] = useState({ visible: false, groupActivityId: '', verificateCode: '', recordId: '' })

  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 [groupStatus, setgroupStatus] = useState('0')

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


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

  // eslint-disable-next-line react-hooks/rules-of-hooks
  const { groupActivityId } = props.location.query
  useEffect(() => {
    getList({ pageNumber: 1, pageSize: 10, groupStatus: groupStatus, groupActivityId: groupActivityId })
  }, [])


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

  function getList(params) {
    console.log(params);
    // 网路请求
    request({ ...apis.groupActivity.shareSuccList, params: { ...params } }).then(res => {
      console.log("process");
      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 })
  }

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


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

  // 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, groupStatus, groupActivityId: groupActivityId, ...props.form.getFieldsValue() })
  }

  // 助力成功/进行中/助力失败
  function radioButtonHandleSizeChange(e) {
    setGInviteData({ visible: false })
    displayNone()

    const { value } = e.target
    setgroupStatus(value)
    if (value == 0) {
      getList({ pageNumber: 1, pageSize: 10, groupStatus: value, groupActivityId: groupActivityId, ...props.form.getFieldsValue() })
    }
    if (value == 1 || value == 2) {
      getFailList({ pageNumber: 1, pageSize: 10, groupStatus: value, groupActivityId: groupActivityId, ...props.form.getFieldsValue() })
    }
  }

  function handleReset() {
    props.form.resetFields();
    getList({ pageNumber: 1, pageSize: 10, groupStatus, groupActivityId: groupActivityId })
  }

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

  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 exportRecord() {
    request({ ...apis.groupActivity.exportShareRecord, responseType: 'blob', params: { groupActivityId: groupActivityId, groupStatus: groupStatus } })
      .then(response => {
        download(response)
      }).catch(error => {

      })
  }

  // 助力记录弹框
  function helpRecord(row) {
    // 关闭核销
    // eslint-disable-next-line max-len
    setVerifierData({ visible: false, groupActivityId: row.groupActivityId, groupStatus: 0 })
    // eslint-disable-next-line max-len
    setGInviteData({ visible: true, groupActivityId: row.groupActivityId, groupStatus: row.status, recordId: row.recordId })
  }
  // 打开核销
  function shareRecordVerify(row) {
    setVerifierData({ visible: true, groupActivityId: row.groupActivityId, groupStatus: 0, recordId: row.recordId })
    setGInviteData({ visible: false, groupActivityId: row.groupActivityId })
  }

  function onSuccess(e) {
    setVerifierData({ visible: false, groupActivityId: e.groupActivityId, groupStatus: 0 })
    getList({ pageNumber: 1, pageSize: 10, ...e });
  }

  function returnList(params) {
    router.push({
      pathname: '/activity/groupActivity/list',
    });
  }

  const publicColumns = [
    {
      title: '开团者',
      dataIndex: 'nickname',
      key: 'nickname',
      align: 'center',
      width: '15%',
    },
    {
      title: '开团者手机号',
      dataIndex: 'phone',
      key: 'phone',
      align: 'center',
      width: '10%',
    },
    {
      title: '开团时间',
      dataIndex: 'createTime',
      key: 'createTime',
      align: 'center',
      width: '15%',
      render: (x, row) => <><span>{row.createTime ? `${moment(row.createTime).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.joinPeople === null ? 0 : record.joinPeople}/{record.groupBuyPeople}</a>,
    },
  ]

  const privateColumns = [
    {
      title: '拼团者',
      dataIndex: 'nickname',
      key: 'nickname',
      align: 'center',
      width: '15%',
    },
    {
      title: '拼团者手机号',
      dataIndex: 'phone',
      key: 'phone',
      align: 'center',
      width: '10%',
    },
    {
      title: '拼团时间',
      dataIndex: 'createTime',
      key: 'createTime',
      align: 'center',
      width: '10%',
      render: (x, row) => <><span>{row.createTime ? `${moment(row.createTime).format('YYYY-MM-DD HH:mm:ss')}` : ''}</span></>
    },
    {
      title: '成团时间',
      dataIndex: 'endTime',
      key: 'endTime',
      align: 'center',
      width: '10%',
      render: (x, row) => <><span>{row.endTime ? `${moment(row.endTime).format('YYYY-MM-DD HH:mm:ss')}` : ''}</span></>
    },
    {
      title: '核销状态',
      dataIndex: 'verificationStatus',
      key: 'verificationStatus',
      align: 'center',
      width: '10%',
      // eslint-disable-next-line no-nested-ternary
      render: (text, records) => {
        if (records.verificationStatus === 0) { return '未核销' }
        if (records.verificationStatus === 1) { return '已核销' }
      },
    },
    {
      title: '操作',
      dataIndex: 'customerId',
      key: 'customerId',
      align: 'center',
      width: '25%',
      render: (x, row) => (
        <>
          {row.verificationStatus === 0 &&
            <AuthButton name="admin.taShare.writeOff" noRight={null}>
              <span style={{ color: '#1990FF', cursor: 'pointer' }} onClick={(e) => shareRecordVerify(row)}>核销</span>
            </AuthButton>
          }
        </>
      ),
    },
  ]


  const changePageNum = pageNumber => {
    getList({ pageNum: pageNumber, pageSize: 10 })
  }

  return (
    <>
      <Form layout="inline" onSubmit={e => handleSubmit(e, props)}>
        <Form.Item>
          {getFieldDecorator('phone')(
            <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={returnList}>
          返回
        </Button>
      </Form>
      <Button name="admin.taShareRecord.export.get" noRight={null} type="primary" onClick={() => exportRecord()} style={{ float: 'right', margin: '20px 0', zIndex: 1 }}>
        导出
      </Button>

      <div style={{ margin: '20px 0' }}>
        <AuthButton name="admin.taShareSuccessRecord.get" noRight={null}>
          <Radio.Group value={groupStatus} onChange={radioButtonHandleSizeChange} buttonStyle="solid">
            <Radio.Button value="0">拼团成功</Radio.Button>
            <Radio.Button value="1">进行中</Radio.Button>
            <Radio.Button value="2">拼团失败</Radio.Button>
          </Radio.Group>
        </AuthButton>
      </div>

      {groupStatus === '0' ?
        <Table dataSource={dataSource.records} columns={privateColumns} pagination={{ total: dataSource.total, onChange }} rowKey="customerList" /> :
        <Table dataSource={dataSource.records} columns={publicColumns} pagination={{ total: dataSource.total, onChange }} rowKey="customerList" />
      }
      <InviteTable visibleData={gInviteData} />
      {/* 核销 */}
      <Verifier visibleData={gVerifierData} onSuccess={(e) => onSuccess(e)} />
    </>
  );
}

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

export default WrappedBody
