import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Form,Input,Button,Radio,Modal } from 'amos-antd';
import { AmosFetch,formatUrl } from 'UTILS/processor';
import { dateToStr } from 'UTILS/DateUtil';
import OltSerUrl from 'CONSTS/urlConsts';
import { message } from 'amos-framework';
import { trim } from 'amos-tool';
import './protocol-detail.scss';
import {objOfStrPropTrim,noSpaceLengthValidate} from './../../common/utils/validate';
const maxDescLength = 250;
const RadioGroup = Radio.Group;
const FormItem = Form.Item;
const createForm = Form.create();
const { TextArea } = Input;
const textAreaStyle = { minRows: 12, maxRows: 16 };


/**
 * 我的协议 详情
 *
 * @class PrivateProtocolDetail
 * @extends {Component}
 */
class PrivateProtocolDetail extends Component {
  constructor(props) {
    super(props);
    this.state = {
      textEdit: false,
      scriptEdit: false,
      detailData: {}//详情对象
    };
  }

  componentWillMount(){

  }

  componentDidMount(){
    let { selected } = this.props;
    if (selected && selected.id){
      this.requestProtocolDetail(selected.id);
    }
  }

  // 根据id获取协议详情数据
  requestProtocolDetail = (id) => {
    AmosFetch.get(formatUrl(OltSerUrl.protocolDetail,{ id })).then(res => {
      if (res.ok) {
        return res.json();
      }
      else
      {
        throw new Error('从服务端获取数据失败！');
      }
    }).then((data)=>{
      if (data.result === 'SUCCESS'){
        if (data.dataList !== null){
          this.setState({ detailData: data.dataList });
        }
      }
    });
  }

