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 Styles from './style.less';
import router from 'umi/router';

import Attribution from './components/attribution'
import AssistConsultant from './components/assistConsultant'
import BatchAssistConsultant from './components/BatchAssistConsultant'
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';
import WxDictSelect from '@/components/SelectButton/WxDictSelect';


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: '' })

  const [assistVisibleData, setAssistVisibleData] = useState({visible: false, customerId: ''})

  const [loadingStatus, setLoadingStatus] = useState(false)

  // 选中的公客信息
  const [personInfo, setPersonInfo] = useState([])

  const [batchAssistVisibleData, setBatchAssistVisibleData] = 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) {
        if (values.startCreateDate){
          values.startCreateDate = moment(values.startCreateDate).format('YYYY-MM-DD HH:mm:ss');
        }
        if (values.endCreateDate){
          values.endCreateDate = moment(values.endCreateDate).format('YYYY-MM-DD HH:mm:ss');
        }
        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
    props.form.validateFields((err, values) => {
      if (!err) {
        getList({ pageNumber: pageNum, pageSize: 10, customerType, ...values })
      }
    });
  }

  // 私客/公客切换
  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: '' })
    setBatchAssistVisibleData({ visible: false, customerId: '' })
  }

  function showRecord(record) {
    setRecordVisibleData({ visible: true, customerId: record.personId })
    setGVisibleData({ visible: false, customerId: '', realtyConsultant: '', buildingId: '' })
    setStatusVisibleData({ visible: false, customerId: '' })
    setRecommendVisibleData({ visible: false, customerId: '' })
    setBatchAssistVisibleData({ 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 })
    setBatchAssistVisibleData({ visible: false, customerId: '' })
  }

  // 推荐客户
  function showRecommend(personId) {
    setRecordVisibleData({ visible: false, customerId: '' })
    setGVisibleData({ visible: false, customerId: '', realtyConsultant: '', buildingId: '' })
    setStatusVisibleData({ visible: false, customerId: '', status: '' })
    setRecommendVisibleData({ visible: true, customerId: personId })
    setBatchAssistVisibleData({ visible: false, customerId: '' })
  }

  //分配置业顾问
  function assistConsultant(personId) {
    setGVisibleData({ visible: false, customerId: '', realtyConsultant: '', buildingId: '' })
    setRecordVisibleData({ visible: false, customerId: '' })
    setStatusVisibleData({ visible: false, customerId: '' })
    setRecommendVisibleData({ visible: false, customerId: '' })
    setAssistVisibleData({ visible: true, customerId: personId })
    setBatchAssistVisibleData({ visible: false, customerId: '' })
  }

  function batchAssistConsultant(){
    if (personInfo.length <= 0){
      return message.info("请至少选择一条数据");
    }
    setGVisibleData({ visible: false, customerId: '', realtyConsultant: '', buildingId: '' })
    setRecordVisibleData({ visible: false, customerId: '' })
    setStatusVisibleData({ visible: false, customerId: '' })
    setRecommendVisibleData({ visible: false, customerId: '' })
    setAssistVisibleData({ visible: false, customerId: '' })
    setBatchAssistVisibleData({ visible: true, customerId: personInfo })
  }

  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 () {
    setLoadingStatus(true)
    const fieldsValue = getFieldsValue()
    request({ ...apis.customer.customerRecommendExport, responseType: 'blob', params: { ...fieldsValue, customerType } })
      .then(response => {
        download(response)
        setLoadingStatus(false)
      }).catch(error => {
        message.err("连接超时");
        setLoadingStatus(false)
      })
  }

  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: '' })
    setAssistVisibleData({ visible: false, customerId: ''})
    setBatchAssistVisibleData({visible: false, customerId: ''})
    getList({ pageNum: 1, pageSize: 10, customerType, ...props.form.getFieldsValue() })
  }

    const rowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
        console.log('selectedRowKeys:', selectedRowKeys, 'selectedRows: ', selectedRows);
        setPersonInfo(selectedRows)
      },
    };

  const publicColumns = [
    {
      title: '头像',
      dataIndex: 'picture',
      key: 'picture',
      align: 'center',
      width: '15%',
      render: (_, record) => <Avatar shape="square" style={{color: 'blue',cursor: 'pointer'}} onClick={() => publicCustomerDetail(record)} 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 style={{color: 'blue',cursor: 'pointer'}} onClick={() => publicCustomerDetail(record)} >{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: 'gender',
      key: 'gender',
      align: 'center',
      width: '10%',
      // eslint-disable-next-line no-nested-ternary
      render: (_, record) => <><span>{record.gender === '1' ? '男' : record.gender === '2' ? '女' : '未知'}</span></>,
    },
    {
      title: '操作',
      dataIndex: 'customerId',
      key: 'customerId',
      align: 'center',
      width: '25%',
      // eslint-disable-next-line no-nested-ternary
      render: (_, record) => (
        <>
          {/* <AuthButton name="admin.customer.public.detail" noRight={null}>
            <Button className={customerType === 'private' ? Styles.displayS : Styles.text } type="link" onClick={() => publicCustomerDetail(record)}>查看详情</Button>
          </AuthButton>
          &nbsp;&nbsp; */}
          <AuthButton name="admin.customer.recommend" noRight={null}>
            <Button className={customerType === 'private' ? Styles.displayS : Styles.text } type="link" onClick={() => showRecommend(record.personId)}>推荐客户</Button>
          </AuthButton>
          <AuthButton name="admin.customer.assign" noRight={null}>
            <Button className={customerType === 'private' ? Styles.displayS : Styles.text } type="link" onClick={() => assistConsultant(record.personId)}>分配置业顾问</Button>
          </AuthButton>
          <AuthButton name="admin.mine.taPointsRecords.point.record" noRight={null}>
            <Button className={Styles.text} type="link" onClick={() => showRecord(record)}>积分记录</Button>
          </AuthButton>
        </>
      ),
    },
  ]

  const privateColumns = [
    {
      title: '头像',
      dataIndex: 'picture',
      key: 'picture',
      align: 'center',
      width: '15%',
      render: (_, record) => <Avatar shape="square" style={{color: 'blue',cursor: 'pointer'}} onClick={() => toCustomerDateil(record)} 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 style={{color: 'blue',cursor: 'pointer'}} onClick={() => toCustomerDateil(record)}>{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>
            </AuthButton>
            &nbsp;&nbsp;
          <AuthButton name="admin.customer.recommend.belong" noRight={null}>
            <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.point.record" 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)}>
        <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>
          {getFieldDecorator('startCreateDate')(
            <DatePicker showTime={{ format: 'HH:mm:ss' }} placeholder="注册开始时间"/>,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('endCreateDate')(
            <DatePicker showTime={{ format: 'HH:mm:ss' }} placeholder="注册结束时间"/>,
          )}
        </Form.Item>
        <Form.Item>
          {getFieldDecorator('sceneType')(
            <WxDictSelect />,
          )}
        </Form.Item>
        <Form.Item>
            <AuthButton name="admin.customer.recommend.search" noRight={null}>
              <Button type="primary" htmlType="submit" >
                查询
              </Button>
            </AuthButton>
            <Button style={{ marginLeft: 8 }} onClick={handleReset}>
              重置
            </Button>
        </Form.Item>
      </Form>
      {
        customerType === 'private' ? 
        <AuthButton name="admin.customer.import" noRight={null}>
          <Button type="primary" loading={loadingStatus} onClick={() => exportCustomer()} style={{ float: 'right', margin: '20px 0', zIndex: 1 }}>
            导出
          </Button>
        </AuthButton> :
        <>
        <AuthButton name="admin.customer.import" noRight={null}>
          <Button type="primary" onClick={() => batchAssistConsultant()} style={{ float: 'right', margin: '20px 0', marginLeft:'20px', zIndex: 1 }}>
            批量分配置业顾问
          </Button>
        </AuthButton>
        <AuthButton name="admin.customer.import" noRight={null}>
          <Button type="primary" loading={loadingStatus} onClick={() => exportCustomer()} style={{ float: 'right', margin: '20px 0', zIndex: 1 }}>
            导出
          </Button>
        </AuthButton>
        </>
      }
      

      <div style={{ margin: '20px 0'}}>
          <Radio.Group value={customerType} onChange={radioButtonHandleSizeChange} buttonStyle="solid">
            <Radio.Button value="private">私客</Radio.Button>
            <Radio.Button value="public">公客</Radio.Button>
          </Radio.Group>
      </div>
      {customerType === 'private' ? 
        <Table 
        // onRow={record => {
        //   return {
        //     onClick: () => toCustomerDateil(record),
        //   };
        // }}
        dataSource={dataSource.records} columns={privateColumns} pagination={{ total: dataSource.total, onChange }} rowKey="customerList" /> :
        <Table rowSelection={rowSelection}
        // onRow={record => {
        //   return {
        //     onClick: () => publicCustomerDetail(record),
        //   };
        // }}
        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()}/>

      {/* 分配置业顾问 */}
      <AssistConsultant visibleData={assistVisibleData} onCancel={() => closeAll()}/>

      {/* 批量分配置业顾问 */}
      <BatchAssistConsultant visibleData={batchAssistVisibleData} onCancel={() => closeAll()}/>
    </>
  );
}

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

export default WrappedBody
