import React, { PureComponent } from "react";
// import { connect } from 'dva';
import style from "styled-components";
import {
  // Input,
  Alert,
  Button,
  Form,
  // TreeSelect,
  // DatePicker,
  // InputNumber,
  // Radio,
  // Icon,
  // Checkbox,
  Tree,
  message,
  Drawer
} from "antd";
// import Drawer from 'react-motion-drawer';
import bcx_utils from "../../../common/bcx_utils";
// import PSelect from "../../../components/Pro/PSelect";
// import * as api from "../../../services/api";

import {
  //searchRoleAndRoleGroupList,//查询角色组与角色列表功能
  //enterpriseRoleSave,//角色新增
  // publicCommonDictGetDictByCodeTypes, //字典数据
  // systemComDepartGetTreeDepart, //选择部门
  systemSysMenuAllMenuTree, //获取所有菜单--树形
  systemComRoleAllotSave, //角色权限新增修改
  systemComRoleAllotGetChildMenuByRoleId //GET获取角色权限
} from "../../../services/api";

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

message.config({
  top: 100,
  right: 5,
  duration: 2
});

// @connect(state => ({ profile: state.profile }))
@Form.create()

// 角色权限抽屉
export default class RoleAllow extends PureComponent {
  constructor(props, context) {
    super(props, context);
    this.state = {
      roleId: this.props.roleId,
      roleName: this.props.caption,
      open: this.props.visiable, //备注
      //权限分配树组件
      checkedKeys: [], //选中的功能权限
      halfCheckedKeys: [], //半勾选状态的节点（比如子节点没有勾选完全时，父节点就会被存储到这里）
      initCheckedKeys: [], //接口返回的初始menuId值
      permissionsTree: [] //部门树
    };
  }
  /******************************生命周期******************************/

  componentDidMount() {
    // this.getAllType(); //获取所有类型-页面需要的数据字典
    // this.getTreeDepart();
    this.systemSysMenuAllMenuTree(); //树
  }
  componentWillReceiveProps(props) {
    if (this.state.roleId !== props.roleId) {
      this.systemComRoleAllotGetChildMenuByRoleId(props.roleId);
    }
    this.setState({
      open: props.visiable,
      roleId: props.roleId,
      roleName: props.caption
    });
  }
  /******************************ajax请求******************************/

  /******************************相关事件******************************/

  //权限分配树形组件
  // onExpand = (expandedKeys) => {
  //   console.log('onExpand', arguments);
  //   // if not set autoExpandParent to false, if children expanded, parent can not collapse.
  //   // or, you can remove all expanded children keys.
  //   this.setState({
  //     expandedKeys,
  //     autoExpandParent: false,
  //   });
  // }

  // 选中节点后
  // getTreeDepart = () => {
  //   systemComDepartGetTreeDepart({}).then(
  //     ({ data = [] }) => {
  //       console.log(data, 'getTreeDepart-选择部门-data');
  //       this.setState({ departTree: data });
  //     },
  //     err => {
  //       console.log(err, 'getTreeDepart-选择部门-err');
  //     }
  //   );
  // };

  //获得公共信息
  // getAllType = () => {
  //   publicCommonDictGetDictByCodeTypes({ codeTypes: 'dataAuthType' }).then(
  //     res => {
  //       console.log('角色权限-权限设置管理范围字典-res:', res);
  //       //判断获取数据是否为空
  //       if (res.data) {
  //         const allTypeData = res.data;
  //         this.setState({
  //           dataAuthType: allTypeData.dataAuthType //权限管理范围
  //         });
  //       }
  //     }
  //   );
  // };

  //权限选中
  // onPermCheck = checkedKeys => {
  //   this.setState({ checkedKeys });
  // };
  onPermCheck = (checkedKeys, info) => {
    // console.log('onPermCheck', checkedKeys, info);
    this.setState({
      checkedKeys,
      halfCheckedKeys: info.halfCheckedKeys
    });
  };

