import KFIcon from '@/components/KFIcon';
import KFModal from '@/components/KFModal';
import {
  addWorkflow,
  cloneWorkflow,
  editWorkflow,
  getWorkflow,
  getWorkflowById,
  removeWorkflow,
} from '@/services/pipeline/index.js';
import themes from '@/styles/theme.less';
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 { useEffect, useRef, 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 { message } = App.useApp();
  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 routeToEdit = (record) => {
    navigate({ pathname: `/pipeline/template/info/${record.id}` });
  };
  const showModal = () => {
    form.resetFields();
    setFormId(null);
    setDialogTitle('新建流水线');
    setIsModalOpen(true);
  };
  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) {
          navigate({ pathname: `/pipeline/template/info/${ret.data.id}` });
        }
      });
    }
  };
  const pageOption = useRef({ page: 1, size: 10 });
  const paginationProps = {
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: () => `共${total}条`,
    total: total,
    page: pageOption.current.page,
    size: pageOption.current.size,
    onChange: (current, size) => paginationChange(current, size),
  };
  // 当前页面切换
  const paginationChange = async (current, size) => {
    // console.log('page', current, size);
    pageOption.current = {
      page: current,
      size: size,
    };
    getList();
  };
  const getList = () => {
    let params = {
      offset: 1,
      page: pageOption.current.page - 1,
      size: pageOption.current.size,
    };
    getWorkflow(params).then((ret) => {
      if (ret.code === 200) {
        setPipeList(ret.data.content);

        setTotal(ret.data.totalElements);
      }
    });
  };
  useEffect(() => {
    getList();
  }, []);
  const columns = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      width: 120,
      align: 'center',
      render: tableCellRender(false, TableCellValueType.Index, {
        page: pageOption.current.page - 1,
        pageSize: pageOption.current.size,
      }),
    },
    {
      title: '流水线名称',
      dataIndex: 'name',
      key: 'name',
      render: tableCellRender(false, TableCellValueType.Link, {
        onClick: routeToEdit,
      }),
    },
    {
      title: '流水线描述',
      dataIndex: 'description',
      key: 'description',
      render: tableCellRender(true),
      ellipsis: { showTitle: false },
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      key: 'create_time',
      render: tableCellRender(false, TableCellValueType.Date),
    },
    {
      title: '修改时间',
      dataIndex: 'update_time',
      key: 'update_time',
      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={async () => {
              modalConfirm({
                title: '复制',
                content: '确定复制该条流水线吗？',
                okText: '确认',
                cancelText: '取消',
                onOk: () => {
                  cloneWorkflow(record.id).then((ret) => {
                    if (ret.code === 200) {
                      message.success('复制成功');
                      getList();
                    } else {
                      message.error('复制失败');
                    }
                  });

                  // if (success) {
                  //   if (actionRef.current) {
                  //     actionRef.current.reload();
                  //   }
                  // }
                },
              });
            }}
          >
            复制
          </Button>
          <ConfigProvider
            theme={{
              token: {
                colorLink: themes['warningColor'],
              },
            }}
          >
            <Button
              type="link"
              size="small"
              key="batchRemove"
              icon={<KFIcon type="icon-shanchu" />}
              onClick={() => {
                modalConfirm({
                  title: '删除后，该流水线将不可恢复',
                  content: '是否确认删除?',
                  onOk: () => {
                    removeWorkflow(record.id).then((ret) => {
                      if (ret.code === 200) {
                        message.success('删除成功');
                        getList();
                      } else {
                        message.error(ret.msg);
                      }
                    });

                    // if (success) {
                    //   if (actionRef.current) {
                    //     actionRef.current.reload();
                    //   }
                    // }
                  },
                });
              }}
            >
              删除
            </Button>
          </ConfigProvider>
        </Space>
      ),
    },
  ];
  return (
    <div className={Styles.PipelineBox}>
      <div className={Styles.pipelineTopBox}>
        <Button type="default" onClick={showModal} icon={<KFIcon type="icon-xinjian2" />}>
          新建流水线
        </Button>
      </div>
      <div className={classNames('vertical-scroll-table', Styles.PipelineTable)}>
        <Table
          columns={columns}
          dataSource={pipeList}
          pagination={paginationProps}
          rowKey="id"
          scroll={{ y: 'calc(100% - 55px)' }}
        />
      </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;
