import fetch from 'dva/fetch';
import React from 'react';
import {
  Form,
  notification,
} from 'antd';
import { connect } from 'dva';
import { getToken } from '../../utils/token';
import config from '@/webPublic/one_stop_public/config';
import FormdataWrapper from '../../utils/object-to-formdata-custom';
import ButtonDiy from '../ButtonDiy/ButtonDiy';
import {  giveFilePostDataInfoForTrue } from '@/webPublic/one_stop_public/Base16';
import SelectModal from '@/webPublic/one_stop_public/App/ExportCurrentInfo/SelectModal';
import { getHeaders } from '@/webPublic/zyd_public/utils/utils';
import { getTransformApi } from '@/webPublic/one_stop_public/2022beidianke/localstorageTransform';
/**
 *
 * 2019/02/21  修改导出方式为fetch
 * 增加 props.fileName 设置导出文件名称
 * mustQuerys 设置搜索条件 demo :
 *  mustQuerys={[{
                hql: 'bean.adminStatus',
                x: '=',
                v: "pass",
                c: 'com.zysoft.app.zydxl.entity.base.BaseImportantWatch$Status',
                notes: 'com.zysoft.app.zydxl.entity.base.BaseImportantWatch$Status',
              }]}
 */



@connect(({ DataObj, loading }) => ({
  DataObj,
  loading: loading.models.DataObj,
}))
@Form.create()
export default class ExportCurrentInfo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      confirmLoading: false,
      showSelectModal: false,
    };
  }

  changeShowSelectModal = () => {
    this.setState({
      showSelectModal: !this.state.showSelectModal,
    })
  }

  exportData = () => {
    let downloadUrl = config.httpServer + '/DataObjApi/exportCurrent';
    let param = {
      dataObjId: this.props.objId,
      query: this.props.query,
      custom: this.props.custom,
      sql: this.props.sql,
      index: this.props.index,
      // token: getToken(),
    };
    if(this.props.openSelectFieldsModal){ // 26598 自定义数据导出---导出字段调整，，，注意数据权限

      this.setState({
        showSelectModal: {
          param,
          downloadUrl,
        }
      });
      return false;
    }
    this.downloadFile(downloadUrl, param);
  };

  downloadFile = async (url, params) => {
    this.setState({ confirmLoading: true });
    let newApi = giveFilePostDataInfoForTrue(params, url);
    if(newApi && newApi.datas){
      newApi.datas.token = getToken();
    }
    const { transformApi, headersApi } = await getTransformApi(newApi.url);
    fetch(transformApi, {
      method: 'POST',
      body: FormdataWrapper(newApi.datas),
      ...getHeaders('', headersApi),
    })
      .then((res) => {
        if (res.status != '200') {
          return res.json();
        } else {
          return res.blob();
        }
      })
      .then((data) => {
        if (data instanceof Blob) {
          let a = document.createElement('a');
          let url = window.URL.createObjectURL(data);
          let filename =
            (this.props.fileName ? this.props.fileName : '导出文件.') + (this.props.ext || 'xlsx');
          a.href = url;
          a.download = filename;
          a.click();
          window.URL.revokeObjectURL(url);
          a = null;
        } else {
          notification.error({
            message: `文件导出错误`,
            description: data.errMsg,
          });
        }
      })
      .catch((err) => {
        notification.error({
          message: `网络请求超时`,
        });
      })
      .finally(() => {
        this.setState({ confirmLoading: false });
      });
  }

  checkDownload = () => {
    if(this.props.beforeDownloadFile){
      this.props.beforeDownloadFile(this.exportData);
    }else{
      this.exportData();
    }
  }

  render() {
    const btn = {
      name: '导出',
      type: 'default',
      className: 'defaultBlue',
      ...(this.props.btn ? this.props.btn : {}),
    };
    const { custom, index, openSelectFieldsModal } = this.props;
    const { showSelectModal } = this.state;
    return (
      <span>
				<ButtonDiy {...btn} loading={this.state.confirmLoading} handleClick={this.checkDownload} />
        {
          openSelectFieldsModal &&
          <SelectModal custom={custom}
                       index={index}
                       changeShow={this.changeShowSelectModal}
                       show={showSelectModal}
                       downloadFile={this.downloadFile.bind(this)}

          />
        }

				<div id="downloadDiv" style={{ display: 'none' }} />
			</span>
    );
  }
}
