import React, { useState, useEffect } from 'react'
import { fetch, apis } from '@/utils/request'

const fetchPhaseList = fetch(apis.buildingOwnerInfo.getPhaseList)
const fetchBuildingList = fetch(apis.buildingOwnerInfo.getBuildingList)
const fetchUnitList = fetch(apis.buildingOwnerInfo.getUnitList)
const fetchLevelList = fetch(apis.buildingOwnerInfo.getLevelList)
const fetchRoomNoList = fetch(apis.buildingOwnerInfo.getRoomNoList)

export default function useRoomSelect() {
  const [phaseList, setPhaseList] = useState([])
  const [buildingList, setBuildingList] = useState([])
  const [unitList, setUnitList] = useState([])
  const [levelList, setLevelList] = useState([])
  const [roomNoList, setRoomNoList] = useState([])

  const [phaseId, setPhaseId] = useState()
  const [buildingId, setBuildingId] = useState()
  const [unitId, setUnitId] = useState()
  const [levelId, setLevelId] = useState()
  const [roomNoId, setRoomNoId] = useState()

  // 获取期
  useEffect(() => {
    fetchPhaseList().then(res => setPhaseList(res))
  }, [])

  // 楼栋
  useEffect(() => {
    if (phaseId) {
      fetchBuildingList({params: {phaseId}}).then(res => setBuildingList(res))
    }
    setBuildingId()
  }, [phaseId])

  // 单元
  useEffect(() => {
    if (phaseId && buildingId) {
      fetchUnitList({params: {phaseId, buildingId}}).then(res => setUnitList(res))
    }
    setUnitId()
  }, [phaseId, buildingId])

  // 楼层
  useEffect(() => {
    if (phaseId && buildingId && unitId) {
      fetchLevelList({params: {phaseId, buildingId, unitId}}).then(res => setLevelList(res))
    }
    setLevelId()
  }, [phaseId, buildingId, unitId])

  // 房号
  useEffect(() => {
    if (phaseId && buildingId && unitId && levelId) {
      fetchRoomNoList({params: {phaseId, buildingId, unitId, levelId}}).then(res => setRoomNoList(res))
    }
    setRoomNoId()
  }, [phaseId, buildingId, unitId, levelId])

  return {
    phaseId,
    setPhaseId,
    buildingId,
    setBuildingId,
    unitId,
    setUnitId,
    levelId,
    setLevelId,
    roomNoId,
    setRoomNoId,
    phaseList,
    buildingList,
    unitList,
    levelList,
    roomNoList
  }
}