  /**
   *
   * 编辑协议基本信息
   * @memberof PrivateProtocolDetail
   */
  handleEditParam = (e) => {
    let protocolName = this.props.form.getFieldValue('protocolName');
    let protocolVersion = this.props.form.getFieldValue('protocolVersion');
    let descr =  this.props.form.getFieldValue('descr');
    let time = this.props.form.getFieldValue('time');
    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.state.detailData;
          let data = Object.assign(oldBasicData,
            { name: protocolName,
              version: protocolVersion,
              descr,
              dicIdScriptLang: null,
              scriptLang: null
            });
          this.submitBasicData(data);
        }
      });
    }
  }

  /**
   * 提交协议基本信息
   */
  submitBasicData = (data) => {
    AmosFetch.post(OltSerUrl.protocolSave,{ 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('编辑失败！');
      }
    });
  }

  /**
   *
   * 编辑协议脚本信息
   * @memberof PrivateProtocolDetail
   */
  handleEditCode = (e) => {
    let realization = this.props.form.getFieldValue('realization');
    let code = trim(this.props.form.getFieldValue('code'));
    if (!code || code === '' ){
      Modal.info({
        title: '提示',
        content: '代码不能为空！',
        okText: '确定'
      });
      return;
    }
    this.setState({ scriptEdit: !this.state.scriptEdit });
    //提交后台
    if (this.state.scriptEdit) {
      this.props.form.validateFields((errors, values) => {
        if (errors){
          this.setState({ textEdit: true });
          return ;
        } else {
          let oldBasicData = this.state.detailData;
          let data = {
            id: oldBasicData.id,
            dicIdScriptLang: realization,
            scriptCode: code
          };
          this.submitBasicData(data);
          this.setState({ detailData: Object.assign(oldBasicData,data) });
        }
      });
    }
  }

  handleAddProperty = (e) => {

  }

  handleDebug = (e) => {
    message.success('测试成功！');
  }

  delProperty = (e) => {
    //delete

    //重新刷新数据
  }

  render() {
    let { getFieldProps } = this.props.form;
    let { textEdit,scriptEdit,detailData } = this.state;
    let titleButtonStyle = textEdit === false ? 'protocol-detail-title-button' : 'protocol-detail-title-button-hidden';
    let titleButtonHiddenStyle = textEdit === false ? 'protocol-detail-title-button-hidden' : 'protocol-detail-title-button';
    let titleContentStyle = textEdit === false ? 'protocol-detail-title-content' : 'protocol-detail-title-content-hidden';
    let titleEditContentStyle = textEdit === false ? 'protocol-detail-title-content-hidden' : 'protocol-detail-title-content';
    let scriptButtonStyle = scriptEdit === false ? 'protocol-detail-property-button' : 'protocol-detail-property-button-hidden';
    let scriptButtonHiddenStyle = scriptEdit === false ? 'protocol-detail-property-button-hidden' : 'protocol-detail-property-button';
    let scriptContentStyle = scriptEdit === false ? 'protocol-detail-property-content' : 'protocol-detail-property-content-hidden';
    let scriptEditContentStyle = scriptEdit === false ? 'protocol-detail-property-content-hidden' : 'protocol-detail-property-content';
    let visibility = detailData.visibility;
    const { scriptLangOptions } = this.props;
    const realizationTypeOption = scriptLangOptions.map((item)=>{

      if (item.value === detailData.dicIdScriptLang){
        if (item.label === 'Groovy'){
          return  <Radio checked key={item.value} value={`${item.value}`}>{item.label}</Radio>;
        } else {
          return  <Radio checked key={item.value} value={`${item.value}`} disabled>{item.label}</Radio>;
        }
      } else {
        if (item.label === 'Groovy'){
          return  <Radio key={item.value} value={`${item.value}`}>{item.label}</Radio>;
        } else {
          return  <Radio key={item.value} value={`${item.value}`} disabled>{item.label}</Radio>;
        }
      }
    }) ;

    //协议名称
    const typeProps = getFieldProps('protocolName', {
      initialValue: detailData.name || '',
      rules: [
          { required: true, message: '名称不能为空！' },
          {validator:noSpaceLengthValidate(50,true,'名称不能为空！')}
      ]
    });
    //版本
    const detailProps = getFieldProps('protocolVersion', {
      initialValue: detailData.version || '',
      rules: [
          { required: true, message: '版本不能为空！' },
          {validator:noSpaceLengthValidate(20,true,'版本不能为空！')}
      ]
    });
    //实现方式
    const realizationProps = getFieldProps('realization', {
      initialValue: `${detailData.dicIdScriptLang}` || '1',
      rules: [
          { required: false, message: '实现方式不能为空！' }
      ]
    });
    //代码
    const codeProps = getFieldProps('code', {
      initialValue: detailData.scriptCode || '',
      rules: [
          { required: false, message: '代码不能为空！' }
      ]
    });

    const descrProps =  getFieldProps('descr', {
      initialValue: detailData.descr || '',
      rules: [
        { validator: noSpaceLengthValidate(maxDescLength,false,null) }
      ]
    });

    console.log(detailData);
    return (
      <div className='protocol-detail'>
        <div className='protocol-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}>
          <span><label className='protocol-title-name'>协议名称： {detailData.name || ''}</label></span>
          <span><label className='protocol-title-name'>版&emsp;&emsp;本： {detailData.version || ''}</label></span>
          <span><label className='protocol-title-name'>时&emsp;&emsp;间： {detailData.createTime ? dateToStr(detailData.createTime) : ''}</label></span>
          <span style={{ 'height': '70px','overflow-y': 'auto','padding': '5px' }} ><label className='protocol-title-name'>说&emsp;&emsp;明： {detailData.descr || ''}</label></span>
        </div>
        <div className={titleEditContentStyle}>
          <Form horizontal onSubmit={this.handleSubmit}>
            <FormItem label='名称: ' labelCol={{ span: 2 }} wrapperCol={{ span: 22 }} >
              <Input disabled={!textEdit} {...typeProps} style={{ width: 250 }} />
            </FormItem>
            <FormItem label='版本: ' labelCol={{ span: 2 }} wrapperCol={{ span: 22 }} >
              <Input disabled={!textEdit} {...detailProps} style={{ width: 250 }} />
            </FormItem>
            <FormItem label='说明: ' labelCol={{ span: 2 }} wrapperCol={{ span: 22 }} >
              <Input disabled={!textEdit} {...descrProps} style={{ width: 250 }} />
            </FormItem>
          </Form>
        </div>
        <div className='protocol-detail-property'>
          <label>脚本信息</label>
          {visibility === 1 ?
            <span>
              <div onClick={this.handleEditCode} className={scriptButtonStyle}>
                <img src={require('./../../../assets/iot/img/list_edit.png')} alt='' />
                <label>编辑</label>
              </div>
              <div onClick={this.handleEditCode} className={scriptButtonHiddenStyle}>
                <img src={require('./../../../assets/iot/img/list_edit.png')} alt='' />
                <label>确认</label>
              </div>
              </span>:null
          }
        </div>
        <div className={scriptContentStyle}>
          <span>
            <label className='protocol-content-name'>实现方式： </label>
            <div className='protocol-content-value'>
              <RadioGroup>
                {realizationTypeOption}
              </RadioGroup>
            </div>
          </span>
          <span style={{ height: 'calc(100% - 50px)' }}>
            <label className='protocol-content-name'>代&emsp;&emsp;码： </label>
            <div className='protocol-content-code'>
              <TextArea value={detailData.scriptCode || ''} />
            </div>
          </span>
        </div>
        <div className={scriptEditContentStyle}>
          <Form horizontal onSubmit={this.handleSubmit}>
            <FormItem label='实现方式: ' labelCol={{ span: 2 }} wrapperCol={{ span: 22 , offset: 0 }} >
              <RadioGroup {...realizationProps}>
                {realizationTypeOption}
              </RadioGroup>
            </FormItem>
            <FormItem label='代码: ' labelCol={{ span: 2 }} wrapperCol={{ span: 12 }} >
              <TextArea {...codeProps} />
              {
                //该功能按钮暂时屏蔽掉，待后期需要打开即可
                // <Button onClick={this.handleDebug}>测试</Button>
              }
            </FormItem>
          </Form>
        </div>
      </div>
    );
  }
}

PrivateProtocolDetail.propTypes = {
  form: PropTypes.any,
  callBack: PropTypes.func
};

export default createForm(PrivateProtocolDetail);
