
import { useState,  useEffect } from 'react';

import Request, {YWRequestConfig} from '@ywfe/request';
// @ts-ignore
import * as querystring from 'querystring';
// @ts-ignore
import { ParsedUrlQueryInput } from 'querystring';
// @ts-ignore
import * as R from 'ramda';
import {configs} from './config';


  const projectId = "PROGOODS";
  let env;
  if(typeof window === 'undefined'){
    env = (process.env.REACT_APP_ENV === 'prod' ? 'prod': process.env.REACT_APP_ENV) || 'prod';
  } else {
    env = window.localStorage.getItem('env') || (process.env.REACT_APP_ENV === 'prod' ? 'prod': process.env.REACT_APP_ENV) || 'prod';
  }
  
  const basePath = configs[projectId] ? configs[projectId][env].API_BASE_URL + `${env === 'mock' ? '/' + 85 : ''}` : '';
  const loginPath = configs['AUTH'] ? configs['AUTH'][env].APPLICATION_URL : '';
  

  

// @ts-ignore




export interface AreaListInput {
  
    
      /** 查询类型 1:省 2:市 3:区 4:街道 */
      type: string;
    
  
    
      /** 编号 type为1时可不传，其余传上级编号 */
      code?: string;
    
  
}

export interface AreaListData {
  
}


const reduceParams = (data: R.Dictionary<AreaListInput>) => {
  if(data instanceof FormData){
    return data;
  }
  const result = R.filter(item => !R.isNil(item) && !R.isEmpty(item))(data) || {};
  return result as unknown as AreaListInput;
}


// 10365 省市区街道四级联动

  export const useGetAreaList = () => {
    let isMount = true;
    const [isAreaListLoading, setIsAreaListLoading] = useState(false);
    const [dataAreaList, setDataAreaList] = useState<AreaListData>({} as AreaListData);
    const getAreaListData = async(inputs: AreaListInput, config?: YWRequestConfig): Promise<AreaListData> => {
      
        const params = reduceParams(inputs as unknown as R.Dictionary<AreaListInput>) || {};
      
      if(isMount){
        setIsAreaListLoading(true);
      }
      
      try{
        
          
          const res: any = await Request.get<AreaListData>(`${basePath}/area/list?${querystring.stringify(params as unknown as ParsedUrlQueryInput)}`, {
            loginHost: loginPath,
            ...config
          });
          
          
          
          if(isMount){
            setDataAreaList(res || {});
            setIsAreaListLoading(false);
          }
          return res;
      } catch(error){
        console.log(error);
        if(isMount){
          setIsAreaListLoading(false);
        }
        return false as unknown as AreaListData;
      }
      
    }

    useEffect(() => {
      return () => {
        isMount = false;
      };
    }, []);
  
    return {
      isAreaListLoading,
      dataAreaList,
      getAreaListData,
    }
  }

