import React, { Component } from "react";
import { AtFloatLayout, AtCheckbox, AtButton } from "taro-ui";

import 'taro-ui/dist/style/components/float-layout.scss';
import 'taro-ui/dist/style/components/checkbox.scss';
import 'taro-ui/dist/style/components/button.scss';
import './index.less';


class CheckboxPicker extends Component {
  constructor(props) {
    super(props);
    this.state = {
        checkboxOption: props.options || [],
        checkedList: []
    }

    this.handleClose = this.handleClose.bind(this);
    this.handleChange = this.handleChange.bind(this);
    this.handleConfirm = this.handleConfirm.bind(this);
  }

  componentDidUpdate(prevProps) {
      if (JSON.stringify(this.props.options) != JSON.stringify(prevProps.options)) {
        this.setState({ checkboxOption: this.props.options });
      }

      if (JSON.stringify(this.props.checkedList) != JSON.stringify(prevProps.checkedList)) {
          this.setState({ checkedList: this.props.checkedList });
      }
  }

  handleClose() {
    this.setState({ checkedList: [] });
    this.props.onClose();
  }

  handleChange(e) {
    this.setState({ checkedList: e });
  }

  handleConfirm() {
    
    const labelArr = [];
    const { checkedList, checkboxOption } = this.state;
    checkedList.map(checkedItem => {
        checkboxOption.map(optionItem => {
            if (checkedItem == optionItem.id) {
                labelArr.push(optionItem.title);
            }
        })
    })
    this.props.onConfirm(checkedList, labelArr);
    this.handleClose();
  }

  render() {
    const { checkboxOption, checkedList } = this.state;
    const newOptions = checkboxOption.filter(item => !!item.id);
    const checkboxOptions = newOptions.map(item => {
        return { label: item.title, value: item.id }
    })
    return (
        <AtFloatLayout isOpened={this.props.isOpened} title={this.props.title} scrollY onClose={this.handleClose}>
            <view style={{ paddingBottom: '90rpx'}}>
                <AtCheckbox
                    options={checkboxOptions}
                    selectedList={checkedList}
                    onChange={this.handleChange}
                />

                <view className='operate-btn' style={{position: 'fixed', left: 0, right: 0, bottom: 0, height: '90rpx', background: '#fff'}}>
                    <AtButton type='primary' size='normal' onClick={this.handleConfirm}>确定</AtButton>
                </view>
            </view>
        </AtFloatLayout>
    )
  }
}

export default CheckboxPicker;
