import React, { Component } from 'react';
import { Tabs, Table  } from 'amos-antd';
import { Modal, AmosAlert, Form, Input, Button, Select, Tree, SplitPane, Icon, Divider, message } from 'amos-framework';
import ToolBar from './ToolBar';
import { 
  getChannelByType, 
  createChannel, 
  deleteChannel, 
  getChannelPoint, 
  addPoint,
  deletePoint,
  deleteChannelPoint } from '../../services/deviceService';

const FormItem = Form.Item;
const TabPane = Tabs.TabPane;
const TreeNode = Tree.TreeNode;
const { TabList, Tab, TabPanel } = Tabs;

const tableColumns = [
  {
    title: '名称',
    dataIndex: 'name',
    key: 'name'
  },
  {
    title: '编码',
    dataIndex: 'pointCode',
    key: 'pointCode'
  },
  {
    title: '地址',
    dataIndex: 'originatorAddress',
    key: 'originatorAddress'
  },
  {
    title: '值',
    dataIndex: 'value',
    key: 'value'
  }
];


class PLCManager extends Component {
    constructor(props){
        super(props);
        this.pageConfig = {
          pageNumber: 0,
          pageSize: 10
        };
        this.state = {
          dataSource: [],
          selectedKeys: [],
          channels: [],
          form: {},
          modal: false,
          rules: {
            name: [
              { required: true, message: '请输入通道名称' },
            ],
            userName: [
              { required: true, message: '请输入用户名' },
            ],
            ip: [
              { required: true, message: '请输入IP地址' },
            ],
            password: [
              { required: true, message: '请输入密码' },
            ]
          }
        };
    }
    
  componentDidMount(){
    document.addEventListener('click', this._handleClick);//页面增加鼠标单击监听
    window.addEventListener('resize', this._resize);
    this.setOncontextmenu();//移除浏览器自带右键菜单
    this.queryPLCChannelList();
  }

  setOncontextmenu =()=>{
    document.oncontextmenu = (e) =>{
      return false;
    };
  }

  componentWillReceiveProps(nextProps) {

  }

  ccomponentWillUnmount() {
    let channelDiv = document.getElementsByClassName('channel')[0];
    let riskModelTabDiv = document.getElementsByClassName('device-data-items')[0];
    channelDiv && channelDiv.removeEventListener('click', this._handleClick);//页面移除鼠标单击监听
    riskModelTabDiv && riskModelTabDiv.removeEventListener('click', this._handleClick);//页面移除鼠标单击监听
    window.addEventListener('resize', this._resize);
  }

  _resize =()=>{
    this.onscroll();
  }

  onscroll =(e)=>{
    const { rightClickNodeTreeItem }  = this.state;
    rightClickNodeTreeItem ? this.setState({ rightClickNodeTreeItem: null }) : '';
  }


  queryRiskSourceTree =(riskSourceId)=>{

  }

 
  onSelect =(selectedKeys,e)=>{

  }

  queryPLCChannelList = () => {
    getChannelByType("OPC_CLIENT").then(
      data => {
        this.setState({ channels: data });
      }
    );
  }

  refeshPLCDetail = (id) =>{
 
  }

  questItemsData = (channelNo) => {
    console.log(channelNo);
    getChannelPoint(channelNo).then(
      data => {
        this.setState({ dataSource: data });
      }
    );
  };

  queryPLCListData = (searchParam, pageNumber, pageSize) => {
    
  }

  onClick = (e,key)=>{

  }

  onToolBarClick = (toolBarFlag) => {
    if (toolBarFlag === 'point-1'){
      const selectedNode = this.state.selectedNode;
      if (!selectedNode) {
        message.danger("请选择通道");
        return;
      }
      this.setState({modal: true, toolBarFlag });
    } else if (toolBarFlag === 'point-3'){
      const { selectedRows } = this.state
      if (selectedRows.length > 1) {
        message.danger("行数大于1，请重新选择");
        return;
      }
      if (selectedRows.length < 1) {
        message.danger("请重新选择数据项");
        return;
      }
      this.setState({modal: true, toolBarFlag, form: selectedRows[0] });
    } else if (toolBarFlag === 'point-2'){
      const { selectedRowKeys } = this.state
      this.deletePoints(selectedRowKeys);
    } 
  }
  deletePoints = (selectedRowKeys) => {
    const {selectedNode} = this.state;
    deletePoint(selectedRowKeys).then(
      data => {
        message.success('操作成功');
        this.questItemsData(selectedNode);
      }
    );
  }

