import React, {PureComponent} from 'react';
import style from "styled-components";
import {Form, Input, Button, Menu, Icon, Modal, message, Radio, Tree, Checkbox, TreeSelect} from 'antd';
import PLoading from "../../../../components/Pro/PLoading";
import bcx_utils from "../../../../common/bcx_utils";
import {
  searchRoleAndRoleGroupList,
  publicCommonDictGetDictByCodeTypes,
  systemComDepartGetTreeDepart,
  systemSysMenuAllMenuTree,
  systemComRoleAllotSave,
  systemComRoleAllotGetChildMenuByRoleId
} from "../../../../services/api";
import * as api from "../../../../services/api";

const FormItem = Form.Item;
const {TreeNode} = Tree;
const RadioboxGroup = Radio.Group;

@Form.create()
/**
 * 配置角色组
 */
//1、Menu 的 onClick 以及 Menu.SubMenu 的 onTitleClick 绑定同一个事件。记录点击菜单栏的位置，保存再currentIndex；
//2、dataSource 存储的是请求的 菜单栏的数据。 根据currentIndex的位置。读取当前选中数据。
//3. 默认角色组的权限不可修改。因为默认组的游标都是["0",n]的形式。依据这个禁用提交按钮。

export default class InitialPermissions extends PureComponent {
  constructor(props, context) {
    super(props, context);
    this.state = {
      dataSource: [],
      currentIndex: ["0", "0"],//当前定位,第一位存储的是一级菜单，第二位存储的是二级菜单。都是从0开始
      dataAuthType: [],//权限管理范围
      departTree: [],//部门树
      permissionsTree: [],//部门树

      departData: "",//特定部门
      radioValue: "",//默认初始化
      checkedKeys: [],//选中的功能权限

      loading: true,//加载中
    };

  }

  /******************************生命周期******************************/

  componentDidMount = () => {
    this.searchRoleAndRoleGroupList();
    this.getAllType(); //获取所有类型
    this.getTreeDepart();
    this.systemSysMenuAllMenuTree();
  }
  componentWillReceiveProps = () => {

  }
  /******************************ajax请求******************************/

    //角色组及角色列表获取
  searchRoleAndRoleGroupList = () => {
    searchRoleAndRoleGroupList().then(
      ({data}) => {
        console.log(data);
        this.setState({dataSource: data}, () => {
          this.systemComRoleAllotGetChildMenuByRoleId("0", "0");
        });
      },
      (err) => {
        console.log(err);
      }
    );
  }
  //获得公共信息
  getAllType = () => {
    publicCommonDictGetDictByCodeTypes({codeTypes: 'dataAuthType'})
      .then(({data = []}) => {
        console.log('角色权限-权限设置管理范围字典asfasfssss-res:', data);
        this.setState({
          dataAuthType: data.dataAuthType//权限管理范围
        });
      });
  };
  //选中节点后
  getTreeDepart = () => {
    systemComDepartGetTreeDepart({}).then(
      ({data = []}) => {
        this.setState({departTree: data});
      },
      err => {
        console.log(err, "getTreeDepart-选择部门-err");
      }
    );
  };

  //获取所有菜单--树形
  systemSysMenuAllMenuTree = () => {
    systemSysMenuAllMenuTree({}).then(
      ({data: [permissionsTree]}) => {
        let newArr = [{...permissionsTree, ...{title: "全部权限"}}];
        //迭代自身，
        const deleteChild = arr => {
          let newArr = JSON.parse(JSON.stringify(arr));
          newArr.map(({title, key, children}, index) => {
            newArr[index] = {
              title, key, children
            };
            if (newArr[index].children.length !== 0) {
              newArr[index].children = deleteChild(children);
            } else {
              delete  newArr[index].children;
            }
          });
          return newArr;
        }
        newArr = deleteChild(newArr);
        this.setState({permissionsTree: newArr});
      },
      (err) => {
        console.log(err);
      }
    );
  }

