import React, { PureComponent } from "react";
import style from "styled-components";
import { Button, Form, TreeSelect, Radio, message, Alert, Drawer } from "antd";
// import Drawer from "react-motion-drawer";
import bcx_utils from "../../../common/bcx_utils";

import {
  publicCommonDictGetDictByCodeTypes, //字典数据
  systemComDepartGetTreeDepart, //选择部门
  systemSysMenuAllMenuTree, //获取所有菜单--树形
  systemComRoleAllotGetDataAuthority, //获取角色数据权限
  systemComRoleAllotSaveDataAuthority //新增角色数据权限
} from "../../../services/api";

const RadioboxGroup = Radio.Group;

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

@Form.create()

// 角色权限抽屉
export default class DataPermissionsSet extends PureComponent {
  constructor(props, context) {
    super(props, context);
    this.state = {
      roleId: this.props.roleId,
      roleName: this.props.caption,
      open: this.props.visiable, //备注
      departData: [], //特定部门
      departName: "", //特定部门名称
      dataAuthType: [], //权限管理范围
      permissionsTree: [], //部门树
      radioValue: "", //默认初始化
      initRadioValue: "", //初始化时候的值，和修改后做比较
      initDepartData: "" //初始化时候的值，和修改后做比较
    };
  }
  /******************************生命周期******************************/

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

  systemComRoleAllotGetDataAuthority = roleId => {
    systemComRoleAllotGetDataAuthority({ roleId }).then(
      res => {
        console.log(res, "获取角色数据权限");
        if (res.retType === "0" && res.data) {
          const resData = res.data;
          this.setState({
            radioValue: resData.dataAuthType,
            initRadioValue: resData.dataAuthType
          });
          if (resData.dataAuthType === "4") {
            let departData = resData.comRolePartDataAuthList.map(
              v => v.departId
            );
            // 过滤掉不在部门内的id（2019-07-31）
            departData = departData.filter(item => this._idIsInTree(item));
            this.setState(
              {
                departData,
                initDepartData: departData
              },
              () => {
                console.log(this.state.departData);
              }
            );
          }
        }
      },
      err => {
        console.log(err, "获取角色数据权限");
      }
    );
  };
  // 判断特定部门是否在树中
  _idIsInTree(id) {
    const treeData = JSON.parse(JSON.stringify(this.state.departTree));
    let boo = false;
    function recursion (arr) {
      for(let i = 0; i < arr.length; i++) {
        if(arr[i].value == id) {
          boo = true;
          break;
        }
        if(arr[i].children) {
          recursion(arr[i].children);
        }
      }
    }
    recursion(treeData);
    return boo;
  }
  // 选中节点后
  getTreeDepart = () => {
    systemComDepartGetTreeDepart({}).then(
      ({ data = [] }) => {
        if (data.length !== 0) {
          data[0].disabled = 1;
        }
        this.setState({ departTree: data });
      },
      err => {
        console.log(err, "getTreeDepart-选择部门-err");
      }
    );
  };

  //获得公共信息
  getAllType = () => {
    publicCommonDictGetDictByCodeTypes({ codeTypes: "dataAuthType" }).then(
      res => {
        //判断获取数据是否为空
        if (res.data) {
          const allTypeData = res.data;
          this.setState({
            dataAuthType: allTypeData.dataAuthType //权限管理范围
          });
        }
      }
    );
  };

  //获取所有菜单--树形
  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);
      }
    );
  };

  /******************************相关事件******************************/
  //表单提交-保存
  handleSaveRoleAllowSubmit = () => {
    const {
      roleId,
      radioValue,
      departData,
      initRadioValue,
      initDepartData
    } = this.state;

    //选择"特定部门"
    let departIds = "";
    if (radioValue === "4") {
      departIds = JSON.stringify(
        departData.map(v => {
          return {
            departId: v
          };
        })
      );
    }
    const obj = {
      roleId,
      dataAuthType: radioValue,
      departIds
    };

    //如果没有改变，禁止提交
    if (radioValue === "4") {
      if (initRadioValue === radioValue && initDepartData === departData) {
        message.info("当前信息未修改，不能保存");
        return;
      }
      if (departData.length === 0) {
        message.info("请选择特定企业部门");
        return;
      }
    } else {
      if (initRadioValue === radioValue) {
        message.info("当前信息未修改，不能保存");
        return;
      }
    }
    console.log("obj", obj);
    this.systemComRoleAllotSaveDataAuthority(obj);
  };

  //角色权限新增修改-保存
  systemComRoleAllotSaveDataAuthority = ajaxData => {
    const { dataAuthType } = ajaxData;
    bcx_utils.preventRepeatAsync(callback =>
      callback(resolve => {
        if (dataAuthType === "") {
          ajaxData.dataAuthType = "1";
          //角色权限新增修改 临时添加
          systemComRoleAllotSaveDataAuthority(ajaxData).then(
            data => {
              console.log(data);
              resolve();
              this.setState({ open: false });
              this.props.refreshList();
            },
            err => {
              console.log(err);
            }
          );
        } else {
          //角色权限新增修改
          systemComRoleAllotSaveDataAuthority(ajaxData).then(
            data => {
              console.log(data);
              resolve();
              this.setState({ open: false });
              this.props.refreshList();
            },
            err => {
              console.log(err);
              resolve();
            }
          );
        }
      })
    );
  };

  //管理范围
  onRadioChange = e => {
    this.setState({ radioValue: e.target.value });
  };
  //管理范围 特定部门选中
  onPartChange = (value, label, extra) => {
    const lastValue = this.state.departData;
    if (
      extra.triggerNode &&
      extra.triggerNode.props &&
      extra.triggerNode.props.treeType === "1"
    ) {
      this.setState({ departData: lastValue, departName: label }, () => {
        console.log("特定部门名称", this.state.departName);
      });
    } else {
      this.setState({ departData: value, departName: label }, () => {
        console.log("特定部门名称", this.state.departName);
      });
    }
  };

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

  //权限管理范围
  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>
      );
    });
  };

  render() {
    return (
      <Box>
        <Drawer
          title={<span>{this.state.roleName}（权限分配）</span>}
          // overlayColor="rgba(0, 0, 0,0)"
          placement="right"
          visible={this.state.open}
          // 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-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}
                            allowClear
                            multiple
                          />
                        </div>
                      )}
                    </div>
                  </div>
                  <div>
                    <Alert
                      message={
                        <div>
                          <span>影响功能数据及页面数据：</span><br/>
                          <span>①组织架构页面，部门及人员查看及管理；</span><br/>
                          <span>②保安人员查询页面，搜索及导出数据；</span><br/>
                          <span>③员工端/App端企业通讯录数据查看。</span><br/>
                        </div>
                      }
                      type="info"
                      showIcon
                    />
                  </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:106px;
       display:inline-block;
       float:left
    }
    .c{
      margin-left:84px;
      vertical-align: top;
      &.perm{
       position: relative;
       top: -7px;
      }
    }
  }
  .drawer-content{
    margin-top:28px;
  }
}`;
