/**
 * 列权限维护
 */
import React, { Component } from 'react';
import { Table, Row, Col, Button, Checkbox, message, Select, Input } from 'antd';
import { $http } from '../../containers/config/https';
import store from '../../store';

const Option = Select.Option;
let userData;
class ColumnAuthoritys extends Component {
  constructor(props) {
    super(props);
    userData = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
    this.state = {
      compontName: '001',
      type: "",
      authList: [],
      columnsC: [{
        title: 'code',
        dataIndex: 'code',
        width: '150px',
        key: 'code',
      }, {
        title: userData.language == "EN" ? "descripts" : '列名',
        dataIndex: 'columnName',
        width: '170px',
        key: 'columnName',
        render: (text, record, index) => {
          return (
            <Input style={{ width: '95%' }} value={text} onChange={this.onChange.bind(this, record, 'columnName')}></Input>
          )
        },
      }, {
        title: userData.language == "EN" ? "width" : '列宽',
        dataIndex: 'width',
        width: '90px',
        key: 'width',
        render: (text, record, index) => {
          return (
            <Input style={{ width: '95%' }} value={text} onChange={this.onChange.bind(this, record, 'width')}></Input>
          )
        },
      }, {
        title: userData.language == "EN" ? "align" : '对齐方式',
        dataIndex: 'align',
        width: '130px',
        key: 'align',
        render: (text, record, index) => {
          return (
            <Select style={{ width: '90%' }} value={text} onChange={this.onSelect.bind(this, record, 'align')}>
              <Option value="L" key="L">{userData.language == "EN" ? "left" : '左对齐'}</Option>
              <Option value="C" key="C">{userData.language == "EN" ? "center" : '居中'}</Option>
              <Option value="R" key="R">{userData.language == "EN" ? "right" : '右对齐'}</Option>
            </Select>
          )
        },
      }, {
        title: userData.language == "EN" ? "display" : '显示',
        key: 'displayFlag',
        dataIndex: 'displayFlag',
        width: '80px',
        render: (text, record, index) => {
          var displayFlag = record.displayFlag
          if (displayFlag === "Y") {
            displayFlag = true
          } else {
            displayFlag = false
          }
          return (
            <Checkbox checked={displayFlag} onChange={this.CheckOnChange.bind(this, record, index, 'displayFlag')}></Checkbox>
          )
        },
      }, {
        title: userData.language == "EN" ? "export" : '导出',
        dataIndex: 'exportFlag',
        key: 'exportFlag',
        width: '80px',
        render: (text, record, index) => {
          var exportFlag = record.exportFlag
          if (exportFlag === "Y") {
            exportFlag = true
          } else {
            exportFlag = false
          }
          return (
            <Checkbox checked={exportFlag} onChange={this.CheckOnChange.bind(this, record, index, 'exportFlag')}></Checkbox>
          )
        }
      }, {
        title: userData.language == "EN" ? "print" : '打印',
        dataIndex: '',
        key: 'pringFlag',
        width: '80px',
        render: (text, record, index) => {
          var pringFlag = record.pringFlag
          if (pringFlag === "Y") {
            pringFlag = true
          } else {
            pringFlag = false
          }
          return (
            <Checkbox checked={pringFlag} onChange={this.CheckOnChange.bind(this, record, index, 'pringFlag')}></Checkbox>
          )
        }
      }],
      columnsB: [{
        title: 'code',
        dataIndex: 'code',
        width: '150px',
        key: 'code',
      }, {
        title: '按钮名称',
        dataIndex: 'columnName',
        width: '200px',
        key: 'columnName',
      }, {
        title: '是否隐藏',
        key: 'displayFlag',
        dataIndex: 'displayFlag',
        width: '',
        render: (text, record, index) => {
          var displayFlag = record.displayFlag
          if (displayFlag === "Y") {
            displayFlag = true
          } else {
            displayFlag = false
          }
          return (
            <Checkbox checked={displayFlag} onChange={this.CheckOnChange.bind(this, record, index, 'displayFlag')}></Checkbox>
          )
        }
      }],
      columns: [],
      data: [],
      selectedRowKeys: [],
      configType: "C",
    }
  }

  //文本内容改变时触发
  onChange = (record, field, e) => {
    record[field] = e.target.value;
    this.forceUpdate();
  }

  //下拉框内容改变时触发
  onSelect = (record, field, value) => {
    record[field] = value;
    this.forceUpdate();
  }

  //复选框勾选触发
  CheckOnChange = (record, index, field) => {
    if (record[field] === "Y") {
      record[field] = "N"
    } else {
      record[field] = "Y"
    }
    var data = this.state.data
    data[index] = record
    this.setState({ data: data })
  }

  getData = (compontName, configType) => {
    let data = {
      params: [{
        compontName: compontName,
        type: configType,
        saveType: this.state.type,
        language: userData.language,
      }]
    };

    let columns = this.state.columnsB;
    if (configType === "C") {
      columns = this.state.columnsC;
    }
    $http.post('urlDeault', this, {
      code: "01040041",
      data: data,
      success: function (res) {
        this.setState({
          compontName: compontName,
          configType: configType,
          columns: columns,
          data: res.result,
          type: res.defaultType,
        })
      }
    });
  }

