import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { OltSerUrl } from './../../../../../consts/urlConsts';
import { Input,Form,Modal } from 'amos-antd';
import { AmosFetch } from '../../../../../utils/processor';
import { Row,Col } from 'amos-framework';

const createForm = Form.create();
const FormItem = Form.Item;
const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 6 }
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 }
  }
};
/**
 * 设备属性
 *
 * @class DeviceProperty
 * @extends {Component}
 */
class DevicePropertyPanel extends Component {
  constructor(props) {
    super(props);
    this.state = {
      attributes: [],
      intfcList: [],
      capabilities: [],
      equipment: {},
      editProperty: false
    };
  }

  /**
   * 初始化
   */
  componentDidMount() {
    let { config,equipmentId } = this.props;
    let propertyContent = config.data ? config.data : {};
    this.getPropertyData(propertyContent.id,equipmentId);
    this.getInterfaceData(propertyContent.id);
  }

  componentWillReceiveProps(nextProps){
    let { nodeId,cfgParamJson } = this.props;
    let nextPropertyContent = nextProps.config.data ? nextProps.config.data : {};
    if (nodeId !== nextProps.nodeId || cfgParamJson !== nextProps.cfgParamJson) {
      this.getPropertyData(nextPropertyContent.id,nextProps.equipmentId);
      this.getInterfaceData(nextPropertyContent.id);
    }
  }

  //设备属性编辑
  onClickProperty = (e,flag) => {
    if (!flag) {
      this.savePropertyToEquipment();
    }
    this.setState({ editProperty: flag });
  }

  //设备能力编辑
  onClickCapacity = (e,item) => {
    let { showDeviceCapacityPanel } = this.props;
    showDeviceCapacityPanel(item,this.getCurrentEquipment);
  }

  //属性编辑
  onAttributeChange = (e,propertyId) => {
    let { attributes } = this.state;
    if (attributes !== undefined) {
      attributes.map((item)=>{
        if (item.id === propertyId) {
          item.valueStr = e.target.value;
        }
      });
    }
  }

  //获取设备能力
  getPropertyData = (id,equipmentId) => {
    // if (id !== undefined) {
    //   let url = `${OltSerUrl.fetchDeviceById}/${id}`;
    //   AmosFetch.get(url).then(res => {
    //     if (res.ok) {
    //       return res.json();
    //     }
    //     else
    //     {
    //       throw new Error('从服务端获取数据失败！');
    //     }
    //   }).then((data)=>{
    //     if (data.result === 'SUCCESS'){
    //       let deviceData = data.dataList;
    //       if (deviceData !== undefined) {
    //         this.getEquipmentData(equipmentId,deviceData.attributes ? deviceData.attributes : []);
    //         this.setState({ capabilities: deviceData.capabilities ? deviceData.capabilities : [] });
    //       }
    //     }
    //   });
    // }
  }

  //获取设备接口
  getInterfaceData = (id) => {
    if (id !== undefined) {
      let url = `${OltSerUrl.fetchDeviceInterfaceById}/${id}`;
      AmosFetch.get(url).then(res => {
        if (res.ok) {
          return res.json();
        }
        else
        {
          throw new Error('从服务端获取数据失败！');
        }
      }).then((data)=>{
        if (data.result === 'SUCCESS'){
          let dataList = data.dataList;
          this.setState({ intfcList: dataList ? dataList : [] });
        }
      });
    }
  }

  //获取设备信息
  getEquipmentData = (id,attributes) => {
    if (id !== undefined) {
      let url = `${OltSerUrl.getEquipmentData}/${id}`;
      AmosFetch.get(url).then(res => {
        if (res.ok) {
          return res.json();
        }
        else
        {
          throw new Error('从服务端获取数据失败！');
        }
      }).then((data)=>{
        if (data.result === 'SUCCESS'){
          let dataList = data.dataList;
          //用设备的属性替换模板默认属性
          attributes.map((item)=> {
            item.valueStr = dataList.cfgParamMap[`equip_${item.id}`];
          });
          this.setState({ equipment: dataList,attributes });
        }
      });
    } else {
      this.setState({ equipment: {} });
    }
  }

