import React from 'react';
import { Link } from 'react-router-dom';
import { Button, Modal, Form, Icon, Upload } 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 { formatTreeData, getMap } from '@src/services/Tools';
import { asyncSMessage } from '@src/services/AsyncTools';
import { CourseModule, CourseVideoType } from '../../../../Constant';
import { System } from '../../../stores/system';
import { Course } from '../../../stores/course';
import { Exercise } from '../../../stores/exercise';

const CourseModuleMap = getMap(CourseModule, 'value', 'label');
const CourseVideoTypeMap = getMap(CourseVideoType, 'value', 'label');

export default class extends Page {
  init() {
    this.exerciseMap = {};
    this.filterForm = [
      {
        key: 'structId',
        type: 'tree',
        allowClear: true,
        tree: [],
        name: '学科',
        placeholder: '标题或正文',
      }, {
        key: 'courseModule',
        type: 'select',
        name: '课程种类',
        allowClear: true,
        select: CourseModule,
        placeholder: '请输入',
      },
    ];
    this.actionList = [{
      key: 'info',
      name: '首页视频',
    }, {
      key: 'addVideo',
      type: 'primary',
      name: '创建视频课程',
      render: (item) => {
        return <Link to='/course/detail?module=video'><Button type='primary'>{item.name}</Button></Link>;
      },
    }, {
      key: 'addOnline',
      type: 'primary',
      name: '创建小班课程',
      render: (item) => {
        return <Link to='/course/detail?module=online'><Button type='primary'>{item.name}</Button></Link>;
      },
    }, {
      key: 'addVs',
      type: 'primary',
      name: '编辑1vs1课程',
      render: (item) => {
        return <Link to='/course/vs'><Button type='primary'>{item.name}</Button></Link>;
      },
    }];
    this.columns = [{
      title: '课程种类',
      dataIndex: 'courseModule',
      render: (text) => {
        return CourseModuleMap[text] || text;
      },
    }, {
      title: '学科',
      dataIndex: 'structId',
      render: (text, record) => {
        return `${record.parentStructId ? `${this.exerciseMap[record.parentStructId]}-` : ''}${this.exerciseMap[record.structId]}`;
      },
    }, {
      title: '类型',
      dataIndex: 'videoType',
      render: (text) => {
        return CourseVideoTypeMap[text] || text;
      },
    }, {
      title: '课程名称',
      dataIndex: 'title',
    }, {
      title: '售价',
      dataIndex: 'price',
    }, {
      title: '试听人数',
      dataIndex: 'trailNumber',
    }, {
      title: '购买数量(含套餐)',
      dataIndex: 'saleNumber',
      render: (text, record) => {
        return text + record.packageSaleNumber;
      },
    }, {
      title: '操作',
      dataIndex: 'handler',
      render: (text, record) => {
        return <div className="table-button">
          {<Link to={`/course/detail/${record.id}`}>编辑</Link>}
          {(record.courseModule === 'online') && <Link to={`/course/student/${record.id}`}>查看学员</Link>}
        </div>;
      },
    }];
    System.getCourseIndex().then(result => {
      return this.refreshInfo(result);
    }).then(() => {
      this.initData();
    });

    Exercise.courseStruct().then((result) => {
      const list = result.map(row => { row.title = `${row.titleZh}`; row.value = row.id; return row; });
      this.filterForm[0].tree = formatTreeData(list, 'id', 'title', 'parentId');
      this.exerciseMap = getMap(result.map(row => {
        row.title = `${row.titleZh}`;
        row.value = row.id;
        return row;
      }), 'id', 'title');

      this.setState({ exercise: result });
    });
  }

  initData() {
    Course.list(Object.assign({ excludeVs: true }, 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);
  }

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

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

  renderView() {
    const { exercise } = this.state;
    return <Block flex>
      {exercise && <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
        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>
          {this.state.uploadErr}
          <Form.Item labelCol={{ span: 5 }} wrapperCol={{ span: 10 }} label={'在线课程'} help={this.state.onlineErr}>
            <Upload
              listType="picture-card"
              showUploadList={false}
              beforeUpload={(file) => System.uploadVideo(file).then((result) => {
                this.changeInfo('onlineVideo', result.url);
              }).catch(err => {
                this.setState({ onlineErr: err.message });
              })}
            >
              {this.state.detail.onlineVideo ? <div>
                <Icon type={this.props.core.loading ? 'loading' : 'plus'} />
                <div className="ant-upload-text">已上传</div>
              </div> : <div>
                <Icon type={this.props.core.loading ? 'loading' : 'plus'} />
                <div className="ant-upload-text">Upload</div>
              </div>}
            </Upload>
          </Form.Item>
          <Form.Item labelCol={{ span: 5 }} wrapperCol={{ span: 10 }} label={'1v1课程'} help={this.state.vsErr}>
            <Upload
              listType="picture-card"
              showUploadList={false}
              beforeUpload={(file) => System.uploadVideo(file).then((result) => {
                this.changeInfo('vsVideo', result.url);
              }).catch(err => {
                this.setState({ vsErr: err.message });
              })}
            >
              {this.state.detail.vsVideo ? <div>
                <Icon type={this.props.core.loading ? 'loading' : 'plus'} />
                <div className="ant-upload-text">已上传</div>
              </div> : <div>
                <Icon type={this.props.core.loading ? 'loading' : 'plus'} />
                <div className="ant-upload-text">Upload</div>
              </div>}
            </Upload>
          </Form.Item>
        </Form>
      </Modal>}
    </Block>;
  }
}