import React, { Component } from 'react';
import { TextareaItem, DatePicker, Button, Toast } from 'antd-mobile';
import { applyPublicCar, fetchCarCategory } from '../../api/index';
import styles from './style.css';
import { formatDate } from '../../utils/index';
import arrIcon from '../../components/Input/Select/images/select_icon@2x.png';
import offCheckIcon from '../../images/Check/radio_off_btn@2x.png';
import onCheckIcon from '../../images/Check/radio_on_btn@2x.png';
import UserInfoContext from '../../context/userinfo-context';

const CustomChildren = ({ extra, onClick, children }) => (
  <div onClick={onClick} className={styles.selectWrap}>
    <div className={extra === '请选择' ? '' : styles.selectValue}>
      {extra === '请选择' ? '年-月-日 时-分' : extra}
    </div>
  </div>
);

class PublicCarApply extends Component {
  constructor(props) {
    super(props);
    this.state = {
      department: props.userinfo.department,
      createDate: formatDate(new Date(), 'yyyy-MM-dd'),
      name: props.userinfo.name,
      categoryId: '',
      userCount: '',
      beginDate: '',
      endDate: '',
      lineDescription: '',
      showAllCategory: false,
      categoryList: [],
    };
  }
  componentDidMount() {
    fetchCarCategory().then(res => {
      this.setState({
        categoryList: res.data,
      });
    });
  }
  selectCategory = id => {
    const { showAllCategory } = this.state;
    if (!showAllCategory) {
      this.toggleCategoryOptions();
    } else {
      this.setState({
        categoryId: id,
        showAllCategory: false,
      });
    }
  };
  toggleCategoryOptions = () => {
    this.setState(({ showAllCategory }) => ({
      showAllCategory: !showAllCategory,
    }));
  };
  onChangeBeginDate = date => {
    const { endDate } = this.state;
    if (endDate && endDate.getTime() < date.getTime()) {
      this.setState({ beginDate: date, endDate: date });
    } else {
      this.setState({ beginDate: date });
    }
  };
  validateForm = () => {
    if (!this.state.categoryId) {
      Toast.fail('请选择用车类型');
      return false;
    }
    if (!this.state.userCount) {
      Toast.fail('请填写用车人数');
      return false;
    }
    if (!this.state.beginDate) {
      Toast.fail('请选择用车开始时间');
      return false;
    }
    if (!this.state.endDate) {
      Toast.fail('请选择用车结束时间');
      return false;
    }
    return true;
  };
  resetForm = () => {
    this.setState({
      createDate: formatDate(new Date(), 'yyyy-MM-dd'),
      categoryId: '',
      userCount: '',
      beginDate: '',
      endDate: '',
      lineDescription: '',
      showAllCategory: false,
    });
  };
  onSubmit = () => {
    if (!this.validateForm()) {
      return;
    }
    let categoryName = JSON.stringify(
      this.state.categoryList.map(i => ({
        id: i.id,
        name: i.name,
        checked: i.id === this.state.categoryId,
      }))
    );
    const entity = {
      department: this.state.department,
      name: this.state.name,
      categoryName: categoryName,
      beginDate: formatDate(this.state.beginDate, 'yyyy-MM-dd hh:mm:ss'),
      endDate: formatDate(this.state.endDate, 'yyyy-MM-dd hh:mm:ss'),
      lineDescription: this.state.lineDescription,
      userCount: this.state.userCount,
    };
    applyPublicCar(entity)
      .then(res => {
        console.log('res: ' + res);
        const { history } = this.props;
        this.resetForm();
        Toast.success(res.msg);
        history.replace('/publicCar/PublicCarList');
      })
      .catch(err => {
        console.log('err: ' + err);
        Toast.fail(err.msg || '提交失败！');
      });
  };
  render() {
    const {
      name,
      department,
      createDate,
      categoryList,
      categoryId,
      lineDescription,
      showAllCategory,
    } = this.state;
    return (
      <div className={styles.bg}>
        <div className={styles.content}>
          <div className={styles.listItem}>
            <div className={styles.itemLabel}>用车部门</div>
            <div className={styles.itemValue}>{department}</div>
          </div>
          <div className={styles.listItem}>
            <div className={styles.itemLabel}>申请时间</div>
            <div className={styles.itemValue}>{createDate}</div>
          </div>
          <div className={styles.listItem}>
            <div className={styles.itemLabel}>申请人</div>
            <div className={styles.itemValue}>{name}</div>
          </div>
          <div className={styles.listItemAutoHeight}>
            <div className={styles.itemLabel}>用车类型</div>
            <div className={styles.itemValue}>
              {categoryId ? null : (
                <div
                  className={styles.selectInput}
                  onClick={this.toggleCategoryOptions}
                >
                  请选择
                  <span className={styles.arrow}>
                    <img src={arrIcon} alt="" />
                  </span>
                </div>
              )}
              {showAllCategory
                ? categoryList.map(i => (
                    <div
                      key={i.id}
                      className={styles.optionItem}
                      onClick={() => this.selectCategory(i.id)}
                    >
                      <div className={styles.radioLabel}>
                        {i.id === categoryId ? (
                          <img src={onCheckIcon} alt="" />
                        ) : (
                          <img src={offCheckIcon} alt="" />
                        )}
                      </div>
                      <div className={styles.radioValue}>{i.name}</div>
                    </div>
                  ))
                : categoryList.map(
                    i =>
                      categoryId === i.id ? (
                        <div
                          key={i.id}
                          className={styles.optionItem}
                          onClick={() => this.selectCategory(i.id)}
                        >
                          <div className={styles.radioLabel}>
                            {i.id === categoryId ? (
                              <img src={onCheckIcon} alt="" />
                            ) : (
                              <img src={offCheckIcon} alt="" />
                            )}
                          </div>
                          <div className={styles.radioValue}>{i.name}</div>
                        </div>
                      ) : null
                  )}
            </div>
          </div>
          <div className={styles.listItem}>
            <div className={styles.itemLabel}>用车人数</div>
            <div className={styles.itemValue}>
              <input
                className={styles.itemInput}
                type="tel"
                maxLength="5"
                value={this.state.userCount}
                onChange={e =>
                  this.setState({
                    userCount: e.target.value.replace(/\D/g, ''),
                  })
                }
              />
            </div>
          </div>
          <div className={styles.listItem}>
            <div className={styles.itemLabel}>用车开始时间</div>
            <div className={styles.itemSelect}>
              <DatePicker
                value={this.state.beginDate}
                onChange={this.onChangeBeginDate}
                minDate={new Date()}
              >
                <CustomChildren className={styles.DateInnerWrap} />
              </DatePicker>
            </div>
          </div>
          <div className={styles.listItem}>
            <div className={styles.itemLabel}>用车结束时间</div>
            <div className={styles.itemSelect}>
              <DatePicker
                value={this.state.endDate}
                onChange={date => this.setState({ endDate: date })}
                minDate={this.state.beginDate}
              >
                <CustomChildren className={styles.DateInnerWrap} />
              </DatePicker>
            </div>
          </div>
          <div className={styles.listItemAutoHeight}>
            <div className={styles.itemLabel}>用车详细线路</div>
            <div className={styles.itemValue}>
              <TextareaItem
                className={styles.textarea}
                placeholder="例：温江校区-富顺县-川大望江校区"
                rows={4}
                count={50}
                value={lineDescription}
                onChange={val =>
                  this.setState({ lineDescription: val.replace(/\n/, '') })
                }
              />
            </div>
          </div>
        </div>
        <Button className={styles.submitBtn} onClick={this.onSubmit}>
          提交
        </Button>
      </div>
    );
  }
}

export default props => (
  <UserInfoContext.Consumer>
    {({ userinfo }) => <PublicCarApply userinfo={userinfo} {...props} />}
  </UserInfoContext.Consumer>
);
