import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Row,Col,Form,Input,Modal } from 'amos-antd';
import { Select } from 'amos-framework';
import { AmosFetch } from 'UTILS/processor';
import { OltSerUrl } from 'CONSTS/urlConsts';
import { message } from 'amos-framework';
import { trim } from 'amos-tool';
import { deviceCategoryEnum } from  './../common/DeviceEnum';
import { enums2array,stringUtil } from './../common/DeviceLang';
import {noSpaceLengthValidate} from './../../common/utils/validate';
import UpLoadImg from './../common/UpLoadImg';
import DeviceProperty from './deviceDetail/DeviceProperty';
import DeviceInterface from './deviceDetail/DeviceInterface';
import DeviceCapacity from './deviceDetail/DeviceCapacity';
import './device-detail.scss';

const maxDescLength = 500;
const FormItem = Form.Item;
const createForm = Form.create();
const Option = Select.Option;
const deviceCategory = enums2array(deviceCategoryEnum).map((item)=>
  <Option key={item.key} value={`${item.key}`}>{item.label}</Option>) ;


/**
 *
 * 我的设备 详情
 * @class PrivateDeviceDetail
 * @extends {Component}
 */
class PrivateDeviceDetail extends Component {
  constructor(props) {
    super(props);
    this.state = {
      textEdit: false,
      loading: false,
      interfaceList: [],
      device: {},
      displayImgUrl: '',
      imageUrl: '',
      imgFile: {},//图片名称
      imgInfo: {},//图片信息
      deviceInterfaces: []
    };
  }

  componentDidMount(){
    let id = this.props.carInfo.id;
    this.getDeviceInfoById(id);
  }

