import { useState, useEffect } from 'react'
import '@/assets/css/iconfont.css'
import { Image, Slider, Textarea, ScrollView } from '@tarojs/components'
import { fetch } from '@/utils/request'
import { API_HELP_FIND_HOUSE_SUBMIT } from '@/constants/api'
import { useSelector } from 'react-redux'
import './index.scss'
import questions from './formData'
import SubmitBuyHouseResult from '../helpToFindHouse/components/SubmitBuyHouseResult/index'

export default function AddedValueService () {

  const user = useSelector(state => state.user)
  const [FormData, setFormData] = useState(questions)

  const [StepId, setStepId] = useState(1)
  const [StepRange, setStepRange] = useState([0, 3])
  const [ResultList, setResultList] = useState([])
  const [ShowPopup, setShowPopup] = useState(false)

  useEffect(() => {
    if (StepId === 1) {
      setStepRange([0, 3])
    } else if (StepId === 2) {
      setStepRange([3, 6])
    } else if (StepId === 3) {
      setStepRange([6, 8])
    } else if (StepId === 4) {
      setStepRange([8, 9])
    }
  }, [StepId])

  const SubmitForm = (data) => {
    data = data || []
    let params = []
    data.map((item) => {
      if (item.key === 'budget') {
        params.push({ ...item, key: 'minPrice', result: item.options[0] * 10000 })
        params.push({ ...item, key: 'maxPrice', result: item.result !== '' ? item.result * 10000 : 5000000 })
      } else {
        if (item.result !== '' || item.resultId !== null) {
          params.push(item)
        }
      }
    })
    params.push({ question: '创建人小程序人员', result: user?.userInfo?.person?.personId, key: 'personId' })
    let payload = {}
    params.map((item) => {
      payload[item.key] = item.result || item.resultId
    })
    fetch({ url: API_HELP_FIND_HOUSE_SUBMIT, method: 'post', payload: { ...payload, questionnaire: JSON.stringify(params), type: 4 } }).then((res) => {
      setResultList(res.taBuildingList || [])
      setShowPopup(true)
    })
  }

  const CutCheckboxs = (index, subItem, subIndex) => {
    return () => {
      let newFormData = [...FormData]
      newFormData[index].options[subIndex].selected = !subItem.selected
      setFormData([...newFormData])
    }
  }

  const CutCheckbox = (item, index) => {
    return () => {
      let newFormData = [...FormData]
      newFormData[index].resultId = item.id
      newFormData[index].result = item.name
      setFormData([...newFormData])
    }
  }

  const Rangehange = (e, index) => {
    let newFormData = [...FormData]
    newFormData[index].result = e.detail.value
    setFormData([...newFormData])
  }

  const remarkInput = (e, index) => {
    let newFormData = [...FormData]
    newFormData[index].remark = e.detail.value
    setFormData([...newFormData])
  }

  const textareaInput = (e, index) => {
    let newFormData = [...FormData]
    newFormData[index].result = e.detail.value
    setFormData([...newFormData])
  }

  const NextStep = () => {
    if (StepId < 4) {
      setStepId(StepId + 1)
    } else {
      let Arr = [...FormData]
      Arr.map((item) => {
        if (item.type === 'checkboxs') {
          item.options.map((subItem) => {
            if (subItem.selected) {
              item.result.push(subItem.name)
            }
          })
        }
      })
      SubmitForm(Arr)
    }
  }

  const PrevStep = () => {
    if (StepId > 1) {
      setStepId(StepId - 1)
    }
  }

  return (
    <view className='components AddedValueService'>
      {
        ShowPopup &&
        <SubmitBuyHouseResult List={ResultList.slice(0, 1)} ShowResult={false}></SubmitBuyHouseResult>
      }
      <ScrollView scroll-y>
        <view className='PageContent'>
          {
            FormData.map((item, index) => (
              <view className='Step' key={`Form-${index}`}>
                {
                  index >= StepRange[0] && index < StepRange[1] &&
                  <view>
                    <text>{item.question}</text>
                    {
                      item.type === 'checkboxs' &&
                      <view className='CheckList'>
                        {
                          item.options.map((subItem, subIndex) => (
                            <view key={`${item.key}-${subIndex}`} className={subItem.selected ? 'active' : ''} onClick={CutCheckboxs(index, subItem, subIndex)}>
                              <text>{subItem.name}</text>
                              <Image mode='heightFix' src={require('@/assets/findHouse-icon1.png')}></Image>
                            </view>
                          ))
                        }
                      </view>
                    }
                    {
                      item.type === 'checkbox' &&
                      <view className='CheckList'>
                        {
                          item.options.map((subItem, subIndex) => (
                            <view key={`${item.key}-${subIndex}`} className={item.resultId === subItem.id ? 'active' : ''} onClick={CutCheckbox(subItem, index)}>
                              <text>{subItem.name}</text>
                              <Image mode='heightFix' src={require('@/assets/findHouse-icon1.png')}></Image>
                            </view>
                          ))
                        }
                      </view>
                    }
                    {
                      item.type === 'checkbox' && item.remark !== undefined &&
                      <view className='Textarea'>
                        <Textarea placeholder='请说出您的其他需求，让我们更好的为您服务！' onInput={(e) => { remarkInput(e, index) }} />
                      </view>
                    }
                    {
                      item.type === 'range' &&
                      <view className='RangeList flex-h'>
                        <view className='flex-item'>
                          <Slider activeColor='#193C83' block-color='#fff' onChange={(e) => { Rangehange(e, index) }} min={item.options[0]} max={item.options[1]} show-value />
                        </view>
                        <text>万</text>
                      </view>
                    }
                    {
                      item.type === 'textarea' &&
                      <view className='Textarea'>
                        <Textarea placeholder='请说出您的其他需求，让我们更好的为您服务！' onInput={(e) => { textareaInput(e, index) }} />
                      </view>
                    }
                  </view>
                }
              </view>
            ))
          }

          <view className='Btn'>
            <text className='active' onClick={NextStep}>下一步</text>
            <text onClick={PrevStep}>返回</text>
          </view>
        </view>
      </ScrollView>
    </view>
  )
}
