import React, { useEffect, useState } from 'react';
import { View, Text } from '@tarojs/components';
import classNames from 'classnames';
import { CompDefault, MetaProps } from '../data-channel';
import connect from '../connect';
import fetchMock from '../../common/fetch-mock';

export interface Props extends MetaProps {
  // 列表数据地址
  url?: string;
  // 选中的项
  selects?: any[];
  // 数据输出事件
  onChange?: Function;
}

export interface State {
  // 可选元素
  items: any[];
}

const defaultValue: CompDefault<Props, State> = {
  props: {
    url: 'fetch-mock/list',
    selects: [],
    onChange: (_value) => {},
  },
  state: {
    items: [],
  },
  meta: {
    nameInfo: {
      nameKey: 'items',
      itemKeyMap: { id: 'id', name: 'title' },
    },
    output: { type: 'single' },
    __mergeCb: (props, meta) => {
      const key = props.filterKey;
      meta.output.key = key;
      if (key?.endsWith && key.endsWith('Ids')) {
        meta.nameInfo.nameKey = key.substr(0, key.length - 3) + 's';
      }
    },
    __nameCb: (name, nameInfo) => {
      const { nameKey, itemKeyMap } = nameInfo;
      // 1.对外暴露的回调 todo
      // 2.内部的处理逻辑
      if (name === 'items') {
        return nameKey;
      }
      if (name === 'setItems') {
        return 'set' + nameKey[0].toUpperCase() + nameKey.substring(1);
      }
      if (name === 'dataList') {
        return nameKey.substring(0, nameKey.length - 1) + 'List';
      }
      // fixme 后期可以考虑替换item.id形式
      if (name === 'id') {
        return itemKeyMap.id;
      }
      if (name === 'title') {
        return itemKeyMap.name;
      }
      return name;
    },
  },
};

/**
 * 区块-可选择的重复块
 */
const BlockRepeatSelect: React.FC<Props> = ({
  selects,
  onChange,
  meta,
}) => {
  const [items, setItems] = useState(defaultValue.state.items);

  useEffect(() => {
    (async () => {
      const dataList = await fetchMock.fetchList('', {});
      setItems(dataList);
    })();
  }, []);

  return (
    <View className='wm-tabs-hub-block'>
      <View className='title-box'>
        <View className='title'>标题</View>
      </View>
      <View className='content-box'>
        {items.map((item) => {
          return (
            <View
              className={classNames(
                'item',
                selects.includes(item.id) && 'active',
              )}
              key={item.id}
              onClick={() => {
                onChange({
                  value: item.id,
                  meta: meta.output,
                });
              }}>
              <Text className='text'>{item.title}</Text>
            </View>
          );
        })}
      </View>
    </View>
  );
};

export default connect(BlockRepeatSelect, defaultValue);
