import React, { Component } from 'react';
import { connect } from 'dva';

import {
  Form,
  Input,
  Button,
  Menu,
  Icon,
  message,
  Modal,
  Select,
  Tooltip
} from 'antd';
import './less/role.less';
import PTable from '../../../components/Pro/PTable';
import NewRole from './NewRole';
import UpdateRole from './UpdateRole';
import UpdateRoleGroup from './UpdateRoleGroup';
import RoleAllow from './RoleAllow';
import APPRoleAllow from './APPRoleAllow';
import NewRoleGroup from './NewRoleGroup';
import DataPermissionsSet from './DataPermissionsSet';
import {
  searchRoleAndRoleGroupList, //查询角色组与角色列表功能
  batchesDelete, //批量删除角色中人员功能
  systemComRoleInsertPerRole, //批量添加角色中人员功能
  enterpriseRoleGet //GET获取角色权限
} from '../../../services/api';
import PartmentButton from '../../../components/PartmentButton';
import $perModal from '../../../utils/modal/perModal';
const { Search } = Input;
const { SubMenu } = Menu;
const { Option } = Select;
const { confirm } = Modal;

// const { Option } = Select;
// const { MenuItemGroup } = Menu;

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

/**
 * 部门管理组件
 */
export default class Role extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      /**
       * 各个抽屉
       */
      roleOpen: false,
      updateRoleOpen: false,
      roleGroupOpen: false,
      updateroleGroupOpen: false,
      roleAllowOpen: false,
      dataPermissionsSetOpen: false,
      appRoleAllowOpen: false,
      /**
       * 抽屉需要
       */
      selectedRowIds: [], //需要删除的信息id值集合
      selectedRowKeys: [],
      roleGroupList: [],
      /**
       * 删除模态框
       */
      ModalText: '请先移除当前部门下的人员，再删除当前角色！',
      visible: false,
      confirmLoading: false,
      /**
       * 批量离职删除模态框
       */
      BulkDeparturesModalText:
        'XXX（手机号）离职后将取消关联的任务及审批流程。是否确定离职处理？',
      bulkDeparturesVisible: false,
      bulkDeparturesConfirmLoading: false,
      // company: '百川信（厦门）网络服务信息有限公司',
      placeholder: '请输入内容',
      // openKeys: ['a1'],
      forceUpdate: false,
      roleGroupSequence: '', //菜单组序列
      roleGroupdefault: [],
      edit: {
        roleId: '',
        roleGroupId: ''
      },
      pageParm: {
        pageSize: '10',
        pageNumber: '1',
        roleId: ''
        // comId: "",
      },
      roleGroupData: [
        {
          roleGroupName: '',
          roleGroupId: '',
          comRolesList: [
            {
              roleName: '',
              roleId: '',
              personCount: '',
              sid: ''
            }
          ]
        }
      ],
      caption: '',
      personCount: '',
      mainManageAllow: true
    };
  }

  //批量添加角色中人员功能
  systemComRoleInsertPerRole = () => {
    systemComRoleInsertPerRole({
      perIds: JSON.stringify(this.state.chargePerIdStr),
      roleId: this.state.roleId
    })
      .then(res => {
        console.log(res, '批量添加角色中人员功能-res1');
        this.refs.PTable.ajaxRequest();
      })
      .catch(err => {
        console.log(err, '批量添加角色中人员功能-err');
      });
  };
  componentWillMount = () => { };
  componentDidMount() {
    this.getSearchRoleAndRoleGroupList();
    // this.getEnterpriseRoleGroupGet();
    // this.getEnterpriseRoleGet();
  }

  getEnterpriseRoleGet = roleId => {
    // enterpriseRoleGet({ roleId: this.state.roleId }).then(data => {
    enterpriseRoleGet({ roleId }).then(data => {
      if (data.data.roleName === '主管理员') {
        this.setState({
          mainManageAllow: true
        });
      } else {
        this.setState({
          mainManageAllow: false
        });
      }
      data.data.personCount
        ? this.setState({
          personCount: data.data.personCount
        })
        : null;
    });
  };

  onSelect = (selectedKeys, info) => {
    console.log('onSelect', info);
  };

  getSearchRoleAndRoleGroupList = () => {
    searchRoleAndRoleGroupList({}).then(data => {
      if (data) {
        this.setState({
          roleGroupData: data.data,
          roleGroupList: data.data
        });
        const pageParm = { ...this.state.pageParm };

        // 寻找与当前roleid匹配的数据
        let currentRoleInfo = [];
        data.data.forEach(item => {
          if (item.comRolesList) {
            const temp = item.comRolesList.filter(
              subItem => subItem.roleId === this.state.roleId
            );
            if (temp.length) {
              currentRoleInfo = temp;
            }
          }
        });

        if (currentRoleInfo.length) {
          pageParm.roleId = this.state.roleId;
          this.getEnterpriseRoleGet(pageParm.roleId); ///获取该角色的权限
          const roleGroupdefault1 = this.state.roleGroupdefault;
          roleGroupdefault1.push(currentRoleInfo[0].roleGroupId.toString());
          console.log('菜单的第一个组key', roleGroupdefault1);
          this.setState({
            pageParm,
            caption: currentRoleInfo[0].roleName,
            roleGroupdefault: roleGroupdefault1,
            personCount: currentRoleInfo[0].personCount
          });
        } else {
          this.setState({
            roleGroupData: data.data,
            personCount: this.state.roleGroupData[0].comRolesList[0]
              .personCount,
            caption: this.state.roleGroupData[0].comRolesList[0].roleName
          });
          pageParm.roleId = this.state.roleGroupData[0].comRolesList[0].roleId;
          this.getEnterpriseRoleGet(pageParm.roleId); ///获取该角色的权限
          const roleGroupdefault1 = this.state.roleGroupdefault;
          roleGroupdefault1.push(
            this.state.roleGroupData[0].roleGroupId.toString()
          );
          this.setState({
            roleGroupSequence: '', //菜单组序列
            pageParm,
            caption: this.state.roleGroupData[0].comRolesList[0].roleName,
            roleGroupdefault: roleGroupdefault1,
            personCount: this.state.roleGroupData[0].comRolesList[0].personCount
          });
        }
      }
    });
  };

  getEnterpriseRoleGroupGet = () => {
    // console.log("getComId:", comId);
    searchRoleAndRoleGroupList().then(data => {
      console.log('getRoleList', data.data);
      if (data) {
        this.setState({
          roleGroupList: data.data
        });
      }
    });
  };
  // 批量删除
  handleDeleteList = () => {
    const that = this;
    const keyNumber = this.state.selectedRowIds.length;
    const keyId = this.state.selectedRowIds;
    console.log('id集合' + keyId);
    if (keyNumber <= 0) {
      message.warning('请选择移除的人员！');
    } else {
      console.log(this.state.selectedRowIds);
      confirm({
        title: '是否确认移除人员',
        okText: '确认',
        cancelText: '取消',
        onOk() {
          that.comJobDelete(keyId);
          that.getSearchRoleAndRoleGroupList();
        },
        onCancel() {
          console.log('Cancel');
        }
      });
    }
  };

  // 订单删除
  comJobDelete = perIds => {
    console.log('perIds', perIds);
    perIds = perIds.join(',');
    batchesDelete({
      perIds,
      roleId: this.state.pageParm.roleId.toString()
    }).then(
      data => {
        console.log('角色人员删除', data);
        this.setState({
          selectedRowIds: [],
          selectedRowKeys: [],
          forceUpdate: true
        }, () => {
          this.setState({
            forceUpdate: false,
          });
        });
        message.info('角色人员删除成功！');
        // this.resetting();
      },
      err => {
        console.log('角色人员删除失败', err);
        message.warning('角色人员删除失败！' + err);
      }
    );
  };
  // rootSubmenuKeys = ['a1', 'a2', 'a3'];

  /**
   * 删除模态框
   */
  showModal = () => {
    this.setState({
      visible: true
    });
  };
  roleMenuClick = e => {
    const pageParm = { ...this.state.pageParm };
    console.log('ClickedroleMenu', e);
    console.log('角色组Id-roleGroupId:', e.keyPath[1]);
    console.log('角色Id-roleId:', e.key);
    pageParm.roleId = e.key;
    this.setState({
      roleId: e.key,
      pageParm,
      roleGroupSequence:
        e.keyPath[1] !== this.state.roleGroupData[0].roleGroupId
          ? e.keyPath[1]
          : '',
      caption: e.item.props.title,
      personCount: e.item.props.personCount,
      selectedRowIds: [], //当切换菜单时，清空列表中选择的行
      selectedRowKeys: []
    });
    this.getEnterpriseRoleGet(e.key);
  };
  handleOk = () => {
    this.setState({
      ModalText: '请先移除当前部门下的人员，再删除当前部门！',
      confirmLoading: true
    });
    setTimeout(() => {
      this.setState({
        visible: false,
        confirmLoading: false
      });
    }, 2000);
  };
  handleCancel = () => {
    console.log('Clicked cancel button');
    this.setState({
      visible: false
    });
  };

  /**
   * 批量离职删除模态框
   */
  showBulkDeparturesModal = () => {
    this.setState({
      bulkDeparturesVisible: true
    });
  };
  handleBulkDeparturesOk = () => {
    this.setState({
      BulkDeparturesModalText:
        'XXX（手机号）离职后将取消关联的任务及审批流程。是否确定离职处理？',
      confirmLoading: true
    });
    setTimeout(() => {
      this.setState({
        bulkDeparturesVisible: false,
        confirmLoading: false
      });
    }, 2000);
  };
  handleBulkDeparturesCancel = () => {
    console.log('Clicked cancel button');
    this.setState({
      bulkDeparturesVisible: false
    });
  };

  handleHeart = item => {
    console.log(item);
  };

  // 下级角色组别
  handleList = () => {
    const listName = this.state.caption;
    const ertContent = [];
    this.state.roleGroupData.forEach(val => {
      if (val.roleGroupName === listName) {
        if (val.comRolesList.length !== 0) {
          val.comRolesList.forEach(text => {
            console.log(text.roleName);
            return ertContent.push(
              <li key={text.roleId}>
                <a href='#'>
                  {text.roleName}
                  <Icon type='right' />
                </a>
              </li>
            );
          });
        } else {
          ertContent.push('');
        }
      }
    });
    return ertContent;
  };
  //新增角色抽屉
  openNewRoleDrawer = open => {
    console.log('新增角色开关：', open);
    this.setState({ roleOpen: open });
    // this.getEnterpriseRoleGroupGet();
    this.getSearchRoleAndRoleGroupList();
  };

  //编辑角色
  openUpdateRoleDrawer = (open, roleId) => {
    const edit = { ...this.state.edit };
    edit.roleId = roleId;
    console.log('修改角色开关：', open, '，当前roleId：', roleId);
    this.setState({ updateRoleOpen: open, edit });
  };

  //菜单权限设置
  openRoleAllowDrawer = (open, roleId) => {
    const edit = { ...this.state.edit };
    edit.roleId = roleId;
    // console.log("修改角色权限开关：", open, "，roleId的：", roleId);
    this.setState({ roleAllowOpen: open, edit });
  };

  //数据权限设置
  openDataPermissionsSetDrawer = (open, roleId) => {
    const edit = { ...this.state.edit };
    edit.roleId = roleId;
    // console.log("修改角色权限开关：", open, "，roleId的：", roleId);
    this.setState({ dataPermissionsSetOpen: open, edit });
  };

  //APP菜单权限设置
  openAPPRoleAllowDrawer = (open, roleId) => {
    const edit = { ...this.state.edit };
    edit.roleId = roleId;
    // console.log("修改角色权限开关：", open, "，roleId的：", roleId);
    this.setState({ appRoleAllowOpen: open, edit });
  };

  //新增角色组抽屉
  openNewRoleGroupDrawer = open => {
    // console.log("新增角色组开关：", open);
    this.setState({ roleGroupOpen: open });
  };

  //编辑角色组抽屉
  openUpdateNewRoleGroupDrawer = (open, rolegroupId) => {
    const edit = { ...this.state.edit };
    edit.roleGroupId = rolegroupId;
    this.setState({
      edit: {
        roleGroupId: rolegroupId
      }
    });
    // console.log("修改角色组开关：", open, "，roleGroupId的：", roleGroupId);
    this.setState({ updateroleGroupOpen: open, edit });
  };

  renderRoleGroup = () => {
    return this.state.roleGroupList.map((val, key) => {
      return (
        <Option key={key} value={val.roleGroupId + ''}>
          {val.roleGroupName}
        </Option>
      );
    });
  };

  // 角色及角色组菜单
  renderCourse = () => {
    const arrs = this.state.roleGroupData.map((val, item) => {
      // if (val.comRolesList.length !== 0) {
      return (
        <SubMenu
          key={val.roleGroupId}
          title={
            <span
              style={{
                display: 'inline-block',
                width: '130px',
                overflow: 'hidden',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap'
              }}
            >
              <Icon
                type='folder-open'
                style={{ fontSize: 14, color: '#909CA8' }}
              />
              <Tooltip title={val.roleGroupName}>
                <span> {val.roleGroupName}</span>
              </Tooltip>
              {val.roleGroupId !== this.state.roleGroupData[0].roleGroupId ? (
                <span
                  style={{ position: 'absolute', right: '30px' }}
                  onClick={this.openUpdateNewRoleGroupDrawer.bind(
                    this,
                    true,
                    val.roleGroupId
                  )}
                >
                  <Icon
                    type='edit'
                    style={{ fontSize: 14, color: '#909CA8' }}
                  />
                </span>
              ) : (
                  ''
                )}
            </span>
          }
        >
          {val.comRolesList.map(name => {
            return (
              <Menu.Item
                key={name.roleId}
                title={name.roleName}
                personCount={name.personCount}
              >
                <Icon type='user' style={{ fontSize: 14, color: '#909CA8' }} />
                {name.roleName}
              </Menu.Item>
            );
          })}
        </SubMenu>
      );
      // } else {
      //   return (<Menu.Item key={val.roleGroupId}>
      //     <Icon type="folder-open" style={{ fontSize: 14, color: '#909CA8' }} />
      //     {val.roleGroupName}
      //   </Menu.Item>);
      // }
    });
    return arrs;
  };

  renderColums = () => {
    const selectedRowKey = this.state.selectedRowKeys;
    const rowSelection = {
      selectedRowKeys: selectedRowKey,
      onChange: selectedRowKeys => {
        this.setState({
          selectedRowKeys
        });
      },
      onSelect: (record, selected) => {
        const selectId = this.state.selectedRowIds;
        if (selected === true) {
          selectId.push(record.perId);
        } else {
          for (let i = 0; i < selectId.length; i++) {
            if (selectId[i] === record.perId) {
              selectId.splice(i, 1);
              break;
            }
          }
        }
        this.setState({
          selectedRowIds: selectId
        });
      },
      onSelectAll: (selected, selectedRows) => {
        let selectId = [];
        if (selected === true) {
          for (let i = 0; i < selectedRows.length; i++) {
            selectId.push(selectedRows[i].perId);
          }
        } else {
          selectId = [];
          // selectedRowKeys:selectedRowKey
        }
        this.setState({
          selectedRowIds: selectId
        });
      }
    };

    const columns = [
      {
        title: '姓名',
        dataIndex: 'name',
        key: 'name'
      },
      {
        title: '组织类型',
        dataIndex: 'orgTypeName',
        key: 'orgTypeName'
      },
      {
        title: '组织名称',
        dataIndex: 'orgName',
        key: 'orgName'
      },
      {
        title: '手机号',
        dataIndex: 'mobilePhone',
        key: 'mobilePhone'
      }
    ];
    return (
      <PTable
        ref='PTable'
        style={{ marginTop: 20 }}
        columns={columns}
        pagination={{
          onChange: () => {
            this.setState({
              selectedRowKeys: []
            });
          }
        }}
        url='searchPerSonByRoleId'
        pageParm={this.state.pageParm}
        rowSelection={rowSelection}
        forceUpdate={this.state.forceUpdate}
        showTotal={total => `共搜素到${total}条记录`}
      />
    );
  };

  updateRoleGroupSequence = () => { };

  render() {
    /**
     * 删除模态框
     */
    const {
      visible,
      confirmLoading,
      ModalText,
      bulkDeparturesVisible,
      bulkDeparturesConfirmLoading,
      BulkDeparturesModalText
    } = this.state;
    return (
      <div className='Role'>
        <div className='department-content'>
          <div className='department-inquiry'>
            <Search
              size='large'
              placeholder={this.state.placeholder}
              style={{ width: 200, display: 'none' }}
              onSearch={value => console.log(value)}
              maxLength={20}
            />
            <div className='depart-button'>
              <Button onClick={this.openNewRoleGroupDrawer.bind(this, true)}>
                新增角色组
              </Button>
              <Button
                onClick={this.openNewRoleDrawer.bind(this, true)}
                className='button-right'
              >
                新增角色
              </Button>
            </div>
            <div className='depart-menu'>
              <Menu
                mode='inline'
                // defaultSelectedKeys={['0']}
                defaultOpenKeys={['0']}
                selectedKeys={[this.state.roleId]}
                // defaultSelectedKeys={[`${this.state.roleGroupData[0].comRolesList[0].roleId}`]}
                // defaultSelectedKeys={[`${this.state.defaultSelectedItem}`]}
                // defaultSelectedKeys={[`407895940217700352`]}
                // defaultOpenKeys={{this.state.roleGroupdefault}}
                onClick={this.roleMenuClick.bind(this)}
                // openKeys={this.state.openKeys}
                // onOpenChange={this.onOpenChange}
                style={{ width: 213 }}
              >
                {this.renderCourse()}
              </Menu>
            </div>
          </div>
          <div className='department-demonstrate'>
            <div className='demonstrate-head'>
              <p className='title'>
                <span className='current-role'>
                  <Icon
                    type='user'
                    style={{
                      fontSize: 20,
                      color: '#909CA8',
                      marginRight: '6px'
                    }}
                  />
                  {this.state.caption}({this.state.personCount}
                  人)
                </span>
                {this.state.roleGroupSequence === '' ? (
                  <Button
                    className='role-button'
                    style={{ marginLeft: '32px' }}
                    onClick={this.openUpdateRoleDrawer.bind(
                      this,
                      true,
                      this.state.pageParm.roleId
                    )}
                    disabled
                  >
                    编辑
                  </Button>
                ) : (
                    <Button
                      className='role-button'
                      style={{ marginLeft: '32px' }}
                      onClick={this.openUpdateRoleDrawer.bind(
                        this,
                        true,
                        this.state.pageParm.roleId
                      )}
                      disabled={this.state.mainManageAllow}
                    >
                      编辑
                    </Button>
                  )}
                <Button
                  className='role-button'
                  onClick={this.openRoleAllowDrawer.bind(
                    this,
                    true,
                    this.state.pageParm.roleId
                  )}
                  disabled={this.state.mainManageAllow}
                >
                  菜单权限
                </Button>
                <Button
                  className='role-button'
                  onClick={this.openDataPermissionsSetDrawer.bind(
                    this,
                    true,
                    this.state.pageParm.roleId
                  )}
                  disabled={this.state.mainManageAllow}
                >
                  数据权限
                </Button>
                <Button
                  style={{ display: 'none' }}
                  className='role-button'
                  onClick={this.openAPPRoleAllowDrawer.bind(
                    this,
                    true,
                    this.state.pageParm.roleId
                  )}
                  disabled={this.state.mainManageAllow}
                >
                  app菜单权限
                </Button>
              </p>
            </div>
            {/* <div className="demonstrate-line"></div> */}
            <div className='subordinate-departments'>
              <div className='division-button'>
                <Button
                  type='primary'
                  icon='plus'
                  disabled={
                    this.state.roleGroupSequence === '' ||
                    this.state.mainManageAllow
                  }
                  onClick={() => {
                    $perModal({
                      onOk: (values, close) => {
                        this.setState({ chargePerIdStr: values.map(val => val.perId) }, () => {
                          this.systemComRoleInsertPerRole();
                          this.getSearchRoleAndRoleGroupList();
                        });
                        close();
                      }
                    });
                  }}
                >
                  添加成员
                </Button>

                {this.state.roleGroupSequence === '' ? (
                  <Button
                    disabled
                    type='danger'
                    ghost
                    onClick={this.handleDeleteList}
                  >
                    批量移除
                  </Button>
                ) : (
                    <Button
                      type='danger'
                      ghost
                      onClick={this.handleDeleteList}
                      disabled={this.state.mainManageAllow}
                    >
                      批量移除
                    </Button>
                  )}
              </div>
              {this.state.pageParm.roleId && (
                <div className='division-table'>{this.renderColums()}</div>
              )}
            </div>
          </div>
        </div>
        {/* 删除模态框 */}
        <div>
          <Modal
            title='提示'
            visible={visible}
            onOk={this.handleOk}
            confirmLoading={confirmLoading}
            onCancel={this.handleCancel}
            okText='确认'
            cancelText='取消'
          >
            <p style={{ textAlign: 'center', fontSize: '14px', color: '#333' }}>
              <i
                className='anticon anticon-exclamation-circle'
                style={{
                  color: '#faad14',
                  fontSize: '22px',
                  marginRight: '16px',
                  verticalAlign: 'middle'
                }}
              />
              {ModalText}
            </p>
          </Modal>
        </div>
        {/* 批量离职删除模态框 */}
        <div>
          <Modal
            title='提示'
            visible={bulkDeparturesVisible}
            onOk={this.handleBulkDeparturesOk}
            confirmLoading={bulkDeparturesConfirmLoading}
            onCancel={this.handleBulkDeparturesCancel}
            okText='确认'
            cancelText='取消'
          >
            <p style={{ textAlign: 'center', fontSize: '14px', color: '#333' }}>
              <i
                className='anticon anticon-exclamation-circle'
                style={{
                  color: '#faad14',
                  fontSize: '22px',
                  marginRight: '16px',
                  verticalAlign: 'middle'
                }}
              />
              {BulkDeparturesModalText}
            </p>
          </Modal>
        </div>
        {/* 菜单权限设置 */}
        <RoleAllow
          onChange={roleAllowOpen => {
            this.setState({ roleAllowOpen });
          }}
          visiable={this.state.roleAllowOpen}
          roleId={this.state.edit.roleId}
          caption={this.state.caption}
          refreshList={() => {
            this.getSearchRoleAndRoleGroupList();
          }}
          wedRoleSequence={this.updateRoleGroupSequence}
        />
        
        {/* 数据权限设置 */}
        <DataPermissionsSet
          onChange={dataPermissionsSetOpen => {
            this.setState({ dataPermissionsSetOpen });
          }}
          visiable={this.state.dataPermissionsSetOpen}
          roleId={this.state.edit.roleId}
          caption={this.state.caption}
          refreshList={() => {
            this.getSearchRoleAndRoleGroupList();
          }}
          wedRoleSequence={this.updateRoleGroupSequence}
        />
        
        {/* APP菜单权限设置 */}
        <APPRoleAllow
          onChange={appRoleAllowOpen => {
            this.setState({ appRoleAllowOpen });
          }}
          visiable={this.state.appRoleAllowOpen}
          roleId={this.state.edit.roleId}
          caption={this.state.caption}
          refreshList={() => {
            this.getSearchRoleAndRoleGroupList();
          }}
          wedRoleSequence={this.updateRoleGroupSequence}
        />
        
        <UpdateRole
          onChange={() => {
            this.setState({ updateRoleOpen: false });
          }}
          visiable={this.state.updateRoleOpen}
          roleId={this.state.edit.roleId}
          refreshList={() => {
            this.getSearchRoleAndRoleGroupList();
          }}
          wedRoleSequence={this.updateRoleGroupSequence}
        />
        <NewRole
          onChange={roleOpen => {
            this.setState({ roleOpen });
          }}
          visiable={this.state.roleOpen}
          refreshList={() => {
            this.getSearchRoleAndRoleGroupList();
          }}
          wedRoleSequence={this.updateRoleGroupSequence}
          roleGroupList={this.state.roleGroupList}
        />
        <NewRoleGroup
          onChange={roleGroupOpen => {
            this.setState({ roleGroupOpen });
          }}
          visiable={this.state.roleGroupOpen}
          refreshList={() => {
            this.getSearchRoleAndRoleGroupList();
          }}
          wedRoleSequence={this.updateRoleGroupSequence}
        />
        <UpdateRoleGroup
          onChange={updateroleGroupOpen => {
            this.setState({ updateroleGroupOpen });
          }}
          visiable={this.state.updateroleGroupOpen}
          roleGroupId={this.state.edit.roleGroupId}
          refreshList={() => {
            this.getSearchRoleAndRoleGroupList();
          }}
          wedRoleSequence={this.updateRoleGroupSequence}
        />
      </div>
    );
  }
}
