import KFIcon from '@/components/KFIcon';
import KFModal from '@/components/KFModal';
import PageTitle from '@/components/PageTitle';
import { useCacheState } from '@/hooks/useCacheState';
import {
  addWorkflow,
  cloneWorkflow,
  editWorkflow,
  getWorkflow,
  getWorkflowById,
  removeWorkflow,
} from '@/services/pipeline/index.js';
import themes from '@/styles/theme.less';
import { to } from '@/utils/promise';
import tableCellRender, { TableCellValueType } from '@/utils/table';
import { modalConfirm } from '@/utils/ui';
import { App, Button, ConfigProvider, Form, Input, Space, Table } from 'antd';
import classNames from 'classnames';
import { useCallback, useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import styles from './index.less';

const { TextArea } = Input;
const Pipeline = () => {
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const [formId, setFormId] = useState(null);
  const [dialogTitle, setDialogTitle] = useState('新建流水线');
  const [pipeList, setPipeList] = useState([]);
  const [total, setTotal] = useState(0);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [cacheState, setCacheState] = useCacheState();
  const [searchText, setSearchText] = useState(cacheState?.searchText);
  const [inputText, setInputText] = useState(cacheState?.searchText);
  const [pagination, setPagination] = useState(
    cacheState?.pagination ?? {
      current: 1,
      pageSize: 10,
    },
  );
  const { message } = App.useApp();

  // 获取流水线模板列表
  const getList = useCallback(() => {
    const params = {
      page: pagination.current - 1,
      size: pagination.pageSize,
      name: searchText || undefined,
    };
    getWorkflow(params).then((res) => {
      if (res && res.data && Array.isArray(res.data.content)) {
        setPipeList(res.data.content);
        setTotal(res.data.totalElements);
      }
    });
  }, [pagination, searchText]);

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

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

  // 编辑
  const editTable = (e, record) => {
    e.stopPropagation();
    getWorkflowById(record.id).then((ret) => {
      if (ret.code === 200) {
        form.resetFields();
        form.setFieldsValue({ ...ret.data });
        setFormId(ret.data.id);
        setDialogTitle('编辑流水线');
        setIsModalOpen(true);
      }
    });
  };

  // 跳转, 缓存当前状态
  const navigateToUrl = (url) => {
    setCacheState({
      pagination,
      searchText,
    });
    navigate(url);
  };

  // 查看详情
  const gotoDetail = (record) => {
    navigateToUrl(`/pipeline/template/info/${record.id}`);
  };

  // 显示 modal
  const showModal = () => {
    form.resetFields();
    setFormId(null);
    setDialogTitle('新建流水线');
    setIsModalOpen(true);
  };

  // modal 取消
  const handleCancel = () => {
    setIsModalOpen(false);
  };

  // 表单提交
  const onFinish = (values) => {
    if (formId) {
      editWorkflow({ ...values, id: formId }).then((ret) => {
        setIsModalOpen(false);
        message.success('编辑成功');
        getList();
      });
    } else {
      addWorkflow(values).then((ret) => {
        setIsModalOpen(false);
        message.success('新建成功');
        if (ret.code === 200) {
          navigateToUrl(`/pipeline/template/info/${ret.data.id}`);
        }
      });
    }
  };

  // 处理删除
  const handlePipelineDelete = (record) => {
    modalConfirm({
      title: '删除后，该流水线将不可恢复',
      content: '是否确认删除?',
      onOk: async () => {
        const { id } = record;
        const [res] = await to(removeWorkflow(id));
        if (res) {
          message.success('删除成功');
          // 如果是一页的唯一数据，删除后，请求第一页的数据
          // 否则直接刷新这一页的数据
          setPagination((prev) => {
            return {
              ...prev,
              current: pipeList.length === 1 ? Math.max(1, prev.current - 1) : prev.current,
            };
          });
        }
      },
    });
  };

  // 处理复制
  const handlePipelineCopy = (record) => {
    modalConfirm({
      title: '确定复制该条流水线吗？',
      okText: '确认',
      cancelText: '取消',
      isDelete: false,
      onOk: async () => {
        const { id } = record;
        const [res] = await to(cloneWorkflow(id));
        if (res) {
          message.success('复制成功');
          getList();
        }
      },
    });
  };

  // 当前页面切换
  const paginationChange = async (current, pageSize) => {
    setPagination({
      current,
      pageSize,
    });
  };

  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      width: 120,
      align: 'center',
      render: tableCellRender(false, TableCellValueType.Index, {
        page: pagination.current - 1,
        pageSize: pagination.pageSize,
      }),
    },
    {
      title: '流水线模板名称',
      dataIndex: 'name',
      key: 'name',
      width: '50%',
      render: tableCellRender(false, TableCellValueType.Link, {
        onClick: gotoDetail,
      }),
    },
    {
      title: '流水线模板描述',
      dataIndex: 'description',
      key: 'description',
      width: '50%',
      render: tableCellRender(true),
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      key: 'create_time',
      width: 180,
      render: tableCellRender(false, TableCellValueType.Date),
    },
    {
      title: '修改时间',
      dataIndex: 'update_time',
      key: 'update_time',
      width: 180,
      render: tableCellRender(false, TableCellValueType.Date),
    },
    {
      title: '操作',
      key: 'action',
      width: 320,
      render: (_, record) => (
        <Space size="small">
          <Button
            type="link"
            size="small"
            key="edit"
            icon={<KFIcon type="icon-bianji" />}
            onClick={(e) => {
              editTable(e, record);
            }}
          >
            编辑
          </Button>
          <Button
            type="link"
            size="small"
            key="clone"
            icon={<KFIcon type="icon-fuzhi" />}
            onClick={() => handlePipelineCopy(record)}
          >
            复制
          </Button>
          <ConfigProvider
            theme={{
              token: {
                colorLink: themes['warningColor'],
              },
            }}
          >
            <Button
              type="link"
              size="small"
              key="batchRemove"
              icon={<KFIcon type="icon-shanchu" />}
              onClick={() => handlePipelineDelete(record)}
            >
              删除
            </Button>
          </ConfigProvider>
        </Space>
      ),
    },
  ];
  return (
    <div className={styles['pipeline-list']}>
      <PageTitle title="流水线模板列表"></PageTitle>
      <div className={styles['pipeline-list__content']}>
        <div className={styles['pipeline-list__content__filter']}>
          <Input.Search
            placeholder="按流水线名称筛选"
            onSearch={onSearch}
            onChange={(e) => setInputText(e.target.value)}
            style={{ width: 300 }}
            value={inputText}
            allowClear
          />
          <Button type="default" onClick={showModal} icon={<KFIcon type="icon-xinjian2" />}>
            新建流水线
          </Button>
        </div>
        <div
          className={classNames('vertical-scroll-table', styles['pipeline-list__content__table'])}
        >
          <Table
            columns={columns}
            dataSource={pipeList}
            pagination={{
              ...pagination,
              total: total,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: () => `共${total}条`,
              onChange: paginationChange,
            }}
            rowKey="id"
            scroll={{ y: 'calc(100% - 55px)' }}
          />
        </div>
      </div>
      <KFModal
        title={dialogTitle}
        image={require('@/assets/img/create-experiment.png')}
        width={825}
        open={isModalOpen}
        className={styles.modal}
        okButtonProps={{
          htmlType: 'submit',
          form: 'form',
        }}
        onCancel={handleCancel}
      >
        <Form
          name="form"
          form={form}
          layout="vertical"
          initialValues={{
            remember: true,
          }}
          onFinish={onFinish}
          autoComplete="off"
        >
          <Form.Item
            label="流水线名称"
            name="name"
            rules={[
              {
                required: true,
                message: '请输入流水线名称',
              },
            ]}
          >
            <Input placeholder="请输入流水线名称" showCount maxLength={64} />
          </Form.Item>
          <Form.Item
            label="流水线描述"
            name="description"
            rules={[
              {
                required: true,
                message: '请输入流水线描述',
              },
            ]}
          >
            <TextArea
              autoSize={{ minRows: 2, maxRows: 5 }}
              placeholder="请输入流水线描述"
              showCount
              maxLength={128}
            />
          </Form.Item>
        </Form>
      </KFModal>
    </div>
  );
};
export default Pipeline;
