import React, { useState, useMemo, useRef } from 'react';
import { Avatar, Button,message } from 'antd';
import router from 'umi/router';
import QueryTable from '@/components/QueryTable';
import apis from '@/services/apis';
import request from '@/utils/request';
import withActions from '@/components/ActionList';
import AuthButton from '@/components/AuthButton';
import Styles from '../style.less';
import IntegralRecord from './components/IntegralRecord';
import Recommend from './components/Recommend';
import AssistConsultant from './components/assistConsultant';
import getSearchFields from './searchFields';

const actionList = {
  integralRecord: 'integralRecord', //积分记录
  recommend: 'recommend', //推荐客户
  assistConsultant: 'assistConsultant', //分配置业顾问
};

const PublicCustomer = () => {
  const ref = useRef();

  const [showModel, SetShowModel] = useState({
    // changeStatus: { visible: true, data: {} },
  });
  const [exportLoding, setExportLoding] = useState(false);
   // 选中的公客信息
   const [personInfo, setPersonInfo] = useState([])

   const [selectedRowKeys, setSelectedRowKeys] = useState([])

  const handShowModel = (record, actionType) => {
    SetShowModel({
      [actionList[actionType]]: {
        visible: true,
        data: record,
      },
    });
  };

  function batchAssistConsultant() {
    console.log(personInfo, 'personInfo')
    console.log(personInfo.length)
    if (personInfo.length <= 0) {
      return message.info('请至少选择一条数据');
    }

    const compareSet = new Set();
    personInfo.filter(record => {
      compareSet.add(record.buildingName)
    })

    if (compareSet.size != 1) {
      return message.info('选中的公客存在于不同项目中，请分开进行分配置业顾问操作');
    }
    handShowModel({
      customerId: personInfo, buildingId: personInfo[0].buildingId
    }, actionList.assistConsultant)
    //   SetShowModel({
    //     [actionList[actionType]]: {
    //       visible: true,
    //       data: record,
    //     },
    //   });
    // };
    // setBatchAssistVisibleData({ visible: true, customerId: personInfo, buildingId: personInfo[0].buildingId })
  }

  function publicCustomerDetail(record) {
    router.push({
      pathname: '/customer/customerlist/publicCustomerDetail',
      query: {
        id: record.personId,
      },
    });
  }

  //导出
  function exportCustomer() {
    console.log(ref.current, 'ref');
    setExportLoding(true);

    request({
      ...apis.customer.customerRecommendExport,
      responseType: 'blob',
      params: ref.current.getSearchData,
    })
      .then(response => {
        download(response);
        setExportLoding(false);
      })
      .catch(() => {
        message.err('连接超时');
        setExportLoding(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();
  }

  const columns = useMemo(() => {
    return [
      {
        title: '头像',
        dataIndex: 'picture',
        key: 'picture',
        align: 'center',
        width: '10%',
        render: (_, record) => (
          <Avatar
            shape="square"
            style={{ color: 'blue' }}
            src={record.picture}
            size={64}
            icon="user"
          />
        ),
      },
      {
        title: '姓名',
        dataIndex: 'name',
        key: 'name',
        align: 'center',
        width: '20%',
      },
      {
        title: '电话',
        dataIndex: 'phone',
        key: 'phone',
        align: 'center',
        width: '20%',
      },
      {
        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: 'sharePersonName',
        key: 'sharePersonName',
        align: 'center',
        width: '20%',
      },
      {
        title: '操作',
        dataIndex: 'customerId',
        key: 'customerId',
        align: 'center',
       
        render: withActions((_, record) => [
          <Button  type="link" onClick={() => publicCustomerDetail(record)}>
            查看详情
          </Button>,

          <AuthButton name="admin.customer.assign" noRight={null}>
            <Button
        
              type="link"
              onClick={() => handShowModel(record, actionList.assistConsultant)}
            >
              分配置业顾问
            </Button>
          </AuthButton>,
        ]),
      },
    ];
  }, []);

  const searchFields = useMemo(getSearchFields, []);

  //操作成功请求数据
  const handleCancel = () => {
    SetShowModel({});
    ref.current.reload();
  };

  const actionRender = () => {
    return (
      <>
      <Button type="danger" loading={exportLoding} onClick={() => exportCustomer()}>
          导出
        </Button>
        <AuthButton name="admin.customer.import" noRight={null}>
          <Button
            type="primary"
            onClick={() => batchAssistConsultant()}
            style={{ marginLeft: '20px' }}
          >
            批量分配置业顾问
          </Button>
        </AuthButton>
        
      </>
    );
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: (selectedRowKeys, selectedRows) => {
      console.log('selectedRowKeys:', selectedRowKeys, 'selectedRows: ', selectedRows);
      setSelectedRowKeys(selectedRowKeys)
      const newSelectedRows = personInfo.filter(x => !selectedRows.some(y => x.customerId === y.customerId))     // 去重
        .concat(selectedRows)                                                                 // 新增选择
        .filter(x => selectedRowKeys.some(y => y === x.customerId))                             // 去掉未选的数据
      setPersonInfo(newSelectedRows)
    },
  };

  return (
    <>
      <QueryTable
        ref={ref}
        rowSelection={rowSelection}
        rowKey="customerId"
        api={apis.customer.customerRecommend}
        searchFields={searchFields}
        params={{
          customerType: 'public',
        }}
        columns={columns}
        actionRender={actionRender}
      />

      <IntegralRecord
        modelProps={showModel[actionList.integralRecord]}
        handleCancel={handleCancel}
        onCancel={() => SetShowModel({})}
      />

      <Recommend
        modelProps={showModel[actionList.recommend]}
        handleCancel={handleCancel}
        onCancel={() => SetShowModel({})}
      />

      <AssistConsultant
        modelProps={showModel[actionList.assistConsultant]}
        handleCancel={handleCancel}
        onCancel={() => SetShowModel({})}
      />
    </>
  );
};

export default PublicCustomer;
