import React from 'react';
import { Link } from 'react-router-dom';
import { Button, Modal, Form, InputNumber, Row, Col } from 'antd';
import './index.less';
import Page from '@src/containers/Page';
import Block from '@src/components/Block';
import FilterLayout from '@src/layouts/FilterLayout';
import ActionLayout from '@src/layouts/ActionLayout';
import TableLayout from '@src/layouts/TableLayout';
import { formatDate, bindSearch, getMap } from '@src/services/Tools';
import { asyncSMessage } from '@src/services/AsyncTools';
import { ExperienceScore, ExperiencePercent, PrepareStatus, ExperienceDay } from '../../../../Constant';
import { System } from '../../../stores/system';
import { Course } from '../../../stores/course';
import { User } from '../../../stores/user';

const PrepareStatusMap = getMap(PrepareStatus, 'value', 'label');
const ExperiencePercentMap = getMap(ExperiencePercent, 'value', 'label');

export default class extends Page {
  init() {
    this.filterForm = [{
      key: 'keyword',
      type: 'input',
      allowClear: true,
      name: '搜索',
      placeholder: '标题或正文',
    }, {
      key: 'userId',
      type: 'select',
      name: '用户',
      allowClear: true,
      select: [],
      number: true,
      placeholder: '请输入',
    }, {
      key: 'prepareStatus',
      type: 'select',
      allowClear: true,
      name: '身份',
      select: PrepareStatus,
      placeholder: '请选择',
    }, {
      key: 'experienceDay',
      type: 'select',
      allowClear: true,
      name: '备考周期',
      select: ExperienceDay,
      placeholder: '请选择',
    }, {
      key: 'experienceScore',
      type: 'select',
      allowClear: true,
      name: '分手成绩',
      select: ExperienceScore,
      placeholder: '请选择',
    }, {
      key: 'experiencePercent',
      type: 'select',
      allowClear: true,
      name: '提分比例',
      select: ExperiencePercent,
      placeholder: '请选择',
    }];
    this.actionList = [{
      key: 'info',
      name: '数据管理',
    }, {
      key: 'add',
      type: 'primary',
      name: '创建',
      render: (item) => {
        return <Link to='/course/experience/detail'><Button>{item.name}</Button></Link>;
      },
    }];
    this.columns = [{
      title: '文章标题',
      dataIndex: 'title',
    }, {
      title: '作者',
      dataIndex: 'user',
      render: (text, record) => {
        return text ? text.nickname : record.nickname;
      },
    }, {
      title: '更新时间',
      dataIndex: 'updateTime',
      render: (text) => {
        return formatDate(text);
      },
    }, {
      title: '身份',
      dataIndex: 'prepareStatus',
      render: (text) => {
        return PrepareStatusMap[text] || text;
      },
    }, {
      title: '备考周期',
      dataIndex: 'experienceDay',
    }, {
      title: '分手成绩',
      dataIndex: 'experienceScore',
    }, {
      title: '提分比例',
      dataIndex: 'experiencePercent',
      render: (text) => {
        return ExperiencePercentMap[text] || text;
      },
    }, {
      title: '阅读数',
      dataIndex: 'viewNumber',
    }, {
      title: '收藏数',
      dataIndex: 'collectNumber',
    }, {
      title: '操作',
      dataIndex: 'handler',
      render: (text, record) => {
        return <div className="table-button">
          {<Link to={`/course/experience/detail/${record.id}`}>编辑</Link>}
        </div>;
      },
    }];
    System.getExperienceInfo().then(result => {
      return this.refreshInfo(result);
    }).then(() => {
      this.initData();
    });

    bindSearch(this.filterForm, 'userId', this, (search) => {
      return User.list(search);
    }, (row) => {
      return {
        title: `${row.nickname}(${row.mobile})`,
        value: row.id,
      };
    }, this.state.search.userId ? Number(this.state.search.userId) : null, null);
  }

  initData() {
    Course.listExperience(this.state.search).then(result => {
      this.setTableData(result.list, result.total);
    });
  }

  refreshInfo(result) {
    this.setState({ info: result });
  }

  infoAction() {
    const { info = {} } = this.state;
    this.open(info);
  }

  changeInfoList(field, index, value) {
    const { detail } = this.state;
    if (!detail[field]) detail[field] = [];
    detail[field][index] = value;
    this.setState({ detail });
  }

  changeInfo(field, value) {
    const { detail } = this.state;
    detail[field] = value;
    this.setState({ detail });
  }

  submitInfo() {
    const { detail } = this.state;
    System.setExperienceInfo(detail).then(() => {
      asyncSMessage('保存成功');
      this.close(false, 'detail');
      return this.refreshInfo(detail);
    });
  }

  renderView() {
    return <Block flex>
      <FilterLayout
        show
        itemList={this.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.tableSort(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.submitInfo();
      }}>
        <Form>
          <Row>
            <Col span={12}><Form.Item labelCol={{ span: 8 }} wrapperCol={{ span: 10 }} label={'学员人数'}>
              <InputNumber value={this.state.detail.number || 0} placeholder={'人数'} onChange={(value) => {
                this.changeInfo('number', value);
              }} />
            </Form.Item></Col>
          </Row>
          <Form.Item label='考分分布' />
          <Row>
            {ExperienceScore.map((row, index) => {
              return <Col span={8}><Form.Item labelCol={{ span: 10 }} wrapperCol={{ span: 14 }} label={row.label}>
                <InputNumber value={this.state.detail.score ? this.state.detail.score[index] || 0 : 0} onChange={(value) => {
                  this.changeInfoList('score', index, value);
                }} />
              </Form.Item></Col>;
            })}
          </Row>
          <Row>
            <Col span={12}><Form.Item labelCol={{ span: 8 }} wrapperCol={{ span: 10 }} label={'出分周期'}>
              <InputNumber value={this.state.detail.period || 0} placeholder={'单位天'} onChange={(value) => {
                this.changeInfo('period', value);
              }} />
            </Form.Item></Col>
          </Row>
          <Form.Item label='提分比例' />
          <Row>
            {ExperiencePercent.map((row, index) => {
              return <Col span={8}><Form.Item labelCol={{ span: 10 }} wrapperCol={{ span: 14 }} label={row.label}>
                <InputNumber value={this.state.detail.percent ? this.state.detail.percent[index] || 0 : 0} onChange={(value) => {
                  this.changeInfoList('percent', index, value);
                }} />
              </Form.Item></Col>;
            })}
          </Row>
        </Form>
      </Modal>}
    </Block>;
  }
}