/**
 * 移动端复选框封装
 */
import React, { Component } from 'react'
import { Checkbox, Flex } from 'antd-mobile';
const AgreeItem = Checkbox.AgreeItem;
export default class CheckBox extends Component {
    constructor(props){
        super(props)
        const value = props.value || {};
        this.state = {
            list:!!value.list?value.list:[]
        }
    }
    triggerChange = (changedValue) => {
        // Should provide an event to pass value to Form.
        const onChange = this.props.onChange;
            if (onChange) {
                this.setState({
                    list:changedValue.list
                })
                // 传入数据源错误导致web端和移动端冲突修改为以下传入
                onChange(changedValue.list);
        }
    }
    componentWillReceiveProps(nextProps) {
        // Should be a controlled component.
        if ('value' in nextProps) {
            const value = nextProps.value;
            this.setState(value);
        }
    }
    handelChange = (value) => {
        let { list } = this.state
        if(list.includes(value)){
            // if (!('value' in this.props)) {
                this.triggerChange({list:this.state.list.filter(item=>item!==value)});
            // }
        }else {
            // if (!('value' in this.props)) {
                this.triggerChange({list:[...list,value]});
            // }
        }
    }
    /**
     * 是否默认选中
     */
    getChecked = (value) => {
        let isArray = Array.isArray
        if(this.props.value){
                if(isArray( this.props.value )){
                    let list = this.props.value
                    return !!list?list.includes(value):false
                } else {
                    let { list } = this.props.value
                    return !!list?list.includes(value):false
                }
        }
    }
    render() {
        let { options,initValue } = this.props
        return (
            <div>
                {
                    options.map((item,index) => {
                        return (
                            <Flex.Item>
                                <AgreeItem key={index} defaultChecked={this.getChecked(item.value)}  onChange={()=>{this.handelChange(item.value)}}>
                                    {item.label}
                                </AgreeItem>
                            </Flex.Item>
                        )
                    })
                }
            </div>
        )
    }
}
