/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2024-04-09 18:07:35
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-09-04 16:57:33
 * @FilePath: /KC-MiddlePlatform/src/pages/platform/components/usersEditer/index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import React, { useEffect, useState } from 'react';
import { Input, Transfer } from 'antd';
import type { EditUsersDataType } from '@/service/user';
import type { TransferDirection } from 'antd/es/transfer';

export interface UserEditerType {
  value?: React.Key[];  // 修复类型声明
  onChange?: (selectedRowKeys: React.Key[]) => void;  // 修复类型声明
  noAction?: boolean;
  total?: EditUsersDataType[];  // 修复类型声明
}

const UserEditer: React.FC<UserEditerType> = ({ value = [], onChange, noAction = false, total = [] }) => {
  const [selectedKeys, setSelectedKeys] = useState<React.Key[]>(value);  // 初始状态为 value
  const [keyword, setKeyword] = useState('');
  const [data, setData] = useState<EditUsersDataType[]>(total);  // 初始状态为 total
  const [targetKeys, setTargetKeys] = useState<React.Key[]>(value);  // 初始状态为 value

  const onSelectHandle = (record: EditUsersDataType, selected: boolean) => {
    if (selected) {
      setSelectedKeys([...selectedKeys, record.id]);
    } else {
      setSelectedKeys(selectedKeys.filter((t) => t !== record.id));
    }
  };

  const onChangeHandle = (selectedRowKeys: React.Key[]) => {
    setSelectedKeys(selectedRowKeys);
    if (onChange) onChange(selectedRowKeys);
  };

  const onSearchHandle = (e: React.ChangeEvent<HTMLInputElement>) => {
    setKeyword(e.target.value);
  };

  const filterOption = (inputValue: string, option: EditUsersDataType) => option.name && option.name.indexOf(inputValue) > -1;

  const handleChange = (newTargetKeys: string[]) => {
    setTargetKeys(newTargetKeys);
    if (onChange) onChange(newTargetKeys);
  };

  const handleSearch = (dir: TransferDirection, value: string) => {
    
  };

  // 同步外部 value 到组件内部状态
  useEffect(() => {
    setTargetKeys(value);
    setSelectedKeys(value);
    setData(total);  // 这里是关键，确保数据也同步
  }, [value, total]);  // 依赖于 value 和 total 的变化

  return (
    <div className="UserEditer">
      <Transfer
        dataSource={data}
        showSearch
        pagination={{ pageSize: 20 }}
        rowKey={(record) => `${record.id}`}
        showSelectAll={true}
        // filterOption={filterOption}
        targetKeys={targetKeys as string[]}
        onChange={handleChange}
        onSearch={handleSearch}
        render={(item) => (item.name ? `${item.name}(${item.account})` : '')}
      />
    </div>
  );
};

export default UserEditer;