  //角色权限新增修改
  systemComRoleAllotSave = (ajaxData) => {
    const {dataAuthType, menuIds} = ajaxData;
    bcx_utils.preventRepeatAsync((callback) => callback((resolve) => {

      if (dataAuthType === "") {
        message.error("请选择管理范围", 1.5, () => {
          resolve();
        });
      } else if (menuIds.length === 0) {
        message.error("请选择功能权限", 1.5, () => {
          resolve();
        });
      } else {
        const hide = message.loading('加载中..',0);
        //角色权限新增修改
        systemComRoleAllotSave(ajaxData).then(
          (data) => {
            hide();
            console.log(data);
            // message.success(data.msg);
            resolve();
          },
          (err) => {
            hide();
            console.log(err);
            message.error(err.msg);
          }
        );
      }
    }))
  }

  //获取角色权限
  systemComRoleAllotGetChildMenuByRoleId = (pos1, pos2) => {
    //清空数据,显示加载中
    this.setState({
      loading: true,
      departData: ""
    });
    console.log('加载中..');
    const hide = message.loading('加载中..');

    const roleId = this.state.dataSource[pos1]["comRolesList"][pos2]["roleId"];
    systemComRoleAllotGetChildMenuByRoleId({roleId}).then(
      ({data: {dataAuthType, departId, menuIds}}) => {
        hide();
        this.setState({radioValue: dataAuthType, checkedKeys: menuIds.split(","), loading: false});
        if (dataAuthType === "4") {
          console.log('加载结束..');
          this.setState({departData: departId.toString()}, () => {
            console.log(this.state.departData);
          });
        }
      },
      (err) => {
        console.log(err);
        this.setState({loading: true})
      }
    );
  }
  /******************************相关事件******************************/


    //菜单点击 更新索引
  itemChange = ({key}) => {
    const arr = key.split("-");
    //设置选中选中索引， 重置右侧选中
    if (arr.length === 2) {
      console.log(arr);
      this.setState({
        currentIndex: arr,
      });
      this.systemComRoleAllotGetChildMenuByRoleId(arr[0], arr[1]);
    }
  }

  //管理范围
  onRadioChange = (e) => {
    this.setState({radioValue: e.target.value,});
  }

  //管理范围 特定部门选中
  onPartChange = (value, label) => {
    this.setState({departData: value});
  }


  //权限选中
  onPermCheck = (checkedKeys) => {
    this.setState({checkedKeys});
  }


  //提交保存信息
  submitForm = () => {
    const {dataSource, currentIndex: [first, second], radioValue, departData, checkedKeys} = this.state;
    const roleId = dataSource[first]["comRolesList"][second]["roleId"];

    //选择"特定部门"
    let departId = "";
    if (radioValue === "4") {
      departId = departData;
    }
    //移除全选时候 组件自动添加的属性。
    if (checkedKeys.includes("0-0")) {
      checkedKeys.pop();
    }
    const ajaxData = {
      roleId,
      dataAuthType: radioValue,
      departId,
      menuIds: checkedKeys.join(),
    };
    this.systemComRoleAllotSave(ajaxData)
  }


  /******************************render******************************/

    // 左侧菜单
  renderCourse = () => {
    const arrs = this.state.dataSource.map((val, key) => {

      const arrLength = val.comRolesList.length;

      const title = (
        <span key={key + "icon"}>
          <Icon type="folder-open" style={{fontSize: 14, color: '#909CA8'}}/><span> {val.roleGroupName} </span>
        </span>
      );

      if (arrLength === 0) {
        return (
          <Menu.Item key={key}>
            <Icon type="folder-open" style={{fontSize: 14, color: '#909CA8'}}/>
            {val.roleGroupName}
          </Menu.Item>
        );
      } else {
        return (
          <Menu.SubMenu
            title={title}
            onTitleClick={this.itemChange}
            key={key}
          >
            {val.comRolesList.map((v, k) => {
              return (
                <Menu.Item
                  key={`${key}-${k}`}
                >
                  <Icon type="user" style={{fontSize: 14, color: '#909CA8'}}/>
                  {v.roleName}
                </Menu.Item>
              );
            })}
          </Menu.SubMenu>
        );
      }
    });
    return arrs;
  };


  //权限管理范围
  renderDataAuthType = () => {
    return this.state.dataAuthType.map((val, key) => {
      return (
        <div key={key} style={{marginBottom: 18}}>
          <Radio key={key} value={val.codeValue + ""}>{val.label}</Radio>
        </div>
      );
    });
  };

