import { IndexViewController } from '@ibiz-template/controller';
import { useRouter } from '@ibiz-template/vue-util';
import Vue, { ref, watch } from 'vue';

export const getView2Value = (item: IParams) => {
  return item.params.view2
    ? (item.params.view2 ? `/${item.params.view2}` : '') +
        (item.params.params2 ? `/${item.params.params2}` : '')
    : '404';
};

export const getView1Value = (item: IParams) => {
  return (
    (item.params.view1 ? `/${item.params.view1}` : '') +
    (item.params.params1 ? `/${item.params.params1}` : '')
  );
};

export interface RouteMsg {
  key: string;
  fullPath: string;
  modelPath?: string;
  caption?: string;
}

export function useIndexRouteManage(
  proxy: Vue,
  controller: IndexViewController,
) {
  const router = useRouter(proxy);

  /** 当前的路由标识，只由二级路由组成，二级路由一致则就是同一个视图 */
  const currentKey = ref('');

  /** 留一份首页的Path */
  const indexPath = ref('');

  /** key操作记录，只维护当前缓存的key，且每个key在集合里唯一，最新操作的排在最前面 */
  const keyHistory = ref<string[]>([]);

  /** 路由信息，每个key对应的全路由和标题之类的信息 */
  const routeMsgs = ref<RouteMsg[]>([]);

  // 监听路由
  watch(
    () => proxy.$route,
    (newVal, oldVal) => {
      // 只处理有二级路由，只有首页的时候不需要
      if (newVal !== oldVal) {
        currentKey.value = getView2Value(newVal);
        indexPath.value = getView1Value(newVal);
        // 更新或新建对应key的全路由信息,主要是三级路由变更时会用
        const find = routeMsgs.value.find(
          item => item.key === currentKey.value,
        );
        if (find) {
          find.fullPath = newVal.fullPath;
        } else {
          routeMsgs.value.push({
            key: currentKey.value,
            fullPath: newVal.fullPath,
            modelPath: '',
            caption: '',
          });
        }
      }
    },
    { deep: true, immediate: true },
  );

  // 监听当前的key，维护数据
  watch(
    currentKey,
    (newVal, oldVal) => {
      if (newVal !== oldVal && newVal) {
        const index = keyHistory.value.indexOf(newVal);
        // 历史记录里没有的新建信息，放入开头
        if (index === -1) {
          keyHistory.value.unshift(newVal);
        } else {
          // 已存在的调整顺序至开头
          keyHistory.value.splice(index, 1);
          keyHistory.value.unshift(newVal);
        }
      }
    },
    { immediate: true },
  );

  /**
   * 更新路由信息
   *
   * @author lxm
   * @date 2022-09-01 16:09:51
   * @param {string} key
   * @param {IData} opts
   */
  const updateRouteMsg = (key: string, opts: Partial<RouteMsg>) => {
    const find = routeMsgs.value.find(item => item.key === currentKey.value);
    if (find) {
      if (opts.caption) find.caption = opts.caption;
      if (opts.modelPath) find.modelPath = opts.modelPath;
    }
  };

  /**
   * 删除路由缓存数据
   *
   * @author lxm
   * @date 2022-09-22 10:09:11
   * @param {string[]} keys 要删除的keys
   */
  const deleteRouteCache = (keys: string[]) => {
    keys.forEach(key => {
      const index = keyHistory.value.indexOf(key);
      if (index !== -1) {
        keyHistory.value.splice(index, 1);
        const msgIndex = routeMsgs.value.findIndex(item => item.key === key);
        routeMsgs.value.splice(msgIndex, 1);
      }
    });
  };

  /**
   * 关闭视图回调
   *
   * @author lxm
   * @date 2022-09-22 10:09:59
   * @param {string} [key=currentKey.value]
   */
  const closeView = (key: string = currentKey.value) => {
    // 找出删除的key在历史记录里的位置
    deleteRouteCache([key]);
    const toKey = keyHistory.value[0];
    if (!toKey) {
      if (controller.model.source.blankMode) {
        window.close();
      } else {
        currentKey.value = '';
        router.push(indexPath.value);
      }
    } else {
      const find = routeMsgs.value.find(item => item.key === toKey);
      router.push(find!.fullPath);
    }
  };

  return {
    currentKey,
    keyHistory,
    routeMsgs,
    updateRouteMsg,
    closeView,
    deleteRouteCache,
  };
}