  onSelectTreeNode = (selectedKeys, { selectedNodes }) =>{
    console.log(selectedNodes);
    this.setState({selectedNode: selectedNodes[0].props.channelNo, selectedKeys});
    this.questItemsData(selectedNodes[0].props.channelNo);
  }

  getToolBar = (parent) => {
    return <ToolBar onButtonClick={this.onToolBarClick} parent={parent} />;
  }

  readerTreeNode = () => {
    const { channels } = this.state;
    return (
      <TreeNode icon={<Icon icon="folder" />} title="通道" key="0-0">
        {channels.map( item=> <TreeNode icon={<Icon icon="file-leaf" />} channel={item} channelNo={item.channelNo} title={item.name} key={item.id} />)}
      </TreeNode>
    );
  }

  onRightClick = ({event, node}) => {
    this.setState({
      rightClickNodeTreeItem: {
        pageX: event.pageX,
        pageY: event.pageY
      }, selectedNode: node.props.channelNo, channel: node.props.channel });
  }
  _handleClick = (event) => {
    this.setState({ rightClickNodeTreeItem: null });
  }
  
  
  //树按钮点击事件
  onButtonClick = (value) => {
    let channelNo = this.state.selectedNode;
    const channel = this.state.channel;
    if (value === '1') {
      this.setState({ modal: true,toolBarFlag: value , form: {} });
    } else if (value === '2') {
      this.setState({ modal: true,toolBarFlag: value, form: channel });
    } else if (value === '3'){
      this.channelDelete(channelNo);
    }
    this.setState({ rightClickNodeTreeItem: null });
  }

  channelDelete = (channelNo) => {
    deleteChannel(channelNo).then(
      data => {
        message.success('删除成功');
        this.queryPLCChannelList();
      }
    );
  }

  
  getModalHeader =(toolBarFlag)=>{
    let header = '';
    if (toolBarFlag === '2') {
      header = '编辑通道';
    } else if (toolBarFlag === '2'){
      header = '添加通道';
    } else if (toolBarFlag === 'point-1'){
      header = '新增数据项';
    } else if (toolBarFlag === 'point-3'){
      header = '编辑数据项';
    }
    return header;
  }


  getNodeTreeRightClickMenu = () => {
    let { pageX, pageY } = { ...this.state.rightClickNodeTreeItem };
    let channelNo = this.state.selectedNode;
    const height = document.body.offsetHeight;
    let overHeight = height - (pageY + 120);
    overHeight > 0 ? '' : pageY = height - 120;
    const tmpStyle = {
      position: 'absolute',
      left: `${pageX}px`,
      top: `${pageY - 45}px`,
      backgroundColor: '#ffffff',
      border: 'solid',
      height: '70px',
      borderWidth: '1px',
      borderColor: '#c9c9c9'
    };
    const menu = (
      <div style={tmpStyle}>
        {!channelNo ? <Button   onClick={()=>this.onButtonClick('1')}  className='risk-model-button' transparent>添加</Button>:
        <Button   onClick={()=>this.onButtonClick('2')}  className='risk-model-button' transparent>编辑</Button>}
        {channelNo ? <Button  onClick={()=>this.onButtonClick('3')}  className='risk-model-button' transparent>删除</Button>:''}
      </div>
    );
    return this.state.rightClickNodeTreeItem  ? menu : '';
  };


  onOk = () =>{
    let form = this.state.form;
    const { toolBarFlag } = this.state;
    if (toolBarFlag === '1' || toolBarFlag === '2') {
      form.serviceType = "OPC_CLIENT";
      createChannel(form).then(
        data => {
          message.success('操作成功');
          this.setState({modal: false});
          this.queryPLCChannelList();
        }
      );
    } else if (toolBarFlag === 'point-1' || toolBarFlag === 'point-3') {
      const selectedNode = this.state.selectedNode;
      form.channelNo = selectedNode;
      addPoint(form).then(
        data => {
          message.success('操作成功');
          this.setState({modal: false});
          this.questItemsData(selectedNode);
        }
      );
    } 
    
  }

  cancel = () => {
    this.setState({ modal: false });
  };

  getModalFooter = () => {
    return [<Button className='amos-btn-minor' key='cancel' onClick={this.cancel}>取消</Button>, <Button key='ok' onClick={() => this.onOk()}>确定</Button>];
  }

  onChange = (key, e) => {
    const value = e.target.value;
    const newForm = Object.assign({}, this.state.form, { [key]: value });
    this.setState({
      form: newForm
    });
  }

