import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Icon from 'amos-icon';
import { message } from 'amos-framework';
import { Modal } from 'amos-antd';
import { OltSerUrl } from './../../../../consts/urlConsts';
import BackgroundItem from './BackgroundItem';
import { fetchSimpleOrgImgsAction,editSubviewImgAction } from './../../../../services/topoService';

/**
 *选择背景界面
 *
 * @class ChooseBackgroundPanel
 * @extends {Component}
 */
class ChooseBackgroundPanel extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      imgFiles: []
    };
  }

  componentWillMount(){

  }

  componentDidMount(){
    this.fetchImgData(this.props.orgCode);
  }

  componentWillReceiveProps(nextProps){
    if (this.props.orgCode !== nextProps.orgCode) {
      this.fetchImgData(nextProps.orgCode);
    }
  }

  /**
   * 打开编辑对话框
   */
  onClick = () => {
    this.setState({ visible: true });
  }

  onThemeChange = (e,bkImg,imgName) => {
    this.props.chooseBackground(imgName);
    this.setState({ selectedImgName: imgName });
  }

  getAllBackgrounds = () => {
    let content = [];
    let { imgFiles } = this.state;
    let { defaultImgName } = this.props;
    imgFiles && imgFiles.map(i => {
      let bkImg = `${OltSerUrl.fetchDeviceImg}/org/${i.uid}`;
      let skinUse;
      if (this.state.selectedImgName === undefined) {
        skinUse = i.uid === defaultImgName ? true : false;
      } else {
        skinUse = i.uid === this.state.selectedImgName ? true : false;
      }
      content.push(<BackgroundItem
        name={i.name}
        bkImg={bkImg}
        skinUse={skinUse}
        onThemeChange={this.onThemeChange}
        imgName={i.uid}
      />);
    });
    return content;
  }

  fetchImgData = (orgCode) => {
    orgCode && fetchSimpleOrgImgsAction(orgCode).then(data => {
      this.setState({ imgFiles: data.imgFiles });
    });
  }

  handCancel = () => {
    this.setState({ visible: false });
  }

  handSubmit = () => {
    let param = {
      id: this.props.subviewId,
      imgName: this.state.selectedImgName
    };
    editSubviewImgAction(param).then(data => {
      message.success('操作成功');
      this.setState({ visible: false });
    });
  }

  render() {
    return (
      <div className="choose-view" onClick={this.onClick} title="选择背景">
        <div className="choose-img-icon" title="选择背景">
          <Icon icon="picture1" />
        </div>
        <Modal maskClosable={false} title='选择背景' closable visible={this.state.visible} onCancel={this.handCancel} onOk={this.handSubmit} width={416}>
          <div className="choose-content">
            {this.getAllBackgrounds()}
          </div>
        </Modal>
      </div>

    );
  }
}

ChooseBackgroundPanel.propTypes = {
  orgCode: PropTypes.string,
  subviewId: PropTypes.string,
  chooseBackground: PropTypes.func,
  defaultImgName: PropTypes.string
};

export default ChooseBackgroundPanel;
