import { useEffect, useState,useCallback } from 'react';
import {httpUtil} from "@/utils"
import { assetsManageService } from '@/services';


export const useGetAssetQuestion = (props) => {
    const {ids} = props
  const [data, setData] = useState<any>(null);
  const [loading, setLoading] = useState<boolean>(false);

  useEffect(() => {
    const fetchData = async () => {
      if (!ids || ids.length === 0) return;

      try {
        setLoading(true);
        const response:any = await assetsManageService.getAllQuestionWarning({dataAssetIds:ids.join(',')})
        if(httpUtil.checkSuccess(response,1)){
            setData(response.data);
        }else{
            httpUtil.showError(response,1)
        }
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [ids]);

  return { tableData:data, tableloading:loading };
};

export const useGetFlowAction = () => {
  const [loading, setLoading] = useState<boolean>(false);

  const saveQuestionItem = useCallback(async (params: any,callback?:any)=>{
    try {
      setLoading(true);
      const response: any = await assetsManageService.saveQuestionItem(params);
      if (httpUtil.checkSuccess(response, 1)) {
        callback?.()
      } else {
        httpUtil.showError(response, 1);
      }
    } finally {
      setLoading(false);
    }
  },[])

  const saveQuestionItemNext = useCallback(async (params: any,callback?:any)=>{
    try {
      setLoading(true);
      const response: any = await assetsManageService.saveQuestionNext(params);
      if (httpUtil.checkSuccess(response, 1)) {
        callback?.()
      } else {
        httpUtil.showError(response, 1);
      }
    } finally {
      setLoading(false);
    }
  },[])

  const saveQuestionItemFinal = useCallback(async (params: any,callback?:any)=>{
    try {
      setLoading(true);
      const response: any = await assetsManageService.saveQuestionFinal(params);
      if (httpUtil.checkSuccess(response, 1)) {
        callback?.()
      } else {
        httpUtil.showError(response, 1);
      }
    } finally {
      setLoading(false);
    }
  },[])

  return { saveQuestionItem, loading,saveQuestionItemNext,saveQuestionItemFinal };
};

export const useGetProcessDetail = (props: {processId: string}) => {
  const {processId} = props;
  const [detail, setDetail] = useState<any>(null);
  const [loading, setLoading] = useState<boolean>(false);

  useEffect(() => {
    
    if(processId)
      fetchData();
  }, [processId]);

  const fetchData = async () => {
    try {
      setLoading(true);
      const response: any = await assetsManageService.getProcessDetail({processId});
      if (httpUtil.checkSuccess(response, 1)) {
        setDetail(response.data);
      } else {
        httpUtil.showError(response, 1);
      }
    } finally {
      setLoading(false);
    }
  };

  const reload=useCallback(()=>{
    if(processId)
      fetchData();
  },[])

  return { detail, detalLoading:loading,reload };
};