/*
 * @Author: 赵伟
 * @Date: 2024-04-11 16:31:18
 * @Description: 选择代码
 */

import KFIcon from '@/components/KFIcon';
import KFModal from '@/components/KFModal';
import { type CodeConfigData } from '@/pages/CodeConfig/List';
import { getCodeConfigListReq, getCodeConfigPageNumReq } from '@/services/codeConfig';
import { CustomPartial } from '@/types';
import { to } from '@/utils/promise';
import type { ModalProps, PaginationProps } from 'antd';
import { Empty, Input, Pagination } from 'antd';
import { useEffect, useState } from 'react';
import CodeConfigItem from '../CodeConfigItem';
import './index.less';

export { type CodeConfigData };

export type SelectCodeData = CustomPartial<
  CodeConfigData,
  | 'id'
  | 'code_repo_name'
  | 'git_url'
  | 'git_branch'
  | 'git_user_name'
  | 'git_password'
  | 'ssh_key'
  | 'is_public'
>;

export interface CodeSelectorModalProps extends Omit<ModalProps, 'onOk'> {
  defaultSelected?: SelectCodeData;
  onOk?: (params: SelectCodeData | undefined) => void;
}

/** 选择代码配置的弹窗，推荐使用函数的方式打开 */
function CodeSelectorModal({ defaultSelected, onOk, ...rest }: CodeSelectorModalProps) {
  const DefaultPageSize = 21;
  const [dataList, setDataList] = useState<CodeConfigData[]>([]);
  const [total, setTotal] = useState(0);
  const [searchText, setSearchText] = useState<string | undefined>(undefined);
  const [inputText, setInputText] = useState<string | undefined>(undefined);
  const [selected, setSelected] = useState(defaultSelected);
  const [isScrolled, setIsScrolled] = useState(false);
  const [pagination, setPagination] = useState<PaginationProps>({
    current: defaultSelected?.id ? 0 : 1, // 为 0 时，不请求，等待接口返回选中的代码配置在第几页
    pageSize: DefaultPageSize,
  });

  useEffect(() => {
    const getCodeConfigPageNum = async (id: number, size: number) => {
      const [res] = await to(
        getCodeConfigPageNumReq(id, {
          size,
        }),
      );
      if (res) {
        setPagination({
          current: typeof res.data === 'number' ? Math.max(0, res.data) + 1 : 1,
          pageSize: DefaultPageSize,
        });
      } else {
        setPagination({
          current: 1,
          pageSize: DefaultPageSize,
        });
      }
    };
    if (defaultSelected?.id) {
      getCodeConfigPageNum(defaultSelected?.id, DefaultPageSize);
    }
  }, [defaultSelected?.id]);

  useEffect(() => {
    // 获取数据请求
    const getDataList = async () => {
      // 为 0 时，不请求，等待接口返回选中的代码配置在第几页
      if (pagination.current === 0) {
        return;
      }
      const params = {
        page: pagination.current! - 1,
        size: pagination.pageSize,
        code_repo_name: searchText || undefined,
      };
      const [res] = await to(getCodeConfigListReq(params));
      if (res && res.data && res.data.content) {
        setDataList(res.data.content);
        setTotal(res.data.totalElements);
      }
    };

    getDataList();
  }, [pagination, searchText]);

  useEffect(() => {
    if (dataList.length > 0 && !isScrolled && defaultSelected?.id) {
      const selectedItem = document.getElementById(`code-config-item-${defaultSelected?.id}`);
      if (selectedItem) {
        selectedItem.scrollIntoView();
      }
      setIsScrolled(true);
    }
  }, [isScrolled, dataList, defaultSelected?.id]);

  // 搜索
  const handleSearch = (value: string) => {
    setSearchText(value);
    setPagination((prev) => ({
      ...prev,
      current: 1,
    }));
  };

  const handleChange = (item: CodeConfigData, checked: boolean) => {
    if (checked) {
      setSelected(item);
    } else {
      setSelected(undefined);
    }
  };

  // 分页切换
  const handlePageChange: PaginationProps['onChange'] = (page, pageSize) => {
    setPagination({
      current: page,
      pageSize: pageSize,
    });
  };

  return (
    <KFModal
      {...rest}
      title="选择代码配置"
      image={require('@/assets/img/modal-code-config.png')}
      width={920}
      onOk={() => onOk?.(selected)}
      destroyOnClose
    >
      <div className="kf-code-selector-modal">
        <Input.Search
          className="kf-code-selector-modal__search"
          placeholder="按代码仓库名称筛选"
          allowClear
          onSearch={handleSearch}
          size="large"
          onChange={(e) => setInputText(e.target.value)}
          suffix={null}
          value={inputText}
          prefix={
            <KFIcon type="icon-sousuo" color="rgba(22,100,255,0.4" style={{ marginLeft: '10px' }} />
          }
        />
        {dataList?.length !== 0 ? (
          <>
            <div className="kf-code-selector-modal__content">
              {dataList?.map((item) => (
                <CodeConfigItem
                  item={item}
                  key={item.id}
                  checked={item.id === selected?.id}
                  onChange={handleChange}
                />
              ))}
            </div>
            <Pagination
              align="end"
              total={total}
              showSizeChanger
              defaultPageSize={20}
              pageSizeOptions={[20, 40, 60, 80, 100]}
              showQuickJumper
              onChange={handlePageChange}
              {...pagination}
            />
          </>
        ) : (
          <div className="kf-code-selector-modal__empty">
            <Empty image={Empty.PRESENTED_IMAGE_SIMPLE}></Empty>
          </div>
        )}
      </div>
    </KFModal>
  );
}

export default CodeSelectorModal;
