import { ref } from 'vue';
import { useRoute } from 'vue-router';
import { getGoafSelectOption } from '/@/views/monitor/sealedMonitor/monitor.api';
import { useMineDepartmentStore } from '/@/store/modules/mine';

/**
 * 适用于关联分析页面的表单钩子
 * @param param.unlink 取消查询采空区后的自动赋值
 * @returns
 */
export function useInitForm({ unlink }: { unlink?: boolean } = {}) {
  const mineStore = useMineDepartmentStore();
  const route = useRoute();
  const loading = ref(false);
  // 默认填充的矿码
  const innerValue = ref<string>('');
  const filters: string[] = ((route.query?.filter as string) || (route.query?.filterout as string))?.split(',') || [];

  if (route.query.deptId) {
    innerValue.value = route.query.deptId as string;
  } else {
    const leaf = mineStore.getDepart?.isLeaf ? mineStore.getDepart : mineStore.findDepart((e) => e.isLeaf, mineStore.getRoot);
    innerValue.value = leaf?.id as string;
  }

  // if (innerValue.value) {
  //   // mineStore.setDepartById(code as string);
  //   initGoafOptions(innerValue);
  // }

  // 采空区选择器
  const goafId = ref((route.query.goafId as string) || '');
  const goafOptions = ref<any[]>([]);

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

        goafId.value = defaultValue;
      })
      .finally(() => {
        loading.value = false;
      });
  }

  return {
    goafOptions,
    goafId,
    innerValue,
    loading,
    filters,
    initGoafOptions,
  };
}
