import React, { useState, useEffect } from 'react';
import { Form, Icon, Input, Button, DatePicker, Select, Card, Row, Col, Pagination, Alert, Table, Avatar, Radio, Modal, Descriptions } 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/router';

import Attribution from './components/attribution'
import IntegralRecord from './components/integralRecord'
import ModalRecommendRecord from './components/recommend'
import ChangeStatus from './components/changeStatus'
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;

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

  // 默认私客
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const [customerType, setCustomerType] = useState('private')

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

  // 积分记录 ============  start
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const [recordVisibleData, setRecordVisibleData] = useState({ visible: false, customerId: '' })
  // 积分记录 ============= end

  // 变更状态 ============  start
  // eslint-disable-next-line react-hooks/rules-of-hooks
  const [statusVisibleData, setStatusVisibleData] = useState({ visible: false, customerId: '', status: '' })
  // 变更状态 ============= end

  // 推荐客户
  const [recommendVisibleData, setRecommendVisibleData] = useState({ visible: false, customerId: '' })

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

  function getList(params) {
    // 网路请求
    request({ ...apis.customer.customerRecommend, 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() {
    setRecordVisibleData({ visible: false, customerId: '' })
    setGVisibleData({ visible: false, customerId: '', realtyConsultant: '' })
    setStatusVisibleData({ visible: false, customerId: '', status: '' })
    setRecommendVisibleData({ visible: false, customerId: '' })
  }

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


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

  // 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) {
    displayNone()

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

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


  // 这里有个 Bug， 就是 Modal 弹框，会联动出现， 比如 我点击 调整归属的Model弹框， 那么 积分记录的Model弹框莫名其妙的也显示了
  // 所有这里临时解决方法是，弹出一个Modal对话框的时候，把其他的对话框给隐藏

  function showGM(record) {
    setGVisibleData({ visible: true, customerId: record.customerId, realtyConsultant: record.realtyConsultant, buildingId: record.buildingId })
    setRecordVisibleData({ visible: false, customerId: '' })
    setStatusVisibleData({ visible: false, customerId: '' })
    setRecommendVisibleData({ visible: false, customerId: '' })
  }

  function showRecord(record) {
    setRecordVisibleData({ visible: true, customerId: record.customerId })
    setGVisibleData({ visible: false, customerId: '', realtyConsultant: '', buildingId: '' })
    setStatusVisibleData({ visible: false, customerId: '' })
    setRecommendVisibleData({ visible: false, customerId: '' })
  }

  function showStatus(record) {
    setRecordVisibleData({ visible: false, customerId: '' })
    setGVisibleData({ visible: false, customerId: '', realtyConsultant: '', buildingId: '' })
    setRecommendVisibleData({ visible: false, customerId: '' })
    setStatusVisibleData({ visible: true, customerId: record.customerId, status: record.status })
  }

  // 推荐客户
  function showRecommend(personId) {
    setRecordVisibleData({ visible: false, customerId: '' })
    setGVisibleData({ visible: false, customerId: '', realtyConsultant: '', buildingId: '' })
    setStatusVisibleData({ visible: false, customerId: '', status: '' })
    setRecommendVisibleData({ visible: true, customerId: personId })
  }
  function toCustomerDateil(record) {
    router.push({
      pathname: '/customer/customerlist/customerDetail',
      query: {
        id: record.customerId,
      },
    });
  }
  // 私客详情
  function publicCustomerDetail(record) {
    router.push({
      pathname: '/customer/customerlist/publicCustomerDetail',
      query: {
        id: record.personId,
      },
    });
  }

  function exportCustomer () {
    const fieldsValue = getFieldsValue()
    request({ ...apis.customer.customerRecommendExport, responseType: 'blob', params: { ...fieldsValue, 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 closeAttribution() {
    setGVisibleData({ visible: false, customerId: '', realtyConsultant: '', buildingId: '' })
    getList({ pageNum: 1, pageSize: 10, customerType, ...props.form.getFieldsValue() })
  }
  // 回调关闭所有弹框
  function closeAll() {
    setRecordVisibleData({ visible: false, customerId: '' })
    setGVisibleData({ visible: false, customerId: '', realtyConsultant: '', buildingId: '' })
    setStatusVisibleData({ visible: false, customerId: '', status: '' })
    setRecommendVisibleData({ visible: false, customerId: '' })
    getList({ pageNum: 1, pageSize: 10, customerType, ...props.form.getFieldsValue() })
  }

  const publicColumns = [
    {
      title: '头像',
      dataIndex: 'picture',
      key: 'picture',
      align: 'center',
      width: '15%',
      render: (_, record) => <Avatar shape="square" src={customerType === 'private' ? record.picture : record.avatarurl} size={64} icon="user" />,
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      align: 'center',
      width: '10%',
      // eslint-disable-next-line no-nested-ternary
      render: (_, record) => <><span>{customerType === 'private' ? record.name : record.nickname}</span></>,
    },
    {
      title: '电话',
      dataIndex: 'phone',
      key: 'phone',
      align: 'center',
      width: '15%',
    },
    {
      title: '推广人员',
      dataIndex: 'sharePersonName',
      key: 'sharePersonName',
      align: 'center',
      width: '15%',
    },
    {
      title: '性别',
      dataIndex: 'sex',
      key: 'sex',
      align: 'center',
      width: '10%',
      // eslint-disable-next-line no-nested-ternary
      render: (_, record) => <><span>{record.sex === 1 ? '男' : record.sex === 2 ? '女' : '未知'}</span></>,
    },
    {
      title: '操作',
      dataIndex: 'customerId',
      key: 'customerId',
      align: 'center',
      width: '25%',
      // eslint-disable-next-line no-nested-ternary
      render: (_, record) => (
        <>
          <AuthButton>
            <Button className={customerType === 'private' ? Styles.displayS : Styles.text } type="link" onClick={() => publicCustomerDetail(record)}>查看详情</Button>
          </AuthButton>
          &nbsp;&nbsp;
          <AuthButton>
            <Button className={customerType === 'private' ? Styles.displayS : Styles.text } type="link" onClick={() => showRecommend(record.personId)}>推荐客户</Button>
          </AuthButton>
        </>
      ),
    },
  ]

  const privateColumns = [
    {
      title: '头像',
      dataIndex: 'picture',
      key: 'picture',
      align: 'center',
      width: '15%',
      render: (_, record) => <Avatar shape="square" src={customerType === 'private' ? record.picture : record.avatarurl} size={64} icon="user" />,
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      align: 'center',
      width: '10%',
      // eslint-disable-next-line no-nested-ternary
      render: (_, record) => <><span>{customerType === 'private' ? record.name : record.nickname}</span></>,
    },
    {
      title: '电话',
      dataIndex: 'phone',
      key: 'phone',
      align: 'center',
      width: '15%',
    },
    {
      title: '性别',
      dataIndex: 'sex',
      key: 'sex',
      align: 'center',
      width: '10%',
      // eslint-disable-next-line no-nested-ternary
      render: (_, record) => <><span>{record.sex === 1 ? '男' : record.sex === 2 ? '女' : '未知'}</span></>,
    },
    {
      title: '置业顾问',
      dataIndex: 'consultantName',
      key: 'consultantName',
      align: 'center',
      width: '15%',
      // eslint-disable-next-line no-nested-ternary
      render: (_, record) => (
        <>
          <span>{record.consultantName}</span>
          <br />
          <span>{record.consultTel}</span>
        </>
      ),
    },
    {
      title: '推广人员',
      dataIndex: 'sharePersonName',
      key: 'sharePersonName',
      align: 'center',
      width: '15%',
    },
    {
      title: '客户状态',
      dataIndex: 'reportRecommendStatus',
      key: 'reportRecommendStatus',
      align: 'center',
      width: '10%',
      // eslint-disable-next-line no-nested-ternary
      render: (text, records) => {
        if (records.status === 1) { return '报备' }
        if (records.status === 2) { return '到访' }
        if (records.status === 3) { return '认筹' }
        if (records.status === 4) { return '签约' }
      },
    },
    {
      title: '操作',
      dataIndex: 'customerId',
      key: 'customerId',
      align: 'center',
      width: '25%',
      // eslint-disable-next-line no-nested-ternary
      render: (_, record) => (
        <>
            &nbsp;
          <AuthButton name="admin.customer.recommend.edit.id.put" noRight={null}>
            <Button className={customerType === 'private' ? Styles.text : Styles.displayS} type="link" onClick={() => showStatus(record)}>变更状态</Button>
            &nbsp;&nbsp;
            <Button className={customerType === 'private' ? Styles.text : Styles.displayS} type="link" onClick={() => showGM(record)}>调整归属</Button>
          </AuthButton>
            &nbsp;&nbsp;
          <AuthButton name="admin.customer.recommend.get" noRight={null}>
            <Button className={customerType === 'private' ? Styles.text : Styles.displayS} type="link" onClick={() => toCustomerDateil(record)}>查看详情</Button>
          </AuthButton>
            &nbsp;&nbsp;
          <AuthButton name="admin.mine.taPointsRecords.id.get" noRight={null}>
            <Button className={customerType === 'private' ? Styles.text : Styles.displayS} type="link" onClick={() => showRecord(record)}>积分记录</Button>
          </AuthButton>
            &nbsp;
          <AuthButton name="admin.mine.taPointsRecords.id.get" noRight={null}>
            <Button className={customerType === 'private' ? Styles.text : Styles.displayS} type="link" onClick={() => showRecommend(record.personId)}>推荐客户</Button>
          </AuthButton>
        </>
      ),
    },
  ]

  return (
    <>
    {console.log('customerType', customerType)}
      <Form layout="inline" onSubmit={e => handleSubmit(e, props)}>
      {customerType === 'private' && <Form.Item>
          {getFieldDecorator('buildingId')(
            <BuildSelect />,
          )}
        </Form.Item>}
        {customerType === 'private' && <Form.Item>
          {getFieldDecorator('status')(
            <Select style={{ width: '180px' }} placeholder="状态" onChange={handleSelectChange}>
              <Option value={1}>报备</Option>
              <Option value={2}>到访</Option>
              <Option value={3}>认筹</Option>
              <Option value={4}>签约</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>
        {customerType === 'private' && <Form.Item>
          {getFieldDecorator('consultName')(
            <Input placeholder="置业顾问" />,
          )}
        </Form.Item>}
        {customerType === 'private' && <Form.Item>
          {getFieldDecorator('consultTel')(
            <Input placeholder="置业顾问电话" />,
          )}
        </Form.Item>}
        <Form.Item>
            <Button type="primary" htmlType="submit" >
              查询
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={handleReset}>
              重置
            </Button>
        </Form.Item>
      </Form>
      <Button type="primary" onClick={() => exportCustomer()} style={{ float: 'right', margin: '20px 0', zIndex: 1 }}>
        导出
      </Button>

      <div style={{ margin: '20px 0'}}>
        <AuthButton name="admin.customer.recommend.get" noRight={null}>
          <Radio.Group value={customerType} onChange={radioButtonHandleSizeChange} buttonStyle="solid">
            <Radio.Button value="private">私客</Radio.Button>
            <Radio.Button value="public">公客</Radio.Button>
          </Radio.Group>
        </AuthButton>
      </div>
      {customerType === 'private' ? 
        <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" /> 
      }
      
      {/* 调整归属 */}
      <Attribution visibleData={gVisibleData} onCancel={() => closeAttribution()}/>

      {/* 积分记录 */}
      <IntegralRecord visibleData={recordVisibleData} onCancel={() => closeAll()} />

      {/* 变更状态 */}
      <ChangeStatus visibleData={statusVisibleData} onCancel={() => closeAll()}/>

      {/* 推荐客户 */}
      <ModalRecommendRecord visibleData={recommendVisibleData} onCancel={() => closeAll()}/>
    </>
  );
}

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

export default WrappedBody
