/*
 * @Description:
 * @Author: zangsuyun
 * @Date: 2021-03-12 14:49:40
 * @LastEditors: wufan
 * @LastEditTime: 2021-05-13 16:35:41
 * @Copyright: © 2020 杭州杰竞科技有限公司 版权所有
 */

import React from "react";
import { Table, Modal, message, Tooltip, Switch, Dropdown, Button } from "antd";
import { Route, withRouter } from "react-router-dom";
import { PageControl } from "@/components";
import { LIVE_SHARE_MAP } from "@/common/constants/academic/cloudClass";
import { appId, shareUrl, LIVE_SHARE } from "@/domains/course-domain/constants";
import ScanFileModal from "../../resource-disk/modal/ScanFileModal";
import WatchData from "./WatchData";
import KnowledgeAPI from "@/data-source/knowledge/request-api";
import ENUM from "../ENUM.js";
import "./KnowledgeBaseList.less";

const DEFAULT_SIZE_UNIT = 1000 * 1000; // 将B转换成M
const { confirm } = Modal;
const ENV = process.env.DEPLOY_ENV || "dev";

class KnowledgeBaseList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      id: "", 
      scanFileModal:null
    };
  }

  handleAdminName = (adminArray) => {
    let adminStr = "";
    adminArray.map((item, index) => {
      if (index < adminArray.length - 1) {
        adminStr = adminStr + item.adminName + "、";
      } else {
        adminStr = adminStr + item.adminName;
      }
    });
    return adminStr;
  };

  handleUp = (index, record) => {
    if (index === 0 && this.props.query.current === 1) {
      return;
    }
    const params = {
      direction: "UP",
      id: record.id,
      storeId: record.storeId,
    };
    KnowledgeAPI.moveKnowledge(params).then((res) => {
      if (res.success) {
        message.success("更新成功");
        this.props.onChange();
      }
    });
  };

  handleDown = (record, index) => {
    const { query, totalCount } = this.props;
    const { current, size } = query;

    if (totalCount === size * (current - 1) + index + 1) {
      return;
    }

    const params = {
      direction: "DOWN",
      id: record.id,
      storeId: record.storeId,
    };

    KnowledgeAPI.moveKnowledge(params).then((res) => {
      if (res.success) {
        message.success("更新成功");
        this.props.onChange();
      }
    });
  };

  getBlob = (url) => {
    return new Promise((resolve) => {
      const xhr = new XMLHttpRequest()

      xhr.open('GET', url, true)
      xhr.responseType = 'blob'
      xhr.onload = () => {
        if (xhr.status === 200) {
          resolve(xhr.response)
        }
      }
      xhr.send()
    })
  }

  saveAs = (blob, filename) => {
    if (window.navigator.msSaveOrOpenBlob) {
      navigator.msSaveBlob(blob, filename)
    } else {
      const link = document.createElement('a')
      const body = document.querySelector('body')

      // 创建对象url
      link.href = window.URL.createObjectURL(blob)
      link.download = filename

      body.appendChild(link)

      link.click()
      body.removeChild(link)

      // 通过调用 URL.createObjectURL() 创建的 URL 对象
      window.URL.revokeObjectURL(link.href)
    }
  }
  // 下载文件
  handleDownload = (folder) => {
    this.getBlob(folder.ossUrl).then((blob) => {
      this.saveAs(blob, folder.folderName)
    })
  }
  
  // 预览文件
  handleScanFile = (folder) => {
    console.log(folder);
    const { folderFormat, folderSize, ossUrl } = folder;
    switch (folderFormat) {
      case "PDF":
        window.open(ossUrl, "_blank");
        break;
      case "WORD":
      case "DOCX":
      case "DOC":
      case "EXCEL":
      case "PPT":
      case "PPTX":
      case "PDF":
        if (
          ((folderFormat === "PPT" ||
            folderFormat === "PPTX" ||
            folderFormat === "DOCX" ||
            folderFormat === "WORD" ||
            folderFormat === "DOC") &&
            folderSize > 10 * DEFAULT_SIZE_UNIT) ||
          (folderFormat === "EXCEL" && folderSize > 5 * DEFAULT_SIZE_UNIT)
        ) {
          Modal.confirm({
            title: "抱歉，不能在线预览",
            content: "由于文件较大，不支持在线预览，请下载后再查看",
            // icon: <Icon type="question-circle" theme="filled" style={{ color: '#FF8534' }}></Icon>,
            cancelText: "取消",
            okText: "下载",
            onOk: () => {
              this.handleDownload(folder)
            },
          });
          break;
        }
        const prefixUrl = "https://view.officeapps.live.com/op/view.aspx?src=";
        const scanUrl = `${prefixUrl}${encodeURIComponent(ossUrl)}`;
        window.open(scanUrl, "_blank");
        break;
      default:
        const scanFileModal = (
          <ScanFileModal
            fileType={folderFormat}
            item={folder}
            close={() => {
              this.setState({ scanFileModal: null });
            }}
          />
        );
        this.setState({ scanFileModal });
        break;
    }
  };

  // 请求表头
  parseColumns = () => {
    const { query, totalCount } = this.props;
    const { current, size } = query;
    const columns = [
      {
        title: "课程名称",
        key: "name",
        dataIndex: "name",
        width: 391,
        fixed: "left",
        render: (val, record) => {
          const { coverUrl, mediaCourseUrl } = record.source;
          let hasCover = false;
          const type = record.type;
          return (
            <div>
              {type === "LIVE" && (
                <div className="record__item">
                  {record.source &&
                    record.source.courseMediaVOS.map((item, index) => {
                      if (item.contentType === "COVER") {
                        hasCover = true;
                        return (
                          <img
                            className="course-cover"
                            key={index}
                            src={item.mediaUrl}
                          />
                        );
                      }
                    })}
                  {!hasCover && (
                    <img
                      className="course-cover"
                      src={"https://image.xiaomaiketang.com/xm/YNfi45JwFA.png"}
                    />
                  )}
                  <div>
                    {val.length > 17 ? (
                      <Tooltip title={val}>
                        <div className="course-name">{val}</div>
                      </Tooltip>
                    ) : (
                      <div className="course-name">{val}</div>
                    )}
                    <div>
                      <span className="course-time">
                        {formatDate(
                          "YYYY-MM-DD H:i",
                          parseInt(record.source.startTime)
                        )}
                        ~{formatDate("H:i", parseInt(record.source.endTime))}
                      </span>
                      <span
                        className="course-status"
                        style={{
                          color:
                            ENUM.courseStateShow[record.source.courseState]
                              .color,
                          border: `1px solid ${
                            ENUM.courseStateShow[record.source.courseState]
                              .color
                          }`,
                        }}
                      >
                        {ENUM.courseStateShow[record.source.courseState].title}
                      </span>
                      {record.hideToUser && (
                        <Tooltip
                          title={
                            <div>课程未成功开课，已在学员知识列表中隐藏</div>
                          }
                        >
                          <i
                            className="icon iconfont"
                            style={{
                              marginLeft: "5px",
                              cursor: "pointer",
                              color: "#FF4F4F",
                              fontSize: "14px",
                            }}
                          >
                            &#xe61d;
                          </i>
                        </Tooltip>
                      )}
                    </div>
                    <div className="teacher-assistant">
                      {record.source.teacherName.length > 4 ? (
                        <Tooltip title={record.source.teacherName}>
                          <span className="teacher">
                            讲师：{record.source.teacherName}
                          </span>
                        </Tooltip>
                      ) : (
                        <span className="teacher">
                          讲师：{record.source.teacherName}
                        </span>
                      )}

                      {record.source.admins.length > 0 && (
                        <>
                          <span className="split"> | </span>
                          {this.handleAdminName(record.source.admins).length >
                          4 ? (
                            <Tooltip
                              title={this.handleAdminName(record.source.admins)}
                            >
                              <span className="assistant">
                                助教：
                                {record.source.admins.map((item, index) => {
                                  return (
                                    <span>
                                      {item.adminName}{" "}
                                      {index <
                                        record.source.admins.length - 1 && (
                                        <span> 、</span>
                                      )}{" "}
                                    </span>
                                  );
                                })}
                              </span>
                            </Tooltip>
                          ) : (
                            <span className="assistant">
                              助教：
                              {record.source.admins.map((item, index) => {
                                return (
                                  <span key={index}>
                                    {item.adminName}{" "}
                                    {index <
                                      record.source.admins.length - 1 && (
                                      <span> 、</span>
                                    )}{" "}
                                  </span>
                                );
                              })}
                            </span>
                          )}
                        </>
                      )}
                    </div>
                  </div>
                </div>
              )}

              {type === "VOICE" && (
                <div className="record__item">
                  {/* 上传了封面的话就用上传的封面, 没有的话就取视频的第一帧 */}
                  <img
                    className="course-cover"
                    src={
                      coverUrl ||
                      `${mediaCourseUrl}?x-oss-process=video/snapshot,t_0,m_fast`
                    }
                  />
                  {val.length > 25 ? (
                    <Tooltip title={val}>
                      <div className="course-name clamp">{val}</div>
                    </Tooltip>
                  ) : (
                    <div className="course-name clamp">{val}</div>
                  )}
                </div>
              )}

              {type === "PICTURE" && (
                <div className="record__item">
                  <img
                    className="course-cover"
                    src={
                      coverUrl ||
                      "https://image.xiaomaiketang.com/xm/YNfi45JwFA.png"
                    }
                  />
                  {val.length > 25 ? (
                    <Tooltip title={val}>
                      <div className="course-name clamp">{val}</div>
                    </Tooltip>
                  ) : (
                    <div className="course-name clamp">{val}</div>
                  )}
                </div>
              )}

              {type === "FOLDER" && (
                <div
                  className="record__item"
                  onClick={() => {
                    this.handleScanFile(record.source);
                  }}
                >
                  <div
                    className={`folder-type ${
                      record.source && record.source.folderFormat
                    }`}
                  />
                  {val.length > 25 ? (
                    <Tooltip title={val}>
                      <div className="course-name clamp">{val}</div>
                    </Tooltip>
                  ) : (
                    <div className="course-name clamp">{val}</div>
                  )}
                </div>
              )}
            </div>
          );
        },
      },
      {
        title: "课程类型",
        key: "type",
        dataIndex: "type",
        align:'center',
        // width: 100,
        render: (val, record) => {
          return (
            <div className="">
              {val ? ENUM.CourseTypeEnum[val] : "-"}
            </div>
          );
        },
      },
      {
        title: "创建人",
        key: "createName",
        dataIndex: "createName",
        align:'center',
        render: (val) => {
          return (
            <div>
              {val && (
                <Tooltip title={val}>
                  <div>{val.length > 4 ? `${val.slice(0, 4)}...` : val}</div>
                </Tooltip>
              )}
            </div>
          );
        },
      },
      {
        title: "观看学员数",
        key: "watchUserCount",
        dataIndex: "watchUserCount",
        align:'right',
        render: (val, item) => {
          return val ? (
            <div
              className="operate"
              style={{display:'block'}}
              onClick={() => this.handleLinkToClassData(item)}
            >
              <span className="operate__item">{val}</span>
            </div>
          ) : (
            0
          );
        },
      },
      {
        title: "",
        width: 48,
      },
      {
        title: "操作",
        key: "operate",
        dataIndex: "operate",
        width: 160,
        fixed: "right",
        render: (val, record, index) => {
          console.log(this.props.categoryId);
          return this.props.categoryId === "0" ? (
            <div className="operate">
              <div
                className="operate__item"
                onClick={() => this.handleDelete(record)}
              >
                移出
              </div>
            </div>
          ) : (
            <div className="operate">
              <div
                className={
                  index === 0 && current === 1
                    ? "operate__item disable"
                    : "operate__item"
                }
                onClick={() => this.handleUp(index, record)}
              >
                上移
              </div>
              <span className="operate__item split"> | </span>
              <div
                className={
                  totalCount === size * (current - 1) + index + 1
                    ? "operate__item disable"
                    : "operate__item"
                }
                onClick={() => this.handleDown(record, index)}
              >
                下移
              </div>
              <span className="operate__item split"> | </span>
              <div
                className="operate__item"
                onClick={() => this.handleDelete(record)}
              >
                移出
              </div>
            </div>
          );
        },
      },
    ];
    return columns;
  };

  handleDelete = (record) => {
    return confirm({
      title: "移出知识",
      content: "确定将分类中此知识移出吗？",
      icon: (
        <span className="icon iconfont default-confirm-icon">&#xe839; </span>
      ),
      okText: "删除",
      okType: "danger",
      cancelText: "取消",
      width: 440,
      height: 188,
      onOk: () => {
        this.deleteConfirm(record);
      },
    });
  };

  // 前往上课数据页面
  handleLinkToClassData = (item) => {
    const { match } = this.props;
    console.log(item);
    localStorage.setItem("WatchData_CourseName", item.name);
    window.RCHistory.push({
      // pathname: `${match.url}/course-data?type=${item.courseType}&id=${item.liveCourseId}`,
      pathname: `${match.url}/course-data?type=${item.type}&id=${item.id}`,
    });
  };

  deleteConfirm = (item) => {
    const params = {
      id: item.id,
      storeId: item.storeId,
    };
    KnowledgeAPI.delKnowledge(params).then((res) => {
      if (res.success) {
        message.success("移出成功");
        this.props.onChange();
        this.props.updateCategoryTree();
      }
    });
  };

  onShowSizeChange = (current, size) => {
    if (current == size) {
      return;
    }
    let _query = this.props.query;
    _query.size = size;
    this.props.onChange(_query);
  };

  render() {
    const { dataSource = [], totalCount, query, match } = this.props;
    const { current, size } = query;
    return (
      <div className="knowledge-base-list">
        <Table
          rowKey={(record) => record.id}
          size="middle"
          dataSource={dataSource}
          columns={this.parseColumns()}
          pagination={false}
          scroll={{ x: 900 }}
          bordered
          className="knowledge-list-table"
        />

        <div className="box-footer">
          {totalCount > 0 && (
            <PageControl
              current={current - 1}
              pageSize={size}
              total={totalCount}
              toPage={(page) => {
                const _query = { ...query, current: page + 1 };
                this.props.onChange(_query);
              }}
              onShowSizeChange={this.onShowSizeChange}
            />
          )}
        </div>

        <Route path={`${match.url}/course-data`} component={WatchData} />

        {this.state.scanFileModal}

      </div>
    );
  }
}

export default withRouter(KnowledgeBaseList);
