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

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

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

type CodeSelectProps = ParameterInputProps;

function CodeSelect({ value, onChange, disabled, ...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="kf-code-select">
      <ParameterInput
        {...rest}
        disabled={disabled}
        value={value}
        onChange={onChange}
        onClick={selectResource}
      ></ParameterInput>
      <Button
        className="kf-code-select__button"
        size="large"
        type="link"
        icon={<KFIcon type="icon-xuanzedaimapeizhi" font={16} />}
        disabled={disabled}
        onClick={selectResource}
      >
        选择代码配置
      </Button>
    </div>
  );
}

export default CodeSelect;
