/* eslint-disable @typescript-eslint/no-use-before-define */
import CustomTree from '@/pages/components/customTree';
import { TeamOutlined } from '@ant-design/icons';
import type { PopoverProps } from 'antd';
import { Alert, Button, Popconfirm, Popover, Space, Tabs } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import React, { useEffect, useState } from 'react';
import SelectConponents from '../selectConponents';
import CustomTable from './table';

interface SelectedTableProps {
  placement?: PopoverProps['placement'];
  selectedOrg?: number;
  onCancel?: () => void;
  onOk?: (values: any) => void;
  orgTreeData?: User.OrganizationNode[];
  value?: any;
  onChange?: (values: any) => void;
}

const SelectedTable: React.FC<SelectedTableProps> = (props) => {
  const {
    placement = 'bottomLeft',
    orgTreeData,
    value: formValue,
    onChange: onBindUserChange,
  } = props;
  const [open, setOpen] = useState<boolean>(false);
  const [tableData, setTableData] = useState<any[]>([]);
  //用户选择列表
  const [selectedRowKeys, setSelectedRowKeys] = useState<[]>([]);
  const [selectedRows, setSelectedRows] = useState<any[]>([]);
  // 用户组
  const [checkedKeys, setCheckedKeys] = useState<any[]>([]);
  const [checkedRow, setCheckedRow] = useState<any[]>([]);

  // 已绑定用户列表选择
  const [bindTableKeys, setBindTableKeys] = useState<any[]>([]);

  useEffect(() => {
    console.log('formValue==========', formValue);
    const userList: any = [];
    const groupList: any = [];
    const userId: any = [];
    const groupId: any = [];
    if (formValue && formValue.length > 0) {
      formValue.forEach((item: any) => {
        if (item.type === 1) {
          userList.push(item);
          userId.push(item.record_id);
        } else {
          groupList.push(item);
          groupId.push(item.record_id);
        }
      });
      setTableData(formValue);
      setSelectedRowKeys(userId);
      setSelectedRows(userList);
      setCheckedKeys(groupId);
      setCheckedRow(groupList);
    }
  }, [formValue]);

  // const onOrgSelect = (selectedKeys: React.Key[], info: any) => {};

  const onCheckChange = (keys: any[], info: any) => {
    // const { checkedNodes } = info;
    console.log('info=========', info);
    setCheckedKeys(keys);
    setCheckedRow(info);
  };

  const onHnadleCancel = () => {
    setOpen(false);
    setSelectedRowKeys([]);
    setSelectedRows([]);
    setCheckedKeys([]);
    setCheckedRow([]);
  };

  const onHandleOk = () => {
    const list: any[] = [];
    // 用户
    (selectedRows || []).forEach((item) => {
      list.push({
        record_id: item.id,
        name: item.user_name,
        type: 1,
      });
    });
    // 用户组
    (checkedRow || []).forEach((item) => {
      list.push({
        record_id: item.id,
        name: item.name,
        type: 2,
      });
    });
    setTableData(list);
    onBindUserChange(list);
    onHnadleCancel();
  };

  const onUserTableSelect = (keys: any[], row: any[]) => {
    console.log('selectedRowKeys changed: ', keys);
    console.log('selectedRowKeys rows: ', row);
    setSelectedRowKeys(keys as any);
    setSelectedRows(row);
  };

  const onSelectChange = (keys: any[]) => {
    console.log('selectedRowKeys changed: ', keys);
    setBindTableKeys(keys as any);
  };

  const handleDelete = (record?: any) => {
    console.log('record=====handleDelete', record);
    if (record) {
      // 单个删除
      const { record_id } = record || {};
      const newData = tableData.filter((item) => item.record_id !== record_id);
      setTableData(newData);
    } else {
      // 批量删除
      const newData = tableData.filter(
        (item) => !bindTableKeys.includes(item.record_id),
      );
      setTableData(newData);
      setSelectedRowKeys([]);
      setSelectedRows([]);
    }
  };

  const getColumns = (): ColumnsType<any> => {
    const columns: ColumnsType<any> = [
      {
        title: '序号',
        dataIndex: 'order',
        key: 'order',
        width: 80,
        render: (_, record, index) => <span>{index + 1}</span>,
      },
      {
        title: '名称',
        dataIndex: 'name',
        key: 'name',
      },
      {
        title: '类型',
        dataIndex: 'type',
        key: 'type',
        render: (text) => (
          <span>{text == 1 ? '用户' : text == 2 ? '用户组' : ''}</span>
        ),
      },
      {
        title: '操作',
        key: 'action',
        render: (_, record) => (
          <Button type="link" onClick={() => handleDelete(record)}>
            删除
          </Button>
        ),
      },
    ];
    return columns;
  };

  const accessPopover = (
    <div style={{ width: '600px' }}>
      <Alert
        message="可切换选择多个不同类型进行绑定"
        type="info"
        showIcon
        closeIcon
      />
      <Tabs>
        <Tabs.TabPane tab="分组" key="1">
          <CustomTree
            checkable={true}
            multiple={true}
            checkStrictly={true}
            treeData={orgTreeData}
            titleField="name"
            keyField="id"
            childrenField="children"
            defaultExpandAll
            onCheck={onCheckChange}
            checkedKeys={checkedKeys}
            icon={<TeamOutlined style={{ fontSize: '15px' }} />}
          />
        </Tabs.TabPane>
        <Tabs.TabPane tab="用户" key="2">
          <SelectConponents
            treeData={orgTreeData}
            onUserTableSelect={onUserTableSelect}
            selectedRowKeys={selectedRowKeys}
          />
        </Tabs.TabPane>
      </Tabs>
      <div
        style={{
          borderTop: '1px solid #e8e8e8',
          marginTop: '10px',
          paddingTop: '10px',
          display: 'flex',
          justifyContent: 'center',
        }}
      >
        <Button
          onClick={onHandleOk}
          style={{ marginRight: '30px' }}
          type={'primary'}
        >
          确定
        </Button>
        <Button onClick={onHnadleCancel}>取消</Button>
      </div>
    </div>
  );

  return (
    <>
      <Space style={{ marginBottom: '10px' }}>
        <Popover
          content={accessPopover}
          title=""
          trigger="click"
          open={open}
          // onOpenChange={setOpen}
          placement={placement}
        >
          <div>
            <Button
              onClick={() => {
                setOpen(true);
              }}
              style={{ marginRight: '15px' }}
            >
              添加
            </Button>
            <Popconfirm
              title=""
              description="删除操作不可逆，请确认是否删除?"
              onConfirm={() => handleDelete()}
              disabled={bindTableKeys.length === 0}
              okText="删除"
              cancelText="取消"
            >
              <Button disabled={bindTableKeys.length === 0}>删除</Button>
            </Popconfirm>
          </div>
        </Popover>
      </Space>
      <CustomTable
        dataSource={tableData}
        onDelete={handleDelete}
        scrollY={400}
        rowKey="record_id"
        pagination={false}
        columns={getColumns()}
        rowSelection={{
          bindTableKeys,
          onChange: onSelectChange,
        }}
      />
    </>
  );
};

export default SelectedTable;
