import React from 'react';
import { Tabs, Button, Icon } from 'antd';
import './index.less';
import Page from '@src/containers/Page';
import Block from '@src/components/Block';
import TreeLayout from '@src/layouts/TreeLayout';
import ActionLayout from '@src/layouts/ActionLayout';
import { formatTreeData } from '@src/services/Tools';
import { asyncDelConfirm, asyncForm, asyncSMessage } from '@src/services/AsyncTools';
// import { System } from '../../../stores/system';
import { Examination } from '../../../stores/examination';
import { Exercise } from '../../../stores/exercise';

export default class extends Page {
  constructor(props) {
    super(props);
    this.exerciseActionList = [{
      key: 'addChild',
      name: '增加子节点',
    }, {
      key: 'addBrother',
      name: '增加兄弟节点',
      selectNum: 1,
    }, {
      key: 'edit',
      name: '编辑',
      selectNum: 1,
    }, {
      key: 'delete',
      name: '批量删除',
      type: 'danger',
      needCheck: 1,
    }];
    this.exerciseItemList = [{
      key: 'id',
      type: 'hidden',
    }, {
      key: 'parentId',
      type: 'tree',
      name: '父节点',
      tree: [],
      fieldNames: { label: 'title', value: 'value', children: 'children' },
      notFoundContent: null,
      onChange: (value) => {
        console.log(value);
      },
    }, {
      key: 'titleZh',
      name: '中文名称',
      type: 'input',
      placeholder: '请输入中文名称',
      required: true,
    }, {
      key: 'titleEn',
      name: '英文名称',
      type: 'input',
      placeholder: '请输入英文名称',
      required: true,
    }, {
      key: 'description',
      name: '描述',
      type: 'textarea',
      placeholder: '请输入描述',
      required: true,
    }];
    this.examinationActionList = [{
      key: 'addChild',
      name: '增加子节点',
    }, {
      key: 'addBrother',
      name: '增加兄弟节点',
      selectNum: 1,
    }, {
      key: 'edit',
      name: '编辑',
      selectNum: 1,
    }, {
      key: 'delete',
      name: '批量删除',
      type: 'danger',
      needCheck: 1,
    }];
    this.examinationItemList = [{
      key: 'id',
      type: 'hidden',
    }, {
      key: 'parentId',
      type: 'tree',
      name: '父节点',
      tree: [],
      fieldNames: { label: 'title', value: 'value', children: 'children' },
      notFoundContent: null,
      onChange: (value) => {
        console.log(value);
      },
    }, {
      key: 'titleZh',
      name: '中文名称',
      type: 'input',
      placeholder: '请输入中文名称',
      required: true,
    }, {
      key: 'titleEn',
      name: '英文名称',
      type: 'input',
      placeholder: '请输入英文名称',
      required: true,
    }, {
      key: 'description',
      name: '描述',
      type: 'textarea',
      placeholder: '请输入描述',
      required: true,
    }];
    this.state.tab = 'exercise';
  }

  initData() {
    this.refresh();
  }

  refresh() {
    const { tab } = this.state;
    if (tab === 'exercise') {
      return this.refreshExercise();
    }
    return this.refreshExamination();
  }

  refreshExercise() {
    Exercise.allStruct().then(result => {
      const list = result.map(row => { row.title = `${row.titleZh}/${row.titleEn}`; return row; });
      this.exerciseItemList[1].tree = formatTreeData([{ title: '根节点', id: 0 }].concat(list), 'id', 'title', 'parentId');
      this.setState({
        exerciseList: list,
        exerciseStruct: formatTreeData(list.map(row => {
          if (row.level < 4) return row;
          row = Object.assign({}, row);
          row.title = <div className='node'>{row.title}<Button className='after-node' size='small' type={row.questionStatus > 0 ? 'primary' : 'ghost'} onClick={(e) => {
            e.preventDefault();
            row.questionStatus = row.questionStatus > 0 ? 0 : 1;
            Exercise.editStruct(row).then(() => {
              this.refresh();
            });
          }}>{row.questionStatus > 0 ? [<Icon type='pause' />, <span>提问中</span>] : [<Icon type="caret-right" />, <span>提问关闭</span>]}</Button></div>;
          return row;
        }), 'id', 'title', 'parentId'),
      });
    });
  }

  refreshExamination() {
    Examination.allStruct().then(result => {
      const list = result.map(row => { row.title = `${row.titleZh}/${row.titleEn}`; return row; });
      this.examinationItemList[1].tree = formatTreeData([{ title: '根节点', id: 0 }].concat(list), 'id', 'title', 'parentId');
      this.setState({
        examinationList: list,
        examinationStruct: formatTreeData(list.map(row => {
          if (row.level !== 2) return row;
          row = Object.assign({}, row);
          row.title = <div className='node'>{row.title}<Button className='after-node' size='small' type={row.questionStatus > 0 ? 'primary' : 'ghost'} onClick={(e) => {
            e.preventDefault();
            row.payStatus = row.payStatus > 0 ? 0 : 1;
            Examination.editStruct(row).then(() => {
              this.refresh();
            });
          }}>{row.payStatus > 0 ? [<Icon type="pay-circle" />, <span>付费</span>] : [<Icon type="eye" />, <span>免费</span>]}</Button></div>;
          return row;
        }), 'id', 'title', 'parentId'),
      });
    });
  }

