import TableTransferList from '@/pages/Setting/components/TableTransfer';
import { postDeviceGetAllDeviceByGroup } from '@/services/device/Device';
import {
  postProjectModelConfigGetProjectModelConfigById,
  putProjectModelConfigUpdateProjectModelConfig,
} from '@/services/project/ProjectModelConfig';
import { postAlgorithmModelGetAllVersionsById } from '@/services/resource/AlgorithmModel';
import { postModelVersionGetModelVersionById } from '@/services/resource/ModelVersion';
import {
  ProForm,
  ProFormDigit,
  ProFormSelect,
  ProFormSwitch,
  ProFormText,
  StepsForm,
} from '@ant-design/pro-components';
import { FormListActionType } from '@ant-design/pro-form/lib';
import { useIntl } from '@umijs/max';
import { Modal, message } from 'antd';
import type { ColumnsType } from 'antd/es/table/interface';
import type { TransferItem, TransferProps } from 'antd/es/transfer';
import React, { useEffect, useRef, useState } from 'react';
import { proFormMaxItemStyleProps, proFormMaxModelWidth, proFormModelWidth } from '../../../../config/defaultForm';

const formContainerWidth: number = 755;
const stepFormItemStyleProps: Record<string, any> = {
  width: formContainerWidth,
};
interface DataType extends API.Device {
  key: string;
}

interface ProjectModelConfigById {
  configId: number;
}

interface TableTransferProps extends TransferProps<TransferItem> {
  dataSource: DataType[];
  leftColumns: ColumnsType<DataType>;
  rightColumns: ColumnsType<DataType>;
}

export type UpdateFormProps = {
  updateModalOpen: boolean;
  handleModal: () => void;
  projectModelConfigId: number;
  groupId: number;
  reload: any;
};

