import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { message, Modal, Connect } from 'amos-framework';
import { broadcastAction } from 'SERVICES/3dService';
import { CONSTS } from 'CONSTS/storageConsts';
import OperateButton from './OperateButton';
import { ruleAction } from 'SERVICES/ruleService';
import StepContent from './StepContent';
import { eventTopics } from '../consts';
import StepCxtBody from './StepCxtBody';
import { tirggerTransTopic } from '../dataProcessor';
import EmptyPage from './EmptyPage';

const eventConnect = Connect.eventConnect;
const recordType = 'OPERATE';
const confirmState = 'CONFIRM';


/**
 *
 * 预案交互区
 * @class ReservePlan
 * @extends {Component}
 */
@eventConnect
class ReservePlan extends Component {
  constructor(props) {
    super(props);
    this.state = {
      show: true,
      display: 'none',
      cxtArry: [],
      oprateBtnCxt: [],
      showFireConfirm: false,
      content: {},
      expanded: false,
      isShowOver: false
    };

  }

  componentWillMount() {

  }

  componentDidMount(){
    this.props.subscribe(eventTopics.optionArea_view, (topic, data) => {//按钮接收
      this.readyOptionAreaData(data);
    });
    this.props.subscribe(eventTopics.record_view, (topic, data) => {
      const { expanded } = this.state;
      expanded && this.refshTimeLine(data.batchNo);
    });
  }

  onAutoClick =(content,flag)=>{
    ruleAction(content,flag).then(e=>{
      // message.success('操作成功');
    },error=>{
      // message.danger('操作失败');
    });
  }

  onButtonClick =(content)=>{
    const { expanded } = this.state;
    if (content.code === 'all_Resource') {
      this.props.trigger(eventTopics.show_fire_equip,content);
    } else if (content.confirm && content.code !== 'all_Resource') {//打开弹出框
      this.open(content);
    } else {//调用后台接口
      ruleAction(content,confirmState).then(e=>{
        message.success('操作成功');
        this.dealCxtArryAfterClick(content);
        expanded && this.refshTimeLine(content.batchNo);
      },error=>{
        message.danger('操作失败');
      });
    }
  }

  onModalOk =(content)=>{
    this.cancel();
    ruleAction(content,confirmState).then(e=>{
      message.success('确认成功');
      if (content.code === 'FIRE_CONFIRM') {
        tirggerTransTopic(CONSTS.forward, { details: { type: 'prePlan', show: true } });
      }
    },error=>{
      message.danger('确认失败');
    });
  }

  getPlanExeRecord =(batchNo)=>{
    batchNo && this.refshTimeLine(batchNo);
  }

  readyOptionAreaData =(data)=>{
    let { cxtArry } = this.state;
    let newArry = [];
    if (cxtArry.length === 0 ) {
      cxtArry.push(data);
    } else {
      const index =  cxtArry.findIndex(item=>item.contingencyPlanId === data.contingencyPlanId);
      if (index < 0 ) {
        newArry = cxtArry.map(item=>{
          if ((JSON.parse(item.buttonJson) || {}).stepCode !== (JSON.parse(data.buttonJson) || {}).stepCode) {
            item.hiddPlanButton = true;
          }
          return item;
        });
      }
      cxtArry = [...newArry,data];
    }
    this.setState({ display: '',cxtArry,isShowOver: false });
  }

  open = (content) => {
    this.setState({
      showFireConfirm: true,
      content
    });
  }

  cancel = () => {
    this.setState({
      showFireConfirm: false,
      content: {}
    });
  }

  refshTimeLine =(batchNo)=>{
    broadcastAction(batchNo,recordType).then(data => {
      const { expanded } = this.state;
      expanded ? '' : this.setState({ expanded: true });//显示按钮明细
      this.setState({ buttonList: data });
    });
  }
  closeStepCxt =()=>{
    this.setState({ expanded: false });
  }

  openStepCxt =(batchNo)=>{
    this.getPlanExeRecord(batchNo);//查询数据
  }

