import { postModelImageCreateModelImage } from '@/services/resource/ModelImage';
import { postModelVersionGetModelVersionFkSelect } from '@/services/resource/ModelVersion';
import {
  ModalForm,
  ProForm,
  ProFormDependency,
  ProFormSelect,
  ProFormText,
} from '@ant-design/pro-components';
import { FormattedMessage, request, useIntl } from '@umijs/max';

import { Button, Form, Space, message } from 'antd';
import axios from 'axios';
import React, { useState } from 'react';
import { proFormItemStyleProps, proFormModelWidth } from '../../../../../config/defaultForm';

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

export type CreateFormProps = {
  createModalOpen: boolean;
  handleModal: () => void;
  values: Partial<API.ModelImage>;
  reload: any;
};
const CreateForm: React.FC<CreateFormProps> = (props) => {
  const intl = useIntl();
  const [form] = Form.useForm<API.ModelImage>();

  const [isFlag, setIsFlag] = useState<boolean>(false);
  // setMode2Options
  const [mode2Options, setMode2Options] = useState<any[]>([]);


  function doFindIPNext() {
    function isValidIPv4(ip: string) {
      const ipv4Regex =
        /^(25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})(\.(25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})){3}$/;
      return ipv4Regex.test(ip);
    }
    function isValidPort(port: string) {
      const portRegex = /^(?!0)([0-9]{1,5})$/; // 不包含 0 的 1 到 5 位数字
      if (portRegex.test(port)) {
        const portNumber = parseInt(port, 10);
        return portNumber > 0 && portNumber <= 65535;
      }

      return false;
    }

    if (!isValidIPv4(form.getFieldValue('IP'))) {
      message.warning('无效的服务器地址');
      return;
    }

    if (!isValidPort(form.getFieldValue('IPPort'))) {
      message.warning('无效的端口');
      return;
    }
    // if()

    setIsFlag(true);
  }
  const handleResponse = (data) => {
    console.log(data, 'handleResponse');
    // 对返回的数据进行处理
  };

  async function postCurrentIP() {
    // http://192.168.10.96:5003/v2/_catalog
    const resp = await axios.get(
      `http://${form.getFieldValue('IP')}:${form.getFieldValue('IPPort')}/v2/_catalog`,
    );
    console.log(resp, 'resp');
    return resp?.data;
  }

  async function doChangeUseIPPort() {
    const resp = await axios.get(
      `http://${form.getFieldValue('IP')}:${form.getFieldValue('IPPort')}/v2/${form.getFieldValue('useIPPort')}/tags/list`,
    );
    let finalData = resp?.data?.tags?.map((v: any) => {
      return {
        label: v,
        value: v,
      };
    });
    setMode2Options(finalData)
    console.log(resp, 'resp');
    // return resp?.data;
    // const resp = await request<API.Response & { data?: API.FkResult; msg?: string }>(
    //   `/v2/ubuntu/tags/list`,
    //   {
    //     method: 'GET',
    //     headers: {
    //       'Content-Type': 'application/json',
    //     },
    //     data: {},
    //   },
    // );
    // console.log(resp, 'resp');
    // return resp;
  }

  return (
    <ModalForm<API.ModelImage>
      width={proFormModelWidth}
      title={intl.formatMessage({
        id: 'resource.model_image.table.list.add',
        defaultMessage: '$$$',
      })}
      open={props.createModalOpen}
      form={form}
      autoFocusFirstInput
      modalProps={{
        destroyOnClose: true,
        onCancel: () => props.handleModal(),
      }}
      submitTimeout={2000}
      onFinish={async (values) => {
        postModelImageCreateModelImage(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;
      }}
    >
      <ProForm.Group>
        <ProFormText
          width={proFormItemStyleProps.column2Width}
          name="name"
          label={
            <FormattedMessage id="resource.model_image.table.list.name" defaultMessage="$$$" />
          }
          placeholder={`${intl.formatMessage({
            id: 'common.please_input',
            defaultMessage: '$$$',
          })}${intl.formatMessage({
            id: 'resource.model_image.table.list.name',
            defaultMessage: '$$$',
          })}`}
          required={true}
          rules={[
            {
              required: true,
              message: (
                <FormattedMessage
                  id="resource.model_image.table.rule.required.name"
                  defaultMessage="name is required"
                />
              ),
            },
          ]}
        />
        <ProFormSelect
          width={proFormItemStyleProps.column2Width}
          name="modelVersionFkId"
          label={
            <FormattedMessage
              id="resource.model_image.table.list.modelVersionFkId"
              defaultMessage="$$$"
            />
          }
          placeholder={`${intl.formatMessage({
            id: 'common.please_select',
            defaultMessage: '$$$',
          })}${intl.formatMessage({
            id: 'resource.model_image.table.list.modelVersionFkId',
            defaultMessage: '$$$',
          })}`}
          required={true}
          showSearch
          debounceTime={1000}
          request={async (keyWord) => {
            const resp = await postModelVersionGetModelVersionFkSelect({
              keyword: keyWord?.keyWords || '',
            });
            return resp.data.list.map((v: any) => {
              return {
                label: v.name,
                value: v.id,
              };
            });
          }}
        />
        <ProFormText
          width={proFormItemStyleProps.column2Width}
          name="path"
          label={
            <FormattedMessage id="resource.model_image.table.list.path" defaultMessage="$$$" />
          }
          placeholder={`${intl.formatMessage({
            id: 'common.please_input',
            defaultMessage: '$$$',
          })}${intl.formatMessage({
            id: 'resource.model_image.table.list.path',
            defaultMessage: '$$$',
          })}`}
          required={false}
        />
        <ProFormText
          width={proFormItemStyleProps.column2Width}
          name="startCode"
          label={
            <FormattedMessage id="resource.model_image.table.list.startCode" defaultMessage="$$$" />
          }
          placeholder={`${intl.formatMessage({
            id: 'common.please_input',
            defaultMessage: '$$$',
          })}${intl.formatMessage({
            id: 'resource.model_image.table.list.startCode',
            defaultMessage: '$$$',
          })}`}
          required={false}
        />
        <ProFormText
          width={proFormItemStyleProps.column2Width}
          name="remark"
          label={
            <FormattedMessage id="resource.model_image.table.list.remark" defaultMessage="$$$" />
          }
          placeholder={`${intl.formatMessage({
            id: 'common.please_input',
            defaultMessage: '$$$',
          })}${intl.formatMessage({
            id: 'resource.model_image.table.list.remark',
            defaultMessage: '$$$',
          })}`}
          required={false}
        />

        {/* 
        // TODO  update联动查询
        */}

        <ProForm.Group
          key="group"
          style={{
            width: proFormItemStyleProps.width,
          }}
        >
          <Space>
            <ProFormText
             width={180}
              name="IP"
              label={'IP地址'}
              placeholder={'请输入IP地址'}
              required={false}
              onChange={() => {
                setIsFlag(false);
              }}
            />
            <ProFormText
            width={110}
              name="IPPort"
              label={'端口号'}
              placeholder={'请输入端口号'}
              required={false}
              onChange={() => {
                setIsFlag(false);
              }}
            />
            <Button style={{ marginTop: 15 }} type="primary" onClick={() => doFindIPNext()}>
              查询
            </Button>
          </Space>
          {isFlag ? (
            <>
              <ProFormDependency name={['IP']}>
                {({ IP }) => {
                  if (IP) {
                    return (
                      <ProFormSelect
                        width={175}
                        name="useIPPort"
                        label="选择1"
                        debounceTime={1000}
                        request={async () => {
                          const resp = await postCurrentIP();
                          return resp?.repositories?.map((v: any) => {
                            return {
                              label: v,
                              value: v,
                            };
                          });
                        }}
                        onChange={() => doChangeUseIPPort()}
                      />
                    );
                  }
                  return <></>;
                }}
              </ProFormDependency>
              <ProFormDependency name={['useIPPort']}>
                {({ useIPPort }) => {
                  if (useIPPort) {
                    return (
                      <ProFormSelect
                      width={175}
                      name="useMode2"
                        label="选择2"
                        debounceTime={1000}
                        options={mode2Options}
                      />
                    );
                  }
                  return <></>;
                }}
              </ProFormDependency>
            </>
          ) : (
            ''
          )}
        </ProForm.Group>
      </ProForm.Group>
    </ModalForm>
  );
};
export default CreateForm;
