import { useState, useEffect } from 'react';
import Taro from '@tarojs/taro';
import withLayout from '@/layout';
import { ScrollView, View, Block, Image } from '@tarojs/components';
import { queryBrandList } from '@/services/common';
import { getImgURL } from '@/utils/image';
import '@/assets/css/iconfont.css';
import './index.scss';

export default withLayout((props) => {
  const { city } = props

  const [list, setList] = useState({});

  useEffect(() => {
    if (city?.id) {
      initData()
    }
  }, [city?.id])

  function initData () {
    queryBrandList({ cityId: city?.id }).then((res) => {
      const { records, data } = res
      const lst = (data || records || []).reduce((prev, cur) => {
        if (prev[cur.indexLetter]) {
          prev[cur.indexLetter].push(cur)
        } else {
          prev[cur.indexLetter] = [cur]
        }
        return prev
      }, {})

      setList(lst)
    })
  }

  function handleSelected (item) {
    Taro.navigateTo({
      url: `/pages/index/brandDetail/index?id=${item.brandId}`,
    })
  }

  const keys = Object.keys(list)
  return (
    <View className='brandList'>
      <ScrollView
        style={{
          height: '100vh',
        }}
        scrollY
      >

        <View className='city-list'>
          {
            keys.map((key) => (
              <Block key={key}>
                <View className='city-initial'>{key}</View>
                {list[key].map((item) => (
                  <View key={item.brandId} className='city-item' onClick={() => handleSelected(item)}>
                    <view>
                      <Image mode='scaleToFill' src={getImgURL(item.brandLogo)}></Image>
                    </view>
                    <text>{item.brandName}</text>
                  </View>
                ))}
              </Block>
            ))
          }
        </View>
      </ScrollView>
    </View>
  );
});
