'use strict';

import React, { Component } from 'react';
import { CardPane, Row, Col, Button } from 'amos-framework';
import PropTypes from 'prop-types';
import {
  fetchPointMeasuresAction,
  fetchPointDetailAction,
  deletePointMeasuresAction,
  batchDeletePointMeasuresAction,
  savePointMeasuresAction,
  batchSavePointMeasuresAction
} from './../../../services/checkInfoService';
import pointInfocss from '../../../styles/view/biz/point/pointInfo.scss';
import AmosGridTable from './../common/tableComponent/table/AmosGridTable';
import BizIcon from './../../common/icon/BizIcon';

//偏移110px
const offsetHeight = 110;
const defaultHeight = 390;

const strUnique = str => {
  if(str){
    let arr = str.split(',')
    let newarr=[...new Set(arr)]
    return newarr.join(",")
  }else{
    return '';
  }
 }

const measuresColumns = self => {
  return [
    {
      title: '级别',
      dataIndex: 'level',
      key: 'level',
      width: '5%',
      className: 'uant-table-thead',
      render: function(text, record, index) {
        let levelText = '一级';
        if (text === '2') {
          levelText = '二级';
        } else if (text === '3') {
          levelText = '三级';
        } else if (text === '4') {
          levelText = '四级';
        } else if (text === '5') {
          levelText = '五级';
        }
        return (
          <div id={'level' + record.id} className={record.edit ? 'editorTable' : ''} contenteditable={`${record.edit}`}>
            {levelText}
          </div>
        );
      }
    },
    {
      title: '事故类型',
      dataIndex: 'accidentType',
      key: 'accidentType',
      width: '5%',
      className: 'uant-table-thead',
      render: function(text, record, index) {
        return (
          <div id={'accidentType' + record.id} className={record.edit ? 'editorTable' : ''} contenteditable={`${record.edit}`}>
            {text}
          </div>
        );
      }
    },
    {
      title: '风险因素',
      dataIndex: 'riskFactors',
      key: 'riskFactors',
      width: '15%',
      className: 'uant-table-thead',
      render: function(text, record, index) {
        return (
          <div id={'riskFactors' + record.id} className={record.edit ? 'editorTable' : ''} contenteditable={`${record.edit}`}>
            {text}
          </div>
        );
      }
    },
    {
      title: '工程措施',
      dataIndex: 'engineering',
      key: 'engineering',
      width: '15%',
      className: 'uant-table-thead',
      render: function(text, record, index) {
        return (
          <div id={'engineering' + record.id} className={record.edit ? 'editorTable' : ''} contenteditable={`${record.edit}`}>
            {text}
          </div>
        );
      }
    },
    {
      title: '管理措施',
      dataIndex: 'manager',
      key: 'manager',
      width: '15%',
      className: 'uant-table-thead',
      render: function(text, record, index) {
        return (
          <div id={'manager' + record.id} className={record.edit ? 'editorTable' : ''} contenteditable={`${record.edit}`}>
            {text}
          </div>
        );
      }
    },
    {
      title: '培训教育',
      dataIndex: 'train',
      key: 'train',
      render: function(text, record, index) {
        return (
          <div id={'train' + record.id} className={record.edit ? 'editorTable' : ''} contenteditable={`${record.edit}`}>
            {text}
          </div>
        );
      }
    },
    {
      title: '个体防护',
      dataIndex: 'protect',
      key: 'protect',
      width: '15%',
      className: 'ant-table-thead',
      render: function(text, record, index) {
        return (
          <div id={'protect' + record.id} className={record.edit ? 'editorTable' : ''} contenteditable={`${record.edit}`}>
            {text}
          </div>
        );
      }
    },
    {
      title: '应急处置',
      dataIndex: 'emergency',
      key: 'emergency',
      width: '15%',
      className: 'ant-table-thead',
      style: {
        background: '#272727',
        textAlign: 'center',
        color: '#FFFFFF'
      },
      render: function(text, record, index) {
        return (
          <div id={'emergency' + record.id} className={record.edit ? 'editorTable' : ''} contenteditable={`${record.edit}`}>
            {text}
          </div>
        );
      }
    }
    /* , {
    title: '操作',
    dataIndex: '',
    key: 'operation',
    className: 'uant-table-thead',
    render: function( text, record, index) {
      return <p><a href="#" onClick={function() { self.onEditClick(record)} }>修改</a>&nbsp;&nbsp;&nbsp;
                <a href="#" onClick={function() { self.onDeleteClick(record)} }>删除</a>&nbsp;&nbsp;&nbsp;
                <a href="#" onClick={function() { self.onSaveClick(record)} }>保存</a>
            </p>;
    }
  }*/
  ];
};

class PointInfo extends Component {
  constructor(props) {
    super(props);
    this.state = {
      searchParam: {},
      pointDetail: {
        pointID: -1,
        checkType: '',
        groupName: '',
        realName: '',
        name: ''
      },
      measures: [],
      dataList: [],
      selectedRows: [],
      dataSource: [],
      selectedRowKeys: [],
      index: 0
    };
  }

  componentWillMount() {
    const { pointID } = this.props;
    pointID && this.onInit(pointID);
  }

  componentWillReceiveProps(nextProps){
    const { pointID } = this.props;
    if (nextProps.pointID && pointID !== nextProps.pointID) {
      this.onInit(nextProps.pointID);
    }
  }

