import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { AmosFetch } from '../../../utils/processor';
import { OltSerUrl } from '../../../consts/urlConsts';
import { Row, Form, Input, Modal } from 'amos-antd';
import { Select } from 'amos-framework';
import { trim } from 'amos-tool';
import { message } from 'amos-framework';
import InterfacePropertyCell from './InterfacePropertyCell';
import AddInterfaceProperty from './AddInterfaceProperty';
import './interface-detail.scss';
import { objOfStrPropTrim, noSpaceLengthValidate } from './../../common/utils/validate';

const FormItem = Form.Item;
const createForm = Form.create();
const Option = Select.Option;

/**
 *
 * 我的接口 详情
 * @class PrivateInterface
 * @extends {Component}
 */
class PrivateInterfaceDetail extends Component {
  constructor(props) {
    super(props);
    this.state = {
      textEdit: false,
      propertyList: []
    };
  }

  componentDidMount() {
    this.requestIntfcAttrs();
  }

  // componentWillReceiveProps(nextProps){
  //   this.setState({
  //     carInfo: nextProps.carInfo
  //   });
  // }
  /**
   * 获取接口属性列表
   */
  requestIntfcAttrs = () => {
    let id = this.props.carInfo.id;
    let url = `${OltSerUrl.deviceInterfaceByid}/${id}`;
    AmosFetch.post(url)
      .then(res => {
        if (res.ok) {
          return res.json();
        } else {
          throw new Error('从服务端获取数据失败！');
        }
      })
      .then(data => {
        this.setState({
          propertyList: data.dataList.content
        });
        this.fetchInterfaceProperty();
      });
  };

  /**
   * 编辑接口参数
   *
   * @memberof PrivateInterfaceDetail
   */
  handleEditParam = e => {
    let commType = this.props.form.getFieldValue('commType');
    let detail = this.props.form.getFieldValue('detail');
    let name = this.props.form.getFieldValue('name');
    let arr = this.props.communityDatas;
    let communityProtocol = null;
    let param = null;
    if (isNaN(commType)) {
      for (let i = 0; i < arr.length; i++) {
        param = arr[i];
        if (param.name === commType) {
          commType = param.id;
          communityProtocol = param;
          break;
        }
      }
    } else {
      for (let j = 0; j < arr.length; j++) {
        param = arr[j];
        if (param.id === parseInt(commType)) {
          commType = param.id;
          communityProtocol = param;
          break;
        }
      }
    }

    this.setState({ textEdit: !this.state.textEdit });
    //提交后台
    if (this.state.textEdit) {
      this.props.form.validateFields((errors, values) => {
        if (errors) {
          this.setState({ textEdit: true });
          return;
        } else {
          let oldBasicData = this.props.carInfo;
          let data = Object.assign(oldBasicData, { dicIdCommMode: commType, remark: detail, attributes: null, communityProtocol, name });
          this.submitBasicData(data);
        }
      });
    }
  };

  /**
   * 提交接口基本信息
   */
  submitBasicData = data => {
    AmosFetch.post(OltSerUrl.interfaceSave, { data })
      .then(res => {
        if (res.ok) {
          return res.json();
        } else {
          throw new Error('从服务端获取数据失败！');
        }
      })
      .then(data => {
        if (data.result === 'SUCCESS') {
          message.success('编辑成功');
        } else {
          this.setState({ textEdit: true });
          message.danger('编辑失败！');
        }
      });
  };

  handleAddProperty = e => {};

  /**
   * 取接口属性
   *
   * @memberof PrivateInterfaceDetail
   */
  fetchInterfaceProperty = visibility => {
    //测试
    let list = this.state.propertyList;
    let viewList = [];
    list.map(data => {
      viewList.push(
        <InterfacePropertyCell
          visibility={visibility}
          key={data.id}
          requestIntfcAttrs={this.requestIntfcAttrs}
          propertyName="null"
          deleteInterfaceProperty={this.deleteInterfaceProperty}
          propertyInfo={data}
        />
      );
    });

    return viewList;
  };

  deleteInterfaceProperty = id => {
    let delfunc = this.delProperty;
    Modal.confirm({
      title: '删除',
      content: '是否删除所选属性？',
      okText: '确定',
      cancelText: '取消',
      onOk() {
        delfunc(id);
      },
      onCancel() {}
    });
  };

  delProperty = id => {
    //delete
    let url = `${OltSerUrl.intfcAttrDelete}/${id}`;
    AmosFetch.del(url)
      .then(res => {
        if (res.ok) {
          return res.text();
        } else {
          throw new Error('从服务端获取数据失败！');
        }
      })
      .then(data => {
        //重新刷新数据
        message.success('删除成功！');
        this.requestIntfcAttrs();
      });
  };