  //生成界面
  getAttributesContent = () => {
    let { attributes,equipment } = this.state;
    let content = [];
    content.push(
      <Row>
        <Col span={4} offset={1} style={{ height: '30px', 'line-height': '30px' }} >
          编码：
        </Col>
        <Col span={18} offset={1} style={{ 'text-align': 'left',height: '30px', 'line-height': '30px' }} >
          <Input style={{ width: '60%' }}
            defaultValue={'BGK-Micro-40D'}
          />
        </Col>
      </Row>);
    content.push(
      <Row>
        <Col span={4} offset={1} style={{ height: '30px', 'line-height': '30px' }} >
          端口：
        </Col>
        <Col span={18} offset={1} style={{ 'text-align': 'left',height: '30px', 'line-height': '30px' }} >
          <Input style={{ width: '60%' }}
            defaultValue={'10003'}
          />
        </Col>
      </Row>);

    // if (equipment.cfgParamMap !== undefined) {
    //   attributes.map((item)=>{
    //     let displayValue = equipment.cfgParamMap[`equip_${item.id}`] === undefined ? item.valueStr : equipment.cfgParamMap[`equip_${item.id}`];
    //     content.push(
    //       <Row>
    //         <Col span={4} offset={1} style={{ height: '30px', 'line-height': '30px' }} >
    //           {item.name}：
    //         </Col>
    //         <Col span={18} offset={1} style={{ 'text-align': 'left',height: '30px', 'line-height': '30px' }} >
    //           {displayValue}
    //         </Col>
    //       </Row>);
    //   });
    // } else {
    //   attributes.map((item)=>{
    //     content.push(
    //       <Row>
    //         <Col span={4} offset={1} style={{ height: '30px', 'line-height': '30px' }} >
    //           {item.name}：
    //         </Col>
    //         <Col span={18} offset={1} style={{ 'text-align': 'left',height: '30px', 'line-height': '30px' }} >
    //           {item.valueStr}
    //         </Col>
    //       </Row>);
    //   });
    // }
    return content;
  }

  //生成编辑界面
  getAttributesEditContent = () => {
    let { attributes,equipment } = this.state;
    let content = [];
    if (equipment.cfgParamMap !== undefined) {
      attributes.map((item)=>{
        let displayValue = equipment.cfgParamMap[`equip_${item.id}`] === undefined ? item.valueStr : equipment.cfgParamMap[`equip_${item.id}`];
        content.push(
          <Row>
            <Col span={4} offset={1} style={{ height: '30px', 'line-height': '30px' }} >
              {item.name}：
            </Col>
            <Col span={18} offset={1} style={{ 'text-align': 'left',height: '30px', 'line-height': '30px' }} >
              <Input style={{ width: '60%' }}
                onChange={(e) => this.onAttributeChange(e, item.id)}
                defaultValue={displayValue}
              />
            </Col>
          </Row>);
      });
    } else {
      attributes.map((item)=>{
        content.push(
          <Row>
            <Col span={4} offset={1} style={{ height: '30px', 'line-height': '30px' }} >
              {item.name}：
            </Col>
            <Col span={18} offset={1} style={{ 'text-align': 'left',height: '30px', 'line-height': '30px' }} >
              <Input style={{ width: '60%' }}
                onChange={(e) => this.onAttributeChange(e, item.id)}
                defaultValue={item.valueStr}
              />
            </Col>
          </Row>);
      });
    }
    return content;
  }