const UpdateForm: React.FC<UpdateFormProps> = (props) => {
  const intl = useIntl();

  const [targetKeys, setTargetKeys] = useState<string[]>([]);
  const [current, setCurrent] = useState(0);

  const [configData, setConfigData] = useState<any>([]);

  const [addrValue, setAddr] = useState('');
  const [projectModelConfig, setProjectModelConfig] = useState<API.ProjectModelConfig>({});
  const [configResult, setConfigResult] = useState<API.ProjectModelConfig>({});
  const [deviceData, setDeviceData] = useState<DataType[]>([]);
  const [selectValue, setSelectValue] = useState<number>(0);
  const [isInit, setIsInit] = useState<boolean>(false);
  const handleSelectChange = (value: number) => {
    if (value !== projectModelConfig.modelVersionFkId) {
      postModelVersionGetModelVersionById({ id: value }).then((resp) => {
        let data = resp.data.modelVersion.modelConfig?.params || [];
        setConfigData(data);
      });
    }
    setSelectValue(value);
  };

  // useEffect(() => {
  //   if (selectValue > 0) {
  //     postModelVersionGetModelVersionById({ id: selectValue }).then((resp) => {
  //       let data = resp.data.modelVersion.modelConfig?.params || [];
  //       setConfigData(data); // 更新状态
  //     });
  //   }
  // }, [selectValue]);

  const actionFormListRef = useRef<
    FormListActionType<{
      name: string;
    }>
  >();

  useEffect(() => {
    setTargetKeys([]);
    setConfigData([]);
    setIsInit(false);
    if (props.updateModalOpen) {
      // getModelData();
      if (props.projectModelConfigId && props.projectModelConfigId !== 0) {
        postProjectModelConfigGetProjectModelConfigById({ id: props.projectModelConfigId }).then(
          (resp) => {
            setProjectModelConfig(resp.data.ProjectModelConfig);
            setTargetKeys(
              (resp.data.ProjectModelConfig?.devices || '').split(',').map((v: string) => {
                return parseInt(v);
              }),
            );
            setConfigData(resp.data.ProjectModelConfig?.modelConfig || []);
            setSelectValue(resp.data.ProjectModelConfig?.modelVersionFkId || 0);
            setIsInit(true);
          },
        );
      }
    } else {
    }
  }, [props.updateModalOpen]);
  const handleChange = (newTargetKeys: string[]) => {
    setTargetKeys(newTargetKeys);
  };
  return (
    <StepsForm<{
      name: string;
    }>
      stepsProps={{
        labelPlacement: 'vertical',
      }}
      current={current}
      onCurrentChange={(value) => {
        setCurrent(value);
        if (value == 1) {
          postDeviceGetAllDeviceByGroup({ id: props.groupId }).then((resp) => {
            setDeviceData(
              (resp.data?.list || []).map((v: API.Device) => {
                return { key: v.id, ...v };
              }),
            );
          });
        }
      }}
      onFinish={async (values) => {
        setCurrent(0);
        return true;
      }}
      formProps={{
        validateMessages: {
          required: '此项为必填项',
        },
      }}
      stepsFormRender={(dom, submitter) => {
        return (
          <Modal
            title="项目部署配置"
            width={proFormMaxModelWidth}
            onCancel={() => {
              setCurrent(0);
              props.handleModal();
            }}
            open={props.updateModalOpen}
            footer={submitter}
            destroyOnClose
          >
            {dom}
          </Modal>
        );
      }}
    >
      <StepsForm.StepForm<{
        config: string;
      }>
        name="config1"
        title="项目参数配置"
        stepProps={{
          description: '业务参数配置',
        }}
        onFinish={async (values: any) => {
          let projectConfig: any = [];
          Object.keys(values).forEach((key) => {
            if (key !== 'modelFkId') {
              projectConfig.push({ name: key, value: values[key] });
            }
          });
          configResult.projectConfig = projectConfig;
          return true;
        }}
      >
        <>
          <ProForm.Group>
            {isInit &&
              (projectModelConfig?.projectConfig || []).map((item: any, index: number) => {
                let value_type = typeof item.value;
                if (value_type === 'number') {
                  return (
                    <ProFormDigit
                      {...proFormMaxItemStyleProps}
                      key={index}
                      name={item.name}
                      label={item.name}
                      initialValue={item.value}
                      tooltip={item.remark}
                    />
                  );
                } else if (value_type === 'boolean') {
                  return (
                    <ProFormSwitch
                      {...proFormMaxItemStyleProps}
                      key={index}
                      name={item.name}
                      label={item.name}
                      initialValue={item.value}
                      tooltip={item.remark}
                    />
                  );
                } else if (value_type === 'string') {
                  return (
                    <ProFormText
                      {...proFormMaxItemStyleProps}
                      key={index}
                      name={item.name}
                      label={item.name}
                      initialValue={item.value}
                      tooltip={item.remark}
                    />
                  );
                } else {
                  return;
                }
              })}
          </ProForm.Group>
        </>
      </StepsForm.StepForm>
      <StepsForm.StepForm<{
        config: string;
      }>
        name="config"
        title="模型参数配置"
        stepProps={{
          description: '模型参数配置',
        }}
        onFinish={async (values: any) => {
          configResult.modelVersionFkId = values.modelFkId;
          let modelConfig: any = [];
          Object.keys(values).forEach((key) => {
            if (key !== 'modelFkId') {
              modelConfig.push({ name: key, value: values[key] });
            }
          });
          configResult.modelConfig = modelConfig;
          return true;
        }}
      >
        <>
          <ProForm.Group>
            {/* <div>{props.projectModelConfigId}</div> */}
            {isInit && projectModelConfig.modelFkId && projectModelConfig.modelFkId !== 0 && (
              <ProFormSelect
              {...proFormMaxItemStyleProps}
                name="modelFkId"
                label="模型版本"
                onChange={handleSelectChange}
                initialValue={projectModelConfig.modelVersionFkId}
                // dependencies 的内容会注入 request 中
                request={async () => {
                  let resp = await postAlgorithmModelGetAllVersionsById({
                    id: projectModelConfig.modelFkId,
                  });
                  return resp.data.list.map((v: any) => {
                    return {
                      label: v.name,
                      value: v.id,
                    };
                  });
                }}
              />
            )}
            {/* <div>
            {selectValue}={projectModelConfig.modelVersionFkId}
          </div> */}
            {isInit &&
              (selectValue !== projectModelConfig.modelVersionFkId
                ? configData.map((item: any, index: number) => {
                    if (typeof item.default === 'number') {
                      return (
                        <ProFormDigit
                          {...proFormMaxItemStyleProps}
                          key={index}
                          name={item.name}
                          label={item.name}
                          initialValue={item.default}
                        />
                      );
                    } else if (typeof item.default === 'boolean') {
                      return (
                        <ProFormSwitch
                          {...proFormMaxItemStyleProps}
                          key={index}
                          name={item.name}
                          label={item.name}
                          initialValue={item.default}
                        />
                      );
                    } else {
                      return (
                        <ProFormText
                          {...proFormMaxItemStyleProps}
                          key={index}
                          name={item.name}
                          label={item.name}
                          initialValue={item.default}
                        />
                      );
                    }
                  })
                : configData.map((item: any, index: number) => {
                    if (typeof item.value === 'number') {
                      return (
                        <ProFormDigit
                        {...proFormMaxItemStyleProps}
                          key={index}
                          name={item.name}
                          label={item.name}
                          initialValue={item.value}
                        />
                      );
                    } else if (typeof item.value === 'boolean') {
                      return (
                        <ProFormSwitch
                        {...proFormMaxItemStyleProps}
                          key={index}
                          name={item.name}
                          label={item.name}
                          initialValue={item.value}
                        />
                      );
                    } else {
                      return (
                        <ProFormText
                        {...proFormMaxItemStyleProps}

                          key={index}
                          name={item.name}
                          label={item.name}
                          initialValue={item.value}
                        />
                      );
                    }
                  }))}
          </ProForm.Group>
        </>
      </StepsForm.StepForm>

      {/* 关联算法模型 */}

      <StepsForm.StepForm<{
        config: string;
      }>
        name="config3"
        title="设备配置"
        stepProps={{
          description: '设备关联配置',
        }}
        onFinish={async (values: any) => {
          configResult.devices = targetKeys.join(',');
          configResult.id = props.projectModelConfigId;
          putProjectModelConfigUpdateProjectModelConfig(configResult)
            .then((resp) => {
              message.success(intl.formatMessage({ id: 'common.success', defaultMessage: '$$$' }));
              props.handleModal();
              props.reload();
              return true;
            })
            .catch(() => {
              message.error(intl.formatMessage({ id: 'common.failure', defaultMessage: '$$$' }));
              return false;
            });
        }}
      >
        <>
          <TableTransferList
            setTargetKeys={setTargetKeys}
            dataSource={deviceData}
            targetKeys={targetKeys}
          ></TableTransferList>
        </>
      </StepsForm.StepForm>
    </StepsForm>
  );
};
export default UpdateForm;