  hiddPlanRoot =(content)=>{
    const { cxtArry } = this.state;
    cxtArry.map(cxt => {
      if (cxt.contingencyPlanId === content.contingencyPlanId ) {
        cxt.hiddPlanButton = true;
      }
      return cxt;
    });
    let exixtButtonArry = cxtArry.filter(item=>!item.hiddPlanButton);
    let lastStep = [];
    if (exixtButtonArry.length === 0) {
      lastStep = cxtArry.filter(item=>parseInt((JSON.parse(item.buttonJson) || {}).stepCode) === parseInt((JSON.parse(content.buttonJson) || {}).stepCode) - 1 && (JSON.parse(item.buttonJson) || {}).operate[0].hide);//上一步挂起的按钮
      lastStep.length > 0 && cxtArry.forEach(item=>{
        if (parseInt((JSON.parse(item.buttonJson) || {}).stepCode) === parseInt((JSON.parse(content.buttonJson) || {}).stepCode) - 1 && (JSON.parse(item.buttonJson) || {}).operate[0].hide){
          item.hiddPlanButton = false;
        }
      });
      lastStep.length > 0 ? this.setState({ cxtArry,isShowOver: false }) :  this.setState({ cxtArry,isShowOver: true });
    } else if (exixtButtonArry.length > 0) {
      this.setState({ cxtArry,isShowOver: false });
    }
  }

  dealCxtArryAfterClick =(content)=>{
    const { cxtArry } = this.state;
    const index =  cxtArry.findIndex(item=>item.contingencyPlanId === content.contingencyPlanId);
    index > -1 ? cxtArry.splice(index,1) : '';//删除点击过的数据
    let exixtButtonArry = cxtArry.filter(item=>!item.hiddPlanButton);
    let lastStep = [];
    if (parseInt(content.stepCode) === 9) {
      this.setState({ cxtArry,isShowOver: false, display: 'none' });
    } else {
      if (cxtArry.length > 0 && exixtButtonArry.length > 0) {
        this.setState({ cxtArry,isShowOver: false });
      } else if (cxtArry.length > 0 && exixtButtonArry.length === 0) {
        lastStep = cxtArry.filter(item=>parseInt((JSON.parse(item.buttonJson) || {}).stepCode) === parseInt(content.stepCode) - 1 && (JSON.parse(item.buttonJson) || {}).operate[0].hide);//上一步挂起的按钮
        lastStep.length > 0 && cxtArry.forEach(item=>{
          if (parseInt((JSON.parse(item.buttonJson) || {}).stepCode) === parseInt(content.stepCode) - 1 && (JSON.parse(item.buttonJson) || {}).operate[0].hide){
            item.hiddPlanButton = false;
          }
        });
        lastStep.length > 0 ? this.setState({ cxtArry,isShowOver: false }) : this.setState({ cxtArry,isShowOver: true });
      } else {
        this.setState({ cxtArry,isShowOver: true });
      }
    }
  }

  renderInteractiveZone =(cxtArry)=>{
    return cxtArry.map(e=>{
      return <OperateButton message={e} key={e.contingencyPlanId} hiddPlanRoot={this.hiddPlanRoot} onButtonClick={this.onButtonClick} onAutoClick={this.onAutoClick} openStepCxt={()=>this.openStepCxt(e.batchNo)} />;
    });
  }

  render() {
    const { cxtArry,showFireConfirm,content,expanded,buttonList,display,isShowOver } = this.state;
    const batchNo = cxtArry ? cxtArry.length > 0 ? cxtArry[0].batchNo : '' : '';
    return (
      <div className='reserve-plan-root' style={{ display }}>
        {this.renderInteractiveZone(cxtArry)}
        {isShowOver && <EmptyPage batchNo={batchNo} openStepCxt={this.openStepCxt} />}
        {expanded && <StepContent header='执行步骤' onClose={this.closeStepCxt} body={<StepCxtBody buttonList={buttonList} onButtonClick={this.onButtonClick} />} {...this.props} />}
        <Modal
          header={content.title || ''}
          visible={showFireConfirm}
          className='fire-confirm-modal'
          destroyContent
          content={content.content || ''}
          onCancel={this.cancel}
          onOk={()=>this.onModalOk(content)}
          okText='是'
          cancelText='否'
        />
      </div>
    );
  }
}

ReservePlan.propTypes = {
  left: PropTypes.number,
  top: PropTypes.number,
  width: PropTypes.number
};

export default ReservePlan;
