/*
  *  角色权限设置
  *
  * @Author:    黎永顺
  * @Date:      2024/8/21
  * @Wechat:
  * @Email:     971387674@qq.com
  * @description:
*/
import React, { Component } from "react";
import * as API from "../../../../apis/taxAgent";
import { Row } from "antd";
import { WeaLocaleProvider, WeaTree } from "ecCom";

const getLabel = WeaLocaleProvider.getLabel;

class AuthTree extends Component {
  constructor(props) {
    super(props);
    this.state = {
      checkedKeys: [], expandedKeys: [], datas: {}
    };
  }

  componentDidMount() {
    const { roleId } = this.props;
    API.getAuthOptTree({ roleId }).then(({ status, data }) => {
      if (status) {
        this.setState({
          datas: {
            canClick: true, id: data.key, nodeid: data.key, isParent: true, name: data.name,
            subs: _.map(data.modules, item => ({
              ...item, canClick: true, id: item.key, nodeid: item.key, pid: data.key, isParent: !_.isEmpty(item.pages),
              subs: _.map(item.pages, o => ({
                ...o, canClick: true, id: `${item.key}-${o.key}`, nodeid: `${item.key}-${o.key}`,
                pid: item.key, isParent: !_.isEmpty(o.opts),
                subs: _.map(o.opts, k => ({
                  canClick: true, id: `${o.key}-${k.key}`, name: k.name, nodeid: `${o.key}-${k.key}`,
                  pid: `${item.key}-${o.key}`, isParent: false, able: k.able
                }))
              }))
            }))
          }
        }, () => this.setState({ expandedKeys: this.initExpandKeys(), checkedKeys: this.initCheckedKeys() }));
      }
    });
  }

  initExpandKeys = () => {
    const { datas } = this.state;
    const parentIds = [];
    const findParent = (node) => {
      if (node.subs && node.subs.length > 0) {
        parentIds.push(node.id);
        node.subs.forEach(child => findParent(child));
      }
    };
    findParent(datas);
    return parentIds;
  };
  initCheckedKeys = () => {
    const { datas } = this.state;
    const checkedIds = [];
    const findCheckedId = (node) => {
      if (node.subs && node.subs.length > 0) {
        node.subs.forEach(child => {
          if (!!child.able) checkedIds.push(child.id);
          findCheckedId(child);
        });
      }
    };
    findCheckedId(datas);
    return checkedIds;
  };

  render() {
    const { checkedKeys, expandedKeys, datas } = this.state;
    return (
      <Row className="tax_role_auth_tree">
        <WeaTree
          checkable onCheck={checkedKeys => this.setState({ checkedKeys })} checkedKeys={checkedKeys}
          expandedKeys={expandedKeys} onExpand={expandedKeys => this.setState({ expandedKeys })}
          datas={datas}
        />
      </Row>
    );
  }
}

export default AuthTree;
