import React, { useMemo, useRef, useCallback, useState } from 'react';
import { Button, Modal, message } from 'antd';
import moment from 'moment';
import apis from '@/services/apis';
import request from '@/utils/request';
import AuthButton from '@/components/AuthButton';
import QueryTable from '@/components/QueryTable';
import BuildingSelect from '@/components/SelectButton/BuildSelect';
import OperButton from '@/components/OperButton';
import withActions from '@/components/ActionList';
import { router } from 'umi';

export default props => {
  const ref = useRef();
  const [visible, setVisible] = useState(false);
  const [data, setData] = useState(false);


  const toEdit = useCallback(row => {
    //跳转到编辑商品
    router.push({
      pathname: '/system/Staff/Edit',
      query: {
        userId: row?.userId || undefined,
      },
    });
  }, []);


  //迁移私客成功回调
  const moveSuccess = e => {
    setVisible(false);
    if (e === 'success') {
      confirm(data)();
      setData()
    }
  };

  const confirm = data => () => {
    // console.log(data, "11111")
    if (data.status === 1) {
      if (data.isConsultant) {
        request({
          ...apis.staff.check,
          params: {
            userId: data.userId,
            personId: data.consultantPersonId,
            buildingId: data.buildingId,
          },
        }).then(res => {
          if (res.length > 0) {
            Modal.confirm({
              title: '此置业顾问下有私客，是否转移私客？',
              okText: '确认',
              cancelText: '取消',
              onOk() {
                setVisible(true);
                setData(data);
              },
            });
          } else {
            const titleMessahe = data.isConsultant
              ? '停用后此员工无法继续登录后台（若为置业顾问停用后在小程序端将成为普通用户）确认进行停用操作？'
              : '停用后此员工无法继续登录后台,确认进行停用操作？';
            Modal.confirm({
              title: titleMessahe,
              okText: '确认',
              cancelText: '取消',
              onOk() {
                request({ ...apis.staff.change, urlData: { id: data.userId, type: 'off' } }).then(
                  res => {
                    message.info('操作成功');
                    ref.current.reload();
                  },
                );
              },
            });
          }
        });
      } else {
        const titleMessahe = data.isConsultant
          ? '停用后此员工无法继续登录后台（若为置业顾问停用后在小程序端将成为普通用户）确认进行停用操作？'
          : '停用后此员工无法继续登录后台,确认进行停用操作？';
        Modal.confirm({
          title: titleMessahe,
          okText: '确认',
          cancelText: '取消',
          onOk() {
            request({ ...apis.staff.change, urlData: { id: data.userId, type: 'off' } }).then(
              res => {
                message.info('操作成功');
                ref.current.reload();
              },
            );
          },
        });
      }
    } else {
      Modal.confirm({
        title: '确认启用该角色？',
        okText: '确认',
        cancelText: '取消',
        onOk() {
          request({ ...apis.staff.change, urlData: { id: data.userId, type: 'on' } }).then(res => {
            message.info('操作成功');
            ref.current.reload();
          });
        },
      });
    }
  };

  const searchFields = [
    {
      name: 'buildingId',
      label: '所属项目',
      placeholder: '请选择项目',
      render: () => <BuildingSelect style={{ width: 160 }} />,
    },
    {
      name: 'jobNumber',
      label: '工号',
      placeholder: '请输入工号',
    },
    {
      name: 'userName',
      label: '姓名',
      placeholder: '请输入姓名',
    },
    {
      name: 'isConsultant',
      label: '类型',
      placeholder: '请选择类型',
      type: 'select',
      options: [
        { label: '全部', value: '' },
        { label: '非置业顾问', value: 0 },
        { label: '置业顾问', value: 1 },
      ],
    },
    {
      name: 'status',
      label: '状态',
      placeholder: '请选择状态',
      type: 'select',
      options: [
        { label: '全部', value: '' },
        { label: '启用', value: 1 },
        { label: '禁用', value: 9 },
      ],
    },
  ];

  const tableColumns = [
    {
      title: '工号',
      key: 'jobNumber',
      dataIndex: 'jobNumber',
      align: 'center',
    },
    {
      title: '姓名',
      dataIndex: 'userName',
      key: 'userName',
      align: 'center',
    },
    {
      title: '电话',
      dataIndex: 'phone',
      key: 'phone',
      align: 'center',
    },
    {
      title: '类型',
      dataIndex: 'isConsultant',
      key: 'isConsultant',
      align: 'center',
      //text===1 改===true 
      render: text => (text === true ? '置业顾问' : '非置业顾问'),
    },
    {
      title: '绑定状态',
      dataIndex: 'miniStatus',
      key: 'miniStatus',
      align: 'center',
      render: text => (text === 1 ? '已绑定' : '未绑定'),
    },
    {
      title: '创建时间',
      dataIndex: 'createDate',
      key: 'createDate',
      align: 'center',
      render: t => moment(t).format('YYYY-MM-DD HH:mm'),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      align: 'center',
      render: text => (text === 1 ? '启用' : '停用'),
    },

    {
      title: '操作',
      key: 'options',
      align: 'center',
      render: withActions(
        (_, row) => [
          <AuthButton name="staff.stop" noRight={null}>
            <OperButton onClick={confirm(row)}>{row.status === 1 ? '停用' : '启用'}</OperButton>
          </AuthButton>,
          <AuthButton name="staff.edit" noRight={null}>
            <OperButton onClick={() => toEdit(row)}>编辑</OperButton>
          </AuthButton>,
        ],
        { noMargin: true },
      ),
    },
  ];

  const actionRender = () => {
    return (
      <AuthButton name="staff.add" noRight={null}>
        <Button type="primary" icon="plus" onClick={() => toEdit()}>
          新增
        </Button>
      </AuthButton>
    );
  };

  return (
    <>
      <QueryTable
        ref={ref}
        rowKey="userId"
        api={apis.staff.taUser}
        columns={tableColumns}
        searchFields={searchFields}
        actionRender={actionRender}
      />

      <Modal
        visible={visible}
        title="分配归属"
        onCancel={() => setVisible(false)}
        footer={null}
        width={900}
      >
        {data && (
          <CustomerChange
            userId={data.userId}
            consultantPersonId={data.consultantPersonId}
            buildingId={data.buildingId}
            onSuccess={moveSuccess}
          />
        )}
      </Modal>
    </>
  );
};
