/*
 * @Author: 赵伟
 * @Date: 2024-04-16 13:58:08
 * @Description: 创建镜像
 */
import { getAccessToken } from '@/access';
import KFIcon from '@/components/KFIcon';
import KFRadio, { type KFRadioItem } from '@/components/KFRadio';
import PageTitle from '@/components/PageTitle';
import SubAreaTitle from '@/components/SubAreaTitle';
import { CommonTabKeys } from '@/enums';
import { createMirrorReq } from '@/services/mirror';
import { to } from '@/utils/promise';
import SessionStorage from '@/utils/sessionStorage';
import { getFileListFromEvent, validateUploadFiles } from '@/utils/ui';
import { useNavigate } from '@umijs/max';
import { App, Button, Col, Form, Input, Row, Upload, UploadFile, type UploadProps } from 'antd';
import { omit } from 'lodash';
import { useEffect, useState } from 'react';
import styles from './index.less';

type FormData = {
  name: string;
  tag: string;
  description: string;
  path?: string;
  upload_type: string;
  fileList?: UploadFile[];
};

const mirrorRadioItems: KFRadioItem[] = [
  {
    title: '基于公网镜像',
    value: CommonTabKeys.Public,
    icon: <KFIcon type="icon-jiyugongwangjingxiang" />,
  },
  {
    title: '本地上传',
    value: CommonTabKeys.Private,
    icon: <KFIcon type="icon-bendishangchuan" />,
  },
];

