import React, {PureComponent} from 'react';
import style from "styled-components";
import {Input, Button, Menu, Icon, Modal, message} from 'antd';
import bcx_utils from "../../../../common/bcx_utils";
import {
  searchRoleAndRoleGroupList,
  enterpriseRoleDeleteById,
  systemComDepartDelete,
  systemComRoleBatchInsertRole
} from "../../../../services/api";


// @connect(state => ({
//   monitor: state.monitor,
// }))

// const { Search } = Input;
// const { Option } = Select;

/**
 * 配置角色
 */
export default class InitialRole extends PureComponent {
  constructor(props, context) {
    super(props, context);
    this.state = {

      dataSource: [],
      dataSourceChace: [],
      currentIndex: ["0"],//当前定位
    };

  }

  /******************************生命周期******************************/
  componentDidMount = () => {
    this.searchRoleAndRoleGroupList();
  }
  /******************************ajax请求******************************/

    //角色组及角色列表获取
  searchRoleAndRoleGroupList = () => {
    searchRoleAndRoleGroupList().then(
      ({data}) => {
        console.log(data);
        this.setState({dataSource: data});
      },
      (err) => {
        console.log(err);
      }
    );
  }

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

    //删除角色
  remove = (roleId, index, child) => {
    const dataSource = bcx_utils.jsoncopy(this.state.dataSource);
    //判断是不是本地生成的数据
    if (roleId !== "") {
      Modal.confirm({
        title: '确认删除该记录?',
        content: '',
        onOk: () => {
          //角色删除功能
          enterpriseRoleDeleteById({roleId}).then(
            ({msg}) => {
              message.success(msg);
              dataSource[index]["comRolesList"] = dataSource[index]["comRolesList"].filter((val, index) => index !== child);
              this.setState({dataSource});
            },
            (err) => {
              console.log(err);
              message.error(err.msg);
            }
          );
        },
        onCancel() {
          console.log('Cancel');
        },
      });
    } else {
      dataSource[index]["comRolesList"] = dataSource[index]["comRolesList"].filter((val, index) => index !== child);
      this.setState({dataSource});
    }
  }


  //增加角色
  add = () => {
    const dataSource = bcx_utils.jsoncopy(this.state.dataSource);
    const [first] = this.state.currentIndex;
    dataSource[first]["comRolesList"].push({
      "roleId": "",
      "roleName": ""
    });
    this.setState({dataSource});
  }

  //菜单点击 更新索引
  itemChange = ({key}) => {
    const arr = key.split("-");
    if (arr.length === 1) {
      this.setState({currentIndex: arr});
    }
  }

  //角色名称修改
  inputChange = (first, second, e) => {
    const dataSource = bcx_utils.jsoncopy(this.state.dataSource);
    dataSource[first]["comRolesList"][second]["roleName"] = e.target.value;
    this.setState({dataSource});
  }


  //添加、修改
  systemComRoleBatchInsertRole = () => {
    const dataSource = bcx_utils.jsoncopy(this.state.dataSource);
    const [first] = this.state.currentIndex;
    const item = dataSource[first];
    const arr = item.comRolesList.map(({roleId, roleName}) => ({roleId, roleName}));
    const ajaxDate = {
      comRoles: JSON.stringify(arr),
      roleGroupId: item.roleGroupId
    };
    systemComRoleBatchInsertRole(ajaxDate).then(
      (data) => {
        console.log(data);
        // message.success(data.msg);
        this.searchRoleAndRoleGroupList();
      },
      (err) => {
        console.log(err);
      }
    );
  }


  /******************************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>
      );
      return (
        <Menu.Item key={key}>
          <Icon type="folder-open" style={{fontSize: 14, color: '#909CA8'}}/>
          {val.roleGroupName}
        </Menu.Item>
      );
    });
    return arrs;
  };


  //配置角色
  renderRoles = () => {

    const {dataSource, currentIndex} = this.state;
    if (!dataSource) {
      return;
    }
    if (dataSource.length === 0) {
      return;
    }
    let arrItem = "";
    const [first] = currentIndex;
    //点击在第一级
    if (currentIndex.length === 1) {
      return (
        arrItem = dataSource[first].comRolesList.map((v, i) => {
          const ifModificate = first !== "0";//判断是否第一项默认组
          return (
            <div key={i} className="item">
              <div className="l ant-form-item-required">
                角色名称:
              </div>
              <Input placeholder="请选择"
                     style={{width: 250, marginRight: 8}}
                     disabled={!ifModificate}
                     maxLength={20}
                     className="c"
                     value={v.roleName}
                     onChange={this.inputChange.bind(this, first, i)}/>
              {ifModificate && (
                <Icon
                  className="dynamic-delete-button"
                  type="minus-circle-o"
                  onClick={this.remove.bind(this, v.roleId, first, i)}
                />
              )}
            </div>
          );
        })
      );
    }
    return arrItem;
  }

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

  render() {
    let ifEdit = true;
    if (this.state.currentIndex[0] === "0") {
      ifEdit = false;
    }
    return (
      <Container>
        <div className="department-content">
          <div className="department-inquiry">
            <div className="depart-menu">
              <Menu
                mode="inline"
                onClick={this.itemChange}
                defaultSelectedKeys={['0']}
                defaultOpenKeys={['0']}
                style={{width: 213}}
              >
                {this.renderCourse()}
              </Menu>
            </div>
          </div>
          <div className="department-right">
            {/*<span className="department-title" style={{display: "none"}}>{this.state.caption}</span>*/}
            <div>
              {this.renderRoles()}
              {ifEdit && (
                <div>
                  <div style={{marginTop: 32, paddingLeft: 109}}>
                    <Button type="dashed" onClick={this.add} style={{width: 250}}>
                      <Icon type="plus"/> 添加
                    </Button>
                  </div>
                  <div style={{marginTop: 32, paddingLeft: 109}}>
                    {/*<Button style={{marginRight: "8px"}}>取消</Button>*/}
                    <Button className="submit" type="primary" htmlType="submit"
                            onClick={this.systemComRoleBatchInsertRole}>保存</Button>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      </Container>
    );
  }
}

/*********************样式*************************** */
const Container = style.div`{
    .item{
      margin-bottom:24px;
      .l{
        display: inline-block;
        text-align: right;
        width: 100px;
        margin-right:8px;
      }
      .c{
      
      }
      .dynamic-delete-button {
        cursor: pointer;
        position: relative;
        top: 4px;
        font-size: 24px;
        color: #d9d9d9;
        transition: all .3s;
      }
      .dynamic-delete-button:hover {
        color: #777;
       }
       .dynamic-delete-button[disabled] {
        cursor: not-allowed;
        opacity: 0.5;
      }
    }
    .ant-btn-primary{
        background-color: #0F71FF;
    }
    .ant-menu-submenu > .ant-menu{
        background:#fff;
    }

    .department-content{
        height: 850px;
        background: #fff;
        border-radius: 5px;
        padding-left: 220px;
        position: relative;
        >div{
          height: 850px;
          overflow: auto;        
        }
        .department-inquiry{
          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;
            }
        }
      }
}`;
