/*
 * @Author: zhoux zhouxia@supervision.ltd
 * @Date: 2023-11-01 13:56:33
 * @LastEditors: zhoux zhouxia@supervision.ltd
 * @LastEditTime: 2023-12-05 17:13:10
 * @FilePath: \general-ai-platform-web\src\pages\Resource\ModelVersionList\components\MyCreateForm.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { postAlgorithmModelGetAlgorithmModelFkSelect } from '@/services/resource/AlgorithmModel';
import { postModelVersionCreateModelVersion } from '@/services/resource/ModelVersion';
import {
  ProForm,
  ProFormInstance,
  ProFormList,
  ProFormSelect,
  ProFormSwitch,
  ProFormText,
  ProFormUploadDragger,
  StepsForm,
} from '@ant-design/pro-components';
import { FormListActionType } from '@ant-design/pro-form/lib';
import { FormattedMessage, useIntl } from '@umijs/max';
import { Form, Modal, UploadFile, message } from 'antd';
import yaml from 'js-yaml';
import React, { useEffect, useRef, useState } from 'react';
import {
  proFormMaxItemStyleProps,
  proFormMaxModelWidth,
  proFormStepsFormProps,
} from '../../../../../config/defaultForm';

export type FormValueType = {
  target?: string;
  template?: string;
  type?: string;
  time?: string;
  frequency?: string;
} & Partial<API.ModelVersion>;

export type MyCreateFormProps = {
  createModalOpen: boolean;
  handleModal: () => void;
  values: Partial<API.ModelVersion>;
  reload: any;
  currentDefaultFieldsData?: Record<string,any>
};
const waitTime = (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};
interface ProjectConfig {
  params: Array<object>;
}
const MyCreateForm: React.FC<MyCreateFormProps> = (props) => {

  const actionFormListRef = useRef<
    FormListActionType<{
      name: string;
    }>
  >();
  const handleFileChange = ({ file }: { file: UploadFile }) => {
    let curFile: any;

    switch (file.status) {
      case 'uploading':
      case 'done':
        curFile = [file];
        break;

      case 'removed':
      default:
        curFile = [];
        break;
    }

    setFileList([...curFile]);
  };
  const intl = useIntl();
  const [isHasModelFkId, setIsHasModelFkId] = useState<boolean>(false)

  const [dataFormList, setDataFormList] = useState<any>([]);
  const dataFormListRef = useRef(dataFormList);
  const [fileList, setFileList] = useState<UploadFile<any>[]>([]);

  const [form] = Form.useForm<API.ModelVersion>();
  const [current, setCurrent] = useState(0);
  const formRef = useRef<ProFormInstance>();
  const [configData, setConfigData] = useState<ProjectConfig>({ params: [] });



  useEffect(()=>{
    if(props.currentDefaultFieldsData){
      // 如果是在模型详情新增版本，ModelFkId不可编辑
      console.log(props.values,'currentDefaultFieldsData')
      setIsHasModelFkId(true)
    } else {
      setIsHasModelFkId(false)
    }
  }, [])
  return (
    <StepsForm<{
      name: string;
    }>
      stepsProps={proFormStepsFormProps.stepsProps}
      current={current}
      onCurrentChange={setCurrent}
      formProps={{
        validateMessages: {
          required: '此项为必填项',
        },
      }}
      stepsFormRender={(dom, submitter) => {
        return (
          <Modal
            title={
              <FormattedMessage id="resource.model_version.table.list.add" defaultMessage="$$$" />
            }
            width={proFormMaxModelWidth}
            onCancel={() => {
              setCurrent(0);
              formRef.current?.resetFields();
              setFileList([]);
              props.handleModal();
            }}
            open={props.createModalOpen}
            footer={submitter}
            destroyOnClose
          >
            {dom}
          </Modal>
        );
      }}
    >
      <StepsForm.StepForm<{
        name: string;
      }>
        name="base"
        formRef={formRef}
        title="创建数据"
        stepProps={{
          description: '填入基本信息',
        }}
        onFinish={async () => {
          // setFormData(formRef.current?.getFieldsValue());
          await waitTime(500);
          return true;
        }}
      >
        <ProForm.Group>
          <ProFormSelect
            width={proFormMaxItemStyleProps.column2Width}
            name="modelFkId"
            label={
              <FormattedMessage
                id="resource.model_version.table.list.modelFkId"
                defaultMessage="$$$"
              />
            }
            placeholder={`${intl.formatMessage({
              id: 'common.please_select',
              defaultMessage: '$$$',
            })}${intl.formatMessage({
              id: 'resource.model_version.table.list.modelFkId',
              defaultMessage: '$$$',
            })}`}
            required={true}
            initialValue={props.values.modelFkId}
            showSearch
            debounceTime={1000}
            disabled={isHasModelFkId}
            request={async (keyWord) => {
              const resp = await postAlgorithmModelGetAlgorithmModelFkSelect({
                keyword: keyWord?.keyWords || '',
              });
              return resp.data.list.map((v: any) => {
                return {
                  label: v.name,
                  value: v.id,
                };
              });
            }}
          />
          <ProFormText
            width={proFormMaxItemStyleProps.column2Width}
            name="version"
            label={
              <FormattedMessage
                id="resource.model_version.table.list.version"
                defaultMessage="$$$"
              />
            }
            placeholder={`${intl.formatMessage({
              id: 'common.please_input',
              defaultMessage: '$$$',
            })}${intl.formatMessage({
              id: 'resource.model_version.table.list.version',
              defaultMessage: '$$$',
            })}`}
            required={false}
          />

          <ProFormText
            width={proFormMaxItemStyleProps.column2Width}
            name="startCode"
            label={
              <FormattedMessage
                id="resource.model_version.table.list.startCode"
                defaultMessage="$$$"
              />
            }
            placeholder={`${intl.formatMessage({
              id: 'common.please_input',
              defaultMessage: '$$$',
            })}${intl.formatMessage({
              id: 'resource.model_version.table.list.startCode',
              defaultMessage: '$$$',
            })}`}
            required={false}
          />
          <ProFormSwitch
            width={proFormMaxItemStyleProps.column2Width}
            name="isEnable"
            label={
              <FormattedMessage
                id="resource.model_version.table.list.isEnable"
                defaultMessage="$$$"
              />
            }
            initialValue={true}
          />
          <ProFormText
            width={proFormMaxItemStyleProps.column2Width}
            name="path"
            label={
              <FormattedMessage id="resource.model_version.table.list.path" defaultMessage="$$$" />
            }
            placeholder={`${intl.formatMessage({
              id: 'common.please_input',
              defaultMessage: '$$$',
            })}${intl.formatMessage({
              id: 'resource.model_version.table.list.path',
              defaultMessage: '$$$',
            })}`}
            required={true}
            rules={[
              {
                required: true,
                message: (
                  <FormattedMessage
                    id="resource.model_version.table.rule.required.path"
                    defaultMessage="path is required"
                  />
                ),
              },
            ]}
          />
          <ProFormText
            width={proFormMaxItemStyleProps.column2Width}
            name="remark"
            label={
              <FormattedMessage
                id="resource.model_version.table.list.remark"
                defaultMessage="$$$"
              />
            }
            placeholder={`${intl.formatMessage({
              id: 'common.please_input',
              defaultMessage: '$$$',
            })}${intl.formatMessage({
              id: 'resource.model_version.table.list.remark',
              defaultMessage: '$$$',
            })}`}
            required={false}
          />
        </ProForm.Group>
      </StepsForm.StepForm>
      <StepsForm.StepForm<{
        config: string;
      }>
        name="config"
        title="业务参数配置"
        stepProps={{
          description: '业务参数配置',
        }}
        onFinish={async (values: any) => {
          setFileList([]);
          let formData = formRef.current?.getFieldsValue();
          if (formData?.modelFkId) {
            await waitTime(500);
            formData.modelConfig = { params: values?.params || [] };
            postModelVersionCreateModelVersion(formData)
              .then(() => {
                message.success(
                  intl.formatMessage({ id: 'common.success', defaultMessage: '$$$' }),
                );
                props.handleModal();
                props.reload();
              })
              .catch(() => {
                message.error(intl.formatMessage({ id: 'common.failure', defaultMessage: '$$$' }));
                return false;
              });
          }
          return true;
        }}
      >
        <ProFormUploadDragger
          width={proFormMaxItemStyleProps.width}
          max={1}
          label={<span className="h3 gn">配置文件上传</span>}
          value={fileList}
          name="dragger"
          fieldProps={{
            onChange: handleFileChange,
            onRemove: () => {
              let index_ids = actionFormListRef.current?.getList()?.map((v, i) => {
                return i;
              });
              actionFormListRef.current?.remove(index_ids || []);
            },
            beforeUpload: (file, fileList) => {
              if (
                !file.name.endsWith('.yaml') &&
                !file.name.endsWith('.yml') &&
                !file.name.endsWith('.json')
              ) {
                message.error('请上传yaml或json文件').then(() => {});
                return false;
              } else {
                let parsedData = {};
                file
                  .text()
                  .then((text) => {
                    if (file.name.endsWith('.yaml') || file.name.endsWith('.yml')) {
                      parsedData = yaml.load(text) as Record<string, unknown>;
                    }
                    if (file.name.endsWith('.json')) {
                      parsedData = JSON.parse(text) as Record<string, unknown>;
                    }
                    if (Object.keys(parsedData).length > 0) {
                      dataFormListRef.current = Object.entries(parsedData).map(([key, value]) => ({
                        name: key,
                        default: value,
                      }));

                      dataFormListRef.current.forEach((v: any, i: number) => {
                        actionFormListRef.current?.add(v, i);
                      });
                    }
                    return true;
                  })
                  .catch(() => {
                    return false;
                  });
              }
            },
          }}
        />
        {/*  // TODO label字重与上面统一, 操作按钮需要与输入框对齐   */}
        <ProFormList
          name="params"
          label={<span className="h3 gn">模型参数</span>}
          actionRef={actionFormListRef}
          itemContainerRender={(doms) => {
            return <ProForm.Group>{doms}</ProForm.Group>;
          }}
          alwaysShowItemLabel
        >
          {(f, index, action) => {
            return (
              <>
                <ProFormText key="name" name="name" label="键名" />
                <ProFormText key="default" name="default" label="默认值" />
              </>
            );
          }}
        </ProFormList>
      </StepsForm.StepForm>
    </StepsForm>
    // <ModalForm<API.ModelVersion>
    //     title={intl.formatMessage({
    //         id: 'common.modal.table.create.title',
    //         defaultMessage: '$$$',
    //     })}
    //     open={props.publishModalOpen}
    //     form={form}
    //     autoFocusFirstInput
    //     modalProps={{
    //         destroyOnClose: true,
    //         onCancel: () => props.handleModal(),
    //     }}
    //     submitTimeout={2000}
    //     onFinish={async (values) => {
    //         console.log(2222, values)
    //         // postModelVersionCreateModelVersion(values).then(()=>{
    //         //     message.success(intl.formatMessage({id: 'common.success', defaultMessage: '$$$'}))
    //         //     props.reload()
    //         // }).catch(()=>{
    //         //     message.error(intl.formatMessage({id: 'common.failure', defaultMessage: '$$$'}))
    //         // })
    //         // props.handleModal();
    //         return true;
    //     }}
    // >
    //
    //
    //
    // </ModalForm>
  );
};
export default MyCreateForm;