  onInit = (id) => {
    this.onInfoReload(id);
    this.onTableReload(id);
  }

  onTableReload = (id) => {
    fetchPointMeasuresAction(id).then(data => {
      let source = new Array();
      data.map(item => {
        item.edit = false;
        source.push(item);
      });
      this.setState({ dataSource: source, selectedRows: [], selectedRowKeys: [] });
    });
  }

  onInfoReload = (id) => {
    fetchPointDetailAction(id).then(data => {
      this.setState({ pointDetail: data });
    });
  }

  onEditClick(record) {
    const { dataSource } = this.state;
    let source = new Array();
    dataSource.map(item => {
      if (record.id === item.id) {
        item.edit = true;
      }
      source.push(item);
    });
    this.setState({ dataSource: source });
  }

  onDeleteClick(record) {
    const { dataSource } = this.state;

    deletePointMeasuresAction(record).then(data => {
      let source = new Array();
      dataSource.map(item => {
        if (record.id !== item.id) {
          source.push(item);
        }
      });
      this.setState({ dataSource: source });
    });
  }
  onBatchDeleteClick() {
    const { selectedRows } = this.state;
    if (selectedRows && selectedRows.length <= 0) {
      return;
    }

    batchDeletePointMeasuresAction(selectedRows).then(data => {});
  }
  onBatchSaveClick() {
    const { dataSource } = this.state;
    if (dataSource && dataSource.length <= 0) {
      return;
    }
    batchSavePointMeasuresAction(dataSource).then(data => {});
  }
  onSaveClick(record) {
    savePointMeasuresAction(record).then(data => {});
  }

  /**
   * 获取复选框选择的数据，并进行回调
   */
  getSelectedRows = (selectedRowKeys, selectedRows) => {
    this.setState({ selectedRows: selectedRows, selectedRowKeys: selectedRows });
  };

  goBackAction = () => {
    // browserHistory.goBack('/biz/patrolpoint');
    // browserHistory.goBack('/biz/patrolpoint');
  };

  render() {
    const { selectedRowKeys, maxHeight, dataSource, searchParam, pointDetail } = this.state;
    const { goBackAction } = this.props;
    const { name, no, realName, checkType, groupName } = pointDetail || {};
    let pointName = name + '(' + no + ')';
    let reactNodespan = React.createElement('span', { style: { color: 'black', backgroundColor: 'transparent' }, height: '100%', width: '100%' }, pointName);

    //设置复选框参数
    let rowSelection = {
      selectedRowKeys: selectedRowKeys,
      onChange: this.onSelectChange
    };
    let groups = strUnique(groupName);
    return (
      <div className='pointinfo-content' style={{ height: '100%' }}>
        <div className="dangerInfo"
          //style={{ float: 'right', 'marginRight': '15px',  'marginTop': '10px', position: 'relative', 'zIndex': '33' }}
          // onClick={() => {
          //   goBackAction();
          // }}
        >
          {/*<img src={require('./../../../assets/fsc/check/back.png')} alt="" />*/}
          <Button icon={<BizIcon icon="fanhui" />} transparent onClick={() => goBackAction()}  />
        </div>
        <CardPane
          title={reactNodespan}
          bordered={false}
          //style={{ border: '1px solid #c9c5c5', height: '100%' }}
          bodyStyle={{ backgroundColor: 'transparent', border: '0px', height: '100%' }}
        >
          <div className="base point-view" style={{ padding: '0px' }}>
            <div>
              <Row id="fxdinfo" type="flex" justify="start" style={{ padding: '0px', height: '45px', marginBottom: '10px' }}>
                <Col className="col_groupcolor" style={{ backgroundColor: '#f2f2f2', padding: '0px' }}>
                  <p>
                    <span>类型</span>
                  </p>
                </Col>
                <Col className="col_groupcolor" style={{ backgroundColor: '#ffffff', padding: '0px' }}>
                  {checkType}
                </Col>
                <Col className="col_groupcolor" style={{ backgroundColor: '#f2f2f2', padding: '0px' }}>
                  部门
                </Col>
                <Col className="col_groupcolor2" style={{ backgroundColor: '#ffffff', paddingLeft: '24px', paddingTop: '2px' }}>
                  {groups}
                </Col>
                <Col className="col_groupcolor" style={{ backgroundColor: '#f2f2f2', padding: '0px' }}>
                  责任人
                </Col>
                <Col className="col_groupcolor3" style={{ backgroundColor: '#ffffff', paddingLeft: '24px', paddingTop: '2px' }}>
                  {realName}
                </Col>
              </Row>
            </div>
            <div className="create-device-root">
              <div className="create-device-host-top">
                <div className="table-title">风险信息</div>
                <div className="table-search" />
              </div>
              <div className="create-device-host-bottom">
                <div className="device-list-content">
                  <AmosGridTable
                    columns={measuresColumns(this)}
                    callBack={()=>{}}
                    dataList={dataSource}
                    getTableDataAction={()=>{}}
                    getSelectedRows={this.getSelectedRows}
                    isPageable={false}
                  />
                </div>
              </div>
            </div>
          </div>
        </CardPane>
      </div>
    );
  }
}

PointInfo.propTypes = {
  goBackAction: PropTypes.func
};

export default PointInfo;
