import KFModal from '@/components/KFModal';
import { AvailableRange } from '@/enums';
import { type CodeConfigData } from '@/pages/CodeConfig/List';
import { addCodeConfigReq, updateCodeConfigReq } from '@/services/codeConfig';
import { to } from '@/utils/promise';
import { Form, Input, Radio, message, type ModalProps } from 'antd';
import { omit } from 'lodash';

export enum VerifyMode {
  Password = 0, // 用户名密码
  SSH = 1, // SSH Key
}

export enum OperationType {
  Create = 0, // 新建
  Update = 1, // 更新
}

type FormData = Partial<CodeConfigData>;

interface AddCodeConfigModalProps extends Omit<ModalProps, 'onOk'> {
  opType: OperationType;
  codeConfigData?: CodeConfigData;
  onOk: () => void;
}

function AddCodeConfigModal({ opType, codeConfigData, onOk, ...rest }: AddCodeConfigModalProps) {
  // 上传请求
  const createCodeConfig = async (formData: FormData) => {
    const params: FormData & { id?: number } = {
      ...formData,
    };
    // 清除多余的信息
    if (formData.code_repo_vis === AvailableRange.Public) {
      omit(params, ['verify_mode', 'git_user_name', 'git_password', 'ssh_key']);
    }
    if (formData.verify_mode === VerifyMode.Password) {
      omit(params, ['ssh_key']);
    } else if (formData.verify_mode === VerifyMode.SSH) {
      omit(params, ['git_user_name', 'git_password']);
    }
    if (opType === OperationType.Update) {
      params.id = codeConfigData?.id;
    }
    const request = opType === OperationType.Create ? addCodeConfigReq : updateCodeConfigReq;
    const [res] = await to(request(params));
    if (res) {
      message.success(opType === OperationType.Create ? '创建成功' : '修改成功');
      onOk?.();
    }
  };

  // 提交
  const onFinish = (formData: FormData) => {
    createCodeConfig(formData);
  };

  // 设置初始值
  const initialValues: FormData = codeConfigData ?? {
    code_repo_vis: AvailableRange.Public,
    verify_mode: VerifyMode.Password,
  };
  if (initialValues.verify_mode === undefined || initialValues.verify_mode === null) {
    initialValues.verify_mode = VerifyMode.Password;
  }

  return (
    <KFModal
      {...rest}
      title="新建代码配置"
      image={require('@/assets/img/create-experiment.png')}
      width={825}
      okButtonProps={{
        htmlType: 'submit',
        form: 'form',
      }}
      destroyOnClose
    >
      <Form
        name="form"
        layout="vertical"
        onFinish={onFinish}
        initialValues={initialValues}
        autoComplete="off"
      >
        {/* 禁止 Chrome 自动填充 */}
        {/* <Input type="text" style={{ display: 'none' }} />
        <Input type="password" style={{ display: 'none' }} /> */}
        <Form.Item
          label="代码仓库名称"
          name="code_repo_name"
          required
          rules={[
            {
              required: true,
              message: '请输入代码仓库名称',
            },
          ]}
        >
          <Input placeholder="请输入代码仓库名称" showCount allowClear maxLength={64} />
        </Form.Item>
        <Form.Item
          label="代码仓库可见性"
          name="code_repo_vis"
          rules={[
            {
              required: true,
              message: '请选择代码仓库可见性',
            },
          ]}
        >
          <Radio.Group>
            <Radio value={AvailableRange.Public}>公开</Radio>
            <Radio value={AvailableRange.Private}>私有</Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item
          label="Git 地址"
          name="git_url"
          rules={[
            {
              required: true,
              message: '请输入 Git 地址',
            },
            {
              type: 'url',
              message: '请输入正确的 Git 地址',
            },
          ]}
        >
          <Input placeholder="请输入 Git 地址" showCount allowClear maxLength={256} />
        </Form.Item>
        <Form.Item
          label="代码分支/Tag"
          name="git_branch"
          rules={[
            {
              required: true,
              message: '请输入代码分支/Tag',
            },
          ]}
        >
          <Input placeholder="请输入代码分支/Tag" showCount allowClear maxLength={64} />
        </Form.Item>
        <Form.Item
          noStyle
          shouldUpdate={(prevValues, currentValues) =>
            prevValues?.code_repo_vis !== currentValues?.code_repo_vis
          }
        >
          {({ getFieldValue }) => {
            return getFieldValue('code_repo_vis') === AvailableRange.Private ? (
              <>
                <Form.Item
                  label="验证方式"
                  name="verify_mode"
                  rules={[
                    {
                      required: true,
                      message: '请选择验证方式',
                    },
                  ]}
                >
                  <Radio.Group>
                    <Radio value={VerifyMode.Password}>用户名/密码</Radio>
                    <Radio value={VerifyMode.SSH}>SSH Key</Radio>
                  </Radio.Group>
                </Form.Item>
                <Form.Item
                  noStyle
                  shouldUpdate={(prevValues, currentValues) =>
                    prevValues?.verify_mode !== currentValues?.verify_mode
                  }
                >
                  {({ getFieldValue }) => {
                    return getFieldValue('verify_mode') === VerifyMode.Password ? (
                      <>
                        <Form.Item
                          label="Git 用户名"
                          name="git_user_name"
                          rules={[
                            {
                              required: true,
                              message: '请输入 Git 用户名',
                            },
                          ]}
                        >
                          <Input
                            placeholder="请输入 Git 用户名"
                            autoComplete="off"
                            showCount
                            allowClear
                            maxLength={64}
                          />
                        </Form.Item>
                        <Form.Item
                          label="Git 密码"
                          name="git_password"
                          rules={[
                            {
                              required: true,
                              message: '请输入 Git 密码',
                            },
                          ]}
                        >
                          <Input.Password
                            autoComplete="new-password"
                            placeholder="请输入 Git 密码"
                            allowClear
                          />
                        </Form.Item>
                      </>
                    ) : (
                      <Form.Item
                        label="SSH Key"
                        name="ssh_key"
                        rules={[
                          {
                            required: true,
                            message: '请输入 SSH Key',
                          },
                        ]}
                      >
                        <Input.TextArea
                          placeholder="请输入 SSH Key"
                          showCount
                          maxLength={1024}
                          autoSize={{ minRows: 3, maxRows: 6 }}
                          allowClear
                        />
                      </Form.Item>
                    );
                  }}
                </Form.Item>
              </>
            ) : null;
          }}
        </Form.Item>
      </Form>
    </KFModal>
  );
}

export default AddCodeConfigModal;
