import { useState, useEffect } from 'react'
import { Image } from '@tarojs/components'
import './index.scss'

export default function FilterForCityArea (props) {

  const { change = () => { }, Cancel = () => { }, defaultValue = [], List = [] } = props
  const [PageList, setPageList] = useState([])

  useEffect(() => {
    if (List.length) {
      let Arr = List.map((item) => { return { ...item, Selected: false } })
      if (defaultValue.length) {
        defaultValue.map((item) => {
          Arr.map((subItem) => {
            if (item === subItem.id) {
              subItem.Selected = true
            }
          })
        })
      } else {
        Arr[0].Selected = true
      }
      setPageList(Arr)
    }
  }, [List])

  const CutArea = (item, index) => {
    return () => {
      let Arr = [...PageList]
      if (item.id === '-') {
        if (!item.Selected) {
          Arr.map((aItem) => { if (aItem.id !== '-') aItem.Selected = false })
          Arr[index].Selected = !item.Selected
        }
      } else {
        if (item.Selected) { // 取消单个勾选
          let Bool = false
          Arr.map((aItem) => { if (aItem.Selected && aItem.id !== '-' && item.id !== aItem.id) Bool = true})
          if (!Bool) Arr[0].Selected = true
          Arr[index].Selected = !item.Selected
        } else { // 单个勾选
          Arr[index].Selected = !item.Selected
          let Bool = false
          Arr.map((aItem) => { if (!aItem.Selected && aItem.id !== '-') Bool = true })
          if (!Bool) {
            Arr.map((aItem) => { if (aItem.id !== '-') aItem.Selected = false })
            Arr[0].Selected = true
          } else {
            Arr[0].Selected = false
          }
        }
      }
      setPageList(Arr)
    }
  }

  const Sure = () => {
    let Arr = []
    PageList.map((item) => { if (item.Selected && item.id !== '-') Arr.push(item.id) })
    change({ name: 'buildingArea', value: Arr })
  }

  return (
    <view className='components FilterForCityArea'>
      {
        PageList.map((item, index) => (
          <view className='ListItem' key={`ListItem${index}`} onClick={CutArea(item, index)}>
            <view>
              <view>
                <text>{item.name}</text>
                <Image className={item.Selected ? 'active' : ''} mode='heightFix' src={require('@/assets/findHouse-icon1.png')}></Image>
              </view>
            </view>
          </view>
        ))
      }
      <view className='Btn flex-h'>
        <view className='flex-item'>
          <text onClick={Cancel}>取消</text>
        </view>
        <view className='flex-item'>
          <text onClick={Sure}>保存</text>
        </view>
      </view>
    </view>
  )
}
