import { ref, reactive, unref , computed} from "vue";
import { useNav } from "/@/layout/hooks/nav";
import { ElMessage } from "element-plus";
import { IDataType } from "/@/api/types";

type Params = {
  code: number;
  message: string;
  handler: () => void;
};

export function useResponseHandle() {
  const { logout } = useNav();
  function responseHandle({ code, message, handler }: Params) {
    const c = Number(code);
    if (c === 0) {
      handler();
    } else if (c >= 100 && c <= 140) {
      logout();
    } else {
      ElMessage.error(message);
    }
  }
  return responseHandle;
}


interface TaskOptions<D>{
  root?: boolean
  initialData?: D
  success?: (data?:D) => void 
}

export function useTask<D = any>({ initialData, root = true, success }: TaskOptions<D> = {  root: true } ) {
  const error = ref(false);
  const loading = ref(false);
  const { logout } = useNav();
  const data = ref<D>(initialData);

  function run(promise: Promise<IDataType<D>>) {
    loading.value = true
    return new Promise(resolve => {
      promise.then(response => {
        loading.value = false
        let { code, message } = response
        code = Number(code)
        
        if(code === 0){
          error.value = false
          data.value = root ? response.data : (response.data as unknown as any).list
          success && success(unref(response.data));
        }else if(code >= 100 && code <= 140){
          logout()
          error.value = true
        }else{
          ElMessage.warning(message)
          error.value = true
        }
        resolve(response)
      });
    })
  }

  return reactive({ run, data, error, loading, logout })
}


export function useTasks(...tasks: ReturnType<typeof useTask>[]){
  return computed(() => ({
    loading: tasks.some(task => task.loading),
    error: tasks.some(task => task.error)
  }))
}
