content: import React from 'react';
  import autoBind from 'react-autobind';
  import Cookies from 'js-cookie';
  import fetch from 'isomorphic-unfetch';
  import Layout from '../components/layout';
  import vars from '../global';
  import Alert from '../components/alert';
  import Prompt from '../components/prompt';
  
  export default class extends React.Component {
    constructor(props) {
      super(props);
      this.title = '整理文件夹';
      this.state = {
        folderList: [],
        showAlert: false,
        currentFolder: null,
        promptValue: '',
        isEditPrompt: false,
      };
      autoBind(this);
    }
  
    componentWillMount() {
      this.getFoldersByUser();
    }
  
    onDel(folder) {
      this.setState({
        showAlert: true,
        currentFolder: folder,
      });
    }
  
    onCancelAlert() {
      this.setState({
        showAlert: false,
        showPrompt: false,
        currentFolder: null,
      });
    }
  
    async onConfirmAlert() {
      this.setState({ showAlert: false });
      Cookies.remove('currentFolder', { path: '' });
      const res = await fetch('/api/v1/delet_folder', {
        method: 'DELETE',
        credentials: 'include', // Don't forget to specify this if you need cookies
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ folderId: this.state.currentFolder.id }),
      });
      const json = await res.json();
  
      if (json.success) {
        this.setState({
          currentFolder: null,
        });
        this.getFoldersByUser();
      } else {
        alert(json.msg || '删除失败');
      }
    }
  
    onConfirmPrompt() {
      const $input = document.getElementsByClassName('prompt-input-node');
      if ($input.length) {
        const v = $input[0].value.trim();
        const self = this;
        if (!v) {
          alert('名称不能为空');
          return;
        }
  
        this.setState({
          showPrompt: false,
        });
  
        async function submitNew() {
          const res = await fetch('/api/v1/create_folder', {
            method: 'POST',
            credentials: 'include', // Don't forget to specify this if you need cookies
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({ folderName: v }),
          });
          const json = await res.json();
          if (json.success) {
            self.getFoldersByUser();
          } else {
            alert(json.msg || '新建失败');
          }
        }
  
        async function submitEdit() {
          const postData = {
            folderId: self.state.currentFolder.id,
            name: v,
          };
          const res = await fetch(`${vars.apiHost}/api/v1/update_folder`, {
            method: 'POST',
            credentials: 'include', // Don't forget to specify this if you need cookies
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify(postData),
          });
          const json = await res.json();
  
          if (json.success) {
            self.getFoldersByUser();
          } else {
            alert(json.msg || '修改失败');
          }
        }
  
        Cookies.remove('currentFolder', { path: '' });
        if (this.state.isEditPrompt) {
          submitEdit();
        } else {
          submitNew();
        }
      }
    }
  
    onEdit(folder) {
      this.setState({
        promptValue: folder.name,
        showPrompt: true,
        isEditPrompt: true,
        currentFolder: folder,
      });
    }
  
    async getFoldersByUser() {
      const res = await fetch(`${vars.apiHost}/api/v1/get_folders_by_user`, {
        method: 'GET',
        credentials: 'include', // Don't forget to specify this if you need cookies
        headers: {
          'Content-Type': 'application/json',
        },
      });
      const json = await res.json();
  
      if (json.success) {
        this.setState({
          folderList: json.data,
        });
      } else {
        alert(json.msg);
      }
    }
  
    new() {
      this.setState({
        promptValue: '',
        showPrompt: true,
        isEditPrompt: false,
        currentFolder: null,
      });
    }
  
    render() {
      const title = this.title;
      const folderList = this.state.folderList;
      const currentFolder = this.state.currentFolder;
  
      return (
        <Layout title={title}>
          <div className="folders">
            <div className="header">
              <div className="back-wrap" onClick={this.back}><a href="/notes" className="back">back</a></div>
              <h1>{title}</h1>
              <div className="new-wrap"><span className="new" role="presentation" onClick={this.new}>new</span></div>
            </div>
  
            <div className="content">
              {
                folderList.length > 1 ? (
                  <ul>
                    {
                      folderList.map(folder => (
                        folder.system ?
                          null :
                          (<li key={folder.id}>
                            <span>{folder.name}</span>
                            <span className="fr" role="presentation" onClick={() => this.onDel(folder)}>[删除]</span>
                            <span className="fr mr" role="presentation" onClick={() => this.onEdit(folder)}>[编辑]</span>
                          </li>)
                      ))
                    }
                  </ul>
                ) : <div className="nothing">没有找到文件夹哦/(ㄒoㄒ)/~~</div>
              }
            </div>
          </div>
  
          <Alert show={this.state.showAlert} hasCancel={true} onCancel={this.onCancelAlert} onConfirm={this.onConfirmAlert}>
            {currentFolder ? `确认删除【${currentFolder.name}】?` : '请选择文件夹'}
          </Alert>
  
          <Prompt
            show={this.state.showPrompt}
            value={this.state.promptValue}
            placeholder="填写文件夹名称"
            onCancel={() => { this.setState({ showPrompt: false }); }}
            onConfirm={this.onConfirmPrompt}
          />
  
          <style jsx>{`
            .fr { float: right; }
            .mr { margin-right: 1rem; }
            .notes { background: #f3f3f3; min-height: 100vh; overflow-y: auto; }
            .header {
              display: flex;
              -webkit-box-pack: justify; /* uc */
              justify-content: space-between;
              height: 2.6rem;
              align-items: center;
              background: #fff;
              padding: 0 1rem;
              box-shadow: 0 0.1rem 0.3rem rgba(0,0,0,0.19);
            }
            .header h1 { font-size: 16px; color: #000; max-width: 10rem; text-align: center; }
            .new-wrap { margin-right: -.5rem; }
            .new {
              display: inline-block;
              width: 0.8rem;
              height: 0.8rem;
              background-size: 0.8rem;
              background-position: center;
              background-repeat: no-repeat;
              text-indent: -999em;
              padding: 0.8rem;
            }
            .new {
              background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAACaElEQVR4Xu2bz4oTQRDG65shCYir4lUQr4pHBY+usApCQhhmzqL4AoJ/Dt5FQT2JF8EXqIZcBAUXCXj0sIuCPsCyKCYnbysJJdEclI2xmoHG3fnmml93V31T3V2droE0/EHD/RcKwAhIqEBRFKt5nj8RkVOLhjWzDQDXVHUzlVnJpkC/3z/SarW2ROTgP5zbHo1GJ4bD4SSFCMkEKMvyOoBnTqcuquprJ1sLSynAAwC3Pdaa2c0QwiMPW5dJKcBjADc8BpvZ3RDCPQ9bl6EAdRX0ti/LkhHAKcA1gIsgdwHPosltkHkAEyFmgkyFeRbgYYinQU/OUJfhcbiugt72e+o43O12D3Q6nTUAp82s5XVyGWdml7IsO+fpazqdvsmy7K2HdTDfReR9COHFInbXFCiK4mye569E5KijczdiZgL4ZlwM6zXAzL4CWFXVj7+32WVRWZbvAJzxduzlYpyKYb3jz7l1VV37qwBVVR0zsy14X1XE6DFOxbARJoiZ7QA4pKqzafHz+SMCqqpqi8hOTKdeNsapGNY7/pz7pqqHl0UABWAEcAo0eA2YLQ6N3gZnAuzXREhEvkwmkwuDweDT0kRo9mOjU+HIfdWN76nDkNurCJAC8HaY1+OsD2B9AOsDWB/A+gBP6sD6ANYHsD6A9QGsD2B9AOsDWB/gyRnqMr7byrqj/Pqz9T6AO56uzOxWCOGhh63LpBTgKoDnHoPN7HII4aWHrcskE6DX66202+1tACvLjDazz+Px+Pi++2hqfudwHsBTETm5SIT5Z3NXVPVD3TfrbZ8sArwGpeYoQGrF/7fxGh8BPwBAdQNfcl5IxAAAAABJRU5ErkJggg==);
            }
            .content ul {
              margin: 0;
              list-style: none;
              padding: 0;
              padding-top: 0.2rem;
            }
            .content ul li {
              padding: 0.5rem;
              padding-left: 1.5rem;
              border-bottom: 1px solid #efefef;
            }
            .nothing {
              padding-top: 3rem;
              text-align: center;
              color: #aaa;
            }
          `}</style>
        </Layout>
      );
    }
  }
  