import { postDeviceGroupGetDeviceGroupTree } from '@/services/device/DeviceGroup';
import { postProjectCreateProject } from '@/services/project/Project';
import { postAlgorithmModelGetAlgorithmModelFkSelect } from '@/services/resource/AlgorithmModel';
import { beforeUploadFile } from '@/utils/common';
import { CloseOutlined, SnippetsOutlined } from '@ant-design/icons';
import type { ProFormInstance } from '@ant-design/pro-components';
import {
  ProForm,
  ProFormList,
  ProFormSwitch,
  ProFormText,
  ProFormUploadDragger,
  StepsForm,
} from '@ant-design/pro-components';
import { FormattedMessage, useIntl } from '@umijs/max';
import { Modal, Switch, Transfer, Tree, message } from 'antd';
import type { TransferDirection } from 'antd/es/transfer';
import { DataNode } from 'antd/es/tree';
import React, { useEffect, useRef, useState } from 'react';
// @ts-ignore
import cookie from 'react-cookies';
interface RecordType {
  key: string;
  title: string;
  description: string;
  chosen: boolean;
}
interface ProjectConfig {
  params: Array<object>;
}
export type FormValueType = {
  target?: string;
  template?: string;
  type?: string;
  time?: string;
  frequency?: string;
} & Partial<API.Project>;

