import React, { useState, useEffect } from 'react';
import { Form, Button, Radio, Icon } from 'antd';
import HouseGrid from './HouseGrid';
import { fetch, apis } from '../../../../../utils/request'
import HelpDoc from './HelpDoc';

const getHouseList = fetch(apis.house.listHouseResources)

function groupHouseList(houseList = []) {
  // 先按照楼层分组
  const floorList = houseList.reduce((list, room) => {
    let found = false

    list.forEach((floor) => {
      if (floor.floorId === room.floorId) {
        found = true
        floor.roomList.push(room)
      }
    })
    
    if (!found) {
      list.push({ ...room, roomList: [ room ]})
    }

    return list
  }, [])

  // 再按照单元分组
  const unitList = floorList.reduce((list, floor) => {
    let found = false
    list.forEach((unit) => {
      if (unit.unitId === floor.unitId) {
        found = true
        unit.floorList.push(floor)
      }
    })
    
    if (!found) {
      list.push({ ...floor, floorList: [ floor ]})
    }

    return list
  }, [])

  // 最后按照楼栋分组
  return unitList.reduce((list, unit) => {
    let found = false
    list.forEach((block) => {
      if (block.blockId === unit.blockId) {
        found = true
        block.unitList.push(unit)
      }
    })
    
    if (!found) {
      list.push({ ...unit, unitList: [ unit ]})
    }

    return list
  }, [])
}

const PreselectionImg = props => {
  const salesBatchId = props.salesBatchId
  const [hotType, setHotType] = useState(2)
  const [blockList, setBlockList] = useState([])
  const [showHelp, setShowHelp] = useState(false)

  useEffect(() => {
    if (salesBatchId) {
      getHouseList({ params: { salesBatchId } }).then(res => {
        const groupedData = groupHouseList(res)
        setBlockList(groupedData)
      })
    }
  }, [salesBatchId])

  return (
    <div>
      <Form layout="inline">
        <Form.Item label="热度选择">
          <Radio.Group onChange={e => setHotType(e.target.value)} value={hotType}>
            <Radio value={1}>基础热度</Radio>
            <Radio value={2}>实际热度</Radio>
            <Radio value={3}>显示热度</Radio>
            <Icon type="question-circle" theme="filled" style={{ fontSize: '18px', color: '#F00' }} onClick={() => setShowHelp(true)} />
          </Radio.Group>
        </Form.Item>
        <div>基础热度即预设的预选数量，实际并不存在用户预选，用来美化数据。实际热度即真实用户预选数量，基础热度+实际热度=显示热度</div>
      </Form>
      <HouseGrid dataset={blockList} hotType={hotType} />
      <HelpDoc visible={showHelp} onCancel={() => setShowHelp(false)} />
    </div>
  )
}

export default PreselectionImg
