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

export interface Props extends MetaProps {
  // 标签
  label: string;
  // 是否必填
  require?: boolean;
  // 数据输出回调
  onChange?: (value: any) => void;
}

export interface State {
  // 开关
  checked: boolean;
}

const defaultValue: CompDefault<Props, State> = {
  props: {
    label: '',
    onChange: (_value) => {},
  },
  state: {
    checked: false,
  },
  meta: {
    compName: 'inline',
    output: { tags: ['form-item'] },
    __mergeCb: (props, meta) => {
      meta.output.key = props.formKey;
    },
  },
};

/**
 * 表单项-开关
 */
const FormItemSwitch: React.FC<Props> = ({
  label,
  onChange = () => {},
  meta,
}) => {
  const [checked, setChecked] = useState<boolean>(defaultValue.state.checked);
  return (
    <View className='wm-tpl-form-item'>
      <View className='area-box'>
        <Text className='label'>{label}</Text>
        <Switch
          checked={checked}
          onChange={() => {
            setChecked(!checked);
            onChange({
              value: checked,
              meta: meta?.output,
            });
          }}
        />
      </View>
    </View>
  );
};

export default connect(FormItemSwitch, defaultValue);
