<template>
  <b-modal id="download-report" ref="downloadReport" hide-footer @ok="onDownloadReport()">
    <div class="download-report-wrap">
      <h3>Download Report</h3>
      <div class="download-steps">
        <div class="parameters step">
          <div class="step-header">
            <div class="step-no">Step 1</div>
            <div class="step-name">Select Parameters</div>
          </div>
          <div class="vue-tree-container">
            <mads-tree
              ref="tree"
              :treeView="'file'"
              :treeOptions="treeOptions"
              :hiddenEntities="[]"
              :selectedNodes="selectedNodes"
              :selectableEntities="['SensorParameter']"
              :type="'organization'"
              :apiKey="'dash_mgmt'"
              :isExportedDashboard="dashboardType === 'exportedDashboard'"
              :currentUser="currentUser"
              :selectedDashboard="selectedDashboard"
              :selectedProject="selectedProject"
              :compareTreeData="compareTreeData"
              :dashboardService="dashboardService"
              :treeService="treeService"
              :entityService="entityService"
              :orgService="orgService"
              :dataInsightService="dataInsightService"
            ></mads-tree>
          </div>
        </div>
        <div class="step vertical-stacked">
        <div class="range">
          <div class="step-header">
            <div class="step-no">Step 2</div>
            <div class="step-name">Select Range</div>
          </div>
          <div class="step-content">
            <b-form>
              <b-form-group label="From">
                <vc-date-picker v-model="fromDate" mode="dateTime">
                  <template v-slot="{ inputValue, inputEvents }">
                    <input
                      :value="inputValue"
                      v-on="inputEvents"
                    />
                  </template>
                </vc-date-picker>
              </b-form-group>
              <b-form-group label="To">
                <vc-date-picker v-model="toDate" mode="dateTime">
                  <template v-slot="{ inputValue, inputEvents }">
                    <input
                      :value="inputValue"
                      v-on="inputEvents"
                    />
                  </template>
                </vc-date-picker>
              </b-form-group>
            </b-form>
          </div>
        </div>
        <div class="file-type">
          <div class="step-header">
            <div class="step-no">Step 3</div>
            <div class="step-name">File Type</div>
          </div>
          <div class="step-content radio-options">
            <b-form-group>
              <b-form-radio-group
                v-model="selectedFileType"
                :options="fileTypeOptions"
                stacked
              ></b-form-radio-group>
            </b-form-group>
          </div>
        </div>
        </div>
        <div class="step vertical-stacked">
          <div class="sheet-preferences">
            <div class="step-header">
              <div class="step-no">Step 4</div>
              <div class="step-name">Sheet Preferences</div>
            </div>
            <div class="step-content radio-options">
              <b-form-group>
                <b-form-radio-group
                  v-model="selectedSheetPreference"
                  :options="sheetPreferences"
                  stacked
                ></b-form-radio-group>
              </b-form-group>
            </div>
          </div>
          <div class="email-info">
            <div class="step-header">
              <div class="step-no">Step 5</div>
              <div class="step-name">Email</div>
            </div>
            <div class="step-content">
              <div style="margin-bottom: 20px;">
                <span>Report will be sent to your email once it is generated</span>
              </div>
              <b-form-group>
                <b-input v-model="reportEmail" placeholder="Enter email"></b-input>
              </b-form-group>
              <div class="error-msg" v-if="errorMessages.length">
                <div v-for="(error, index) in errorMessages" :key="index">{{error}}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="mads-footer">
        <!-- <b-button variant="primary" class="reset-btn" @click="onReset()">Reset</b-button> -->
        <b-button variant="outline-primary" @click="onCancel()">Cancel</b-button>
        <b-button variant="primary" @click="onDownloadReport()">Download</b-button>
      </div>
    </div>
  </b-modal>
</template>

<script>
import MadsTree from './madsTree/index.vue'

