import React, { useState } from 'react';
import Taro from '@tarojs/taro';
import { ScrollView, View } from '@tarojs/components';
import Button from '../../components/button';
import util from '../../common/util';
import { bindOnChange, CompDefault, MetaProps } from '../data-channel';
import connect from '../connect';

export interface Props extends MetaProps {
  // 表单块列表
  blocks: any[];
}

export interface State {
  // 表单内容（由内部组件提供）
  params: { [key: string]: string };
}

const defaultValue: CompDefault<Props, State> = {
  props: { blocks: [] },
  state: { params: {} },
  meta: {
    compName: 'form:表单',
    inputs: [{ key: 'blocks', type: 'array', tags: ['jsx'] }],
  },
};

/**
 * 页面-表单页
 */
const PageForm: React.FC<Props> = ({ blocks }) => {
  const [params, setParams] = useState(defaultValue.state.params);

  /**
   * 表单值改变回调
   */
  blocks = blocks.map((block) => {
    bindOnChange(block, ({ value, meta }) => {
      params[meta.key] = value;
      setParams(params);
    });
    return block;
  });

  /**
   * 表单提交回调
   */
  const onSubmit = () => {
    for (let i = 0; i < blocks.length; i++) {
      let block = blocks[i];
      if (
        block.info.require &&
        block.info.meta.output.tags?.includes('form-item') &&
        !params[block.info.meta.output.key]
      ) {
        Taro.showToast({
          title: '请输入' + block.info.label,
          icon: 'none',
          duration: 2000,
        });
        return;
      }
    }
    // todo：提交调用后台接口
  };

  return (
    <View className='wm-form-page'>
      <ScrollView scrollY className='scroll-view'>
        {blocks}
      </ScrollView>
      <View className='bottom'>
        <Button onClick={() => onSubmit()}>提交</Button>
      </View>
    </View>
  );
};

export default connect(PageForm, defaultValue);
