/* eslint-disable @typescript-eslint/no-use-before-define */
import CustomTree from '@/pages/components/customTree';
import { deleteUser } from '@/services/userList';
import {
  DeleteOutlined,
  DownOutlined,
  PlusOutlined,
  TeamOutlined,
} from '@ant-design/icons';
import { Button, Input, message, Popconfirm, Popover, Table } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import React, { useEffect, useState } from 'react';
import { OrganizationNode, Device } from './contast';
import styles from './index.less';
import EditModal from './mod/eidtDevice';
import CreatGroup from './mod/group';

const UserListPage: React.FC = () => {
  const [orgTreeData, setOrgTreeData] = useState<OrganizationNode[]>([]);
  const [selectedOrg, setSelectedOrg] = useState<string>('');

  // 用户列表
  const [dataSource, setDataSource] = useState<Device[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [searchText, setSearchText] = useState<string>('');
  const [selectedRowKeys, setSelectedRowKeys] = useState<[]>([]);

  // 分页参数
  const [currentPage, setCurrentPage] = useState<number>(1);
  const [pageSize, setPageSize] = useState<number>(10);
  const [total, setTotal] = useState<number>(0);
  // 编辑用户
  const [currentUserInfo, setCurrentUserInfo] = useState<any>({
    visible: false,
  });

  // 添加分组
  const [visible, setVisible] = useState<boolean>(false);

  // 获取用户分组组织树
  useEffect(() => {
    getGroupList();
  }, []);

  // 获取用户列表数据
  useEffect(() => {
    getDataSource();
  }, [selectedOrg, currentPage, pageSize]);

  const getGroupList = () => {
    const mockOrgData: OrganizationNode[] = [
      {
        name: 'Headquartershdy',
        id: '1',
        children: [
          {
            name: 'HR Department',
            id: '2',
          },
          {
            name: 'IT Department',
            id: '3',
            children: [
              {
                name: 'Frontend Team',
                id: '4',
              },
              {
                name: 'Backend Team',
                id: '5',
              },
            ],
          },
          {
            name: 'Finance Department',
            id: '6',
          },
        ],
      },
    ];
    setSelectedOrg(mockOrgData[0].id as string);
    setOrgTreeData(mockOrgData);
  };

  const getDataSource = () => {
    setLoading(true);
    setTimeout(() => {
      const startIndex = (currentPage - 1) * pageSize;
      const mockUsers: Device[] = Array.from(
        { length: pageSize },
        (_, index) => ({
          id: `${startIndex + index + 1}`,
          username: `User ${startIndex + index + 1}`,
          loginName: `login${startIndex + index + 1}`,
          userGroup:
            index % 3 === 0 ? 'Admin' : index % 3 === 1 ? 'Manager' : 'User',
          userType:
            index % 4 === 0
              ? 'Full-time'
              : index % 4 === 1
              ? 'Part-time'
              : index % 4 === 2
              ? 'Contractor'
              : 'Intern',
        }),
      );

      setDataSource(mockUsers);
      setTotal(100);
      setLoading(false);
    }, 300);
  };

  const onDelete = (device?: Device) => {
    const { user_id } = device || {};
    const payload = {
      ids: user_id ? [user_id] : selectedRowKeys,
    };
    deleteUser(payload as any).then((res) => {
      console.log('res=====', res);
      const { success } = res || {};
      if (success) {
        message.success('删除成功');
        setSelectedRowKeys([]);
        getDataSource();
      }
    });
  };

  const handleEditUserInfo = (device: Device) => {
    setCurrentUserInfo({
      recordData: { ...device },
      visible: true,
    });
  };

  const columns: ColumnsType<Device> = [
    {
      title: '显示名称',
      dataIndex: 'username',
      key: 'username',
    },
    {
      title: '终端名称',
      dataIndex: 'loginName',
      key: 'loginName',
    },
    {
      title: '终端分组',
      dataIndex: 'userGroup',
      key: 'userGroup',
    },
    {
      title: 'IP地址',
      dataIndex: 'sex',
      key: 'sex',
    },
    {
      title: '终端标识',
      dataIndex: 'mac_addr',
      key: 'mac_addr',
    },
    {
      title: '终端类型',
      dataIndex: 'device_type',
      key: 'device_type',
    },
    {
      title: '操作',
      key: 'actions',
      align: 'center',
      width: 150,
      render: (_, record) => (
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <Button type="link" onClick={() => handleEditUserInfo(record)}>
            编辑
          </Button>
          <Popover
            placement="bottomRight"
            content={
              <div>
                <Popconfirm
                  title=""
                  description="删除操作不可逆，请确认是否删除?"
                  onConfirm={() => onDelete(record)}
                  // onCancel={cancel}
                  okText="删除"
                  cancelText="取消"
                >
                  <Button type="link">删除</Button>
                </Popconfirm>
                <div>
                  <Button type="link" onClick={() => {}}>
                    绑定用户
                  </Button>
                </div>
                <div>
                  <Button type="link" onClick={() => {}}>
                    绑定镜像
                  </Button>
                </div>
              </div>
            }
          >
            <a onClick={(e) => e.preventDefault()}>
              更多
              <DownOutlined style={{ fontSize: '0.7rem' }} />
            </a>
          </Popover>
        </div>
      ),
    },
  ];

  const onOrgSelect = (selectedKeys: React.Key[]) => {
    if (selectedKeys.length > 0) {
      setSelectedOrg(selectedKeys[0] as string);
      setCurrentPage(1);
    }
  };

  const handlePageChange = (page: number, size: number) => {
    setCurrentPage(page);
    setPageSize(size);
  };

  const handlePageSizeChange = (current: number, size: number) => {
    setCurrentPage(1);
    setPageSize(size);
  };

  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    console.log('selectedRowKeys changed: ', newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys as any);
  };

  const onDeleteGroup = () => {};

  return (
    <div className={styles.user_content}>
      <div className={styles.left_content}>
        <div className={styles.search}>
          <div style={{ paddingBottom: '5px' }}>
            <Button
              type="text"
              style={{ marginRight: '8px', fontSize: '16px' }}
              icon={<PlusOutlined />}
              onClick={() => setVisible(true)}
            />
            <Popconfirm
              title=""
              description="删除操作不可逆，请确认是否删除?"
              onConfirm={() => onDeleteGroup()}
              // onCancel={cancel}
              okText="删除"
              cancelText="取消"
              disabled={selectedOrg === ''}
            >
              <Button
                type="text"
                style={{ fontSize: '16px' }}
                icon={<DeleteOutlined />}
              />
            </Popconfirm>
          </div>
          <Input.Search
            placeholder="请输入名称"
            style={{ marginBottom: 6 }}
            onSearch={(value) => console.log('Search org:', value)}
          />
        </div>
        <div className={styles.tree_box}>
          <CustomTree
            treeData={orgTreeData}
            titleField="name"
            keyField="id"
            childrenField="children"
            defaultExpandAll
            onSelect={onOrgSelect}
            selectedKeys={[selectedOrg]}
            icon={<TeamOutlined style={{ fontSize: '15px' }} />}
          />
        </div>
      </div>
      <div className={styles.right_content}>
        <div className={styles.teble_content}>
          <div
            style={{
              marginBottom: 16,
              display: 'flex',
              justifyContent: 'space-between',
            }}
          >
            <div>
              <Popconfirm
                title=""
                description="删除操作不可逆，请确认是否删除?"
                onConfirm={() => onDelete()}
                // onCancel={cancel}
                okText="删除"
                cancelText="取消"
                disabled={selectedRowKeys.length === 0}
              >
                <Button
                  disabled={selectedRowKeys.length === 0}
                  style={{ marginRight: '8px' }}
                >
                  删除
                </Button>
              </Popconfirm>
              <Button style={{ marginRight: '8px' }} onClick={getDataSource}>
                刷新
              </Button>
            </div>
            <div>
              <div>
                <Input.Search
                  placeholder="Search users"
                  value={searchText}
                  onChange={(e) => setSearchText(e.target.value)}
                  style={{ width: 300 }}
                  onSearch={(value) => {
                    console.log('Search user:', value);
                    setCurrentPage(1); // Reset to first page when searching
                  }}
                />
              </div>
            </div>
          </div>
          <div className={styles.teble_box}>
            <Table
              columns={columns}
              dataSource={dataSource}
              loading={loading}
              rowKey="id"
              rowSelection={{
                selectedRowKeys,
                onChange: onSelectChange,
              }}
              pagination={{
                current: currentPage,
                pageSize: pageSize,
                total: total,
                onChange: handlePageChange,
                onShowSizeChange: handlePageSizeChange,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total) => {
                  return `共${total}条数据`;
                },
              }}
              scroll={{ x: 'max-content', y: 55 * 12 }}
            />
          </div>
        </div>
      </div>
      <CreatGroup
        visible={visible}
        onCancel={() => {
          setVisible(false);
        }}
        selectedOrg={selectedOrg}
        onOk={() => {}}
        orgTreeData={orgTreeData}
      />
      <EditModal
        selectedOrg={selectedOrg}
        orgTreeData={orgTreeData}
        currentUserInfo={currentUserInfo}
        onCancel={() => {
          setCurrentUserInfo({
            recordData: {},
            visible: false,
          });
        }}
        onOk={() => {}}
      />
    </div>
  );
};

export default UserListPage;
