/*
 * @Description:
 * @Author: zangsuyun
 * @Date: 2021-03-12 14:25:52
 * @LastEditors: zangsuyun
 * @LastEditTime: 2021-04-10 11:23:08
 * @Copyright: © 2020 杭州杰竞科技有限公司 版权所有
 */

import React, { useState, useEffect } from "react";

import { Button, Menu, Dropdown, message, Modal } from "antd";
import SelectPrepareFileModal from "@/modules/prepare-lesson/modal/SelectPrepareFileModal";
import User from "@/common/js/user";
import Service from "@/common/js/service";
import KnowledgeAPI from "@/data-source/knowledge/request-api";
import MoveModal from '../../teach-tool/modal/MoveModal';
import Bus from "@/core/bus";
import './KnowledgeBaseOpt.less';

export default function KnowledgeBaseOpt({
  categoryId,
  selectedRowKeys,
  updateCategoryTree,
  onChange,
  onChangeKeys,
}) {
  const [modal, setModal] = useState(null);
  const [openMoveModal, setOpenMoveModal] = useState(false);
  const [data, setData] = useState([]);



  useEffect(() => {
    queryCategoryTree();
  }, []);

  useEffect(() => {
    clearSelect();
  }, [categoryId])

  // 查询分类树
  function queryCategoryTree() {
    let query = {
      storeId: User.getStoreId(),
      withCount: true,
    };
    KnowledgeAPI.getCategoryTree(query).then((res) => {
      const { categoryList = [] } = res.result;
      let list = renderTreeNodes(categoryList);
      setData(list);
    });
  }

  function renderTreeNodes(data) {
    let newTreeData = data.map((item) => {
      item.title = item.categoryName;
      item.value = item.id;
      item.key = item.id;
      if (item.sonCategoryList) {
        item.children = renderTreeNodes(item.sonCategoryList);
      }
      return item;
    });
    return newTreeData;
  };


  function handUpload(refIds) {
    const params = {
      categoryId: categoryId,
      refIds,
      storeId: User.getStoreId(),
      createId: User.getStoreUserId(),
      type: "FOLDER",
    };
    KnowledgeAPI.addKnowledge(params).then(({ success }) => {
      if (success) {
        message.success("新增成功");
        onChange();
        updateCategoryTree();
        setModal(null);
      }
    });
    setModal(null);
  }

  function handleAddFile() {
    let modal = (
      <SelectPrepareFileModal
        multiple={true}
        scene="knowledge"
        operateType="select"
        isOpen={true}
        accept=".ppt,.pptx,.doc,.docx,.pdf,.jpg,.jpeg,.png,.xlsx,.xls"
        tooltip="支持文件类型：ppt、word、excel、pdf、jpg、jpeg、png"
        selectTypeList={["JPG", "JPEG", "PNG", 'DOC', 'PDF', 'EXCEL', 'application/msword', 'application/vnd.ms-powerpoint']} // DOC 包含 .pptx,.docx,.xls.XLSX,WORD:DOC
        onClose={() => {
          setModal(null);
        }}
        onSelect={handUpload}
      />
    );
    setModal(modal);
  }

  function batchMove() {
    if (_.isEmpty(selectedRowKeys)) {
      message.warning('请先选择要移动的知识');
      return null;
    }
    setOpenMoveModal(true);
  }

  function batchMoveRemote(categoryId) {
    const data = {
      categoryId,
      ids: selectedRowKeys,
      storeId: User.getStoreId(),
    };
    Service.Hades('public/hades/batchMoveKnowledgeCategory', data, { reject: true }).then((res) => {
      if (res.success) {
        message.success('移动成功');
        onChange();
        Bus.trigger('knowledgeCategoryTree');
        clearSelect();
      } else {
        message.error('移动失败');
      }
    }).catch(() => {
      message.error('移动失败');
    })
  }

  function batchDelete() {
    if (_.isEmpty(selectedRowKeys)) {
      message.warning('请先选择要删除的知识');
      return null;
    }
    Modal.confirm({
      title: "确定要删除知识吗？",
      content: "删除后，不可恢复。",
      icon: (
        <span className="icon iconfont default-confirm-icon">&#xe839; </span>
      ),
      okText: "删除",
      cancelText: "取消",
      onOk: () => {
        const data = {
          ids: selectedRowKeys,
          storeId: User.getStoreId(),
        };
        Service.Hades('public/hades/batchDelKnowledge', data, { reject: true }).then((res) => {
          if (res.success) {
            message.success('删除成功');
            onChange();
            Bus.trigger('knowledgeCategoryTree');
            clearSelect();
          } else {
            message.error('删除失败');
          }
        }).catch(() => {
          message.error('删除失败');
        })
      },
    })
  }

  function onSelectPaper(keys) {
    if (keys.length > 50) {
      message.warning('最多只能选择50个知识');
      return null;
    }
    onChangeKeys(keys);
  };

  function clearSelect() {
    onChangeKeys([]);
  }

  return (
    <div className="knowledge-course-opt">
      {_.isEmpty(selectedRowKeys) ?
        categoryId !== '0' && <Button type="primary" onClick={handleAddFile} className="mr8">
          添加资料
        </Button>
        : <div className="select-container">
          <span className="con">
            <div>
              <span className="icon iconfont tip">&#xe6f2;</span>
              <span className="text">已选择{selectedRowKeys.length}项</span>
            </div>
            <div>
              <span className="clear" onClick={clearSelect}>清空</span>
            </div>
          </span>
        </div>
      }
      <Button
        className="mr8"
        onClick={() => {
          batchMove();
        }}
      >批量移动</Button>
      <Button
        onClick={() => {
          batchDelete();
        }}
      >批量删除</Button>
      {modal}
      {openMoveModal &&
        <MoveModal
          visible={openMoveModal}
          title="知识"
          data={data}
          categoryId={categoryId}
          length={selectedRowKeys.length}
          onCancel={() => setOpenMoveModal(false)}
          onOk={(categoryId) => {
            batchMoveRemote(categoryId);
            setOpenMoveModal(false);
          }}
        />
      }
    </div>
  );
}
