import React, { useEffect, useState } from 'react';
import { View, ScrollView } from '@tarojs/components';
import fetchMock from '../../common/fetch-mock';
import useRefState from '../../common/hooks/use-ref-state';
import { bindOnChange, CompDefault, MetaProps } from '../data-channel';
import connect from '../connect';

export interface Props extends MetaProps {
  // 列表项
  listItem: JSX.Element;
  // 列表筛选条件
  filters: JSX.Element[];
  // todo 这个字段要优化
  showType?: string;
  // todo 这个字段要优化
  orientation?: string;
}

export interface State {
  // 页面状态
  pageFlag: 'loading' | 'loaded' | 'empty';
  // 查询条件
  params: { [key: string]: any };
  // 列表数据
  dataList: any[];
}

/**
 * 默认值
 */
const defaultValue: CompDefault<Props, State> = {
  props: {
    listItem: <View>我是一行</View>,
    filters: [],
    showType: 'small',
    orientation: 'vertical',
  },
  state: {
    pageFlag: 'loading', // 0:加载中 1:加载完毕 2:为空 fixme 还要优化 012可读性差
    params: {},
    dataList: [],
  },
  meta: {
    compName: 'pageList:分页列表',
    inputs: [{ key: 'filters', type: 'array', tags: ['jsx'] }],
  },
};

const ListPagination: React.FC<Props> = ({
  listItem,
  filters,
  showType,
  orientation,
}) => {
  const [pageFlag, setPageFlag] = useState(defaultValue.state.pageFlag);
  const [params, setParams] = useState(defaultValue.state.params);
  const [dataList, dataListRef, setDataList] = useRefState(
    defaultValue.state.dataList,
  );

  useEffect(() => {
    (async () => {
      qryDataList();
    })();
  }, []);

  // @ts-ignore
  const qryDataList = async () => {
    setPageFlag('loading');
    const result = (await fetchMock.fetchPageList('xxxx', params)) as any;
    setDataList(dataListRef.current.concat(result.dataList));
    if (result.dataList.length === 0) {
      setPageFlag('empty');
    } else {
      setPageFlag('loaded');
    }
  };

  const onChangeParam = (key, value) => {
    if (key) {
      params[key] = value;
      setParams(params);
    } else {
      setParams({ ...value });
    }
    setDataList([]);
    qryDataList();
  };

  filters = filters.map((item) => {
    bindOnChange(item, ({ value, meta }) => {
      if (meta?.tags.includes('search-item')) {
        if (meta.type === 'combine') {
          Object.keys(value).forEach((key) => {
            onChangeParam(key, value[key]);
          });
        } else {
          onChangeParam(meta.key, value);
        }
      }
    });
    return item;
  });

  //判断一列还是两列，再判断垂直还是水平
  let listItemStyle = showType === 'small' ? 'listSmallItem' : 'listBigItem';
  let listStyle = showType === 'small' ? 'listSmall' : 'listBig';
  if (orientation === 'horizontal') {
    listItemStyle = 'listHorizontalItem';
  }

  return (
    <View className='wm-list'>
      {filters}
      <ScrollView
        className={listStyle}
        scrollY={orientation === 'vertical'}
        scrollX={orientation === 'horizontal'}
        onScrollToLower={() => qryDataList()}>
        <View className={listItemStyle}>
          {dataList.map((item) => {
            return listItem;
          })}
        </View>
        {orientation === 'vertical' && (
          <View>
            {pageFlag === 'loading' && (
              <View className='tip'>玩命加载中...</View>
            )}
            {pageFlag === 'empty' && <View className='tip'>列表为空</View>}
            {pageFlag === 'loaded' && (
              <View className='tip'>我是有底线的...</View>
            )}
          </View>
        )}
      </ScrollView>
    </View>
  );
};

export default connect(ListPagination, defaultValue);
