/*
 * @Author: 赵伟
 * @Date: 2024-10-08 15:36:08
 * @Description: 流水线选择代码配置表单
 */

import CodeSelectorModal from '@/components/CodeSelectorModal';
import KFIcon from '@/components/KFIcon';
import { openAntdModal } from '@/utils/modal';
import { Button } from 'antd';
import classNames from 'classnames';
import ParameterInput, { type ParameterInputProps } from '../ParameterInput';
import './index.less';

export {
  requiredValidator,
  type ParameterInputObject,
  type ParameterInputValue,
} from '../ParameterInput';

type CodeSelectProps = ParameterInputProps;

/** 代码配置选择表单组件 */
function CodeSelect({
  value,
  size,
  disabled,
  className,
  style,
  onChange,
  ...rest
}: CodeSelectProps) {
  // 选择代码配置
  const selectResource = () => {
    const { close } = openAntdModal(CodeSelectorModal, {
      onOk: (res) => {
        if (res) {
          const { id, code_repo_name, git_url, git_branch, git_user_name, git_password, ssh_key } =
            res;
          const jsonObj = {
            id,
            name: code_repo_name,
            code_path: git_url,
            branch: git_branch,
            username: git_user_name,
            password: git_password,
            ssh_private_key: ssh_key,
          };
          const jsonObjStr = JSON.stringify(jsonObj);
          onChange?.({
            value: jsonObjStr,
            showValue: code_repo_name,
            fromSelect: true,
            ...jsonObj,
          });
        } else {
          onChange?.(undefined);
        }
        close();
      },
    });
  };

  // 删除
  const handleRemove = () => {
    onChange?.(undefined);
  };

  return (
    <div className={classNames('kf-code-select', className)} style={style}>
      <ParameterInput
        {...rest}
        size={size}
        disabled={disabled}
        value={value}
        onChange={onChange}
        onClick={selectResource}
        onRemove={handleRemove}
      ></ParameterInput>
      <Button
        className="kf-code-select__button"
        size={size}
        type="link"
        icon={<KFIcon type="icon-xuanzedaimapeizhi" font={16} />}
        disabled={disabled}
        onClick={selectResource}
      >
        选择代码配置
      </Button>
    </div>
  );
}

export default CodeSelect;
