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, 
  getIecChannelPoint, 
  addPoint,
  deletePoint,
  downloadIecTmpl,
  deleteIecChannelPoint } from '../../../services/deviceService';

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

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


class IEC104ClientManager extends Component {
    constructor(props){
        super(props);
        this.pageConfig = {
          pageNumber: 0,
          pageSize: 10
        };
        this.state = {
          yxDataSource: [],
          yCDataSource: [],
          selectedKeys: [],
          channels: [],
          form: {},
          modal: false,
          rules: {
            name: [
              { required: true, message: '请输入通道名称' },
            ],
            commonAddress: [
              { required: true, message: '请输入公共地址' },
            ],
            ip: [
              { required: true, message: '请输入IP地址' },
            ],
            port: [
              { 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("IEC_CLIENT").then(
      data => {
        this.setState({ channels: data });
      }
    );
  }

  refeshPLCDetail = (id) =>{
 
  }

  questItemsData = (channelNo, pointType) => {
    console.log(channelNo);
    if (!channelNo) {
      this.setState({ yxDataSource: [] });
      this.setState({ ycDataSource: [] });
      return;
    }
    getIecChannelPoint(channelNo, pointType).then(
      data => {
        if (pointType === 'yx') {
          this.setState({ yxDataSource: data });
        } else if (pointType === 'yc') {
          this.setState({ ycDataSource: 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);
    }  else if (toolBarFlag === 'point-5') {
      const {selectedNode, pointType} = this.state;
      deleteIecChannelPoint(selectedNode, pointType).then(
        data => {
          message.success('操作成功');
          this.questItemsData(selectedNode, pointType);
        }
      );
    } else if (toolBarFlag === 'point-6') {
      downloadIecTmpl();
    }
  }
  deletePoints = (selectedRowKeys) => {
    const {selectedNode, pointType} = this.state;
    deletePoint(selectedRowKeys).then(
      data => {
        message.success('操作成功');
        this.questItemsData(selectedNode, pointType);
      }
    );
  }

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

  reload = () => {
    const { selectedNode , pointType } = this.state;
    this.questItemsData(selectedNode, pointType);
  }

  getToolBar = (pointType) => {
    const { selectedNode } = this.state;
    return <ToolBar reload={this.reload} onButtonClick={this.onToolBarClick} pointType={pointType} serviceId={selectedNode} />;
  }

  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 = "IEC_CLIENT";
      createChannel(form).then(
        data => {
          if (data) {
            message.danger(data);
            return;
          }
          message.success('操作成功');
          this.setState({modal: false});
          this.queryPLCChannelList();
        }
      );
    } else if (toolBarFlag === 'point-1' || toolBarFlag === 'point-3') {
      const selectedNode = this.state.selectedNode;
      const { pointType } = this.state;
      form.channelNo = selectedNode;
      form.pointType = pointType;
      addPoint(form).then(
        data => {
          message.success('操作成功');
          this.setState({modal: false});
          this.questItemsData(selectedNode, pointType);
        }
      );
    } 
    
  }

  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="port" {...formItemLayout} >
            <Input
              value={form.port}
              placeholder="请输入端口号"
              onChange={(e) => this.onChange('port', e)}
            />
          </FormItem>
          <FormItem label="公共地址" field="commonAddress" {...formItemLayout} >
            <Input
              value={form.commonAddress}
              placeholder="请输入公共地址"
              onChange={(e) => this.onChange('commonAddress', 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>数据项编码</span>} field="pointCode" {...formItemLayout} >
            <Input
              value={form.pointCode}
              placeholder="请输入数据项编码"
              onChange={(e) => this.onChange('pointCode', e)}
            />
          </FormItem>
          <FormItem label={<span>信息地址</span>} field="originatorAddress" {...formItemLayout} >
            <Input
              value={form.originatorAddress}
              placeholder="请输入信息地址"
              onChange={(e) => this.onChange('originatorAddress', e)}
            />
          </FormItem>
          {/* <FormItem label="点位类型" field="pointType" {...formItemLayout} >
            <Select value={form.pointType} onChange={this.onPointTypeChange}>
              <Option value="yx">遥信</Option>
              <Option value="yc">遥测</Option>
            </Select>
          </FormItem> */}
        </Form>
      );
    }
    return "";
  }

  onPointTypeChange = (value, item) => {
    const newForm = Object.assign({}, this.state.form, { pointType: value });
    this.setState({
      form: newForm
    });
  }

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

  handleChange = (key) => {
    this.setState({pointType: key});
    const {selectedNode} = this.state;
    this.questItemsData(selectedNode, key);
  }

  render() {
    let {
      selectedKeys,
      selectedNode,
      toolBarFlag,
      selectedRowKeys,
      pointType,
      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"
            activeKey={pointType}
            defaultActiveKey={pointType}
            onChange={this.handleChange}
            tabBarExtraContent={this.getToolBar(pointType)}
          >
              <TabPane tab={<span>遥信转发表</span>} key="yx">
                <Table
                  columns={tableColumns}
                  rowKey={record => record.id}
                  rowSelection={rowSelection}
                  bordered
                  dataSource={this.state.yxDataSource} > 
                </Table>
              </TabPane>
              <TabPane tab={<span>遥测转发表</span>} key="yc">
                <Table
                  columns={tableColumns}
                  rowKey={record => record.id}
                  rowSelection={rowSelection}
                  bordered
                  dataSource={this.state.ycDataSource} > 
                </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>
    );
  }
}

IEC104ClientManager.propTypes = {

};

export default IEC104ClientManager;