import React from 'react';
import { Link } from 'react-router-dom';
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 { getMap, formatDate, formatTreeData, formatSeconds, bindSearch } from '@src/services/Tools';
import { asyncSMessage, asyncDelConfirm } from '@src/services/AsyncTools';
import { AnswerStatus, SwitchSelect, MoneyRange } from '../../../../Constant';
import { User } from '../../../stores/user';
import { Exercise } from '../../../stores/exercise';
import { Course } from '../../../stores/course';

const AnswerStatusMap = getMap(AnswerStatus, 'value', 'label');
const SwitchSelectMap = getMap(SwitchSelect, 'value', 'label');
export default class extends Page {
  init() {
    // this.actionList = [{
    //   key: 'ignore',
    //   type: 'danger',
    //   name: '批量忽略',
    //   needSelect: 1,
    // }];
    this.exerciseMap = {};
    this.filterForm = [{
      key: 'structId',
      type: 'tree',
      allowClear: true,
      name: '学科',
      select: [],
      placeholder: '请选择',
      number: true,
    }, {
      key: 'courseId',
      type: 'select',
      allowClear: true,
      name: '课程',
      select: [],
      placeholder: '请选择',
      number: true,
    }, {
      key: 'answerStatus',
      type: 'select',
      allowClear: true,
      name: '回答状态',
      select: AnswerStatus,
      number: true,
    }, {
      key: 'showStatus',
      type: 'select',
      allowClear: true,
      name: '展示状态',
      select: SwitchSelect,
    }, {
      key: 'userId',
      type: 'select',
      name: '用户',
      allowClear: true,
      select: [],
      number: true,
      placeholder: '请输入',
    }, {
      key: 'moneyRang',
      type: 'select',
      allowClear: true,
      name: '消费金额',
      select: MoneyRange,
      number: true,
    }, {
      key: 'time',
      type: 'daterange',
      name: '提问时间',
    }];
    this.columns = [{
      title: '学科',
      dataIndex: 'course.structId',
      render: (text, record) => {
        return `${record.course.parentStructId ? `${this.exerciseMap[record.course.parentStructId]}-` : ''}${this.exerciseMap[record.course.structId]}`;
      },
    }, {
      title: '课程',
      dataIndex: 'course.title',
    }, {
      title: '课时',
      dataIndex: 'courseNo.no',
    }, {
      title: '位置',
      dataIndex: 'position',
      render: (text) => {
        return `${text}`;
      },
    }, {
      title: '提问者',
      dataIndex: 'user.nickname',
    }, {
      title: '消费金额',
      dataIndex: 'user.totalMoney',
    }, {
      title: '提问时间',
      dataIndex: 'createTime',
      render: (text) => {
        return text ? formatDate(text, 'YYYY-MM-DD HH:mm:ss') : '';
      },
    }, {
      title: '倒计时',
      sorter: true,
      dataIndex: 'expireTime',
      render: (text, record) => {
        const end = new Date(record.answerTime) || new Date();
        const cost = (end.getTime() - new Date(record.createTime).getTime()) / 1000;
        if (text) {
          if (record.askTime - cost > 0) return `${formatSeconds(text - cost)}/${formatSeconds(text)}`;
          return `0/${formatSeconds(text)}`;
        }
        return '-';
      },
    }, {
      title: '回答者',
      dataIndex: 'manager.username',
    }, {
      title: '回答时间',
      sorter: true,
      dataIndex: 'answerTime',
      render: (text) => {
        return text ? formatDate(text, 'YYYY-MM-DD HH:mm:ss') : '';
      },
    }, {
      title: '回答状态',
      dataIndex: 'answerStatus',
      render: (text) => {
        return AnswerStatusMap[text] || text;
      },
    }, {
      title: '展示状态',
      dataIndex: 'showStatus',
      render: (text) => {
        return SwitchSelectMap[text] || text;
      },
    }, {
      title: '操作',
      dataIndex: 'handler',
      render: (text, record) => {
        return <div className="table-button">
          {(
            <Link to={`/student/ask/course/detail/${record.id}`}>编辑</Link>
          )}
        </div>;
      },
    }];
    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);
    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 });
    });

    Course.list().then((result) => {
      this.filterForm[1].select = result.list.map(row => {
        row.value = row.id;
        return row;
      });
    });
  }

  initData() {
    const { search } = this.state;
    const data = Object.assign({ hasRecord: true }, search);
    if (data.time) {
      data.startTime = data.time[0] || '';
      data.endTime = data.time[1] || '';
    }
    Course.listAsk(data).then(result => {
      this.setTableData(result.list, result.total);
    });
  }

  ignoreAction() {
    const { selectedKeys } = this.state;
    asyncDelConfirm('忽略确认', '是否忽略选中提问?', () => {
      return Promise.all(selectedKeys.map(row => User.editAsk({ id: row, ignoreStatus: 1 }))).then(() => {
        asyncSMessage('操作成功!');
        this.refresh();
      });
    });
  }

  renderView() {
    const { exercise } = this.state;
    return <Block flex>
      {exercise && <FilterLayout
        show
        itemList={this.filterForm}
        data={this.state.search}
        onChange={data => {
          if (data.time.length > 0) {
            data.time = [data.time[0].format('YYYY-MM-DD HH:mm:ss'), data.time[1].format('YYYY-MM-DD HH:mm:ss')];
          }
          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}
      />
    </Block>;
  }
}