  getContext = (toolBarFlag) => {
    let form = this.state.form;
    const rules = this.state.rules;

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
        className: 'colspanlab'
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
        className: 'colspan'
      }
    };

    if (toolBarFlag === '1' || toolBarFlag === '2') {
      return (
        <Form style={{ width: 300, padding: '30px 0 0 0' }} className="basic-demo" ref={component => this.form = component} model={form} rules={rules}>
          <FormItem label={<span>通道名称</span>} field="name" {...formItemLayout} >
            <Input
              value={form.name}
              placeholder="请输入通道名称"
              onChange={(e) => this.onChange('name', e)}
            />
          </FormItem>
          <FormItem label={<span>服务器地址</span>} field="ip" {...formItemLayout} >
            <Input
              value={form.ip}
              placeholder="请输入服务器地址"
              onChange={(e) => this.onChange('ip', e)}
            />
          </FormItem>
          <FormItem label={<span>用户名</span>} field="userName" {...formItemLayout} >
            <Input
              value={form.userName}
              placeholder="请输入用户名"
              onChange={(e) => this.onChange('userName', e)}
            />
          </FormItem>
          <FormItem label="密码" field="password" {...formItemLayout} >
            <Input
              value={form.password}
              type="password"
              placeholder="请输入密码"
              onChange={(e) => this.onChange('password', e)}
            />
          </FormItem>
        </Form>
      );
    } else if (toolBarFlag === 'point-1' || toolBarFlag === 'point-3') {
      
      return (
        <Form style={{ width: 300, padding: '30px 0 0 0' }} className="basic-demo" ref={component => this.form = component} model={form} rules={rules}>
          <FormItem label={<span>数据项名称</span>} field="name" {...formItemLayout} >
            <Input
              value={form.name}
              placeholder="请输入通道名称"
              onChange={(e) => this.onChange('name', e)}
            />
          </FormItem>
          <FormItem label={<span>itemId</span>} field="originatorAddress" {...formItemLayout} >
            <Input
              value={form.originatorAddress}
              placeholder="请输入itemId"
              onChange={(e) => this.onChange('originatorAddress', e)}
            />
          </FormItem>
          <FormItem label={<span>数据项编码</span>} field="pointCode" {...formItemLayout} >
            <Input
              value={form.pointCode}
              placeholder="请输入数据项编码"
              onChange={(e) => this.onChange('pointCode', e)}
            />
          </FormItem>
        </Form>
      );
    }
    return "";
  }

  onSelectChange = (selectedRowKeys,selectedRows) => {
    this.setState({selectedRowKeys,selectedRows});
  }

  render() {
    let {
      selectedKeys,
      selectedNode,
      toolBarFlag,
      selectedRowKeys,
      modal
    } = this.state;

    let rowSelection = {
      selectedRowKeys: selectedRowKeys,
      onChange: this.onSelectChange
    };

    return (
      <div>
      <SplitPane percentage={true} mainPaneMinSize={15} secondaryMinSize={85}>
        <div className="channel" >
          <Tree 
            showIcon 
            defaultExpandAll 
            selectedKeys={selectedKeys}
            onSelect={this.onSelectTreeNode}
            onRightClick={this.onRightClick}
            defaultSelectedKeys={['0-0-0']}>
            
            {this.readerTreeNode()}
          </Tree>
        </div>
        <div className="device-data-items" >
          <div className="plc-title">
            <div className="con-eva-key">编号: </div>
            <div className="con-eva-value">{selectedNode}</div>
          </div>
          <Divider className="plc-divider" />
          <div  className="plc-body">  
          <Tabs
            className="quyu-info-tab"
            type="card"
            tabBarExtraContent={this.getToolBar(this)}
          >
              <TabPane tab={<span>数据项</span>}>
                <Table
                  columns={tableColumns}
                  rowKey={record => record.id}
                  rowSelection={rowSelection}
                  bordered
                  dataSource={this.state.dataSource} > 
                </Table>
              </TabPane>
            </Tabs>
          </div>
        </div>
      </SplitPane>
      <Modal
          header={this.getModalHeader(toolBarFlag)}
          visible={modal}
          className="risk-model-model"
          destroyContent
          width={'30%'}
          content={this.getContext(toolBarFlag)}
          onCancel={() => this.cancel()}
          onOk={() => this.onOk()}
          footer={this.getModalFooter()}
          outterClosable={false}
        />
      {this.getNodeTreeRightClickMenu()}
      </div>
    );
  }
}

PLCManager.propTypes = {

};

export default PLCManager;