/*
 * @Author: Nian Yi
 * @Date: 2022-04-12 12:27:34
 * @LastEditTime: 2022-04-14 16:38:30
 * @LastEditors: Nian Yi
 * @Description: theme
 * @FilePath: /easyvadmin/src/scripts/utils/theme.ts
 * 奥利给
 */
import { isRefScreen, isPanel, isComponent, deepFind } from 'utils/utils';
import { request } from 'utils/fetch';
import { api } from 'constants/config';
import { getId } from 'utils/interaction';
import { Status } from 'models/theme.types';
import { ScreensById } from 'models/screen.types';
import { Panel } from 'models/panel.types';

export function findComponent({
  screensById,
  panelsById,
  screenId
}: {
  screensById: ScreensById;
  panelsById: {
    [x: string]: Panel;
  };
  screenId: number;
}) {
  // 查询当前页面组件
  const screen = screensById[screenId];
  if (screen) {
    const flatLayers = deepFind(
      screen.layers,
      (item) => {
        return !Array.isArray(item?.components);
      },
      'components'
    ); // 多维数组抹平
    const layers = flatLayers // 动态面板+组件
      .filter((d) => !isRefScreen(d.id));
    return layers.reduce((all, curr) => {
      if (isPanel(curr.id)) {
        // 动态面板
        const id = getId(curr.id);
        const { states } = panelsById[id] || {};
        if (Array.isArray(states)) {
          const _states = states.reduce((total, id) => {
            const result = findComponent({
              screensById,
              panelsById,
              screenId: id
            });
            return total.concat(result).flat(2);
          }, []);
          return all.concat(_states);
        }
      } else if (isComponent(curr.id)) {
        return all.concat(curr.id);
      }
      return all;
    }, []);
  }
}

export function monitorThemeStatus(id, callback, signal) {
  // 监控主题应用状态
  let Timer;
  return request(api.screensThemeStatus, { id }, undefined, undefined, { signal: signal }).then((result) => {
    if (result && result?.status === Status.CancelTask) {
      Timer && clearTimeout(Timer);
      callback(result);
    } else if (result && result.status === Status.StartTask) {
      Timer = setTimeout(() => {
        monitorThemeStatus(id, callback, signal);
      }, window.appConfig.THEME_TIME || 3000);
    } else {
      callback(result);
    }
    return Timer;
  });
}

export function linearGradientTransform() {
  //
}