  addChildAction() {
    const { tab, exerciseList, examinationList, selectedKeys } = this.state;
    let itemList;
    let node = 0;
    if (tab === 'exercise') {
      itemList = this.exerciseItemList;
      if (selectedKeys.length > 0) {
        node = exerciseList.filter(row => row.id === Number(selectedKeys[0]))[0].id;
      }
    } else {
      itemList = this.examinationItemList;
      if (selectedKeys.length > 0) {
        node = examinationList.filter(row => row.id === Number(selectedKeys[0]))[0].id;
      }
    }
    asyncForm('新增', itemList, { parentId: `${node}` }, data => {
      console.log(data);
      let handler;
      if (tab === 'exercise') {
        handler = Exercise.addStruct(data);
      } else {
        handler = Examination.addStruct(data);
      }
      return handler.then(() => {
        asyncSMessage('新增成功!');
        this.refresh();
      });
    });
  }

  addBrotherAction() {
    const { tab, exerciseList, examinationList, selectedKeys } = this.state;
    let itemList;
    let node;
    if (tab === 'exercise') {
      itemList = this.exerciseItemList;
      if (selectedKeys.length > 0) {
        node = exerciseList.filter(row => row.id === Number(selectedKeys[0]))[0].parentId;
      }
    } else {
      itemList = this.examinationItemList;
      if (selectedKeys.length > 0) {
        node = examinationList.filter(row => row.id === Number(selectedKeys[0]))[0].parentId;
      }
    }
    asyncForm('新增', itemList, { parentId: `${node}` }, data => {
      let handler;
      if (tab === 'exercise') {
        handler = Exercise.addStruct(data);
      } else {
        handler = Examination.addStruct(data);
      }
      return handler.then(() => {
        asyncSMessage('新增成功!');
        this.refresh();
      });
    });
  }

  editAction() {
    const { tab, exerciseList, examinationList, selectedKeys } = this.state;
    let itemList;
    let list;
    if (tab === 'exercise') {
      itemList = this.exerciseItemList;
      list = exerciseList;
    } else {
      itemList = this.examinationItemList;
      list = examinationList;
    }
    asyncForm('编辑', itemList, list.filter(row => row.id === Number(selectedKeys[0])).map(row => {
      row.parentId = `${row.parentId}`;
      return row;
    })[0], data => {
      let handler;
      if (tab === 'exercise') {
        handler = Exercise.editStruct(data);
      } else {
        handler = Examination.editStruct(data);
      }
      return handler.then(() => {
        asyncSMessage('编辑成功!');
        this.refresh();
      });
    });
  }

  deleteAction() {
    const { tab, checkedKeys } = this.state;
    asyncDelConfirm('删除确认', '是否删除选中节点?', () => {
      if (tab === 'exercise') {
        return Promise.all(checkedKeys.map(row => Examination.delStruct({ id: row })));
      }
      return Promise.all(checkedKeys.map(row => Examination.delStruct({ id: row })));
    }).then(() => {
      asyncSMessage('删除成功!');
      this.refresh();
    });
  }

  renderExamination() {
    const { loading } = this.state;
    return <Block loading={loading}>
      <ActionLayout
        itemList={this.exerciseActionList}
        selectedKeys={this.state.selectedKeys}
        checkedKeys={this.state.checkedKeys}
        onAction={key => this.onAction(key)} />
      <TreeLayout autoExpandParent defaultExpandAll checkable itemList={this.state.examinationStruct} selectedKeys={this.state.selectedKeys} onSelect={(selectedKeys) => {
        this.setState({ selectedKeys });
      }} checkedKeys={this.state.checkedKeys} onCheck={(checkedKeys) => {
        this.setState({ checkedKeys });
      }} />
    </Block>;
  }

  renderExercise() {
    const { loading } = this.state;
    return <Block loading={loading}>
      <ActionLayout
        itemList={this.exerciseActionList}
        selectedKeys={this.state.selectedKeys}
        checkedKeys={this.state.checkedKeys}
        onAction={key => this.onAction(key)} />
      <TreeLayout autoExpandParent defaultExpandAll checkable itemList={this.state.exerciseStruct} selectedKeys={this.state.selectedKeys} onSelect={(selectedKeys) => {
        this.setState({ selectedKeys });
      }} checkedKeys={this.state.checkedKeys} onCheck={(checkedKeys) => {
        this.setState({ checkedKeys });
      }} />
    </Block>;
  }

  renderView() {
    const { tab } = this.state;
    return <Block><Tabs activeKey={tab} onChange={(value) => {
      this.setState({ tab: value, selectedKeys: [], checkedKeys: [] });
      this.refresh();
    }}>
      <Tabs.TabPane tab="练习结构" key="exercise">
        {this.renderExercise()}
      </Tabs.TabPane>
      <Tabs.TabPane tab="模考结构" key="examination">
        {this.renderExamination()}
      </Tabs.TabPane>
    </Tabs></Block>;
  }
}