export default {
  components: {
    MadsTree
  },
  props: {
    dashboardType: {
      type: String
    },
    currentUser: {},
    selectedDashboard: {},
    selectedProject: {},
    compareTreeData: {},
    dashboardService: {},
    treeService: {},
    entityService: {},
    orgService: {},
    dataInsightService: {}
  },
  data () {
    return {
      treeOptions: {
        selectable: true,
        singleSelect: false
      },
      selectedNodes: [],
      fromDate: null,
      toDate: null,
      selectedFileType: 'xlsx',
      fileTypeOptions: [
        { text: 'CSV', value: 'csv', disabled: true },
        { text: 'XLS', value: 'xls', disabled: true },
        { text: 'XLSX', value: 'xlsx' },
        { text: 'PDF', value: 'pdf', disabled: true }
      ],
      selectedSheetPreference: 'preference1',
      sheetPreferences: [
        { html: '<span>Create multiple sheets by <span class="blue-txt">Project.Gateway</span> name</span>', value: 'preference1' },
        { html: '<span>Merge into a single sheet with one timestamp column</span>', value: 'preference2', disabled: true },
        { html: '<span>Merge into a single sheet with multiple timestamp columns by  <span class="blue-txt">Project.Gateway</span> name</span>', value: 'preference3', disabled: true }
      ],
      reportEmail: '',
      errorMessages: []
    }
  },
  methods: {
    open () {
      this.$refs.downloadReport.show()
    },
    onCancel () {
      this.$refs.downloadReport.hide()
    },
    getEntities () {
      let selectedNodes = this.$refs.tree.getSelectedNodes()
      return this.$_.map(selectedNodes, (node) => {
        return {
          sensor_id: node.parentId,
          param_uuid: node.uuid
        }
      })
    },
    downloadReport (payload) {
      let config = { orgId: this.selectedDashboard.org_id, id: this.selectedDashboard.id }

      this.dashboardService.downloadReport(config, payload)
        .then((response) => {
          this.$emit('on-success', response.message)
          this.$refs.downloadReport.hide()
        })
        .catch((error) => {
          this.$emit('on-error', error.title)
          this.errorMessages = this.$_.concat([], this.errorMessages, error.detail)
        })
    },
    downloadExportedDashboardReport (payload) {
      let dashboardToken = localStorage.getItem('dashboard_token')
      let dashboardUUID = localStorage.getItem('dashboard_uuid')
      let config = { uuid: dashboardUUID }

      this.dashboardService.downloadExportedDashboardReport(config, payload, dashboardToken)
        .then((response) => {
          if (response.error) {
            this.$emit('on-error', response.title)
            this.errorMessages = this.$_.concat([], this.errorMessages, response.detail)
          } else {
            this.$emit('on-success', response.message)
            this.$refs.downloadReport.hide()
          }
        })
    },
    onDownloadReport () {
      let entities = this.getEntities()
      this.errorMessages = []

      if (!this.reportEmail || (this.$_.size(entities) <= 0)) {
        if (!this.reportEmail) {
          this.errorMessages = this.$_.concat([], this.errorMessages, 'Please enter email')
        }
        if (this.$_.size(entities) <= 0) {
          this.errorMessages = this.$_.concat([], this.errorMessages, 'No parameters selected')
        }
        return
      }

      let payload = {
        entities: entities,
        date_to: this.$moment(this.toDate).format('x'),
        date_from: this.$moment(this.fromDate).format('x'),
        email_to: this.reportEmail
      }

      if (this.dashboardType === 'exportedDashboard') {
        this.downloadExportedDashboardReport(payload)
      } else {
        this.downloadReport(payload)
      }
    },
    onReset () {
      this.selectedNodes = []
    }
  }
}
</script>

<style lang="scss" scoped>
  .download-report-wrap {
    width: 100%;
    padding: 20px;
    h3 {
      font-size: 18px;
      font-weight: bold;
    }
    .download-steps {
      display: flex;
      margin-top: 20px;
      justify-content: space-between;
      height: calc(100% - 105px);
      .step {
        width: 320px;
        .step-header {
          height: 60px;
          background-color: #e2e2e2;
          padding: 5px 10px;
          border-top-left-radius: 4px;
          border-top-right-radius: 4px;
          .step-no {
            font-size: 16px;
          }
          .step-name {
            font-size: 15px;
          }
        }
        .step-content {
          padding: 0 10px;
          margin-top: 10px;
        }
        &.parameters {
          .vue-tree-container {
            overflow: auto;
            height: 500px;
          }
        }
        .vertical-stacked {
          display: flex;
          flex-direction: column;
          justify-content: flex-end;
        }
        .range, .sheet-preferences {
          height: 290px;
          margin-bottom: 10px;
        }
        .file-type, .email-info {
          height: 260px;
        }
      }
      .parameters, .range, .file-type, .sheet-preferences, .email-info {
        border: 1px solid #e2e2e2;
        border-radius: 4px;
      }
    }
    .mads-footer {
      height: 75px;
      display: flex;
      align-items: center;
      justify-content: flex-end;
      .btn {
        margin: 0 5px;
      }
      .reset-btn {
        margin: 0 auto 0 0;
      }
    }
  }
</style>

<style lang="scss">
  #download-report{
    .modal-dialog{
      max-width: 1040px;
    }
    .range > .step-content {
      form {
        display: flex;
        justify-content: space-between;
        .form-group {
          width: 146px;
          margin-right: 0 !important;
          input {
            width: 100%;
          }
        }
      }
    }
    .radio-options {
      .custom-radio {
        margin-bottom: 10px;
        .blue-txt {
          color: #3576AB;
        }
      }
    }
  }
</style>
