/*
 * @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 { git_url, git_branch, code_repo_name } = res;
          const jsonObj = {
            code_path: git_url,
            branch: git_branch,
          };
          const jsonObjStr = JSON.stringify(jsonObj);
          const showValue = code_repo_name;
          onChange?.({
            value: jsonObjStr,
            showValue,
            fromSelect: true,
            ...jsonObj,
          });
        } else {
          onChange?.({
            value: undefined,
            showValue: undefined,
            fromSelect: false,
          });
        }
        close();
      },
    });
  };

  return (
    <div className={classNames('kf-code-select', className)} style={style}>
      <ParameterInput
        {...rest}
        size={size}
        disabled={disabled}
        value={value}
        onChange={onChange}
        onClick={selectResource}
      ></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;
