import React, { useState } from 'react'
import { CRUDProps } from '../../types';
import { Action } from '../../../../types';
import { getTableRowsData } from '../../utils';
import { createObject, functionInOneFrame } from '../../../../utils/helper';
import { IScopedContext } from '../../../../Scoped';
import { filter } from '../../../../utils/tpl';
import { TableRenderer } from '../../../Table';
import { Modal } from 'antd';
import { Icon } from '../../../../components/icons';
import { ITableStore } from '../../../../store/table';

interface CommonModalProps {
  props: CRUDProps;
  crudRef: any;
  dialogShow: boolean;
  drawerShow: boolean;
  searchTimer: ReturnType<typeof setTimeout>;
  showTableEditWarmModal: () => void,
  search(values?: any, silent?: boolean, clearSelection?: boolean, forceReload?: boolean, resolve?: (value: any) => void, reject?: (error: any) => void, isChild?: boolean, postData?: any, init?: boolean): void,
  tableStore: ITableStore | null,
  handleAction: (e: React.UIEvent<any> | undefined,
    action: Action,
    ctx: any,
    throwErrors?: boolean,
    delegate?: IScopedContext,
    isItemAction?: boolean) => void,
  afterSearchFn: () => void,
  reloadTarget: (target: string, data: any) => void,
  control?: any,
}
export const CommonModal: React.FC<CommonModalProps> = ({ props, dialogShow,
  drawerShow, tableStore, crudRef, showTableEditWarmModal, handleAction, search, afterSearchFn, reloadTarget, control }) => {
  const { store, render, env, translate } = props


  const baseModalConfirm = (type: 'drawer' | 'dialog') => {
    return async (values: object[],
      action: Action,
      ctx: any,
      components: Array<any>) => {
      const {
        store,
        pageField,
      } = props;
      // Jay 下一个、上一个不用关闭
      if (!['next', 'prev'].includes(action.actionType || '')) {
        switch (type) {
          case 'drawer':
          default:
            store.closeDrawer(true);
            break
          case 'dialog':
            store.closeDialog(true);
            break;
        }
      }

      const tableRows: any[] = getTableRowsData(store, tableStore)

      const dialogAction = store.action as Action;

      // 自动聚焦第一个搜索栏，释放内存
      functionInOneFrame(() =>
        (crudRef?.current?.querySelector('input[type="text"]') as HTMLElement)?.focus()
      )


      if (
        ['next', 'prev'].includes(action.actionType || '') &&
        typeof ctx.nextIndex === 'number' &&
        tableRows[ctx.nextIndex]
      ) {
        if (tableStore) {
          const count = tableStore.modified;
          if (count > 0) {
            showTableEditWarmModal();
            return;
          }
        }
        return handleAction(
          undefined,
          {
            ...dialogAction
          },
          createObject(
            createObject(store.data, {
              index: ctx.nextIndex
              // Jay
              // initApiDisable: 0
            }),
            tableRows[ctx.nextIndex]
          )
        );
      } else if (values.length) {
        const value = values[0];
        ctx = createObject(ctx, value);
        const component = components[0];

        // 提交来自 form
        if (component && component.props.type === 'form') {
          // 数据保存了，说明列表数据已经无效了，重新刷新。
          if (value && (value as any).__saved) {
            const reload = action.reload ?? dialogAction.reload;
            // 配置了 reload 则跳过自动更新。
            reload ||
              search(
                dialogAction.__from ? { [pageField || 'page']: 1 } : undefined,
                undefined,
                true,
                true,
                afterSearchFn
              );
          } else if (
            value &&
            ((value.hasOwnProperty('items') && (value as any).items) ||
              value.hasOwnProperty('ids')) &&
            control.bulkUpdate
          ) {
            control.bulkUpdate(value, (value as any).items);
          }
        }
      }

      const reload = action.reload ?? dialogAction.reload;
      if (reload) {
        reloadTarget(reload, ctx);
      }

      const redirect = action.redirect ?? dialogAction.redirect;
      if (redirect) {
        env.jumpTo(filter(redirect, ctx), dialogAction);
      }
    }
  }

  const handleBaseModalClose = (type: 'dialog' | 'drawer') => {
    return (confirmed?: boolean,
      formInstance?: any,
      tableInstance?: TableRenderer) => {

      // 自动聚焦第一个搜索栏，释放内存
      functionInOneFrame(() =>
        (crudRef?.current?.querySelector('input[type="text"]') as HTMLElement)?.focus()
      )

      if (tableInstance) {
        const count = tableInstance.props.store.modified;
        if (count > 0) {
          showTableEditWarmModal();
          return;
        }
      }
      // Jay
      if (formInstance) {
        const { promptPageLeave } = formInstance.props;
        if (promptPageLeave && formInstance.is_edit) {
          Modal.confirm({
            title: (
              <div>
                提示
                <div style={{ position: 'absolute', right: '10px', top: '10px', fontSize: '12px', cursor: "pointer" }} onClick={() => { Modal.destroyAll() }} >
                  <Icon icon="close" className="icon" />
                </div>
              </div>
            ),
            content: '新的修改没有保存，确认要离开？',
            getContainer: env.getModalContainer,
            zIndex: 1020,
            okText: translate('confirm'),
            cancelText: translate('cancel'),
            onOk: () => closeModal(type),
            className: 'ant-modal-adaptation-style'
          });
          return;
        }
      }
      closeModal(type);
    }
  }

  const handleDialogConfirm = async (
    values: object[],
    action: Action,
    ctx: any,
    components: Array<any>,
  ) => {
    return await baseModalConfirm('dialog')(values, action, ctx,
      components)
  }
  const handleDrawerConfirm = async (
    values: object[],
    action: Action,
    ctx: any,
    components: Array<any>,
  ) => {
    return await baseModalConfirm('drawer')(values, action, ctx,
      components)
  }

  const closeModal = (type: 'dialog' | 'drawer' = 'dialog') => {
    switch (type) {
      case 'dialog':
        store.closeDialog();
        break;
      case 'drawer':
        store.closeDrawer();
        break;
    }
  }

  const handleDialogClose = (
    confirmed?: boolean,
    formInstance?: any,
    tableInstance?: TableRenderer
  ) => {
    return handleBaseModalClose('dialog')(confirmed, formInstance, tableInstance)
  }
  const handleDrawerClose = (
    confirmed?: boolean,
    formInstance?: any,
    tableInstance?: TableRenderer
  ) => {
    return handleBaseModalClose('drawer')(confirmed, formInstance, tableInstance)
  }

  return <>
    {dialogShow ?
      render(
        'dialog',
        {
          ...((store.action as Action) &&
            ((store.action as Action).dialog as object)),
          type: 'dialog'
        },
        {
          key: 'dialog',
          data: store.dialogData,
          onConfirm: handleDialogConfirm,
          onClose: handleDialogClose,
          show: store.dialogOpen,
          replace: store.replace
        }
      ) : null
    }
    {
      drawerShow ?
        render(
          'drawer',
          {
            ...((store.action as Action) &&
              ((store.action as Action).drawer as object)),
            type: 'drawer'
          },
          {
            key: 'drawer',
            data: store.drawerData,
            onConfirm: handleDrawerConfirm,
            onClose: handleDrawerClose,
            show: store.drawerOpen,
            onAction: handleAction,
          }
        ) : null}
  </>
}
