import createExperimentIcon from '@/assets/img/create-experiment.png';
import editExperimentIcon from '@/assets/img/edit-experiment.png';
import KFModal from '@/components/KFModal';
import { type PipelineGlobalParam } from '@/types';
import { Form, Input, Radio, Select, type FormRule } from 'antd';
import { useState } from 'react';
import styles from './index.less';

type FormData = {
  name?: string;
  description?: string;
  workflow_id?: string | number;
  global_param?: PipelineGlobalParam[];
};

type AddExperimentModalProps = {
  isAdd: boolean;
  open: boolean;
  onCancel: () => void;
  onFinish: () => void;
  workflowList: Workflow[];
  initialValues: FormData;
};

interface Workflow {
  id: string | number;
  name: string;
  global_param?: PipelineGlobalParam[] | null;
}

// 根据参数设置输入组件
export const getParamComponent = (paramType: number, isSensitive?: number): JSX.Element => {
  // 防止后台返回不是 number 类型
  if (Number(paramType) === 3) {
    return (
      <Radio.Group>
        <Radio value={1}>是</Radio>
        <Radio value={0}>否</Radio>
      </Radio.Group>
    );
  }
  if (isSensitive && Number(isSensitive) === 1) {
    return <Input.Password visibilityToggle={false} allowClear />;
  }
  return <Input placeholder="请输入值" allowClear />;
};

// 根据参数设置校验规则
export const getParamRules = (paramType: number, required: boolean = false): FormRule[] => {
  const rules = [];
  // 防止后台返回不是 number 类型
  if (Number(paramType) === 2) {
    rules.push({
      pattern: /^-?((0(\.0*[1-9]\d*)?)|([1-9]\d*(\.\d+)?))$/,
      message: '整型必须是数字',
    });
  }
  if (required) {
    rules.push({ required: true, message: '请输入值' });
  }
  return rules;
};

// 根据参数设置 label
export const getParamType = (param: PipelineGlobalParam): string => {
  const paramTypes: Readonly<Record<number, string>> = {
    1: '字符串',
    2: '整型',
    3: '布尔类型',
  };
  return param.param_name + `（${paramTypes[param.param_type]}）`;
};

function AddExperimentModal({
  isAdd,
  open,
  onCancel,
  onFinish,
  workflowList = [],
  initialValues = {},
}: AddExperimentModalProps) {
  const modalTitle = isAdd ? '新建实验' : '配置实验';
  const modalIcon = isAdd ? createExperimentIcon : editExperimentIcon;
  const workflowDisabled = isAdd ? false : true;
  const [globalParam, setGlobalParam] = useState<PipelineGlobalParam[]>(
    initialValues.global_param || [],
  );
  const [form] = Form.useForm();

  const tailLayout = {
    labelCol: { span: 24 },
    wrapperCol: { span: 24 },
  };

  const layout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 20 },
  };

  const paramLayout = {
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
  };

  // 除了流水线选择发生变化
  const handleWorkflowChange = (id: string | number) => {
    const pipeline: Workflow | undefined = workflowList.find((v) => v.id === id);
    if (pipeline && pipeline.global_param) {
      setGlobalParam(pipeline.global_param);
      form.setFieldValue('global_param', pipeline.global_param);
    } else {
      setGlobalParam([]);
      form.setFieldValue('global_param', []);
    }
  };
  return (
    <KFModal
      className={styles['add-experiment-modal']}
      title={modalTitle}
      image={modalIcon}
      open={open}
      okButtonProps={{
        htmlType: 'submit',
        form: 'form',
      }}
      onCancel={onCancel}
      destroyOnClose={true}
      width={825}
    >
      <Form
        name="form"
        layout="horizontal"
        initialValues={initialValues}
        onFinish={onFinish}
        autoComplete="off"
        form={form}
        {...layout}
        labelAlign="left"
        labelWrap
      >
        <Form.Item
          label="实验名称"
          name="name"
          rules={[{ required: true, message: '请输入实验名称' }]}
        >
          <Input placeholder="请输入实验名称" maxLength={64} showCount allowClear />
        </Form.Item>
        <Form.Item
          label="实验描述"
          name="description"
          rules={[{ required: true, message: '请输入实验描述' }]}
          style={{ marginBottom: '48px' }}
        >
          <Input.TextArea
            placeholder="请输入实验描述"
            maxLength={128}
            autoSize={{ minRows: 2, maxRows: 5 }}
            showCount
            allowClear
          />
        </Form.Item>
        <Form.Item
          label="选择流水线"
          name="workflow_id"
          rules={[{ required: true, message: '请选择流水线' }]}
        >
          <Select
            disabled={workflowDisabled}
            placeholder="请选择流水线"
            onChange={handleWorkflowChange}
          >
            {Array.isArray(workflowList)
              ? workflowList.map((item) => {
                  return (
                    <Select.Option key={item.id} value={item.id}>
                      {item.name}
                    </Select.Option>
                  );
                })
              : null}
          </Select>
        </Form.Item>
        {globalParam.length > 0 && (
          <Form.Item
            label="运行参数"
            tooltip="展示关联的流水线的参数，脱敏的参数以xxxx展示"
            {...tailLayout}
          >
            <div className={styles.global_param_item}>
              <Form.List name="global_param">
                {(fields) =>
                  fields.map(({ key, name, ...restField }) => (
                    <Form.Item
                      {...restField}
                      {...paramLayout}
                      key={key}
                      label={getParamType(globalParam[name])}
                      name={[name, 'param_value']}
                      rules={getParamRules(globalParam[name]['param_type'])}
                    >
                      {getParamComponent(
                        globalParam[name]['param_type'],
                        globalParam[name]['is_sensitive'],
                      )}
                    </Form.Item>
                  ))
                }
              </Form.List>
            </div>
          </Form.Item>
        )}
      </Form>
    </KFModal>
  );
}

export default AddExperimentModal;
