import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Editable,ColorPicker,Collapse,message } from 'amos-framework';
import { Upload,Progress,Button,Select } from 'amos-antd' ;
import { OltSerUrl } from '../../../../consts/urlConsts';
import Icon from 'amos-icon';
import { editSubviewAction,editSubviewImgAction } from './../../../../services/topoService';

const Panel = Collapse.Panel;
const HEXSIZE = 1024;
const imgStyle = { width: '76px', height: '76px' };
const ButtonGroup = Button.Group;
const Option = Select.Option;
const layoutAttr = [
  { title: '拉伸', value: 1 },
  { title: '平铺', value: 2 }
  // { title: '适应', value: 3 },
  // { title: '居中', value: 4 },
  // { title: '填充', value: 5 }
];
/**
 *
 *
 * @class TopoConfigDefaultPanel
 * @extends {Component}
 */
class TopoConfigDefaultPanel extends Component {
  constructor(props){
    super(props);
    let percent = props.subviewInfo.imgOpacity;
    let imgLayout = props.subviewInfo.imgLayout;
    this.state = {
      collapseKey: ['1','2'],
      loading: false,
      file: undefined,
      imageUrl: undefined,
      percent: percent ? 100 - (percent * 100) : 0,
      imgLayout: imgLayout ? imgLayout : 1
    };
  }
  componentWillMount() {

  }

  componentDidMount(){

  }

  componentWillReceiveProps(nextProps) {

  }

  componentWillUnmount() {

  }

  //折叠面板区滑动条控制
  onChangeCollapseSize = (key) =>{
    if (key !== undefined && key.length !== undefined) {
      this.setState({ collapseKey: key });
    }
  }

  onSelectChange = (e,imgName) => {
    let { chooseBackground,subviewInfo } = this.props;
    let { percent } = this.state;
    percent = 1 - (percent / 100);
    subviewInfo.imgOpacity = percent;
    subviewInfo.imgName = imgName;
    editSubviewAction(subviewInfo).then(data => {
      chooseBackground({ imgName,percent });
    });
  }

  onLayoutChange = (layout) => {
    let { chooseBackground,subviewInfo } = this.props;
    subviewInfo.imgLayout = layout;
    editSubviewAction(subviewInfo).then(data => {
      this.setState({ imgLayout: layout });
      chooseBackground({ layout });
    });
  }

  //折叠面板折叠操作区内容
  getCollapseHead = (name,index) => {
    let imgPath = this.props.getImgPath(index,this.state.collapseKey);
    let content = [];
    content.push(<div className='config-collapse-head'>
      <label className='config-collapse-text'>{name}</label>
      {imgPath}
    </div>);
    return content;
  }

  getDefaultImg = () => {
    let content = [];
    for (let index = 1; index < 7; index++) {
      let imgSrc = `${OltSerUrl.fetchDeviceImg}/graph/default_${index}.png`;
      content.push(<div key={index} className='default-img-panel' onClick={e => this.onSelectChange(e,`default_${index}.png`)} >
        <img src={imgSrc} alt='' />
      </div>);
    }
    return content;
  }