  //获取所有菜单--树形
  systemSysMenuAllMenuTree = () => {
    systemSysMenuAllMenuTree({}).then(
      ({ data: [permissionsTree] }) => {
        let newArr1 = [{ ...permissionsTree, ...{ title: "全部权限" } }];
        //迭代自身，
        const deleteChild = arr => {
          const newArr = JSON.parse(JSON.stringify(arr));
          newArr.forEach(({ 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;
        };
        newArr1 = deleteChild(newArr1);
        this.setState({ permissionsTree: newArr1 });
      },
      err => {
        console.log(err);
      }
    );
  };

  //获取角色权限
  systemComRoleAllotGetChildMenuByRoleId = roleId => {
    // this.setState({ loading: true })
    console.log("获取角色权限-当前角色ID", this.state.roleId);
    systemComRoleAllotGetChildMenuByRoleId({ roleId }).then(
      ({ data: { menuIds } }) => {
        // (data) => {
        // console.log("拉取所有权限值值值！！！！！！！", data);
        this.setState({
          checkedKeys: menuIds.split(","),
          initCheckedKeys: menuIds
        });
      },
      err => {
        console.log(err);
        // this.setState({ loading: true })
      }
    );
  };

  //表单提交-保存
  handleSaveRoleAllowSubmit = () => {
    const {
      roleId,
      checkedKeys,
      halfCheckedKeys,
      initCheckedKeys
    } = this.state;

    const concatCheckedKeys = [...checkedKeys, ...halfCheckedKeys];
    //移除全选时候 组件自动添加的属性。
    if (concatCheckedKeys.includes("0-0")) {
      // if (checkedKeys.includes("0-0")) {
      // checkedKeys.pop();
      concatCheckedKeys.pop();
    }
    const obj = {
      roleId,
      // menuIds: checkedKeys.join()
      menuIds: concatCheckedKeys.join()
    };

    //如果没有改变，禁止提交
    if (initCheckedKeys === concatCheckedKeys.join()) {
      message.info("当前信息未修改，不能保存");
      return;
    }
    // console.log("initCheckedKeys",initCheckedKeys);
    // console.log("concatCheckedKeys",concatCheckedKeys.join());
    this.systemComRoleAllotSave(obj);
  };

  //角色权限新增修改-保存
  systemComRoleAllotSave = ajaxData => {
    const { menuIds } = ajaxData;
    bcx_utils.preventRepeatAsync(callback =>
      callback(resolve => {
        if (menuIds.length === 0) {
          message.error("请选择功能权限", 1.5, () => {
            resolve();
          });
        } else {
          //角色权限新增修改
          systemComRoleAllotSave(ajaxData).then(
            data => {
              console.log(data);
              resolve();
              this.setState({ open: false });
              this.props.refreshList();
            },
            err => {
              console.log(err);
              resolve();
            }
          );
        }
      })
    );
  };

  /******************************render******************************/
  //权限分配树形组件
  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() {
    return (
      <Box>
        <Drawer
          // overlayColor='rgba(0, 0, 0,0)'
          placement="right"
          visible={this.state.open}
          title={<span>{this.state.roleName}（权限分配）</span>}
          // noTouchClose
          width={600}
          // zIndex={999}
          className="permissions-allocation"
          onChange={open => {
            this.props.onChange(open);
            this.setState({ open });
          }}
          onClose={() => this.setState({ open: false })}
          destroyOnClose
          style={{
            height: "calc(100% - 55px)",
            overflow: "auto",
            paddingBottom: 53
          }}
        >
          {/* <div className='drawer'> */}
          <div>
            {/* <div className='drawer-header'>
              {this.state.roleName}（权限分配）
            </div> */}
            {/* <div className='drawer-content'> */}
            <div>
              <div className="permissions-form">
                <div className="permissions-bottom">
                  <div className="item">
                    <Alert message="注：本功能用于配置角色人员登录企业端使用的菜单权限，有授权则可见可操作，反之不可见不可操作。不控制App端的菜单权限。
" type="warning" showIcon />
                    <div className="l ant-form-item-required">菜单权限:</div>
                    <div className="c perm permissions-tree">
                      <Tree
                        checkable
                        onCheck={this.onPermCheck}
                        checkedKeys={this.state.checkedKeys}
                        className="permissions-tree"
                      >
                        {this.renderTreeNodes(this.state.permissionsTree)}
                      </Tree>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            {/* <div className='drawer-footer'> */}
            <div
              style={{
                position: "absolute",
                bottom: 0,
                width: "100%",
                borderTop: "1px solid #e8e8e8",
                padding: "10px 16px",
                textAlign: "right",
                left: 0,
                background: "#fff",
                borderRadius: "0 0 4px 4px"
              }}
            >
              <Button
                style={{
                  marginRight: 8
                }}
                onClick={() => this.setState({ open: false })}
              >
                取消
              </Button>
              <Button
                onClick={this.handleSaveRoleAllowSubmit}
                type="primary"
                style={{ marginLeft: 8 }}
                htmlType="submit"
              >
                保存
              </Button>
            </div>
          </div>
        </Drawer>
      </Box>
    );
  }
}

/************************样式************************/

const Box = 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;
      }
    }
  }
  .drawer-content{
    margin-top:28px;
  }
}`;
