import React from 'react';
import './index.less';
import { DatePicker } from 'antd-mobile';
import Page from '@src/containers/Page';
import Assets from '@src/components/Assets';
import { formatDate } from '@src/services/Tools';
import { Textbook } from '../../../stores/textbook';

export default class extends Page {
  initState() {
    return {
      date: new Date(),
    };
  }

  initData() {
    Textbook.getInfo()
      .then(result => {
        this.setState(result);
      });
    this.refreshYear(this.state.date);
  }

  refreshYear(date) {
    this.setState({ date });
    Textbook.listYear(date.getFullYear())
      .then((list) => {
        const map = {};
        list.forEach((row) => {
          const d = new Date(row.startDate);
          const month = d.getMonth() + 1;
          if (!map[month]) {
            map[month] = [];
          }
          map[month].push(d.getDate());
        });
        const months = Object.keys(map).map(key => {
          return {
            value: key,
            list: map[key],
          };
        });
        this.setState({ months });
      });
  }

  renderView() {
    const { latest = {}, date, months = [] } = this.state;
    return (
      <div>
        <div className="title">最新换库</div>
        <div className="main">{latest.startDate ? formatDate(latest.startDate, 'YYYY年MM月DD日') : ''}</div>
        <div className="title">
          历史记录
          <div className="date">
            <DatePicker value={date} mode="year" onChange={value => {
              this.refreshYear(value);
            }}>
              <div>
                {date.getFullYear()}年
                <Assets name="down_down3" />
              </div>
            </DatePicker>
          </div>
        </div>
        <div className="list">
          {(months || []).map(month => {
            return <div className="item">
              <div className="d">{month.value}月</div>
              <div className="v">
                {month.list.map(row => {
                  return <span>{row}</span>;
                })}
              </div>
            </div>;
          })}
        </div>
      </div>
    );
  }
}