  //权限分配树形组件
  renderTreeNodes = (data) => {
    return data.map((item) => {
      if (item.children) {
        return (
          <TreeNode title={item.title} key={item.key} dataRef={item}>
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode {...item} dataRef={item}/>;
    });
  }


  /******************************render******************************/

  render() {

    const {dataSource, loading} = this.state;
    const [first, second] = this.state.currentIndex;
    return (
      <div>
        {dataSource.length !== 0 && (
          <Container>
            <div className="department-content">
              <div className="department-inquiry">
                <div className="depart-menu">
                  <Menu
                    mode="inline"
                    onClick={this.itemChange}
                    style={{width: 213}}
                    defaultSelectedKeys={['0-0']}
                    defaultOpenKeys={['0']}
                  >
                    {this.renderCourse()}
                  </Menu>
                </div>
              </div>
              <div className="department-right">
                {loading ? <PLoading/> : (
                  <div>
                    <header className="edit-header">
                      <h2>{dataSource[first]["comRolesList"][second]["roleName"]}（权限分配）</h2>
                    </header>
                    <div className="permissions-form">
                      <div className="permissions-top">
                        <div className="item">
                          <div className="l ant-form-item-required">
                            管理范围:
                          </div>
                          <div className="c">
                            <RadioboxGroup onChange={this.onRadioChange} value={this.state.radioValue}>
                              {this.renderDataAuthType()}
                            </RadioboxGroup>
                            {this.state.radioValue === "4" && (
                              <div>
                                <TreeSelect
                                  dropdownStyle={{maxHeight: 400, overflow: "auto"}}
                                  style={{width: 294, margin: "0 0 24px 20px"}}
                                  placeholder="请选择特定企业部门"
                                  treeData={this.state.departTree}
                                  value={this.state.departData}
                                  treeDefaultExpandAll
                                  onChange={this.onPartChange}
                                />
                              </div>
                            )}
                          </div>
                        </div>
                      </div>
                      <div className="permissions-bottom">
                        <div className="item">
                          <div className="l ant-form-item-required">
                            功能权限:
                          </div>
                          <div className="c perm">
                            <Tree
                              checkable
                              onCheck={this.onPermCheck}
                              checkedKeys={this.state.checkedKeys}
                            >
                              {this.renderTreeNodes(this.state.permissionsTree)}
                            </Tree>
                          </div>
                        </div>
                      </div>
                      <div style={{paddingLeft: 82, marginTop: 24}}>
                        {/*<Button>取消</Button>*/}
                        {first === "0" && (
                          <Button type="primary" style={{marginLeft: 8}} htmlType="submit" disabled={true}>保存</Button>
                        )}
                        {first !== "0" && (
                          <Button type="primary" style={{marginLeft: 8}} htmlType="submit" className="blue"
                                  onClick={this.submitForm}>保存</Button>
                        )}
                      </div>
                    </div>
                  </div>
                )}


              </div>
            </div>
          </Container>
        )}
      </div>
    );
  }
}

/*********************样式*************************** */
const Container = style.div`{
    .item{
      .l{
         font-size: 14px;
         color: #666666;
         width:84px;
         display:inline-block;
         float:left
      }
      .c{
        margin-left:84px;
        vertical-align: top;
        &.perm{
         position: relative;
         top: -7px;
        }
      }
    }
    .ant-btn-primary.blue{
        background-color: #0F71FF;
    }
    .ant-menu-submenu > .ant-menu{
        background:#fff;
    }

    .department-content{
        min-height: 600px;
        background: #fff;
        border-radius: 5px;
        padding-left: 220px;
        position: relative;
        .department-inquiry{
          overflow-y: auto;
          height: 600px;
          width: 220px;
          position: absolute;
          top: 0;
          left: 0;
          input{
            color: #333;
          }
          .depart-menu{
            span{
              color: #333;
              font-size: 14px;
            }
            ul li{
              color: #333;
              font-size: 14px;
            }
          }
        }
        .department-right{
            margin-left:1px;
            padding:0px 24px;
            border-left:1px solid #eee;
            min-height:600px;
            .department-title{
                font-size: 16px;
                color: #333333;
            }
        }
      }
}`;