  // 保存列权限
  saveData = () => {
    let data = {
      params: [{
        tableData: this.state.data,
        updateUser: userData.userID,
        type: this.state.type,
        language: userData.language,
        compontName: this.state.compontName,
      }]
    };
    $http.post('urlDeault', this, {
      code: "01040039",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          message.success('保存成功！');
          this.props.onCancel();
        }
      }
    });
  }

  // 删除列权限
  delData = () => {
    let data = {
      params: [{
        updateUser: userData.userID,
        type: this.state.type,
        compontName: this.state.compontName,
      }]
    };
    $http.post('urlDeault', this, {
      code: "01040101",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          message.success('删除成功！');
          this.getData(this.props.compontName, this.props.configType);
        }
      }
    });
  }

  componentDidMount() {
    this.props.onRef(this);
    this.reloadData();
  }

  // componentWillReceiveProps(nextprops) {
  //   if (nextprops.visible) {
  //     this.setState({
  //       columns: [],
  //       data: [],
  //       selectedRowKeys: [],
  //     }, () => {
  //       this.getEditAuth();
  //       this.getData(nextprops.compontName, nextprops.configType);
  //     })
  //   }
  // }
  
  // 获取编辑权限
  getEditAuth = () => {
    let data = { params: [{}] };
    $http.post('urlDeault', this, {
      code: "01040094",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          this.setState({ authList: res.result.authList })
        }
      }
    });
  }

  reloadData = () => {
    this.setState({
      columns: [],
      data: [],
      selectedRowKeys: [],
    }, () => {
      this.getEditAuth();
      this.getData(this.props.compontName, this.props.configType);
    })
  }

  //选择权限类型
  selectChage = (value) => {
    this.setState({
      type: value,
      selectedRowKeys: []
    },
      () => {
        this.getData(this.state.compontName, this.state.configType);
      });
  }

  //上移
  handleUp = () => {
    var keys = this.state.selectedRowKeys
    var data = this.state.data
    var newKeys = []
    keys = keys.sort(function (m, n) {
      if (m < n) return -1
      else if (m > n) return 1
      else return 0
    });
    for (var i = 0; i < keys.length; i++) {
      if (keys[i] === 0) {
        newKeys.push(keys[i])
        continue
      }
      var curRowData = data[keys[i]]
      var curRowKey = curRowData.key
      var upRowData = data[keys[i] - 1]
      var upRowKey = upRowData.key
      upRowData.key = curRowKey
      curRowData.key = upRowKey
      data[keys[i]] = upRowData
      data[keys[i] - 1] = curRowData
      newKeys.push(keys[i] - 1)
    }
    this.setState(
      {
        data: data,
        selectedRowKeys: newKeys
      }
    )
  }

  //下移
  handleDown = () => {
    var keys = this.state.selectedRowKeys
    var data = this.state.data
    var newKeys = []
    keys = keys.sort(function (m, n) {
      if (m < n) return -1
      else if (m > n) return 1
      else return 0
    });
    for (var i = keys.length - 1; i >= 0; i--) {
      if (keys[i] === data.length - 1) {
        newKeys.push(keys[i])
        continue
      }
      var curRowData = data[keys[i]]
      var upRowData = data[keys[i] + 1]
      var curRowKey = curRowData.key
      var upRowKey = upRowData.key
      upRowData.key = curRowKey
      curRowData.key = upRowKey
      data[keys[i]] = upRowData
      data[keys[i] + 1] = curRowData
      newKeys.push(keys[i] + 1)
    }
    this.setState(
      {
        data: data,
        selectedRowKeys: newKeys
      }
    )
  }

  render() {
    const rowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
        this.setState({ selectedRowKeys: selectedRowKeys })
      },
      getCheckboxProps: record => ({
        disabled: record.name === 'Disabled User', // Column configuration not to be checked
        name: record.name,
      }),
      selectedRowKeys: this.state.selectedRowKeys
    };

    return (
      <div>
        <div className="table-operations">
          <Row>
            <Col span={24}>
              <Select value={this.state.type} style={{ width: 120 }} onChange={this.selectChage}>
                {this.state.authList.map((item, index) => {
                  return (<Option value={item.value} key={index + ""}>{item.descripts}</Option>);
                })}
              </Select>
              <Button type="primary" onClick={this.handleUp} style={{ margin: '3px 10px 38px 13px' }}>{userData.language == "EN" ? "moveUP" : "向上移动"}</Button>
              <Button type="primary" onClick={this.handleDown} style={{ margin: '3px 10px 38px 13px' }}>{userData.language == "EN" ? "moveDown" : "向下移动"}</Button>
              <Button type="primary" className="margiRight16" onClick={this.saveData} style={{ margin: '3px 10px 38px 13px' }}>{userData.language == "EN" ? "save" : "保存"}</Button>
              <Button type="primary" className="margiRight16" onClick={this.delData} style={{ margin: '3px 10px 38px 13px' }}>{userData.language == "EN" ? "deleteCurrent" : "删除当前配置"}</Button>
            </Col>
          </Row>
        </div>
        <Table
          style={{ height: store.getState().tableHeight.y - 100 + 'px' }}
          rowSelection={rowSelection}
          columns={this.state.columns}
          dataSource={this.state.data}
          pagination={false} bordered
          rowKey={(data, index) => {
            return index
          }}
          scroll={{ y: store.getState().tableHeight.y - 140, x: 800 }}
        />
      </div>
    );
  }
}

export default ColumnAuthoritys;  