
import React, { useState, useEffect,useMemo} from 'react';
import {GET_USER_TYPE} from '@/services/user';

const bookCreater=options=>{
  const {
    service,
    idKey='value',
    titleKey='label',
    keyName='key',
    defaultTypes=null
  }=options;
  
  return (props)=>{
    const [types,setTypes]=useState(defaultTypes||null);

    const init=async ()=>{
      let ret = await service();
      if(+ret?.code===0){
        setTypes(ret.data||[]);
      }
    }
    useEffect(()=>{
      if(defaultTypes)return;
      init();
    },[]);

    const getData=({id,title,key}={})=>{
      let name='';
      if(id){
        name=idKey
      }
      else if(title){
        name=titleKey
      }
      else if(key){
        name=keyName;
      }

      for(let i=0;i<types.length;i++){
        if(''+types[i][name]===''+id){
          return types[i];
        }
      }
      return null;
    }

    const getTitle=(id)=>{
      if(types){
        for(let i=0;i<types.length;i++){
          if(''+types[i][idKey]===''+id){
            return types[i][titleKey];
          }
        }
      }
      return '';
    }
    const getId=(title)=>{
      if(types){
        for(let i=0;i<types.length;i++){
          if(''+types[i][titleKey]===''+title){
            return types[i][idKey];
          }
        }
      }
      return '';
    }

    const isReady=()=>{
      return types!==null;
    }
    const reload=()=>{
      if(defaultTypes)return;
      init();
    }
    const getList=()=>{
      let ret=[]
      for(let i=0;i<types.length;i++){
        let item = types[i];
        ret.push({
          label:item[titleKey],
          value:item[idKey],
          key:item[keyName]
        })
      }
      return ret;
    }
    

    return {types,getTitle,getId,isReady,reload,getData,getList}
  }
}

export const useUserType = bookCreater({
  service:GET_USER_TYPE,
})
export const useTaskState=bookCreater({
  defaultTypes:[
    {label:'进行中',value:'1',key:'run'},
    {label:'已完成',value:'5',key:'complete'},
  ]
});