export type CreateFormProps = {
  createModalOpen: boolean;
  handleModal: () => void;
  values: Partial<API.Project>;
  reload: any;
};
const waitTime = (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

/**styles 配置 */
const formContainerWidth: number = 755
const stepFormItemStyleProps: Record<string, any> = {
  width: formContainerWidth,
};

const treeData1: any[] = [
  {
    title: '0-0',
    key: '0-0',
    children: [
      {
        title: '0-0-0',
        key: '0-0-0',
        children: [
          { title: '0-0-0-0', key: '0-0-0-0' },
          { title: '0-0-0-1', key: '0-0-0-1' },
          { title: '0-0-0-2', key: '0-0-0-2' },
        ],
      },
      {
        title: '0-0-1',
        key: '0-0-1',
        children: [
          { title: '0-0-1-0', key: '0-0-1-0' },
          { title: '0-0-1-1', key: '0-0-1-1' },
          { title: '0-0-1-2', key: '0-0-1-2' },
          { title: '0-0-1-0', key: '0-0-1-3' },
          { title: '0-0-1-1', key: '0-0-1-4' },
          { title: '0-0-1-2', key: '0-0-1-5' },
          { title: '0-0-1-0', key: '0-0-1-6' },
          { title: '0-0-1-1', key: '0-0-1-7' },
          { title: '0-0-1-2', key: '0-0-1-8' },
          { title: '0-0-1-0', key: '0-0-1-9' },
          { title: '0-0-1-1', key: '0-0-1-10' },
          { title: '0-0-1-2', key: '0-0-1-11' },
          { title: '0-0-1-0', key: '0-0-1-12' },
          { title: '0-0-1-1', key: '0-0-1-13' },
          { title: '0-0-1-2', key: '0-0-1-14' },
          { title: '0-0-1-0', key: '0-0-1-15' },
          { title: '0-0-1-1', key: '0-0-1-16' },
          { title: '0-0-1-2', key: '0-0-1-17' },
          { title: '0-0-1-0', key: '0-0-1-18' },
          { title: '0-0-1-1', key: '0-0-1-19' },
          { title: '0-0-1-2', key: '0-0-1-20' },
          { title: '0-0-1-0', key: '0-0-1-21' },
          { title: '0-0-1-1', key: '0-0-1-22' },
          { title: '0-0-1-2', key: '0-0-1-23' },
          { title: '0-0-1-0', key: '0-0-1-24' },
          { title: '0-0-1-1', key: '0-0-1-25' },
          { title: '0-0-1-2', key: '0-0-1-26' },
          { title: '0-0-1-0', key: '0-0-1-27' },
          { title: '0-0-1-1', key: '0-0-1-28' },
          { title: '0-0-1-2', key: '0-0-1-29' },
          { title: '0-0-1-0', key: '0-0-1-30' },
          { title: '0-0-1-1', key: '0-0-1-31' },
          { title: '0-0-1-2', key: '0-0-1-32' },
          { title: '0-0-1-0', key: '0-0-1-33' },
          { title: '0-0-1-1', key: '0-0-1-34' },
          { title: '0-0-1-2', key: '0-0-1-35' },
        ],
      },
      {
        title: '0-0-2',
        key: '0-0-2',
      },
    ],
  },
  {
    title: '0-1',
    key: '0-1',
    children: [
      { title: '0-1-0-0', key: '0-1-0-0' },
      { title: '0-1-0-1', key: '0-1-0-1' },
      { title: '0-1-0-2', key: '0-1-0-2' },
    ],
  },
  {
    title: '0-2',
    key: '0-2',
  },
];

const MyCreateForm: React.FC<CreateFormProps> = (props) => {
  const [treeData, setTreeData] = React.useState<DataNode[]>([]);
  const [modalData, setModalData] = useState<RecordType[]>([]);
  const [targetKeys, setTargetKeys] = useState<string[]>([]);
  const [selectKeys, setSelectKeys] = useState([]);
  const [filePath, setFilePath] = useState('');
  const [configData, setConfigData] = useState<ProjectConfig>({ params: [] });
  const intl = useIntl();
  const [isAuto, setIsAuto] = useState(true);
  const formRef = useRef<ProFormInstance>();
  const formRef3 = useRef<ProFormInstance>();
  const [current, setCurrent] = useState(0);
  const getModelData = () => {
    postAlgorithmModelGetAlgorithmModelFkSelect({ keyword: '' }).then((res) => {
      console.log(444, res);
      let result = (res.data?.list || []).map((v: any) => {
        return {
          key: v.id,
          title: v.name,
          chosen: false,
        };
      });
      setModalData(result);
    });
    // setMockData(tempMockData);
    // setTargetKeys(tempTargetKeys);
  };

  const handleChange = (newTargetKeys: string[]) => {
    setTargetKeys(newTargetKeys);
  };
  useEffect(() => {
    setTargetKeys([]);
    if (props.createModalOpen) {
      getModelData();
      postDeviceGroupGetDeviceGroupTree()
        .then((resp: API.Response) => {
          setTreeData(resp.data.tree);
        })
        .catch(() => {});
    } else {
      formRef.current?.resetFields();
    }
  }, [props.createModalOpen]);
  const handleSearch = (dir: TransferDirection, value: string) => {
    postAlgorithmModelGetAlgorithmModelFkSelect({ keyword: value }).then((res) => {
      console.log(444, res);
      let result = (res.data?.list || []).map((v: any) => {
        return {
          key: v.id,
          title: v.name,
          chosen: false,
        };
      });
      setModalData(result);
    });
  };
  return (
    <StepsForm<{
      name: string;
    }>
      stepsProps={{
        labelPlacement: 'vertical',
      }}
      current={current}
      onCurrentChange={setCurrent}
      onFinish={async () => {
        let formData = formRef.current?.getFieldsValue();
        if (formData?.name) {
          formData.inferConfig = { models: targetKeys, params: configData?.params || [] };
          formData.groupIds = selectKeys;
          formData.projectFilePath = filePath;
          postProjectCreateProject(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;
      }}
      formProps={{
        validateMessages: {
          required: '此项为必填项',
        },
      }}
      stepsFormRender={(dom, submitter) => {
        return (
          <Modal
            title="分步表单"
            width={803}
            onCancel={() => {
              setCurrent(0);
              formRef.current?.resetFields();
              formRef3.current?.resetFields();
              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>
          <ProFormText
            {...stepFormItemStyleProps}
            name="name"
            label={<FormattedMessage id="project.project.table.list.name" defaultMessage="$$$" />}
            placeholder={`${intl.formatMessage({
              id: 'common.please_input',
              defaultMessage: '$$$',
            })}${intl.formatMessage({
              id: 'project.project.table.list.name',
              defaultMessage: '$$$',
            })}`}
            required={true}
            rules={[
              {
                required: true,
                message: (
                  <FormattedMessage
                    id="project.project.table.rule.required.name"
                    defaultMessage="name is required"
                  />
                ),
              },
            ]}
          />
          <ProFormText
            width={680}
            name="code"
            label={<FormattedMessage id="project.project.table.list.code" defaultMessage="$$$" />}
            placeholder={`${intl.formatMessage({
              id: 'common.please_input',
              defaultMessage: '$$$',
            })}${intl.formatMessage({
              id: 'project.project.table.list.code',
              defaultMessage: '$$$',
            })}`}
            required={!isAuto}
            initialValue=""
            disabled={isAuto}
            rules={
              isAuto
                ? []
                : [
                    {
                      required: true,
                      message: (
                        <FormattedMessage
                          id="project.project.table.rule.required.code"
                          defaultMessage="code is required"
                        />
                      ),
                    },
                  ]
            }
            addonAfter={
              <Switch
                checked={isAuto}
                checkedChildren={<FormattedMessage id="common.auto" defaultMessage="$$$" />}
                unCheckedChildren={<FormattedMessage id="common.edit" defaultMessage="$$$" />}
                onChange={setIsAuto}
              />
            }
          />
          <ProFormText
            {...stepFormItemStyleProps}
            name="info"
            label={<FormattedMessage id="project.project.table.list.info" defaultMessage="$$$" />}
            placeholder={`${intl.formatMessage({
              id: 'common.please_input',
              defaultMessage: '$$$',
            })}${intl.formatMessage({
              id: 'project.project.table.list.info',
              defaultMessage: '$$$',
            })}`}
            required={true}
            rules={[
              {
                required: true,
                message: (
                  <FormattedMessage
                    id="project.project.table.rule.required.info"
                    defaultMessage="info is required"
                  />
                ),
              },
            ]}
          />
          <ProFormText
            {...stepFormItemStyleProps}
            name="remark"
            label={<FormattedMessage id="project.project.table.list.remark" defaultMessage="$$$" />}
            placeholder={`${intl.formatMessage({
              id: 'common.please_input',
              defaultMessage: '$$$',
            })}${intl.formatMessage({
              id: 'project.project.table.list.remark',
              defaultMessage: '$$$',
            })}`}
            required={false}
          />
        </ProForm.Group>
        <ProForm.Group>
          <ProFormSwitch
            width="lg"
            name="isEnable"
            label={
              <FormattedMessage id="project.project.table.list.isEnable" defaultMessage="$$$" />
            }
            initialValue={true}
          />
        </ProForm.Group>
      </StepsForm.StepForm>
      {/* 关联算法模型 */}
      <StepsForm.StepForm<{
        model: string;
      }>
        name="model"
        title="关联算法模型"
        stepProps={{
          description: '选择算法模型',
        }}
        onFinish={async () => {
          return true;
        }}
      >
        <Transfer
          dataSource={modalData}
          showSearch
          titles={['未选模型', '已选模型']}

          locale={{ itemUnit: '项', itemsUnit: '项', searchPlaceholder: '请输入搜索内容' }}
          targetKeys={targetKeys}
          onChange={handleChange}
          onSearch={handleSearch}
          style={{ marginBottom: '20px' }}
          listStyle={{width: 289, height: 300}}
          operationStyle={{width: 100, alignItems: 'center'}}
          render={(item) => item.title}
        />
      </StepsForm.StepForm>
      {/* 上传业务代码 */}
      <StepsForm.StepForm<{
        project_file: string;
      }>
        name="project_file"
        title="上传业务代码"
        style={{width: stepFormItemStyleProps.width}}
        stepProps={{
          description: '上传业务代码格式为(.zip,.tar.gz)',
        }}
        onFinish={async (values: any) => {
          if ('projectFilePath' in values && values['projectFilePath'].length > 0) {
            let projectFilePath = values['projectFilePath'][0]?.response?.data?.path || '';
            setFilePath(projectFilePath);
          }
          return true;
        }}
      >
        <ProFormUploadDragger
          label="上传文件"
          name="projectFilePath"
          action="/api/v1/file/uploadFile"
          max={1}
          fieldProps={{
            name: 'file',
            beforeUpload: beforeUploadFile,
            data: { path: 'project/files' },
            headers: {
              'X-CSRFToken': cookie.load('csrftoken'),
              Authorization: `Bearer ${localStorage.getItem('access') || ''}`,
            },
          }}
        />
      </StepsForm.StepForm>
      {/* 业务参数配置 */}
      <StepsForm.StepForm<{
        config: string;
      }>
        name="config"
        title="业务参数配置"
        stepProps={{
          description: '业务参数配置',
        }}
        onFinish={async (values: any) => {
          setConfigData(values);
          return true;
        }}
      >
        {/* <Icon type="delete" /> */}
        {/* TODO 图标需要替换 */}
        <ProFormList
          style={{width: stepFormItemStyleProps.width}}
          copyIconProps={{
            Icon: SnippetsOutlined,
          }}
          deleteIconProps={{
            Icon: CloseOutlined,
          }}
          name="params"
          label="模型参数"
          initialValue={[]}
        >
          <ProForm.Group>
            <ProFormText key="name" name="name" label="键名" />
            <ProFormText key="default" name="default" label="默认值" />
            <ProFormText key="remark" name="remark" label="备注" />
          </ProForm.Group>
        </ProFormList>
      </StepsForm.StepForm>
      {/* 关联网点 */}
      <StepsForm.StepForm<{
        group: string;
      }>
        name="group"
        title="关联网点"
        stepProps={{
          description: '选择网点',
        }}
        onFinish={async () => {
          return true;
        }}
        style={{width: stepFormItemStyleProps.width}}
        formRef={formRef3}
      >
        <div style={{paddingBottom: 10}}>{'选择网点'}</div>
        <Tree
          checkable
          defaultExpandAll={true}
          defaultCheckedKeys={[]}
          autoExpandParent={true}
          onCheck={(checkedKeys: any) => {
            // form.setFieldsValue({menuIds: checkedKeys})
            setSelectKeys(checkedKeys);
            // formRef3.current?.setFieldValue('groupIds', checkedKeys)
          }}
          treeData={treeData}
          // loadData={({treeNode}) => {
          //   return treeData
          // }}
        />
      </StepsForm.StepForm>
    </StepsForm>
  );
};
export default MyCreateForm;
