import React, {forwardRef, useImperativeHandle, useRef, useState} from 'react';
import {message, Transfer} from "antd";
import {TableRowSelection} from "antd/es/table/interface";
import {difference} from 'lodash';
import {ProTable} from '@ant-design/pro-components';
import {institutionUserList} from "@/services/user";
import {ActionType, ProColumns} from "@ant-design/pro-table";
import {batchAddTagUser, batchRemoveTagUser, listUser} from "@/services/tag";

export type TagUserProp = {
  tag?: API.Tag;
}

const UserTagTransfer: React.FC<TagUserProp> = forwardRef((props, ref) => {
  const {tag} = props;
  const [dataSource, setDataSource] = useState([]);
  const [targetKeys, setTargetKeys] = useState<number[]>();
  const [hasTagUserIds, setHasTagUserIds] = useState<number[]>();
  const leftRef = useRef<ActionType>();
  const rightRef = useRef<ActionType>();

  const onChange = (nextTargetKeys: number[]) => {
    setTargetKeys(nextTargetKeys);
    let add: number[] = []
    let remove: number[] = []
    nextTargetKeys.forEach(item => {
      if (!hasTagUserIds?.includes(item)) {
        add.push(item)
      }
    })

    hasTagUserIds?.forEach(item => {
      if (!nextTargetKeys.includes(item)) {
        remove.push(item)
      }
    })

    if (add.length > 0) {
      batchAddTagUser({
        tagId: tag?.id,
        userIds: add
      }).then(response => {
        if (response.code === 200) {
          rightRef.current?.reload();
        } else {
          message.error(response.message)
        }
      })
    }

    if (remove.length > 0) {
      batchRemoveTagUser({
        tagId: tag?.id,
        userIds: remove
      }).then(response => {
        if (response.code === 200) {
          rightRef.current?.reload();
        } else {
          message.error(response.message)
        }
      })
    }
  };

  useImperativeHandle(ref, () => ({
    reload,
  }));

  const reload = () => {
    leftRef.current?.reload();
    rightRef.current?.reload();
  }

  return <div><Transfer showSelectAll={false} dataSource={dataSource} onChange={onChange} targetKeys={targetKeys}
                        rowKey={(record) => record.id}
  >
    {({
        direction,
        filteredItems,
        onItemSelectAll,
        onItemSelect,
        selectedKeys: listSelectedKeys,
        disabled: listDisabled,
      }) => {
      const rowSelection: TableRowSelection<API.UserList> = {
        getCheckboxProps: item => ({disabled: listDisabled || (direction === 'left' && targetKeys?.includes(item.id))}),
        onSelectAll(selected, selectedRows) {
          const treeSelectedKeys = selectedRows
            .map(({id}) => id);
          const diffKeys = selected
            ? difference(treeSelectedKeys, listSelectedKeys)
            : difference(listSelectedKeys, treeSelectedKeys);
          onItemSelectAll(diffKeys as string[], selected);
        },
        onSelect(item, selected) {
          onItemSelect(item.id, selected);
        },
        selectedRowKeys: listSelectedKeys,
      };

      const dataColumns: ProColumns<API.UserList>[] = [
        {
          dataIndex: 'id',
          title: '序列号',
          hideInSearch: true
        },
        {
          dataIndex: 'phone',
          title: '手机号',
          hideInSearch: true
        },
        {
          dataIndex: 'name',
          title: '姓名',
          hideInSearch: true
        },
      ];

      return (
        <ProTable<API.UserList>
          actionRef={direction === 'left' ? leftRef : rightRef}
          rowSelection={rowSelection}
          columns={dataColumns}
          size="small"
          search={false}
          pagination={{pageSize: 10}}
          tableAlertRender={false}
          tableAlertOptionRender={false}
          rowKey={record => record.id!}
          request={async (params = {}, sort, filter) => {
            if (direction == 'left') {
              const response = await institutionUserList({
                institutionId: tag.institutionId,
                name: params.name,
                phone: params.phone,
                page: params.current,
                size: params.pageSize,
                includeSelf: true,
              });
              if (response.code === 200) {
                setDataSource(response.data!.records!)
                return {
                  data: response.data!.records,
                  success: true,
                  total: response.data!.total,
                };
              } else {
                message.error(response.message)
                return {}
              }
            } else {
              const response = await listUser({
                tagId: tag.id,
                page: params.current,
                size: params.pageSize,
              });
              if (response.code === 200) {
                // setDataSource(response.data!.records!)
                let targetKey: number[] = [];
                response.data!.records!.forEach(item => {
                  targetKey.push(item.id)
                })
                setTargetKeys(targetKey);
                setHasTagUserIds(targetKey);
                return {
                  data: response.data!.records,
                  success: true,
                  total: response.data!.total,
                };
              } else {
                message.error(response.message)
                return {}
              }
            }
          }}
          options={false}
          style={{pointerEvents: listDisabled ? 'none' : undefined}}
        />
      );
    }}
  </Transfer></div>

})

export default UserTagTransfer;
