/*
 * @Description:
 * @Author: zangsuyun
 * @Date: 2021-03-12 14:49:40
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-06-11 16:44:59
 * @Copyright: © 2020 杭州杰竞科技有限公司 版权所有
 */

import React from "react";
import { Modal, message, Tooltip, Switch, Dropdown, Button } from "antd";
import { Route, withRouter } from "react-router-dom";
import { PageControl, XMTable } 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) => {
    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",
        render: (val, record) => {
          const { coverUrl, mediaCourseUrl, courseDivision } = record.source
          let hasCover = false
          const type = record.type
          return (
            <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>

          )
        }
      },
      {
        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: "",
    
      },
      {
        title: "操作",
        key: "operate",
        dataIndex: "operate",
        width: 160,
        fixed: "right",
        render: (val, record, index) => {
          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;
    localStorage.setItem("WatchData_CourseName", item.name);
    window.RCHistory.push({
      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) {
        const { onChange, updateCategoryTree, selectedRowKeys, onSelectChange } = this.props;
        message.success("移出成功");
        onChange();
        updateCategoryTree();
        if (selectedRowKeys.includes(item.id)) {
          onSelectChange(_.reject(selectedRowKeys, value => value === item.id));
        }
      }
    })
  }

  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, selectedRowKeys, onSelectChange } = this.props;
    const { current, size } = query;
    const rowSelection = {
      selectedRowKeys,
      preserveSelectedRowKeys: true,
      onChange: onSelectChange,
    }
    return (
      <div className="knowledge-base-list">
        <XMTable
          rowKey={(record) => record.id}
          rowSelection={rowSelection}
          size="middle"
          dataSource={dataSource}
          columns={this.parseColumns()}
          pagination={false}

          bordered
          className="knowledge-list-table"
          renderEmpty={{
            description: <span style={{ display: 'block', paddingBottom: 24 }}>暂无数据</span>
          }}
        />

        <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)
