import React from 'react';
import { Button, Col, Row, Input, message, Modal, Checkbox, Table } from 'antd';
import { $http } from 'containers/config/https';
import 'assets/css/system.css'


export default class MenuAuthorizationModel extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      roleId: "",
      visible1: false,//弹框显示状态
      confirmLoading: false,// 组件loading
      name: '', // 角色名称
      checked: false, // 是否仅显示生效
      tableData: [], // 表格数据
      tableLoading: true, // 表格loading
      rowId: '', // 选中行ID
      copyId: '',
      sideMenu: [], // 侧菜单
      headerMenu: [], // 头菜单
    };

    // 表格行设置
    this.columns = [{
      key: 1,
      title: '角色名称',
      dataIndex: 'Descripts',
      align: "left",
      width: 100
    }, {
      key: 2,
      title: '默认菜单类型',
      dataIndex: 'DefaultMenuType',
      align: "center",
      width: 100,
      render(DefaultMenuType) {
        let config = {
          '1': '头菜单',
          '2': '侧菜单'
        }
        return config[DefaultMenuType];
      }
    }];
  }
  // componentDidMount() {
  //   this.handleQuery()
  // }    

  componentWillReceiveProps(nextProps) {
    // 当修改选择的数据后刷新数据
    this.setState({ copyId: "" })
  }

  componentDidMount() {
    //console.log(this.props.handleThis)
    this.setState({ copyId: "" })
    this.handleQuery();
    // 数据异步请求，请求成功之后setState
    this.setState({
      showLoading: false
    })
  }

  // 显示弹框
  showModal = () => {
    this.setState({
      visible1: true,
    });
  }

  //复制授权
  handleOk = () => {
    let user = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
    let data = {
      params: [{
        GroupDr: this.props.handleThis.state.roleId,
        CopyGroupDr: this.state.copyId,
        CreateUserDr: user.userID
      }]
    }
    // console.log(data) 
    if (Number(this.props.handleThis.state.roleId) !== Number(this.state.copyId)) {
      $http.post('urlS', this, {
        code: '2610',
        data: data,
        success: (res) => {
          if (+res.errorCode === 0) {
            message.success('保存成功')
            // this.handleQuery(this.state.copyId)
            // 关闭弹窗
            this.props.handleOk();
            // 调用右侧表格查询接口刷新表格
            this.getAuthorizationList(this.props.roleId);
          }
        }
      })
    } else {
      message.success('暂不支持复制')
    }
  }

  // 关闭弹框
  handleCancel = () => {
    this.setState({
      visible1: false,
    });
  }

  // 查询条件 --- 角色名称
  onChangeName = (e) => {
    // console.log(e.target.value)
    this.setState({ name: e.target.value });
  }

  // 获取Checkbox操作后的值
  handleCheckbox = (e) => {
    this.setState({ checked: e.target.checked });
  }

  // 点击图标查询该角色所有的菜单
  handleOnExpand = (expanded, record) => {
    let data = {
      params: [{
        GroupDr: record.ID
      }]
    }
    $http.post('urlS', this, {
      code: "2612",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          for (let i = 0; i < res.result.length; i++) {
            if (res.result[i].MenuDesc === '头菜单') {
              this.setState({ headerMenu: res.result[i].Menu })
            } else if (res.result[i].MenuDesc === '侧菜单') {
              this.setState({ sideMenu: res.result[i].Menu })
            }
          }
        } else {
          message.error('查询失败：' + res.errorMessage)
        }
      },
      error: function (error) {
        message.error('查询失败：' + error)
      }
    })
  }

  // 查询所有角色
  handleQuery = () => {
    let checked = '';
    if (this.state.checked === true) {
      checked = '可用'
    } else {
      checked = '不可用'
    }
    let data = {
      params: [{
        Descripts: this.state.name, // 角色名称
        PostDr: '', // 岗位
        Status: checked, // 记录状态
      }],
      pagination: [{
        pageSize: '',
        currentPage: 1,
        sortColumn: "Describe",
        sortOrder: "asc"
      }]
    }
    $http.post('urlS', this, {
      code: "2101",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0 && res.result) {
          for (var i = 0; i < res.result.Data.length; i++) {
            res.result.Data[i].key = i
            res.result.Data[i].children = [];
            res.result.Data[i].rowClassName = i + 'class';
          }
          this.setState({ tableData: res.result.Data, tableLoading: false });
        } else {
          // 数据加载失败关闭loading
          this.setState({ tableLoading: false });
        }
      }
    })
  }

  // 设置行属性
  onClickRow = (record) => {
    return {
      // 单击行选中
      onClick: () => {
        if (this.state.copyId === "") {
          this.setState({ copyId: record.ID })
        } else {
          if (this.state.copyId !== record.ID) {
            this.setState({ copyId: record.ID })
          } else {
            this.setState({
              copyId: "",
            });
          }
        }
      }
    }
  }

  // 展开的行变化时触发
  handelOnExpandedRowsChange = (expandedRows) => {
    if (expandedRows.length > 1) {
      // shift()：移除数组中的第一个元素，即第一次点击所得到的那个对象
      expandedRows.shift()
    }
  }

  // 表格行的类名
  setRowClassName = (record) => {
    return record.ID === this.state.copyId ? 'clickRowStyle' : '';
  }

  render() {
    const { confirmLoading } = this.state;
    return (
      <Modal
        width={600}
        title="复制授权等信息"
        visible={this.props.visible}
        onOk={this.handleOk}
        onCancel={this.props.handleOk}
        confirmLoading={confirmLoading}
      >
        <div className="table-operations">
          <Row>
            <Col span={18}>
              角色名称：<Input placeholder="请输入角色名称" value={this.state.name
              } style={{ width: '150px', marginRight: '20px' }} onChange={this.onChangeName} />
              <Checkbox checked={this.state.checked} onChange={this.handleCheckbox}>仅显示生效</Checkbox>
            </Col>
            <Col span={6}>
              <Button type="primary" onClick={this.handleQuery}>查询</Button>
            </Col>
          </Row>
          <div style={{ marginTop: '24px' }}>
            <Table
              rowClassName={this.setRowClassName}
              style={{ height: '400px', maxHeight: '400px', overflow: 'scroll' }}
              dataSource={this.state.tableData}
              columns={this.columns}
              pagination={false}
              //bordered
              onRow={this.onClickRow}
              loading={this.state.tableLoading}
              onExpand={this.handleOnExpand}
              onExpandedRowsChange={this.handelOnExpandedRowsChange}
              expandedRowRender={record => (
                <div style={{ textAlign: 'left' }}>
                  <Row>
                    <Col span={12}>
                      <div>
                        <h3>头菜单</h3>
                        <ul>
                          {this.state.headerMenu ? this.state.headerMenu.map(item => {
                            return <li key={item.key}>{item.MenuDetailDrDesc}</li>
                          }) : ''}
                        </ul>
                      </div>
                    </Col>
                    <Col span={12}>
                      <div>
                        <h3>侧菜单</h3>
                        <ul>
                          {this.state.sideMenu ? this.state.sideMenu.map(item => {
                            return <li key={item.key}>{item.MenuDetailDrDesc}</li>
                          }) : ''}
                        </ul>
                      </div>
                    </Col>
                  </Row>
                </div>
              )}
            />
          </div>
        </div>
      </Modal>
    )
  }
}