import React from 'react';
import { Link } from 'react-router-dom';
import { Button, Modal, Checkbox, Form, InputNumber } 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';
import { SwitchSelect } from '../../../../Constant';

const SwitchSelectMap = getMap(SwitchSelect, 'value', 'label');
const filterForm = [
  {
    key: 'chapter',
    type: 'select',
    allowClear: true,
    name: 'chapter',
    placeholder: '请选择',
    number: true,
  },
  {
    key: 'isTrail',
    type: 'select',
    name: '试用',
    allowClear: true,
    placeholder: '请选择',
    number: true,
    select: SwitchSelect,
  },
  // {
  //   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: 'introduction',
      name: '编辑前言',
      render: (item) => {
        return <Link to='/subject/sentence/article?i=1'><Button>{item.name}</Button></Link>;
      },
    }, {
      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: '名称',
      dataIndex: 'title',
    }, {
      title: '试用',
      dataIndex: 'isTrail',
      render: (text) => {
        return SwitchSelectMap[text ? 1 : 0] || '';
      },
    }, {
      title: '练习',
      dataIndex: 'exercise',
      render: () => {
        const item = this.structMap[this.state.search.chapter];
        return SwitchSelectMap[item.exercise ? 1 : 0] || '';
      },
    }, {
      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.progress == null || result.progress === 100) {
          this.actionList[1].disabled = false;
          result.progress = 100;
        } else {
          this.actionList[1].disabled = true;
        }
        this.setState({ progress: result.progress });
      });
    }, 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 });
  }

  changeTrail(number) {
    const { detail } = this.state;
    detail.trailPages = number;
    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('删除确认', '是否删除选中?', () => {
      let handler;
      if (item.exercise) {
        handler = Promise.all(selectedKeys.map(row => Sentence.delQuestion({ id: row })));
      } else {
        handler = Promise.all(selectedKeys.map(row => Sentence.delArticle({ id: row })));
      }
      return handler.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();
      }}>
        <Form>
          <Form.Item labelCol={{ span: 4 }} wrapperCol={{ span: 16 }} label='试用页数'>
            <InputNumber value={this.state.detail.trailPages || 0} onChange={(value) => {
              this.changeTrail(value);
            }} />
          </Form.Item>
        </Form>
        <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>;
  }
}