/*
 * @Author: yuananting
 * @Date: 2021-02-22 17:51:28
 * @LastEditors: yuananting
 * @LastEditTime: 2021-03-31 18:33:23
 * @Description: 助学工具-新建编辑课程分类模态框
 * @Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 */
import React, { Component } from "react";
import { Modal, Form, Input } from "antd";
import User from "@/common/js/user";
import QuestionBankService from "@/domains/question-bank-domain/QuestionBankService";
class NewEditCourseCategoryModal extends Component {
  formRef = React.createRef();
  constructor(props) {
    super(props);
    this.state = {
      treeData: [],
      categoryName:
        this.props.type === "edit" ? this.props.node.categoryName : null,
    };
  }

  componentDidMount() {
    this.queryCategoryTree();
  }

  // 查询分类树
  queryCategoryTree = () => {
    let query = {
      bizType: "QUESTION",
      count: false,
      source: 0,
      userId: User.getStoreUserId(),
      tenantId: User.getStoreId(),
    };
    QuestionBankService.queryCategoryTree(query).then((res) => {
      const { result = [] } = res;
      this.setState({ treeData: result });
    });
  };

  // 确定新增或编辑
  confirmOperate = async () => {
    const { categoryName } = this.state;
    const { node, addLevelType, type } = this.props;
    let params = {
      source: 0,
      tenantId: User.getStoreId(),
      userId: User.getStoreUserId(),
    };
    if (type === "new") {
      //新增
      params.categoryName = categoryName;
      if (addLevelType === "equal") {
        params.parentId = node ? node.parentId : 0;
        params.categoryLevel = node ? node.categoryLevel : 0;
      } else {
        params.parentId = node.id;
        params.categoryLevel = node.categoryLevel + 1;
      }
      try {
        await this.formRef.current.validateFields();
        QuestionBankService.addCategory(params).then((res) => {
          if (res.success) {
            this.props.close();
          }
        });
      } catch (e) {
        console.log(e);
      }
    } else {
      // 编辑
      params.categoryId = node.id;
      params.parentId = node.parentId;
      params.categoryLevel = node.categoryLevel;
      params.categoryName = categoryName;
      try {
        await this.formRef.current.validateFields();
        QuestionBankService.editCategory(params).then((res) => {
          if (res.success) {
            this.props.close();
          }
        });
      } catch (e) {
        console.log(e);
      }
    }
  };

  // 校验是否重名
  checkExist = (sameLevelNodes, categoryName) => {
    if (sameLevelNodes.length > 0 && sameLevelNodes[0].parentId === "0") {
      if (categoryName === "未分类") {
        return true;
      }
    }
    var result = null;
    sameLevelNodes.forEach((item) => {
      if (result != null) {
        return result;
      }
      if (item.categoryName === categoryName) {
        result = item;
      }
    });
    return result;
  };

  // 查询同级节点
  getEqualLevelNodes = (data, parentId) => {
    let nodes = [];
    data.forEach((item) => {
      if (item.parentId === parentId) {
        nodes.push(item);
      }
      if (item.sonCategoryList) {
        nodes.push(...this.getEqualLevelNodes(item.sonCategoryList, parentId));
      }
    });
    return nodes;
  };

  // 查询子级节点
  getChildLevelNodes = (data, id) => {
    let nodes = [];
    data.forEach((item) => {
      if (item.id === id && item.sonCategoryList) {
        nodes.push(...item.sonCategoryList);
      }
      if (item.sonCategoryList) {
        nodes.push(...this.getChildLevelNodes(item.sonCategoryList, id));
      }
    });
    console.log(nodes)
    return nodes;
  };

  getSameLevelNodes = (data, type) => {
    let sameLevelNodes = [];
    if (type === "equal") {
      let parentId = this.props.node ? this.props.node.parentId : "0";
      sameLevelNodes = this.getEqualLevelNodes(data, parentId);
    } else {
      sameLevelNodes = this.getChildLevelNodes(data, this.props.node.id);
    }
    return sameLevelNodes;
  };

  render() {
    const { title, label, addLevelType } = this.props;
    const { categoryName, treeData } = this.state;
    const _that = this;
    return (
      <Modal
        visible={true}
        title={title}
        onOk={this.confirmOperate}
        onCancel={() => this.props.close()}
      >
        <Form ref={this.formRef}>
          <Form.Item
            name="categoryName"
            label={label}
            required
            rules={[
              {
                required: true,
                message: `请输入${label}`,
              },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  let sameLevelNodes = _that.getSameLevelNodes(
                    treeData,
                    addLevelType
                  );
                  if (_that.checkExist(sameLevelNodes, value)) {
                    return Promise.reject("此分类名称已存在");
                  } else {
                    return Promise.resolve();
                  }
                },
              }),
            ]}
          >
            <Input
              defaultValue={categoryName}
              placeholder={`请输入${title}，最多10个字`}
              maxLength={10}
              autoComplete="off"
              onChange={(e) => {
                this.setState({
                  categoryName: e.target.value,
                });
              }}
            />
          </Form.Item>
        </Form>
      </Modal>
    );
  }
}
export default NewEditCourseCategoryModal;
