/*
 * @Author: Michael
 * @Date: 2020-01-29 11:27:34
 * @Last Modified by: 吴文洁
 * @Last Modified time: 2020-07-22 16:25:30
 * 查看学员名单
 */
import React from "react";
import {
  Modal,
  Button,
  Input,
  Table,
  Popconfirm,
  message,
  Tooltip,
} from "antd";
import PropTypes from "prop-types";
import { PageControl } from "@/components";
import SelectStudent from "./select-student/index";

import "./LiveStudentListModal.less";

const { Search } = Input;
const isTeacher = !!window.currentUserInstInfo.teacherId;

const liveTypeMap = {
  LIVE: "直播",
  PLAYBACK: "回放",
};

const expandedColumns = [
  {
    title: "类型",
    dataIndex: "liveType",
    key: "liveType",
    render: (text) => <span>{liveTypeMap[text]}</span>,
  },
  {
    title: "进入时间",
    dataIndex: "entryTime",
    key: "entryTime",
    render: (text) => (
      <span>{formatDate("YYYY-MM-DD H:i", parseInt(text))}</span>
    ),
  },
  {
    title: "离开时间",
    dataIndex: "leaveTime",
    key: "leaveTime",
    render: (text) => (
      <span>{formatDate("YYYY-MM-DD H:i", parseInt(text))}</span>
    ),
  },
  { title: "观看时长", dataIndex: "lookingTime", key: "lookingTime" },
];

const STATUS_ENUM = {
  'NORMAL': '在读',
  'POTENTIAL': '潜在',
  'HISTORY': '历史',
  'ABANDON': '废弃',
};

class LiveStudentListModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      query: {
        current: 1,
        size: 10,
        nameOrPhone: null,
        liveCourseId: props.liveItem.liveCourseId,
      },
      total: 1,
      studentList: [],
      studentModal: null,
      after: true,
    };
  }

  componentDidMount() {
    this.fetchStudentList();
  }

  fetchStudentList = (current = 1) => {
    const query = _.clone(this.state.query);
    query.current = current;
    window.axios
      .Apollo("public/businessLive/getStudentList", query)
      .then((res) => {
        const { records = [], total } = res.result;

        this.setState({
          studentList: records,
          total,
          query,
        });
      });
  };

  hanldSelect = () => {
    const { query: { liveCourseId } } = this.state;
    axios.Apollo('public/businessLive/getCourseDetail', { liveCourseId})
      .then((res) => {
        const { result = {} } = res;
        const { consumeStudentIds, studentIds } = result;
        const studentList = [];
        const excludeStudentIds = studentIds;
        const excludeConsumeStudentIds = _.pluck(consumeStudentIds, 'studentId');
        this.setState({ excludeStudentIds, excludeConsumeStudentIds});

        _.each(studentIds, (item) => {
          studentList.push({ studentId: item });
        });
      
        const studentModal = (
          <SelectStudent
            liveCourseId={liveCourseId}
            studentList={studentList}
            excludeStudentIds={excludeStudentIds}
            after={true}
            close={() => { this.setState({  studentModal: null }); }}
            onSelect={(studentIds) => {
              this.handleSelectStudent(studentIds)
            }}
          />
        )

        this.setState({ studentModal });
      })
  };

  handleSelectStudent = (studentIds) => {
    const {
      liveType,
      liveCourseId,
      podium,
      quota,
    } = this.props.liveItem;

    if (liveType !== "SMALL_CLASS_INTERACTION" && (studentIds.length) > 1000) {
      message.info(`最多选择1000人`);
      return;
    } else if (liveType == "SMALL_CLASS_INTERACTION" && (studentIds.length) > podium) {
      message.info(`最多选择${podium}人`);
      return;
    } else {
      const param = {
        liveCourseId: liveCourseId,
        studentIds: studentIds
      };
      axios.Apollo("public/businessLive/addCourseStu", param).then(res => {
        if (res.success) {
          this.setState({
            studentModal: null
          });
          message.success("学员变更成功");
          this.fetchStudentList();
          this.props.refresh();
        }
      });
    }
  };

  // 移除学员
  removeStudent = (studentId) => {
    const { liveCourseId } = this.props.liveItem;
    const param = {
      liveCourseId,
      studentId,
    };
    window.axios
      .Apollo("public/businessLive/moveCourseStu", param)
      .then((res) => {
        message.success("移除学员成功");
        this.fetchStudentList(1);
        this.props.refresh();
      });
  };

  parseColumns = () => {
    const { type, liveItem } = this.props;
    const columns = [
      { title: "姓名", dataIndex: "studentName", key: "studentName" },
      {
        title: "手机号",
        dataIndex: "phone",
        width: 150,
        key: "phone",
        render: (text, record) => {
          return (
            <p>
              {!(
                (!window.NewVersion && !window.currentUserInstInfo.teacherId) ||
                (window.NewVersion && Permission.hasEduStudentPhone())
              )
                ? (text || "").replace(/(\d{3})(\d{4})(\d{4})/, "$1****$3")
                : text}
              <Tooltip
                title={`${record.wechatStatus ? "已绑定微信" : "未绑定微信"}`}
              >
                <span
                  className="icon iconfont"
                  style={
                    record.wechatStatus
                      ? {
                          color: "#00D20D",
                          fontSize: "16px",
                          marginLeft: 6,
                        }
                      : {
                          color: "#BFBFBF",
                          fontSize: "16px",
                          marginLeft: 6,
                        }
                  }
                >
                  &#xe68d;
                </span>
              </Tooltip>
            </p>
          );
        },
      }
    ];

    // 非互动班课类型增加学员类型
    if (type !== 'interactive') {
      columns.push({
        title: '学员类型',
        key: 'statusEnum',
        dataIndex: 'statusEnum',
        render: (val) => {
          return STATUS_ENUM[val];
        }
      });
    }
  
    // 如果是非视频课, 显示操作的条件是课程未开始,且不是T端
    // 如果是视频课,那么只要满足不是T端就可以了
    if ((liveItem.courseState === "UN_START" || type === 'videoCourse') && !isTeacher) {
      // 未开始
      columns.push({
        title: "操作",
        dataIndex: "operate",
        key: "operate",
        align:'right',
        render: (text, record) => {
          return (
            <Popconfirm
              title="你确定要移出这个学员吗?"
              onConfirm={() => {
                // 如果是非视频课,且直播间类型是自研, 且晚于开课前30分钟, 不允许移出
                if (
                  liveItem.channel == "XIAOMAI" &&
                  liveItem.startTime - Date.now() < 1800000
                ) {
                  Modal.warning({
                    title: "不可移出",
                    icon: (
                      <span className="icon iconfont default-confirm-icon">
                        &#xe6f4;
                      </span>
                    ),
                    content: "晚于开课前30分钟，不能移出学员",
                  });
                } else {
                  this.removeStudent(record.studentId);
                }
              }}
            >
              <span className="live-operate">移出</span>
            </Popconfirm>
          );
        },
      });
    }
    return columns;
  }

  render() {
    const { studentList, query, total } = this.state;
    const { current, size } = query;
    return (
      <Modal
        title="查看学员名单"
        visible={true}
        width={680}
        footer={null}
        maskClosable={false}
        closeIcon={<span className="icon iconfont modal-close-icon">&#xe6ef;</span>}
        className="live-student-list-modal"
        onCancel={this.props.close}
      >
        {/* 任意状态都可以添加学员 */}
        <div className="live-student-list-modal__operate">
          {
            !isTeacher &&
            <Button type="primary" onClick={this.hanldSelect}>
              添加上课学员
            </Button>
          }
          <Search
            placeholder="搜索学员姓名/手机号"
            style={{ width: 200 }}
            onSearch={(value) => {
              this.setState({
                query: {
                  ...this.state.query,
                  nameOrPhone: value
                }
              }, () => {
                this.fetchStudentList(1);
              });
            }}
            className="search"
          />
        </div>
        <Table
          size="small"
          columns={this.parseColumns()}
          dataSource={studentList}
          pagination={false}
          scroll={{ y: 400 }}
          className="live-student-table table-no-scrollbar"
        />
        <PageControl
          size="small"
          current={current - 1}
          pageSize={size}
          total={Number(total)}
          toPage={(page) => {
            this.fetchStudentList(page + 1);
          }}
        />
        {this.state.studentModal}
      </Modal>
    );
  }
}

LiveStudentListModal.propTypes = {
  liveItem: PropTypes.object,
  status: PropTypes.string,
  close: PropTypes.func,
  refresh: PropTypes.func, // 刷新列表
};

export default LiveStudentListModal;
