content: import 'eonasdan-bootstrap-datetimepicker';
  import $ from 'jquery';
  import URL from 'js-handy-url';
  import moment from 'moment';
  import tl from '../util/translator';
  import React from 'react';
  import ReactDOM from 'react-dom';
  import app from '../app/app';
  import messaging from '../util/messaging';
  import templateFields from '../data/Template';
  import DataTable from '../util/DataTable';
  import DynForm from '../util/DynForm';
  import open from '../util/openFormInTab';
  import actions from '../util/actions';
  
  class InvoiceSender extends React.Component {
  
      constructor(props) {
          super(props);
  
          let that = this;
          let languages = [];
  
          props.dataEntries.forEach(function (entry) {
              if ( languages.indexOf(entry.language) === -1) {
                  languages.push(entry.language);
              }
          });
  
          this.state = {
              languages: languages,
              selectActions: [
                  {
                      action: 'preview-pdf', icon: 'file',
                      func: function (entity, url, e) {
                          e.preventDefault();
                          if (that.validateEntityLine(entity.id)) {
                              url = (new URL(url)).addParameters(that.getEntityInvoiceData(entity.id));
                              open('POST', url, {}, '_blank');
                          }
                      }
                  },
                  {
                      action: 'preview-any-email', icon: 'envelope',
                      func: function (entity, url, e) {
                          e.preventDefault();
                          if (that.validateEntityLine(entity.id)) {
                              let data = that.getEntityInvoiceData(entity.id);
  
                              data.template = JSON.stringify(that.refs.templateform.getValues(true));
                              open('POST', url, data, '_blank');
                          }
                      }
                  }
              ]
              , customColls: [
                  {
                      name: 'invoiceNo',
                      input: 'text',
                      type: 'string',
                      title: tl.t('invoice.invoice-no.title'),
                      className: 'width-s invoice-no-inp',
                      bindTo: 'invoiceNumber',
                      required: true
                  },
                  {
                      name: 'personal',
                      input: 'checkbox',
                      type: 'boolean',
                      title: tl.t('invoice.personal.title')
                  },
                  {
                      name: 'repeater',
                      input: 'checkbox',
                      type: 'boolean',
                      title: tl.t('invoice.repeater.title'),
                      bindTo: 'repeater'
                  }
  
              ]
          };
      }
  
      componentDidMount(e) {
          $(ReactDOM.findDOMNode(this)).find('.widget-datetime-input').each(function () {
              $(this).datetimepicker({
                  format: $(this).data('format') ? $(this).data('format') : 'DD.MM.YYYY'
              });
          });
      }
  
      updateInitialInvoiceNo(e) {
          e.preventDefault();
          const that = this;
          const form = $(ReactDOM.findDOMNode(this.refs.form));
          let initial_no = this.refs.invoiceNumber.value;
  
          form.find('table input.select-cbx').each(function () {
              let el = $(this),
                  id = el.val()
              ;
  
              if (!el.closest('tr').hasClass('disabled')) {
                  let invoiceNo = that.refs.table.refs.view.refs['line_' + id].refs.custom_invoiceNo;
                  let num = (initial_no++).toString();
                  invoiceNo.setValue('0000'.substr(0, 3 - num.length ) + num);
              }
          });
      }
  
      getEntityInvoiceData(entityId) {
          return {
              'personal': $('#' + entityId + '-personal').prop("checked"),
              'repeater': $('#' + entityId + '-repeater').prop("checked"),
              'invoice-no': $('#' + entityId + '-invoiceNo').val(),
              'invoice-weeks': $('#invoice-weeks').val(),
              'invoice-date': $('#invoice-date-input').val()
          }
      }
  
      getFormData() {
          let form = $(ReactDOM.findDOMNode(this.refs.form)),
              conf = {},
              workConf = {},
              valid = true,
              that = this,
              invoiceNumbers = []
          ;
  
          form.find('table input.select-cbx').each(function () {
              var el = $(this),
                  id = el.val()
              ;
  
              if (!el.closest('tr').hasClass('disabled')) {
  
                  let strId = 'id-' + id;
  
                  workConf[strId] = that.getEntityInvoiceData(id);
                  invoiceNumbers.push(workConf[strId]['invoice-no']);
              }
          });
  
          // it should be sorted by invoice number
          invoiceNumbers.sort();
          invoiceNumbers.forEach(function (iNo) {
              Object.keys(workConf).forEach(function (id) {
                  if (workConf[id]['invoice-no'] === iNo) {
                      conf[id] = workConf[id];
                  }
              })
          });
  
          return !valid ? null : {
              conf: JSON.stringify(conf),
              'invoice-weeks': this.refs['invoice-weeks'].value,
              'invoice-date': this.refs['invoice-date-input'].value,
              'handling': 'invoice',	// the handling parameter
              'template': JSON.stringify(this.refs.templateform.getValues(true))
          };
      }
  
      downloadZips(e) {
          e.preventDefault();
          open('POST', app.util.getAppUrl(app.util.getCurrentPath(), 'downloadCourseInvoicesZip'), this.getFormData(), '_blank');
      }
  
      downloadPdfs(e) {
          e.preventDefault();
          open('POST', app.util.getAppUrl(app.util.getCurrentPath(), 'downloadCourseInvoices'), this.getFormData(), '_blank');
      }
  
      submitForm(e) {
          e.preventDefault();
  
          let modal = messaging.getCurrentModal()
              , that = this
              , url = app.util.getAppUrl(app.util.getCurrentPath(), 'send-emails')
              , data = this.getFormData()
          ;
  
          if (data) {
  
              modal.showLoading();
  
              $.ajax({
                  method: "POST",
                  dataType: 'json',
                  url: url,
                  data: data,
                  success: function (data) {
                      // first we mirror the database
                      for (var i = 0; i < that.props.dataEntries.length; i++) {
                          var entity = that.props.dataEntries[i];
                          if ($.inArray(entity.id, data.data.processed) > -1) {
                              entity.invoiceNumber = $('#' + entity.id + '-invoiceNo').val();
                              entity.repeater = $('#' + entity.id + '-repeater').prop("checked");
                          }
                      }
  
                      that.refs.table.setState({data: that.props.dataEntries});
  
                      app.messanger.addMessage(data.message, data.success ? 'success' : 'danger');
                      modal.hideLoading();
                  },
                  error: function (xhr, status, error) {
                      app.messanger.addMessage('Sorry, something went wrong: ' + status, 'danger');
                      modal.hideLoading();
                  }
              })
          }
      }
  
      validateEntityLine (entityId) {
          let invoiceNoValid = this.refs.table.refs.view.refs['line_' + entityId].refs.custom_invoiceNo.isValid();
  
          return invoiceNoValid;
      }
  
      render() {
          let result,
              loadUrl = app.util.getAppUrl('query/Template/item', 'name:INVOICE_EMAIL')
          ;
  
          this.invoiceNoCounter = 0;
  
  
          result = <div className="invoice-select-wrapper">
              <p>{tl.t('course.send_invoice.description')}</p>
  
              <div id="email-form">
                  <DynForm ref="templateform" loadData={loadUrl} hideModalActions={true} className={'template-form'}
                           data={templateFields.getEmailFields()}
                           fieldDefs={ {Template: templateFields.getEmailFields()} }
                           allowedLanguages={this.state.languages}
                  />
              </div>
  
              <form className="form-inline">
                  <div className="form-group">
                      <label className="sr-only" htmlFor="invoice-number-input">{tl.t('invoice.counter')}</label>
                      <input ref="invoiceNumber" type="text" className="form-control" id="invoice-number-input"
                             name="invoice-number-input" placeholder={tl.t('invoice.counter')}/>
                  </div>
                  <button type="button" onClick={this.updateInitialInvoiceNo.bind(this)}
                          className="btn btn-primary">{tl.t('global.fill')}</button>
              </form>
  
              <form ref="form" className="sendForm form-inline">
                  <DataTable ref="table" data={this.props.dataEntries} customColls={this.state.customColls}
                             actions={[actions.SELECT]} customActions={this.state.selectActions}
                             entityName={this.props.entityName} definition={this.props.definition}/>
  
                  <p>
                      <label htmlFor="invoice-weeks">{tl.t('course.invoice-weeks')}</label> <input ref="invoice-weeks"
                                                                                                   type="text"
                                                                                                   className="form-control"
                                                                                                   style={{width: '42px'}}
                                                                                                   id="invoice-weeks"
                                                                                                   name="invoice-weeks"
                                                                                                   defaultValue="6"/>
                      <label htmlFor="invoice-weeks">{tl.t('course.weeks')}</label>
  
                      <label htmlFor="invoice-date-input">, {tl.t('invoice.date')}</label> <span
                      data-format="DD.MM.YYYY" className="input-group date widget-datetime-input">
                              <span className="input-group-addon">
                                  <span className="glyphicon glyphicon-calendar"/>
                              </span>
                              <input ref="invoice-date-input" type="text" defaultValue={moment().format('DD.MM.YYYY')}
                                     className="form-control" id="invoice-date-input" name="invoice-date-input"
                                     placeholder={tl.t('invoice.date')}/>
                          </span>
                  </p>
                  <hr/>
                  <div className="text-right">
                      <div className="btn-group pull-left" role="group" aria-label="...">
                          <button type="button" className="btn btn-default" disabled="disabled"><i className="glyphicon glyphicon-download-alt"/> {tl.t('course.download-registrations.as')}
                          </button>
                          <button type="button" className="btn btn-primary"
                                  onClick={this.downloadPdfs.bind(this)}>{tl.t('course.download.as.pdf')}</button>
                          <button type="button" className="btn btn-primary"
                                  onClick={this.downloadZips.bind(this)}>{tl.t('course.download.as.zip')}</button>
                      </div>
  
                      <button type="button" className="btn btn-primary"
                              onClick={this.submitForm.bind(this)}>{tl.t('course.send_invoice')}</button>
                      <button type="button" onClick={messaging.closeCurrentModal}
                              className="btn btn-link">{tl.t('global.close')}</button>
                  </div>
              </form>
          </div>;
  
  
          return result;
      }
  
  
  }
  
  // the actual function
  export default function (dataEntries, definition, entityName) {
      let modal = messaging.createModal('Send ' + dataEntries.length + ' Invoices',
          ( <InvoiceSender dataEntries={dataEntries} definition={definition} entityName={entityName}/> )
          , true
      );
      modal.show();
  };
  	
  