/*
 * @Author: 赵伟
 * @Date: 2024-10-10 09:55:12
 * @Description: 代码配置
 */

import KFEmpty, { EmptyType } from '@/components/KFEmpty';
import KFIcon from '@/components/KFIcon';
import PageTitle from '@/components/PageTitle';
import { deleteCodeConfigReq, getCodeConfigListReq } from '@/services/codeConfig';
import { getGitUrl } from '@/utils';
import { openAntdModal } from '@/utils/modal';
import { to } from '@/utils/promise';
import { modalConfirm } from '@/utils/ui';
import { App, Button, Input, Pagination, PaginationProps } from 'antd';
import { useCallback, useEffect, useState } from 'react';
import AddCodeConfigModal, { OperationType } from '../components/AddCodeConfigModal';
import CodeConfigItem from '../components/CodeConfigItem';
import styles from './index.less';

// 代码配置数据
export type CodeConfigData = {
  id: number;
  code_repo_name: string;
  is_public: boolean;
  git_url: string;
  git_branch: string;
  git_user_name: string;
  git_password: string;
  ssh_key: string;
  verify_mode: number;
  create_by: string;
  create_time: string;
  update_by: string;
  update_time: string;
};

export type ResourceListRef = {
  reset: () => void;
};

function CodeConfigList() {
  const [dataList, setDataList] = useState<CodeConfigData[] | undefined>(undefined);
  const [total, setTotal] = useState(0);
  const [pagination, setPagination] = useState<PaginationProps>({
    current: 1,
    pageSize: 20,
  });
  const [searchText, setSearchText] = useState<string | undefined>(undefined);
  const [inputText, setInputText] = useState<string | undefined>(undefined);
  const { message } = App.useApp();

  // 获取数据请求
  const getDataList = useCallback(async () => {
    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);
    } else {
      setDataList([]);
      setTotal(0);
    }
  }, [pagination, searchText]);

  useEffect(() => {
    getDataList();
  }, [getDataList]);

  // 删除请求
  const deleteRecord = async (id: number) => {
    const [res] = await to(deleteCodeConfigReq(id));
    if (res) {
      message.success('删除成功');
      // 如果是一页的唯一数据，删除后，请求第一页的数据
      // 否则直接刷新这一页的数据
      setPagination((prev) => {
        return {
          ...prev,
          current: dataList!.length === 1 ? Math.max(1, prev.current! - 1) : prev.current,
        };
      });
    }
  };

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

  // 删除
  const handleRemove = (record: CodeConfigData) => {
    modalConfirm({
      title: '确定删除这个代码配置吗？',
      onOk: () => {
        deleteRecord(record.id);
      },
    });
  };

  // 修改
  const handleEdit = (record: CodeConfigData) => {
    const { close } = openAntdModal(AddCodeConfigModal, {
      opType: OperationType.Update,
      codeConfigData: record,
      onOk: () => {
        getDataList();
        close();
      },
    });
  };

  // 查看
  const handleClick = (record: CodeConfigData) => {
    const { git_url, git_branch } = record;
    const url = getGitUrl(git_url, git_branch);
    window.open(url, '_blank');
  };

  // 新建
  const createCodeConfig = () => {
    const { close } = openAntdModal(AddCodeConfigModal, {
      opType: OperationType.Create,
      onOk: () => {
        getDataList();
        close();
      },
    });
  };

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

  return (
    <div className={styles['code-config']}>
      <PageTitle title="代码配置"></PageTitle>
      <div className={styles['code-config__list']}>
        <div className={styles['code-config__list__header']}>
          <span>数据总数：{total} 个</span>
          <Input.Search
            placeholder="按代码仓库名称筛选"
            allowClear
            onSearch={handleSearch}
            style={{
              width: 300,
              marginRight: '20px',
              marginLeft: 'auto',
            }}
            onChange={(e) => setInputText(e.target.value)}
            value={inputText}
          />
          <Button
            type="default"
            style={{ marginRight: 0 }}
            onClick={createCodeConfig}
            icon={<KFIcon type="icon-xinjian2" />}
          >
            新建代码配置
          </Button>
        </div>

        {dataList && dataList.length !== 0 && (
          <>
            <div className={styles['code-config__list__content']}>
              {dataList.map((item) => (
                <CodeConfigItem
                  item={item}
                  key={item.id}
                  onRemove={handleRemove}
                  onEdit={handleEdit}
                  onClick={handleClick}
                />
              ))}
            </div>
            <Pagination
              align="end"
              total={total}
              showSizeChanger
              defaultPageSize={20}
              pageSizeOptions={[20, 40, 60, 80, 100]}
              showQuickJumper
              onChange={handlePageChange}
              {...pagination}
            />
          </>
        )}
        {dataList && dataList.length === 0 && (
          <KFEmpty
            className={styles['code-config__list__empty']}
            type={EmptyType.NoData}
            title="暂无数据"
            content={'很抱歉，没有搜索到您想要的内容\n建议刷新试试'}
            hasFooter={true}
            onButtonClick={getDataList}
          />
        )}
      </div>
    </div>
  );
}

export default CodeConfigList;
