/*
 * @Author: yuananting
 * @Date: 2021-02-22 17:51:28
 * @LastEditors: yuananting
 * @LastEditTime: 2021-03-18 09:32:59
 * @Description: 助学工具-题库-题库新建或编辑题库分类模态框
 * @Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 */
import React, { Component } from "react";
import { Modal, Form, Input, message } from "antd";
import User from "@/common/js/user";
import QuestionBankService from "@/domains/question-bank-domain/QuestionBankService";
class NewEditQuestionBankCategory 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();
    // this.getSameLevelNodes(this.props.treeData);
  }

  // 查询分类树
  queryCategoryTree = () => {
    let query = {
      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);
      }
    }
  };

  getEqualLevelNodes = (data, parentId) => {
    let nodes = [];
    data.forEach((item) => {
      if (item.parentId === parentId) {
        nodes.push(item);
      }
      if (item.children) {
        nodes.push(...this.getEqualLevelNodes(item.children, parentId));
      }
    });
    return nodes;
  };

  getChildLevelNodes = (data, id) => {
    let nodes = [];
    data.forEach((item) => {
      if (item.id === id && item.children) {
        nodes.push(...item.children);
      }
      if (item.children) {
        nodes.push(...this.getChildLevelNodes(item.children, id));
      }
    });
    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;
  };

  // 查询是否重名
  checkExist = (sameLevelNodes, categoryName) => {
    var result = null;
    sameLevelNodes.forEach((item) => {
      if (result != null) {
        return result;
      }
      if (item.categoryName === categoryName) {
        result = item;
      }
    });
    return result;
  };

  render() {
    const { title, label, treeData, addLevelType } = this.props;
    const { categoryName } = 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}
              onChange={(e) => {
                this.setState({
                  categoryName: e.target.value,
                });
              }}
            />
          </Form.Item>
        </Form>
      </Modal>
    );
  }
}
export default NewEditQuestionBankCategory;
