import React from 'react';
import { Modal, Button } from 'antd';
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, bindSearch } from '@src/services/Tools';
import { asyncSMessage, asyncDelConfirm } from '@src/services/AsyncTools';
import { FeedbackStatus, FeedbackModule, MoneyRange, AskTarget, FeedbackQuestionType } from '../../../../Constant';
import { User } from '../../../stores/user';
import { Question } from '../../../stores/question';
import { Course } from '../../../stores/course';

const FeedbackStatusMap = getMap(FeedbackStatus, 'value', 'label');
const FeedbackModuleMap = getMap(FeedbackModule, 'value', 'label');
const FeedbackQuestionTypeMap = getMap(FeedbackQuestionType, 'value', 'label');
const AskTargetMap = getMap(AskTarget, 'value', 'label');
export default class extends Page {
  init() {
    this.actionList = [{
      key: 'handle',
      type: 'danger',
      name: '批量修改',
      needSelect: 1,
    }, {
      key: 'nohandle',
      type: 'danger',
      name: '批量不修改',
      needSelect: 1,
    }, {
      key: 'ignore',
      type: 'danger',
      name: '批量忽略',
      needSelect: 1,
    }];
    this.filterF = null;
    this.filterForm = [{
      key: 'module',
      type: 'select',
      allowClear: true,
      name: '类型',
      select: FeedbackModule,
      placeholder: '请选择',
      onChange: (value) => {
        this.changeSearch(this.filterForm, this, value, null);
        this.filterF.setFieldsValue({ questionType: null, keyword: null, target: null, moduleId: null });
      },
    }, {
      key: 'questionType',
      type: 'select',
      allowClear: true,
      name: '单项',
      select: FeedbackQuestionType,
    }, {
      key: 'keyword',
      type: 'input',
      allowClear: true,
      name: '题目id',
      placeholder: '题目ID',
    }, {
      key: 'target',
      type: 'select',
      allowClear: true,
      name: '勘误区域',
      select: AskTarget,
    }, {
      key: 'moduleId',
      type: 'select',
      allowClear: true,
      name: '资料',
      select: [],
      placeholder: '资料',
    }, {
      key: 'status',
      type: 'select',
      allowClear: true,
      name: '处理状态',
      number: true,
      select: FeedbackStatus,
    }, {
      key: 'userId',
      type: 'select',
      name: '用户',
      allowClear: true,
      select: [],
      number: true,
      placeholder: '请输入',
    }, {
      key: 'moneyRang',
      type: 'select',
      allowClear: true,
      name: '消费金额',
      select: MoneyRange,
      number: true,
    }, {
      key: 'keyword',
      type: 'input',
      allowClear: true,
      name: '勘误名称',
    }];
    this.columns = [{
      title: '类型',
      dataIndex: 'module',
      render: (text) => {
        return FeedbackModuleMap[text];
      },
    }, {
      title: '学科单项',
      dataIndex: 'questionType',
      render: (text) => {
        return FeedbackQuestionTypeMap[text];
      },
    }, {
      title: '对象',
      dataIndex: 'title',
    }, {
      title: '勘误区域',
      dataIndex: 'target',
      render: (text) => {
        return AskTargetMap[text] || '';
      },
    }, {
      title: '提交时间',
      dataIndex: 'createTime',
      render: (text) => {
        return text ? formatDate(text) : '-';
      },
    }, {
      title: '用户',
      dataIndex: 'user.nickname',
    }, {
      title: '消费金额',
      dataIndex: 'user.totalMoney',
    }, {
      title: '处理状态',
      dataIndex: 'status',
      render: (text) => {
        return FeedbackStatusMap[text] || text;
      },
    }, {
      title: '操作',
      dataIndex: 'handler',
      render: (text, record) => {
        return <div className="table-button">
          {(
            <a onClick={() => {
              this.detailAction(record);
            }}>查看</a>
          )}
        </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);
    this.changeSearch(this.filterForm, this, this.state.search.module, this.state.search.moduleId);
  }

  changeSearch(list, component, key, value) {
    if (key === 'data') {
      bindSearch(list, 'moduleId', component, (search) => {
        if (key === 'question') {
          return Question.listNo(search);
        }
        return Course.listData(search);
      }, (row) => {
        if (key === 'question') {
          return {
            title: row.title,
            value: row.questionId,
          };
        }
        return {
          title: row.title,
          value: row.id,
        };
      }, value ? Number(value) : null, null);
      list[1].disabled = true;
      list[2].disabled = true;
      list[3].disabled = true;
      list[4].disabled = false;
    } else if (key === 'question') {
      list[1].disabled = false;
      list[2].disabled = false;
      list[3].disabled = false;
      list[4].disabled = true;
    } else {
      list[1].disabled = true;
      list[2].disabled = true;
      list[3].disabled = true;
      list[4].disabled = true;
    }
    component.setState({ load: false });
  }

  initData() {
    User.listFeedbackError(this.state.search).then(result => {
      result.list = result.list.map(row => {
        row.position = row.position.split(',');
        return row;
      });
      this.setTableData(result.list, result.total);
    });
  }

  detailAction(row) {
    this.setState({ detail: row });
  }

  handleDetail() {
    const { detail } = this.state;
    asyncDelConfirm('处理确认', '是否处理选中记录?', () => {
      return User.editFeedbackError({ id: detail.id, status: 1 }).then(() => {
        asyncSMessage('操作成功!');
        this.setState({ detail: null });
        this.refresh();
      });
    });
  }

  nohandleDetail() {
    const { detail } = this.state;
    asyncDelConfirm('不处理确认', '是否不处理选中记录?', () => {
      return User.editFeedbackError({ id: detail.id, status: 3 }).then(() => {
        asyncSMessage('操作成功!');
        this.setState({ detail: null });
        this.refresh();
      });
    });
  }

  ignoreDetail() {
    const { detail } = this.state;
    asyncDelConfirm('忽略确认', '是否忽略选中记录?', () => {
      return User.editFeedbackError({ id: detail.id, status: 2 }).then(() => {
        asyncSMessage('操作成功!');
        this.setState({ detail: null });
        this.refresh();
      });
    });
  }

  handleAction() {
    const { selectedKeys } = this.state;
    asyncDelConfirm('修改确认', '是否修改选中记录?', () => {
      return Promise.all(selectedKeys.map(row => User.editFeedbackError({ id: row, status: 1 }))).then(() => {
        asyncSMessage('操作成功!');
        this.refresh();
      });
    });
  }

  nohandleAction() {
    const { selectedKeys } = this.state;
    asyncDelConfirm('不修改确认', '是否不修改选中记录?', () => {
      return Promise.all(selectedKeys.map(row => User.editFeedbackError({ id: row, status: 3 }))).then(() => {
        asyncSMessage('操作成功!');
        this.refresh();
      });
    });
  }

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

  renderView() {
    return <Block flex>
      <FilterLayout
        show
        ref={(ref) => { this.filterF = ref; }}
        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 title='勘误详情' footer={null} closable onCancel={() => {
        this.setState({ detail: null });
      }}>
        <p>类型:{FeedbackModuleMap[this.state.detail.module]}</p>
        {this.state.detail.module === 'data' && <p>勘误对象:{<Link to={`/course/data/detail/${this.state.detail.moduleId}`}>{this.state.detail.title}</Link>}</p>}
        {this.state.detail.module === 'question' && <p>勘误对象:{<Link to={`/subject/question/${this.state.detail.moduleId}`}>{this.state.detail.title}-{AskTargetMap[this.state.detail.position[0]]}</Link>}</p>}
        {this.state.detail.position.length > 1 && <p>错误位置:{this.state.detail.position[0]}页,{this.state.detail.position[1]}行{this.state.detail.position[2] ? `题号:${this.state.detail.position[2]}` : ''}</p>}
        <p>错误内容:{this.state.detail.originContent}</p>
        <p>应修改为:{this.state.detail.content}</p>
        {!this.state.detail.status && <p><Button type="primary" onClick={() => {
          this.handleDetail();
        }}>确认修改</Button><Button type="primary" onClick={() => {
          this.nohandleDetail();
        }}>无需修改</Button><Button type="ghost" onClick={() => {
          this.ignoreDetail();
        }}>忽略</Button></p>}
      </Modal>}
    </Block>;
  }
}