/**
 * 事务页面。 根据一站式服务大厅的事务接口。达到增删发起事务流程
 * 2019年10月23日 09:48:13
 * 钟是志
 *
 * */

import { message } from 'antd';
import React, { Fragment } from 'react';
import * as service from '../publicApiService';
import * as destructionFunc from '../destruction';
import { Link } from 'dva/router';
import { getApplyPage } from '../publicApiService';
import { getToken } from '@/utils/authority';

import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import List from './List';
import pageSetting from './pageSetting';
import ButtonDiy from '@/baseComponent/ButtonDiy';
import Shell from '@/baseComponent/Shell';
import config from '@/config/config';

export default class AffairPage extends React.Component {
  constructor(props) {
    super(props);
    let pathname = this.props.location.pathname;
    const { dataBaseId, workId } = this.props;
    this.state = {
      showIframe: false,
      columns: [],
      pathname,
      workId: workId || '',
      searchCondition: [],
      dataBaseId: '',
      addFields: [], // 新增时填写的字段。
      renderIframe: true,
    };
  };

  getFormDetail = (workId) => {
    service.getFormDetail(workId).then((response) => {
      if (typeof response.unifiedServicePatternModel === 'undefined') {
        return false;
      }
      destructionFunc.destructionGetDetail(response).then((x) => {
        const { addFields, tableInfo, allConfigSetInfo } = x;
        this.setState({
          addFields,
          tableInfo,
          allConfigSetInfo,
        }, () => {
          this.giveDetailColumns();
        });
      });
    });
  };

  giveDetailColumns = () => {
    const { columns, workId, dataBaseId, addFields } = this.state;
    columns.push(
      {
        dataIndex: 'operation',
        title: '操作',
        fixed: columns.length > 12 ? 'right' : false,
        render: (text, record) => {
          return (<Link to={
            {
              pathname: './Detail',
              state: {
                workId,
                dataBaseId,
                record,
                addFields,
              },

            }}>
            详情
          </Link>);
        },
      },
    );
    this.setState({
      columns,
    });
  };

  handleButtonSet = () => {
    const { canApply, otherButtons = [] } = this.props;
    if(canApply === false){
      return [
        ...otherButtons,
      ];
    }
    return [
      {
        type: 'add',
        name: '申请',
        component: 'Normal',
        handleClick: () => {
          this.setState({
            showIframe: true,
          }, () => {
          });
        },
      },
      ...otherButtons,
    ];
  };

  handleSearchSet = () => {
    const { columns, searchCondition } = this.state;
    const { onResponse } = this.props;
    const pageSearch = {
      search: {
        field: {},
        getPageService: getApplyPage,
        responseCallBack: (response) => {
          if (onResponse) {
            onResponse(response);
          }
          return response;
        },
        condition: searchCondition,
        nameSpan: { big: 8, small: 9 },
        fileSpan: { big: 4, small: 4 },
      },
      tableRowKey: 'id',
      columns,
    };
    return pageSearch;
  };

  getColumns = () => {
    const { workId } = this.state;
    service.getColumns(workId).then((response) => {
      if (response) {
        this.setState({
          columns: response,
        }, () => {
          this.getFormDetail(workId);
        });
      }
    });
  };

  componentDidMount() {
    if (!getToken()) {
      message.error('您的数据未同步,请联系管理员!');
      return false;
    }
    const {  pathname } = this.state;
    const { dataBaseId, workId } = this.props;
    if(dataBaseId || workId){
      this.setState({
        workId,
        dataBaseId,
      },()=>{
        this.getColumns();
      });
    }else{
      service.getId(pathname).then((x)=>{
        this.setState({
          workId: x.workId,
          dataBaseId: x.dataBaseId,
        },()=>{
          this.getColumns();
        })
      });
    }


    window.addEventListener('message', (event) => {
      if (event.data === 'returnList') {
        this.returnList(true);
      }
      if (event && event.data && event.data.indexOf && event.data.indexOf('iframeHeight') > -1) {
        let height = Number(event.data.split('-')[1]);
        const iframe = document.getElementById('applyIframeId');
        if (iframe) {
          iframe.height = height;
        }
      }
    }, false);

    return true;
  }

  returnList = (needSearchList = false) => {
    this.setState({
      renderIframe: false,
    },()=>{
      if(needSearchList){
        this.ListComponent.getPage();
      }
      this.setState({
        showIframe: false,
        renderIframe: true, // 重新挂载IFrame 保证申请数据不会再次显示出来
      });
    });
  };

  render() {
    const { workId, dataBaseId, addFields, showIframe, renderIframe } = this.state;
    if(!workId){
      return null;
    }
    const url = config.onestopPC.split('/#/');
    let iframeUrl = `${url[0]}/#/IFrameForApply?id=${workId}&token=${getToken()}`;
    console.log(iframeUrl);
  //  iframeUrl = `http://localhost:8000/onestop/IFrameForApply?id=${workId}&token=${getToken()}`;
    return (
      <PageHeaderWrapper title="">
        <div style={{
          display: showIframe ? 'none' : 'block',
        }}>
          <List listConfig={pageSetting.listConfig}
                pageButton={this.handleButtonSet({})}
                pageSearch={this.handleSearchSet({})}
                addFields={addFields}
                ref={ListComponent => this.ListComponent = ListComponent}
                workId={workId}
                dataBaseId={dataBaseId}
          />
        </div>
        <div style={{
          visibility: showIframe ? 'visible' : 'hidden',
          width: '100%',
          backgroundColor: '#fff',
          paddingLeft: '24px',
        }}>
          <Shell>
            <div style={{
              height: '54px',
              padding: '12px 0 12px 12px',
              display: showIframe ? 'block' : 'none',
            }}>
              <ButtonDiy name="返回"
                         className="defaultBlue"
                         handleClick={this.returnList}
                         icon="arrow-left"
              />
            </div>
          </Shell>
          {
            renderIframe ?
              <iframe src={iframeUrl}
                      frameBorder={0}
                      id='applyIframeId'
                      name='applyIframe'
                      marginWidth="0"
                      marginHeight="0"
                      allowTransparency="yes"
                      seamless
                      scrolling={'auto'}
                      style={{
                        width: '100%',
                        minHeight: '800px',
                        overflowY: 'hidden',
                        backgroundColor: '#fff',
                      }}
              /> : null
          }

        </div>
      </PageHeaderWrapper>
    );

  }
}