function MirrorCreate() {
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const [isAddVersion, setIsAddVersion] = useState(false); // 是制作镜像还是新增镜像版本
  const { message } = App.useApp();

  const uploadProps: UploadProps = {
    action: '/api/mmp/image/upload',
    headers: {
      Authorization: getAccessToken() || '',
    },
    maxCount: 1,
    defaultFileList: [],
  };

  useEffect(() => {
    const name = SessionStorage.getItem(SessionStorage.mirrorNameKey);
    if (name) {
      form.setFieldValue('name', name);
      setIsAddVersion(true);
    }
    return () => {
      SessionStorage.removeItem(SessionStorage.mirrorNameKey);
    };
  }, [form]);

  // 创建公网、本地镜像
  const createPublicMirror = async (formData: FormData) => {
    const upload_type = formData['upload_type'];

    if (upload_type === CommonTabKeys.Public) {
      const params = {
        ...omit(formData, ['upload_type']),
        upload_type: 0,
        image_type: 0,
      };
      const [res] = await to(createMirrorReq(params));
      if (res) {
        message.success('创建成功');
        navigate(-1);
      }
    } else {
      const fileList = formData['fileList'] ?? [];
      if (validateUploadFiles(fileList)) {
        const file = fileList[0];
        const params = {
          ...omit(formData, ['fileList', 'upload_type']),
          path: file.response.data.url,
          file_size: file.response.data.fileSize,
          file_name: file.response.data.fileName,
          upload_type: 1,
          image_type: 0,
        };
        const [res] = await to(createMirrorReq(params));
        if (res) {
          message.success('创建成功');
          navigate(-1);
        }
      }
    }
  };

  // 提交
  const handleSubmit = (values: FormData) => {
    createPublicMirror(values);
  };

  // 取消
  const cancel = () => {
    navigate(-1);
  };

  // 上传前认证
  const beforeUpload: UploadProps['beforeUpload'] = () => {
    const fileList = form.getFieldValue('fileList');
    if (Array.isArray(fileList) && fileList.length >= 1) {
      message.error('只允许上传一个文件');
      return Upload.LIST_IGNORE;
    }
    return true;
  };

  return (
    <div className={styles['mirror-create']}>
      <PageTitle title={!isAddVersion ? '创建镜像' : '新增镜像版本'}></PageTitle>
      <div className={styles['mirror-create__content']}>
        <div>
          <Form
            name="mirror-create"
            labelCol={{ flex: '135px' }}
            wrapperCol={{ flex: 1 }}
            labelAlign="left"
            form={form}
            initialValues={{ upload_type: CommonTabKeys.Public }}
            onFinish={handleSubmit}
            size="large"
            autoComplete="off"
          >
            <SubAreaTitle
              title="基本信息"
              image={require('@/assets/img/mirror-basic.png')}
              style={{ marginBottom: '26px' }}
            ></SubAreaTitle>
            <Row gutter={10}>
              <Col span={10}>
                <Form.Item
                  label="镜像名称和版本"
                  name="name"
                  rules={[
                    {
                      required: true,
                      message: '请输入镜像名称',
                    },
                    {
                      pattern: /^[a-z0-9/._-]*$/,
                      message: '只支持小写字母、数字、点(.)、下划线(_)、中横线(-)、斜杠(/)',
                    },
                  ]}
                  className={styles['mirror-create__content__name-row']}
                >
                  <Input
                    placeholder="请输入镜像名称"
                    maxLength={64}
                    disabled={isAddVersion}
                    showCount
                    allowClear
                  />
                </Form.Item>
              </Col>
              <Col span={10}>
                <Form.Item
                  label=" "
                  name="tag_name"
                  labelCol={{ flex: '20px' }}
                  wrapperCol={{ flex: 1 }}
                  required={false}
                  rules={[
                    {
                      required: true,
                      message: '请输入镜像版本',
                    },
                    {
                      pattern: /^[a-zA-Z0-9._-]+$/,
                      message: '镜像版本只支持字母、数字、点(.)、下划线(_)、中横线(-)',
                    },
                  ]}
                >
                  <Input placeholder="请输入镜像版本" maxLength={64} showCount allowClear />
                </Form.Item>
              </Col>
            </Row>
            {!isAddVersion && (
              <Row gutter={10}>
                <Col span={20}>
                  <Form.Item
                    label="镜像描述"
                    name="description"
                    rules={[
                      {
                        required: true,
                        message: '请输入镜像描述',
                      },
                    ]}
                  >
                    <Input.TextArea
                      autoSize={{ minRows: 2, maxRows: 6 }}
                      placeholder="请输入镜像描述"
                      maxLength={128}
                      showCount
                      allowClear
                    />
                  </Form.Item>
                </Col>
              </Row>
            )}
            <Row gutter={10}>
              <Col span={20}>
                <Form.Item
                  label="版本描述"
                  name="version_description"
                  rules={[
                    {
                      required: true,
                      message: '请输入版本描述',
                    },
                  ]}
                >
                  <Input.TextArea
                    autoSize={{ minRows: 2, maxRows: 6 }}
                    placeholder="请输入版本描述"
                    maxLength={128}
                    showCount
                    allowClear
                  />
                </Form.Item>
              </Col>
            </Row>
            <SubAreaTitle
              title="镜像构建"
              image={require('@/assets/img/mirror-version.png')}
              style={{ marginTop: '20px', marginBottom: '24px' }}
            ></SubAreaTitle>
            <Row gutter={10}>
              <Col span={10}>
                <Form.Item
                  label="构建方式"
                  name="upload_type"
                  rules={[
                    {
                      required: true,
                      message: '请选择构建方式',
                    },
                  ]}
                >
                  <KFRadio items={mirrorRadioItems}></KFRadio>
                </Form.Item>
              </Col>
            </Row>
            <Form.Item
              noStyle
              shouldUpdate={(prevValues, curValues) =>
                prevValues.upload_type !== curValues.upload_type
              }
            >
              {({ getFieldValue }) => {
                const type = getFieldValue('upload_type');
                if (type === CommonTabKeys.Public) {
                  return (
                    <>
                      <Row gutter={10}>
                        <Col span={10}>
                          <Form.Item label="仓库类型" required>
                            <span className={styles['mirror-create__content__type']}>公网</span>
                          </Form.Item>
                        </Col>
                      </Row>
                      <Row gutter={10}>
                        <Col span={10}>
                          <Form.Item
                            label="镜像地址"
                            name="path"
                            rules={[
                              {
                                required: true,
                                message: '请输入镜像地址',
                              },
                            ]}
                          >
                            <Input
                              placeholder="请输入镜像地址"
                              maxLength={128}
                              showCount
                              allowClear
                            />
                          </Form.Item>
                        </Col>
                      </Row>
                    </>
                  );
                } else {
                  return (
                    <>
                      <Row gutter={10}>
                        <Col span={10}>
                          <Form.Item
                            label="镜像文件"
                            name="fileList"
                            valuePropName="fileList"
                            getValueFromEvent={getFileListFromEvent}
                            rules={[
                              {
                                required: true,
                                message: '请上传镜像文件',
                              },
                            ]}
                          >
                            <Upload {...uploadProps} beforeUpload={beforeUpload}>
                              <Button type="link" style={{ paddingLeft: 0, paddingRight: 0 }}>
                                选择镜像文件
                              </Button>
                            </Upload>
                          </Form.Item>
                        </Col>
                      </Row>
                    </>
                  );
                }
              }}
            </Form.Item>

            <Form.Item wrapperCol={{ offset: 0, span: 16 }}>
              <Button type="primary" htmlType="submit">
                确定
              </Button>
              <Button
                type="default"
                htmlType="button"
                onClick={cancel}
                style={{ marginLeft: '20px' }}
              >
                取消
              </Button>
            </Form.Item>
          </Form>
        </div>
      </div>
    </div>
  );
}

export default MirrorCreate;