  /**
   * 查询设备信息
   *
   * @memberof PrivateDeviceDetail
   */
  getDeviceInfoById = (id) => {
    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;
        this.setState({ device: deviceData,displayImgUrl: deviceData.img });
      }
    });
  }

  getBase64 = (img, callback) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  }

  /**
   * 设置图片
   *
   * @memberof AddDevice
   */
  setImgFile = (imgFile) => {
    this.setState({ imgFile });
  }

  /**
   *
   *提交图片至后台
   * @memberof UpLoadImg
   */
  upLoadImgToSave = (binaryImg) => {
    let name = this.state.imgFile.name;
    let imgInfo = { 'binaryImg': binaryImg,'imgName': name };
    this.saveDeviceParam(imgInfo);
  };
  /**
   * 编辑设备参数
   *
   * @memberof PrivateDeviceDetail
   */
  handleEditParam = (e) => {
    if (this.state.textEdit !== false) {
      this.props.form.validateFields((errors, values) => {
        if (errors){
          return ;
        } else {
          let { deviceName } = this.state;
          if (deviceName !== undefined && '' === deviceName)
          {
            message.success('设备名称不能为空！');
            return;
          }
          const reader = new FileReader();
          reader.addEventListener('load', () => this.upLoadImgToSave(reader.result));
          let originalImgFile = this.state.device.img;
          let newImgFile = this.state.imgFile;
          if ((JSON.stringify(newImgFile) === '{}') || (originalImgFile === newImgFile.name)) {
            this.saveDeviceParam();
          } else {
            //如果选择了图片则读取图片数据
            reader.readAsBinaryString(this.state.imgFile);
          }
        }
        this.setState({ textEdit: !this.state.textEdit });
      });
    } else {
      this.setState({ textEdit: !this.state.textEdit });
    }
  }

  saveDeviceParam = (e) => {
    let id = this.props.carInfo.id;
    let model = this.props.form.getFieldValue('model');
    let type = this.props.form.getFieldValue('type');
    let desc = this.props.form.getFieldValue('descr');
    let viewPath = this.props.form.getFieldValue('viewPath');
    let deviceName = this.props.form.getFieldValue('deviceName');
    let industryId = this.props.form.getFieldValue('industryId');
    let postData = { id,model,type,viewPath,desc,name: deviceName };
    if (Number.isInteger(industryId)){
      Object.assign(postData,{ industryId });
    }
    let url = `${OltSerUrl.deviceBasicInfoUpdate}`;
    if (e !== undefined) {
      Object.assign(postData,e);
    }
    //提交后台
    AmosFetch.post(url,{ data: postData }).then(res => {
      if (res.ok) {
        return res.json();
      }
      else
      {
        throw new Error('从服务端获取数据失败！');
      }
    }).then((data)=>{
      if (data.result === 'SUCCESS'){
        if (data.dataList === -1) {
          message.danger('设备原型名称重复！');
        } else {
          message.success('编辑成功！');
        }
        this.setState({ imgFile: {} });
      } else {
        message.danger('编辑失败！');
      }
      //刷新详情页面
      this.getDeviceInfoById(id);
    });
  }

  handleAddProperty = (e) => {

  }

  handleChange = (info) => {
    if (info.file.status === 'uploading') {
      this.setState({ loading: true });
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      this.getBase64(info.file.originFileObj, imageUrl => this.setState({
        imageUrl,
        loading: false
      }));
    }
  }

  /**
   *
   * 上传图片大小控制
   *
   * @memberof PrivateDeviceDetail
   */
  beforeUpload = (file) => {
    const isJPG = file.type === 'image/jpeg';
    if (!isJPG) {
      message.error('You can only upload JPG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!');
    }
    return isJPG && isLt2M;
  }

  saveDeviceInterfaces = (e) =>{
    this.setState({ deviceInterfaces: e });
  }

  render() {
    let { getFieldProps } = this.props.form;
    let { textEdit,device,deviceInterfaces } = this.state;
    let { type,model,descr,name,viewPath,img,visibility,industryId } = device;
    let titleButtonStyle = textEdit === false ? 'device-detail-title-button' : 'device-detail-title-button-hidden';
    let titleButtonHiddenStyle = textEdit === false ? 'device-detail-title-button-hidden' : 'device-detail-title-button';
    let titleContentStyle = textEdit === false ? 'device-detail-title-content' : 'device-detail-title-content-hidden';
    let titleEditContentStyle = textEdit === false ? 'device-detail-title-content-hidden' : 'device-detail-title-content';
    let equiptemplateIndustryOptions = this.props.equiptemplateIndustryOptions?this.props.equiptemplateIndustryOptions:[];
    let industry ='';
    equiptemplateIndustryOptions.forEach(function(value, index, array) {
      if(value.value === industryId){
        industry = value.label?value.label:'';
      }
  });
    //名称
    const nameProps = getFieldProps('deviceName', {
      initialValue: name ? name : '',
      rules: [
          { required: true, message: '名称不能为空！' },
          { validator: noSpaceLengthValidate(null,true,'名称不能为空！') }
      ]
    });
    //型号
    const typeProps = getFieldProps('model', {
      initialValue: model ? model : '',
      rules: [
          { required: true, message: '型号不能为空！' },
          { validator: noSpaceLengthValidate(null,true,'型号不能为空！') }
      ]
    });
    //类别
    const categoryProps = getFieldProps('type', {
      initialValue: `${type}`,
      rules: [
          { required: true, message: '类别不能为空！' }
      ]
    });
    //行业
    const industryProps = getFieldProps('industryId', {
      initialValue: `${industry}`,
      rules: [
          { required: true, message: '所属行业不能为空！' }
      ]
    });
    //视图路径
    const viewPathProps = getFieldProps('viewPath', {
      initialValue: viewPath ? viewPath : '',
      rules: [
      ]
    });

    //说明
    const detailProps = getFieldProps('descr', {
      initialValue: descr ? descr : '',
      rules: [
        { validator: noSpaceLengthValidate(maxDescLength,false,null) }
      ]
    });
    let displayImgUrl = this.state.displayImgUrl;
    let srcImgUrl = displayImgUrl === '' ? `${OltSerUrl.fetchDeviceImg}/default.png` : `${OltSerUrl.fetchDeviceImg}/${displayImgUrl}`;
    return (
      <div className='device-detail'>
        <div className='device-detail-cell'>
          <div className='device-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}>
            <div className='device-detail-basic-img'>
              <img alt="device" src={srcImgUrl} style={{ 'max-width': '300px','max-height': '158px' }} />
            </div>
            <div className='device-detail-basic-info'>
              <div style={{ height: '30px' }}>
                <label className='device-title-name'>名称:</label>
                <label className='device-title-value'>{name}</label>
              </div>
              <div style={{ height: '30px' }}>
                <label className='device-title-name'>型号:</label>
                <label className='device-title-value'>{model}</label>
              </div>
              <div style={{ height: '30px' }}>
                <label className='device-title-name'>类别:</label>
                <label className='device-title-value'>{stringUtil(deviceCategoryEnum, type)}</label>
              </div>
              <div style={{ height: '30px' }}>
                <label className='device-title-name'>所属行业:</label>
                <label className='device-title-value'>{industry}</label>
              </div>
              {/* <div style={{ height: '30px' }}>
                <label className='device-title-name'>视图路径:</label>
                <label className='device-title-value'>{viewPath}</label>
              </div> */}
              <div className='device-detail-descr'>
                <label className='device-title-descr-name'>说明:</label>
                <label className='device-title-descr-value'>{descr}</label>
              </div>
            </div>
          </div>
          <div className={titleEditContentStyle}>
            <div className='device-detail-edit-img'>
              <UpLoadImg setImgFile={this.setImgFile} defaultImg={srcImgUrl} />
            </div>
            <div className='device-detail-basic-info'>
              <Form horizontal>
                <FormItem label='名称: ' labelCol={{ span: 4 }} wrapperCol={{ span: 6 }} >
                  <Input {...nameProps} />
                </FormItem>
                <FormItem label='型号: ' labelCol={{ span: 4 }} wrapperCol={{ span: 6 }} >
                  <Input {...typeProps} />
                </FormItem>
                <FormItem label='类别: ' style={{ height: '42px' }} labelCol={{ span: 4 }} wrapperCol={{ span: 6 }} >
                  <Select style={{ width: '100%',height: '32px' }}
                    {...categoryProps}
                  >
                    {deviceCategory}
                  </Select>
                </FormItem>


                <FormItem label='所属行业: ' style={{ height: '42px' }} labelCol={{ span: 4 }} wrapperCol={{ span: 6 }} >
                  <Select style={{ width: '100%',height: '32px' }}
                    {...industryProps} placeholder="请选择所属行业"
                  >
                    {
                      equiptemplateIndustryOptions.map(comm => {
                        return (<Option key={`${comm.value}Option`} value={comm.value}>{comm.label}</Option>);
                      })
                    }
                  </Select>
                </FormItem>


                {/* <FormItem label='视图路径: ' labelCol={{ span: 1 }} wrapperCol={{ span: 4 }} >
                  <Input {...viewPathProps} />
                </FormItem> */}
                <FormItem label='说明: ' labelCol={{ span: 4 }} wrapperCol={{ span: 6 }} >
                  <Input {...detailProps} />
                </FormItem>
              </Form>
            </div>
          </div>
        </div>
        <div className='current-device-detail'>
          <DeviceProperty getDeviceInfoById={this.getDeviceInfoById} device={device} />
          <DeviceInterface saveDeviceInterfaces={this.saveDeviceInterfaces} getDeviceInfoById={this.getDeviceInfoById} device={device} />
          <DeviceCapacity deviceInterfaces={deviceInterfaces} getDeviceInfoById={this.getDeviceInfoById} device={device} />
        </div>
      </div>
    );
  }
}

PrivateDeviceDetail.propTypes = {
  form: PropTypes.any,
  callBack: PropTypes.func,
  carInfo: PropTypes.any,
  equiptemplateIndustryOptions: PropTypes.any
};

export default createForm(PrivateDeviceDetail);