  /**
   *
   *图片加载到浏览器
   * @memberof UpLoadIcon
   */
  getBase64 = (img, callback) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  };

  //更新名称
  updateSubviewName = (key,name) => {
    let { updateSubviewName,subviewInfo } = this.props;
    subviewInfo.name = name;
    subviewInfo.flag='2';//代表是子视图调用刷新
    editSubviewAction(subviewInfo).then(data => {
      message.success('操作成功');
      updateSubviewName(name);
    });
  }

  /**
   *监听
   *
   * @memberof UpLoadIcon
   */
  handleChange = (info) => {
    this.setState({ file: info.file });
    if (info.file.status === 'uploading') {
      this.setState({ loading: true });
      return;
    }
    if (info.file.status === 'done') {
      this.getBase64(info.file.originFileObj, imageUrl => this.setState({
        imageUrl,
        loading: false
      }));
      this.imgFile = info.file.originFileObj;
      this.saveSubGraphImgAction();
    }
  }

  /**
   *
   *图片校验
   * @memberof UpLoadIcon
   */
  beforeUpload = (file) => {
    var pattern = /image\/(gif|jpeg|png|jpg|bmp)$/;
    const isImg = pattern.test(file.type);
    if (!isImg) {
      message.danger('请选择符合格式的图片！（gif|jpeg|png|jpg|bmp）');
    }
    const isLt2M = file.size / HEXSIZE < 500;
    if (!isLt2M) {
      message.danger('图片最大为 500Kb!');
    }
    return isImg && isLt2M;
  };

  /**
   *
   *保存图片
   * @memberof UpLoadImg
   */
  saveSubGraphImgAction = () => {
    const reader = new FileReader();
    reader.addEventListener('load', () => this.upLoadImgToSave(reader.result));
    let imgFile = this.imgFile;
    if (JSON.stringify(imgFile) === '{}') {
      let imgInfo = { 'binaryImg': null,'imgName': 'default.png' };
      this.saveSubGraphImg(imgInfo);
    } else {
      if (imgFile !== undefined) {
        reader.readAsBinaryString(this.imgFile);
      } else {
        message.danger('请选择要替换的背景图片！');
      }
    }
  };

  /**
   *
   *提交图片至后台
   * @memberof UpLoadImg
   */
  upLoadImgToSave = (binaryImg) => {
    let name = `${this.imgFile.uid}-${this.imgFile.name}`;//使用name+uid作为图片名，以防图片名冲突
    let imgInfo = { 'binaryImg': binaryImg,'imgName': name };
    this.saveSubGraphImg(imgInfo);
  };

  saveSubGraphImg = (imgInfo) => {
    let { subviewInfo,updateBkImg } = this.props;
    Object.assign(imgInfo,{ id: subviewInfo.id });
    editSubviewImgAction(imgInfo).then(data => {
      message.success('操作成功');
      updateBkImg(imgInfo.imgName);
      this.handCancel();
    });
  }

  /**
   * 关闭新增对话框
   */
  handCancel = () => {
    this.setState({
      loading: false,
      file: undefined,
      imageUrl: undefined
    });
    this.imgFile = undefined;
  }

  increase = () => {
    let percent = this.state.percent + 10;
    if (percent > 100) {
      percent = 100;
    }
    let { chooseBackground } = this.props;
    let opacity = 1 - (percent / 100);
    let { subviewInfo } = this.props;
    subviewInfo.imgOpacity = opacity;
    editSubviewAction(subviewInfo).then(data => {
      let param = {
        percent: opacity
      };
      chooseBackground(param);
      this.setState({ percent });
    });
  }

  decline = () => {
    let percent = this.state.percent - 10;
    if (percent < 0) {
      percent = 0;
    }
    let { chooseBackground } = this.props;
    let opacity = 1 - (percent / 100);
    let { subviewInfo } = this.props;
    subviewInfo.imgOpacity = opacity;
    editSubviewAction(subviewInfo).then(data => {
      let param = {
        percent: opacity
      };
      chooseBackground(param);
      this.setState({ percent });
    });
  }

  render() {
    let { collapseKey,percent,imgLayout } = this.state;
    let { subviewInfo } = this.props;
    let imgName = subviewInfo.imgName;
    const uploadButton = (
      <div className='upload-icon-panel'>
        {this.state.loading ? <Icon type={'loading'} /> : imgName !== null && imgName.includes('.') ?
          <img src={`${OltSerUrl.fetchDeviceImg}/graph/${imgName}`} alt="" style={imgStyle} />
        : <img src={require('./../../../../assets/iot/topo/background/upload.png')} alt="" style={{ paddingTop: '0px' }} />
        }
      </div>
    );
    const imageUrl = this.state.imageUrl;
    const url = OltSerUrl.addDevice;
    return (
      <div className='topo-config-default-content-root'>
        <Collapse activeKey={collapseKey}  onChange={key => this.onChangeCollapseSize(key)} >
          <Panel showArrow={false} header={this.getCollapseHead('视图信息','1')} key="1">
            <div className='default-base-info'>
              <div className='subview-name'>
                <div className='subview-name-title'>视图名称：</div>
                <div className='subview-name-value' title={subviewInfo.name}>
                  <Editable value={subviewInfo.name}
                    onChange={(e) => this.updateSubviewName('name', e)}
                    showOkCancel={false}
                    style={{ width: '150px',marginLeft: '10px' }}
                    innerValueStyle={{ width: '150px' }}
                    placeholder={'请输入'}
                  />
                </div>
              </div>
              <div className='subview-num'>
                <div className='subview-num-title'>设备数量：</div>
                <div className='subview-num-value' title={subviewInfo.num}>{subviewInfo.num}</div>
              </div>
              <div className='subview-descr'>
                <div className='subview-descr-title'>说明：</div>
                <div className='subview-descr-value' title={''}>{''}</div>
              </div>
            </div>
          </Panel>
          <Panel showArrow={false} header={this.getCollapseHead('画布背景','2')} key="2">
            <div className='default-background-info'>
              <div className='background-color'>
                <div className='background-color-title'>背景颜色：</div>
                <div className='background-color-value'>
                  <ColorPicker direction={'left'} align={'left'} onColorChange={e => this.onSelectChange(e,e.hex)} />
                </div>
              </div>
              <div className='background-img'>
                <div className='background-img-title'>默认背景：</div>
                <div className='background-img-value'>
                  {this.getDefaultImg()}
                </div>
              </div>
              <div className='background-user-img'>
                <div className='background-user-img-title'>
                  <div>自定义背景：</div>
                  <div className='background-user-img-tip'>*图片小于500kb</div>
                </div>
                <div className='background-user-img-value'>
                  <Upload
                    name="avatar"
                    listType="picture-card"
                    showUploadList={false}
                    action={url}
                    beforeUpload={this.beforeUpload}
                    onChange={this.handleChange}
                  >
                    {imageUrl ? <img src={imageUrl} alt="" style={imgStyle} /> : uploadButton}
                  </Upload>
                </div>
              </div>
              <div className='background-transparency'>
                <div className='background-transparency-title'>透明度：</div>
                <div className='background-transparency-value'>
                  <Progress percent={percent} />
                  <ButtonGroup>
                    <Button onClick={this.decline} icon="minus" />
                    <Button onClick={this.increase} icon="plus" />
                  </ButtonGroup>
                </div>
              </div>
              <div className='background-layout'>
                <div className='background-layout-title'>背景排布：</div>
                <div className='background-layout-value'>
                  <Select value={imgLayout} style={{ width: 91 }} placeholder='请选择' onSelect={e => this.onLayoutChange(e)} >
                    {
                      layoutAttr.map(data => <Option key={data.value} value={data.value}>{data.title}</Option>)
                    }
                  </Select>
                </div>
              </div>
            </div>
          </Panel>
        </Collapse>
      </div>
    );
  }
}

TopoConfigDefaultPanel.propTypes = {
  getImgPath: PropTypes.func,
  subviewInfo: PropTypes.object,
  updateSubviewName: PropTypes.func,
  updateBkImg: PropTypes.func,
  chooseBackground: PropTypes.func
};

export default TopoConfigDefaultPanel;
