import React, { useState, useEffect } from 'react';
import { Button, Table, message, Modal } from 'antd';

import apis from '../../../services/apis';
import request from '../../../utils/request';
import ModalAttribution from '../components/attribution';
import { router } from 'umi';

function body(props) {
    console.log('props.localtion.query: ', props.location.query)

    const { id } = props.location.query
    

    // eslint-disable-next-line react-hooks/rules-of-hooks
    const [dataSource, setDataSource] = useState({ records: [], current: 1, size: 10, total: 0 })
    // eslint-disable-next-line react-hooks/rules-of-hooks
    const [consultant, setConsultant] = useState({ consultantUserId: '', consultantName: '' })

    // eslint-disable-next-line react-hooks/rules-of-hooks
    const [selectedRowIndex, setSelectedRowIndex] = useState([])

    // eslint-disable-next-line react-hooks/rules-of-hooks
    const [customerIdList, setCustomerIdList] = useState([])

    // eslint-disable-next-line react-hooks/rules-of-hooks
    const [visibleData, setVisibleData] = useState({ visible: false, realtyConsultant: '', buildingId: '', userId: '' })

    // eslint-disable-next-line react-hooks/rules-of-hooks
    const [userData, setUserData] = useState({})

    // eslint-disable-next-line react-hooks/rules-of-hooks
    useEffect(() => {
        if (id) {
            getList({ pageNumber: 1, pageSize: 99999, userId: id })
            getUserData(id)
        }
    }, [])

    function getList(params) {
        // 网路请求
        request({ ...apis.customer.byUserIdSelectCustomer, urlData: { id: params.userId }, params: { ...params } }).then(res => {
          setDataSource(res)
        }).catch(() => {

        })
    }

     // 查询列表
    function getUserData(userId) {
        request({ ...apis.staff.getTaUser, urlData: { id: userId } }).then((data) => {
            setUserData(data)
        })
    }

    function onShow() {
        setVisibleData({ visible: true, realtyConsultant: '', buildingId: userData.buildingId, userId: userData.userId })
    }

    function onCancel() {
        setVisibleData({ visible: false, realtyConsultant: '', buildingId: '', userId: '' })
    }

    function onSuccess({ realtyConsultant, name }) {
        setConsultant({ consultantUserId: realtyConsultant, consultantName: name })
    }

    function onSubmit() {
        if (customerIdList.length !== dataSource.total) {
            message.error('存在未分配归属客户')
            return
        }

        if (consultant.consultantId === '') {
            message.error('请选择分配归属的置业顾问')
            return
        }

        Modal.confirm({
            title: '确认保存后，当前员工下的客户数据将转移',
            content: '同时删除此员工所有数据，确认进行保存操作？',
            okText: '确认',
            cancelText: '取消',
            onOk () {
                request({ ...apis.staff.departure, urlData: { id: userData.userId }, params: { customerIdList, consultantUserId: consultant.consultantUserId } }).then(() => {
                    message.info('操作成功')
                    props.onFresh()
                    router.go(-1)
                }).catch(() => {
          
                })
            },
          });
    }

    const rowSelection = {
        selectedRowKeys: selectedRowIndex,
        hideDefaultSelections: true,
        onChange: (selectedRowKeys, selectedRows) => {
          console.log('selectedRowKeys: ', selectedRowKeys, 'selectedRows: ', selectedRows, selectedRowKeys);
          setSelectedRowIndex(selectedRowKeys)
          setCustomerIdList(selectedRows.map(p => p.customerId))
        },
    };

    const columns = [
        {
          title: '用户名',
          dataIndex: 'name',
          key: 'name',
          align: 'center',
        },
        {
          title: '手机号',
          dataIndex: 'phone',
          align: 'center',
          key: 'phone',
        },
        {
            title: '状态',
            dataIndex: 'reportRecommendStatus',
            key: 'reportRecommendStatus',
            align: 'center',
            // 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: 'consultantName',
            key: 'consultantName',
            align: 'center',
            render: (text, records, index) => {
                return selectedRowIndex.includes(index) ? consultant.consultantName : ''
            },
        },
      ];

    return (
        <>
            <Button type="primary" onClick={() => onShow()}>分配归属</Button>
            <Table rowSelection={rowSelection} dataSource={dataSource.records} columns={columns} pagination={{ pageSize: dataSource.size, current: dataSource.current, total: dataSource.total }} />
            <div style={{ display: 'flex', justifyContent: 'center', marginTop: '20px' }}>
                <Button type="primary" onClick={() => onSubmit()}>保存</Button>
                &nbsp;&nbsp;&nbsp;&nbsp;
                <Button onClick={() => router.go(-1)}>取消</Button>
            </div>

            {/* 选择只顾问弹框 */}
            <ModalAttribution visibleData={visibleData} onCancel={() => onCancel()} onSuccess={e => onSuccess(e)}/>
        </>
    )
}

export default body
