import React from 'react';
import { Link } from 'react-router-dom';
import { Button, Modal, Checkbox } from 'antd';
import './index.less';
import Page from '@src/containers/Page';
import Block from '@src/components/Block';
import EditTableCell from '@src/components/EditTableCell';
import FilterLayout from '@src/layouts/FilterLayout';
import ActionLayout from '@src/layouts/ActionLayout';
import TableLayout from '@src/layouts/TableLayout';
import { getMap } from '@src/services/Tools';
import { asyncSMessage, asyncDelConfirm } from '@src/services/AsyncTools';
import { Sentence } from '../../../stores/sentence';
import { Slient } from '../../../stores/slient';

const filterForm = [
  {
    key: 'chapter',
    type: 'select',
    allowClear: true,
    name: 'chapter',
    placeholder: '请选择',
    number: true,
  },
  // {
  //   key: 'part',
  //   type: 'select',
  //   allowClear: true,
  //   name: '状态',
  //   number: true,
  //   placeholder: '请选择',
  // },
];
export default class extends Page {
  constructor(props) {
    super(props);
    this.structMap = {};
    this.actionList = [{
      key: 'struct',
      name: '编辑章节',
    }, {
      key: 'auto',
      name: '重新组卷',
    }, {
      key: 'article',
      name: '新建文章',
      render: (item) => {
        return <Link to='/subject/sentence/article'><Button>{item.name}</Button></Link>;
      },
    }, {
      key: 'question',
      name: '新建题目',
      render: (item) => {
        return <Link to='/subject/sentence/question'><Button>{item.name}</Button></Link>;
      },
    }, {
      key: 'delete',
      name: '批量删除',
      needSelect: 1,
    }];
    this.columns = [{
      title: 'chapter',
      dataIndex: 'chapter',
    }, {
      title: 'part',
      dataIndex: 'part',
    }, {
      title: 'title',
      dataIndex: 'title',
    }, {
      title: '操作',
      dataIndex: 'handler',
      render: (text, record) => {
        const item = this.structMap[this.state.search.chapter];
        return <div className="table-button">
          {item.exercise > 0 ? (<Link to={`/subject/sentence/question/${record.id}`}>编辑</Link>) : (<Link to={`/subject/sentence/article/${record.id}`}>编辑</Link>)}
        </div>;
      },
    }];
    this.structColumns = [{
      title: 'chapter',
      dataIndex: 'chapter',
      render: (text, record, index) => {
        return index + 1;
      },
    }, {
      title: '短名称',
      dataIndex: 'short',
      render: (text, record, index) => {
        return <EditTableCell value={text} onChange={(v) => {
          this.changeStruct(index, 'short', v);
        }} />;
      },
    }, {
      title: '长名称',
      dataIndex: 'title',
      render: (text, record, index) => {
        return <EditTableCell value={text} onChange={(v) => {
          this.changeStruct(index, 'title', v);
        }} />;
      },
    }, {
      title: '练习章',
      dataIndex: 'exercise',
      render: (text, record, index) => {
        return <Checkbox onChange={(e) => {
          if (e.target.checked) this.changeStruct(index, 'exercise', 1, 0);
        }} checked={!!text} />;
      },
    }];
  }

  initAuto() {
    this.outPage();
    this.interval = setInterval(() => {
      Slient.sentenceAuto().then((result) => {
        if (result.process == null || result.process === 100) {
          this.actionList[1].disabled = false;
          result.process = 100;
        } else {
          this.actionList[1].disabled = true;
        }
        this.setState({ process: result.process });
      });
    }, 30000);
  }

  outPage() {
    if (this.interval) {
      clearInterval(this.interval);
    }
  }

  init() {
    Sentence.getStruct().then(result => {
      return this.refreshStruct(result);
    }).then(() => {
      this.initData();
    });
  }

  initData() {
    const item = this.structMap[this.state.search.chapter];
    if (!item) return;
    if (item.exercise) {
      Sentence.listQuestion(this.state.search).then(result => {
        result.list = result.list.map(row => {
          row.chapter = this.state.search.chapter || 0;
          return row;
        });
        this.setTableData(result.list, result.total);
      });
    } else {
      Sentence.listArticle(this.state.search).then(result => {
        this.setTableData(result.list, result.total);
      });
    }
  }

  refreshStruct(result) {
    result = result || {};
    result.chapters = result.chapters || [];
    filterForm[0].select = result.chapters.map((row, index) => { row.value = index + 1; return row; });
    this.structMap = getMap(filterForm[0].select, 'value');
    this.setState({ struct: result });
  }

  autoAction() {
    asyncDelConfirm('组卷确认', '是否重新组卷?', () => {
      return Sentence.auto().then(() => {
        asyncSMessage('开始组卷！');
        this.refresh();
      });
    });
  }

  structAction() {
    const { struct = {} } = this.state;
    this.open(struct);
  }

  changeStruct(index, field, value, other) {
    const { detail } = this.state;
    if (other !== undefined) {
      detail.chapters.forEach((row) => {
        row[field] = other;
      });
    }
    detail.chapters[index][field] = value;
    this.setState({ detail });
  }

  submitStruct() {
    const { detail } = this.state;
    Sentence.setStruct(detail).then(() => {
      asyncSMessage('保存成功');
      this.close(false, 'detail');
      return this.refreshStruct(detail);
    }).then(() => {
      return this.initData();
    });
  }

  deleteAction() {
    const { selectedKeys } = this.state;

    const item = this.structMap[this.state.search.chapter];
    if (!item) return;
    asyncDelConfirm('删除确认', '是否删除选中?', () => {
      if (item.exercise) {
        return Promise.all(selectedKeys.map(row => Sentence.delQuestion({ id: row })));
      }
      return Promise.all(selectedKeys.map(row => Sentence.delArticle({ id: row })));
    }).then(() => {
      asyncSMessage('删除成功!');
      this.refresh();
    });
  }

  renderView() {
    return <Block flex>
      <FilterLayout
        show
        itemList={filterForm}
        data={this.state.search}
        onChange={data => {
          this.search(data);
        }} />
      <ActionLayout
        itemList={this.actionList}
        selectedKeys={this.state.selectedKeys}
        onAction={key => this.onAction(key)}
      />
      <TableLayout
        select
        columns={this.columns}
        list={this.state.list}
        pagination={this.state.page}
        loading={this.props.core.loading}
        onChange={(pagination, filters, sorter) => this.tableChange(pagination, filters, sorter)}
        onSelect={(keys, rows) => this.tableSelect(keys, rows)}
        selectedKeys={this.state.selectedKeys}
      />
      {this.state.detail && <Modal visible closable title='编辑章节' onCancel={() => {
        this.close(false, 'detail');
      }} onOk={() => {
        this.submitStruct();
      }}>
        <TableLayout
          rowKey={'title'}
          columns={this.structColumns}
          list={this.state.detail.chapters}
          pagination={false}
        />
        <Button onClick={() => {
          const { detail } = this.state;
          detail.chapters.push({});
          this.setState({ detail });
        }}>增加chapter</Button></Modal>}
    </Block>;
  }
}