  //生成界面
  getCapacitysContent = () => {
    let { capabilities } = this.state;
    let content = [];
    content.push(
      <Row>
        <Col span={4} offset={1} style={{ height: '30px', 'line-height': '30px' }}>
          {'经纬度'}
        </Col>
        <Col span={18} offset={1} style={{ 'text-align': 'left', height: '30px', 'line-height': '30px' }} >
          <div onClick={(e) => this.onClickCapacity(e,'经纬度')} className='edit-interface-img'>
            <img src={require('./../../../../../assets/iot/img/list_nlsx.png')} alt='' style={{ position: 'relative', top: '5px' }} />
          </div>
        </Col>
      </Row>);
    content.push(
      <Row>
        <Col span={4} offset={1} style={{ height: '30px', 'line-height': '30px' }}>
          {'压力'}
        </Col>
        <Col span={18} offset={1} style={{ 'text-align': 'left', height: '30px', 'line-height': '30px' }} >
          <div onClick={(e) => this.onClickCapacity(e,'压力')} className='edit-interface-img'>
            <img src={require('./../../../../../assets/iot/img/list_nlsx.png')} alt='' style={{ position: 'relative', top: '5px' }} />
          </div>
        </Col>
      </Row>);
    return content;
  }

  //获取当前设备
  getCurrentEquipment = () => {
    let { equipment } = this.state;
    return equipment;
  }

  //保存设备属性信息
  savePropertyToEquipment = () => {
    let { attributes,equipment } = this.state;
    if (equipment.id === undefined) {
      let { updateNodeConfig, nodeId,cfgParamJson } = this.props;
      if (attributes !== undefined) {
        attributes.map((item)=>{
          let key = `equip_${item.id}`;
          let value = item.valueStr;
          //有属性：覆盖，没数据：添加
          if (cfgParamJson.hasOwnProperty(key))
          {
            cfgParamJson[key] = value;
          } else {
            Object.assign(cfgParamJson,{ [key]: value });
          }
        });
        //保存到缓存
        updateNodeConfig(nodeId, cfgParamJson);
      }
    } else {
      let equipmentAttributes = equipment.cfgParamMap;
      if (attributes !== undefined) {
        attributes.map((item)=>{
          let key = `equip_${item.id}`;
          let value = item.valueStr;
          //有属性：覆盖，没数据：添加
          if (equipmentAttributes.hasOwnProperty(key))
          {
            equipmentAttributes[key] = value;
          } else {
            Object.assign(equipmentAttributes,{ [key]: value });
          }
        });
        equipment.cfgParamJson = JSON.stringify(equipmentAttributes);
        //保存到后台
        AmosFetch.post(OltSerUrl.addEquipmentAttribute, { data: equipment }).then(res => {
          if (res.ok) {
            return res.json();
          }
          else {
            throw new Error('从服务端获取数据失败！');
          }
        }).then((data) => {
          if (data.result === 'SUCCESS') {
            Modal.warning({
              title: '系统提示',
              content: '编辑成功！',
              okText: '确定'
            });
          } else {
            Modal.error({
              title: '系统提示',
              content: '编辑失败！',
              okText: '确定'
            });
          }
        });
      }
    }
  }

  //更新名称
  updateName = (name) => {
    // let { equipment } = this.state;
    // let { config,getSubgraphData,subviewId,nodeId,updateNodeName } = this.props;
    // if (equipment.id === undefined) {
    //   updateNodeName(nodeId,name);
    // } else {
    //   let propertyContent = config.data;
    //   let newConfig = {
    //     label: name,
    //     type: config.type,
    //     data: propertyContent,
    //     style: config.style
    //   };
    //   let id = propertyContent.id;
    //   let postData = { id,name,nodeId,config: JSON.stringify(newConfig) };
    //   let url = `${OltSerUrl.updateNodeName}`;
    //   //提交后台
    //   AmosFetch.post(url,{ data: postData }).then(res => {
    //     if (res.ok) {
    //       return res.json();
    //     }
    //     else
    //     {
    //       throw new Error('从服务端获取数据失败！');
    //     }
    //   }).then((data)=>{
    //     if (data.result === 'SUCCESS'){
    //       getSubgraphData(subviewId,nodeId);
    //     } else {
    //       //失败时提示
    //       Modal.error({
    //         title: '系统提示',
    //         content: '编辑失败！',
    //         okText: '确定'
    //       });
    //     }
    //   });
    // }
  }

