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

export interface Props extends MetaProps {
  // tabs数据列表
  items?: any[];
  // 数据输出通道
  onChange: Function;
}

export interface State {
  // 当前项id
  current: number | string;
}

const defaultValue: CompDefault<Props, State> = {
  props: {
    items: [
      { key: '', name: '全部' },
      { key: 'WAIT', name: '待发货' },
      { key: 'RECEIVE', name: '待收货' },
      { key: 'COMPLETED', name: '已完成' },
      { key: 'VOID', name: '已作废' },
    ],
    onChange: (_value) => {},
  },
  state: {
    current: 0,
  },
  meta: {
    inputs: [{ key: 'items', keyMap: { id: 'key', name: 'name' } }],
    output: { tags: ['search-item'] },
  },
};

/**
 * 普通tabs
 */
const TabsCommon: React.FC<Props> = ({ items, onChange, meta }) => {
  const [current, setCurrent] = useState(defaultValue.state.current);
  return (
    <View className='wm-tpl-tabs'>
      <ScrollView>
        <View className='container space-between'>
          {items &&
            items.map((item) => {
              const keyMap = meta.inputs[0].keyMap;
              const id = item[keyMap.id];
              const active = current === id || (current === 0 && !item.key);
              return (
                <View
                  key={id}
                  className={classNames('tab', active && 'active')}
                  onClick={() => {
                    setCurrent(id);
                    onChange({
                      value: id,
                      meta: meta?.output,
                    });
                  }}>
                  <Text className='text'>{item[keyMap.name]}</Text>
                  {active && <View className='line'></View>}
                </View>
              );
            })}
        </View>
      </ScrollView>
    </View>
  );
};

export default connect(TabsCommon, defaultValue);