  render() {
    let { getFieldProps } = this.props.form;
    let { textEdit } = this.state;
    let { carInfo, communityDatas } = this.props;
    let name = carInfo ? carInfo.name : '';
    let comMethod = carInfo && carInfo.communityProtocol ? carInfo.communityProtocol.name : '';
    let info = carInfo ? carInfo.remark : '';
    let titleButtonStyle = textEdit === false ? 'interface-detail-title-button' : 'interface-detail-title-button-hidden';
    let titleButtonHiddenStyle = textEdit === false ? 'interface-detail-title-button-hidden' : 'interface-detail-title-button';
    let titleContentStyle = textEdit === false ? 'interface-detail-title-content' : 'interface-detail-title-content-hidden';
    let titleEditContentStyle = textEdit === false ? 'interface-detail-title-content-hidden' : 'interface-detail-title-content';
    let visibility = carInfo.visibility;
    console.log(carInfo);
    //通讯方式
    const nameProps = getFieldProps('name', {
      initialValue: name || '',
      rules: [{ required: true, message: '名称不能为空！' }, { validator: noSpaceLengthValidate(50, true, '名称不能为空！') }]
    });

    //通讯方式
    const typeProps = getFieldProps('commType', {
      initialValue: `${comMethod}`,
      rules: [{ required: true, message: '通讯方式不能为空！' }]
    });
    //说明
    const detailProps = getFieldProps('detail', {
      initialValue: info || '',
      rules: [{ validator: noSpaceLengthValidate(500, false, null) }]
    });
    return (
      <div className="interface-detail">
        <Row>
          <div className="interface-detail-name">
            <div className="interface-detail-title">
              <label>基本信息</label>
              {visibility === 1 ? (
                <span>
                  <div onClick={this.handleEditParam} className={titleButtonStyle}>
                    <img src={require('./../../../assets/iot/img/list_edit.png')} alt="" />
                    <label>编辑</label>
                  </div>
                  <div onClick={this.handleEditParam} className={titleButtonHiddenStyle}>
                    <img src={require('./../../../assets/iot/img/list_edit.png')} alt="" />
                    <label>确认</label>
                  </div>
                </span>
              ) : null}
            </div>
            <div className={titleContentStyle}>
              <Row>
                <label className="interface-title-name">名称：{name}</label>
              </Row>
              <Row>
                <label className="interface-title-name">通讯方式：{comMethod}</label>
              </Row>
              <Row style={{ height: '65px', 'overflow-y': 'auto' }}>
                <label className="interface-title-name">说明：{info}</label>
              </Row>
            </div>
            <div className={titleEditContentStyle}>
              <Form horizontal>
                <FormItem label="名称: " labelCol={{ span: 2 }} wrapperCol={{ span: 22 }} style={{ marginBottom: '10px' }}>
                  <Input {...nameProps} style={{ width: 250 }} />
                </FormItem>
                <FormItem label="通讯方式: " labelCol={{ span: 2 }} wrapperCol={{ span: 22 }} style={{ marginBottom: '10px' }}>
                  <Select {...typeProps} dropdownStyle={{ maxHeight: '200px', overflow: 'overlay' }} style={{ width: 250, height: '32px' }}>
                    {communityDatas.map(comm => {
                      return (
                        <Option key={`${comm.id}Option`} value={`${comm.id}`}>
                          {comm.name}
                        </Option>
                      );
                    })}
                  </Select>
                </FormItem>
                <FormItem label="说明: " labelCol={{ span: 2 }} wrapperCol={{ span: 22 }} style={{ marginBottom: '10px' }}>
                  <Input {...detailProps} style={{ width: 250 }} />
                </FormItem>
              </Form>
            </div>
          </div>
        </Row>
        <Row>
          <div className="interface-detail-name">
            <div className="interface-detail-property">
              <label>接口参数</label>
              {visibility === 1 ? <AddInterfaceProperty requestIntfcAttrs={this.requestIntfcAttrs} intfcId={carInfo.id} /> : null}
            </div>
            <div className="interface-detail-property-content">
              <div className="interface-detail-property-scroll">{this.fetchInterfaceProperty(visibility)}</div>
            </div>
          </div>
        </Row>
      </div>
    );
  }
}

PrivateInterfaceDetail.propTypes = {
  form: PropTypes.any,
  callBack: PropTypes.func,
  carInfo: PropTypes.any, //接口详情对象
  communityDatas: PropTypes.any //通讯方式列表
};

export default createForm(PrivateInterfaceDetail);