  render() {
    let { config,deviceLabel } = this.props;
    let { editProperty } = this.state;
    let propertyContent = config.data ? config.data : {};
    let name = config.label === undefined ? propertyContent.name : config.label;
    // let displayImgUrl = propertyContent.img;
    // let srcImgUrl = displayImgUrl === '' ? `${OltSerUrl.fetchDeviceImg}/default.png` : `${OltSerUrl.fetchDeviceImg}/${displayImgUrl}`;
    return (
      <div className='device-property-panel'>
        {/*<div className='property-img-info'>
          <img src={srcImgUrl} alt='device' width='100%' height='100%' />
    </div>*/}
        <div className='head-one'>设备信息</div>
        <div className='head-two'>
          <div className='head-two-one'>

          </div>
          <div className='head-two-two'>
            删除
          </div>
          <div className='head-two-three'>
            取消
          </div>
          <div className='head-two-four'>
            完成
          </div>
        </div>
        <div className='property-basic-info'>
          <div className='property-basic-info-label'>
            <label>基本信息</label>
            <img src={require('./../../../../../assets/iot/topo/u2074.png')} alt='' className='img-line' />
            <img src={require('./../../../../../assets/iot/topo/expand.png')} alt='' className='img-last-temp' />
          </div>
          <div style={{ height: '100%' }}>
            <Row>
              <Col span={4} offset={1} style={{ height: '30px','line-height': '30px' }} >
                名称：
              </Col>
              <Col span={18} offset={1} style={{ 'text-align': 'left' }} >
                <Input style={{ width: '60%' }}
                  value={deviceLabel}
                />
              </Col>
            </Row>
            <Row>
              <Col span={4} offset={1} style={{ height: '30px','line-height': '30px' }}>
                型号：
              </Col>
              <Col span={18} offset={1} style={{ 'text-align': 'left',height: '30px','line-height': '30px' }} >
                <Input style={{ width: '60%' }}
                  defaultValue={'BGK-Micro-40D'}
                />
              </Col>
            </Row>
            <Row>
              <Col span={4} offset={1} style={{ height: '30px','line-height': '30px' }}>
                类别：
              </Col>
              <Col span={18} offset={1} style={{ 'text-align': 'left',height: '30px','line-height': '30px' }} >
                <Input style={{ width: '60%' }}
                  defaultValue={'传感设备'}
                />
              </Col>
            </Row>
            <Row>
              <Col span={4} offset={1} style={{ height: '30px','line-height': '30px' }}>
                备注：
              </Col>
              <Col span={18} offset={1} style={{ 'text-align': 'left',height: '30px','line-height': '30px' }} >
                <Input style={{ width: '60%' }}
                  defaultValue={deviceLabel}
                />
              </Col>
            </Row>
          </div>
        </div>
        <div className='property-property-info'>
          <div className='property-property-info-title'>
            <label>设备属性</label>
            <img src={require('./../../../../../assets/iot/topo/u2074.png')} alt='' className='img-line' />
            <img src={require('./../../../../../assets/iot/topo/expand.png')} alt='' className='img-last-temp' />
          </div>
          {editProperty ? this.getAttributesEditContent() : this.getAttributesContent()}
        </div>
        <div className='property-interface-info'>
          <div className='property-interface-info-label'>
            <label>数据采集</label>
            <img src={require('./../../../../../assets/iot/topo/u2074.png')} alt='' className='img-line' />
            <img src={require('./../../../../../assets/iot/topo/expand.png')} alt='' className='img-last-temp' />
          </div>
          {this.getCapacitysContent()}
        </div>
      </div>
    );
  }
}

DevicePropertyPanel.propTypes = {
  config: PropTypes.object,
  form: PropTypes.any,
  getSubgraphData: PropTypes,
  subviewId: PropTypes.string,
  nodeId: PropTypes.string,
  showDeviceCapacityPanel: PropTypes.func,
  equipmentId: PropTypes.number,
  updateNodeConfig: PropTypes.func,
  cfgParamJson: PropTypes.object,
  updateNodeName: PropTypes.func,
  deviceLabel: PropTypes.string
};

export default createForm(DevicePropertyPanel);
