import { get, last } from 'lodash-es';
import { ref } from 'vue';
import { useRoute } from 'vue-router';
import { getGoafSelectOption } from '../monitor.api';
import { useMineDepartmentStore } from '/@/store/modules/mine';

export function useInitForm() {
  const mineStore = useMineDepartmentStore();
  const route = useRoute();

  // 如果generation为true，表示是模板路由直接当作密闭监测页面使用，就不会有/:id后缀
  const departId = route.meta.generation ? undefined : (last(route.path.split('/')) as string);
  // 获取到路由携带的id后进行过滤
  const dep = mineStore.findDepartById(departId);
  // 获取到query携带的矿id，如有就默认选中该矿
  const rawcode = route.query.deptId as string;
  // 给历史数据默认填充的矿码
  const hiscode = rawcode
    ? rawcode
    : get(
        mineStore.findDepart((e) => e.isLeaf, dep || mineStore.getRoot),
        'id'
      );

  // 采空区选择器
  const goafId = ref('');
  const goafOptions = ref<any[]>([]);

  function initGoafOptions(deptId) {
    return getGoafSelectOption({ deptId }).then(({ options, defaultValue }) => {
      goafOptions.value = options;
      if (options.some((e) => e.value === goafId.value)) return;
      goafId.value = defaultValue;
    });
  }

  return {
    departId,
    goafOptions,
    goafId,
    rawcode,
    hiscode,
    route,
    initGoafOptions,
  };
}
