import {
  useGetDesktopHomeCommonFunctionList,
  usePostDesktopHomeCommonFunctionSort,
  usePostDesktopHomeCommonFunctionDelete,
  useGetDesktopHomeCommonEntryTree,
  usePostDesktopHomeCommonFunctionAdd,
} from '@/generated/api';
import {useDesktopStore} from './useDesktopStore';


export const useDesktop = () => {
  const [state, dispatch] = useDesktopStore();
  const {getDesktopHomeCommonFunctionListData} = useGetDesktopHomeCommonFunctionList();
  const {postDesktopHomeCommonFunctionSortData} = usePostDesktopHomeCommonFunctionSort();
  const {postDesktopHomeCommonFunctionDeleteData} = usePostDesktopHomeCommonFunctionDelete();
  const {getDesktopHomeCommonEntryTreeData} = useGetDesktopHomeCommonEntryTree();
  const {postDesktopHomeCommonFunctionAddData} = usePostDesktopHomeCommonFunctionAdd();

  const initFunctions = async () => {
    const res = await getDesktopHomeCommonFunctionListData();
    if(res){
      dispatch({
        type: 'init_functions',
        payload: {
          data: res.list
        }
      })
    }
    
    return res.list || [];
  }

  const dragFunctions = async (resourceIdList: string[], functions: any[]) => {
    const res = await postDesktopHomeCommonFunctionSortData({resourceIdList});
    console.log('dragFunctions', res);
    if(res){
      dispatch({
        type: 'drag_functions',
        payload: {
          data: functions
        }
      })
    }
    return res;
  }
  
  const delectFunction = async (resourceId: string) => {
    const res = await postDesktopHomeCommonFunctionDeleteData({resourceIdList: [resourceId]});
    if(res){
      dispatch({
        type: 'delete_function',
        payload: {
          data: resourceId
        }
      })
    }
    return res;
  }

  const addFunctions = async (resourceIdList: string[]) => {
    const res = await postDesktopHomeCommonFunctionAddData({resourceIdList});
    if(res){
      initFunctions()
    }
    return res;
  }

  const initMenus = async () => {
    const res = await getDesktopHomeCommonEntryTreeData();
    if(res && res.list){
      dispatch({
        type: 'init_menus',
        payload: {
          data: res.list
        }
      })
    }
    return res && res.list ? res.list : [];
  }

  const toggleSelected = (selected: string[]) => {
    dispatch({
      type: 'toggle_selected',
      payload: {
        data: selected
      }
    })
  }
  
  
  return {
    initMenus,
    initFunctions,
    delectFunction,
    toggleSelected,
    addFunctions,
    dragFunctions
  };
};
