<template>
  <div>
    <v-overlay :value="rendering" z-index="999">
      <v-progress-circular indeterminate size="64"></v-progress-circular>
    </v-overlay>
    <v-row justify="center">
      <v-dialog
        scrollable
        max-width="600px"
        v-model="isVisible"
        @keydown.esc="cancel"
        data-cy="reportselector"
      >
        <v-card elevation="24">
          <v-card-title class="text-h5 lighten-2" primary-title>
            <span> {{ $ay.t("Report") }} </span>
          </v-card-title>

          <v-card-text style="height: 500px;">
            <v-list>
              <v-list-item
                v-for="item in reportList"
                :key="item.id"
                @click="renderReport(item.id, item.name)"
              >
                <v-list-item-title>{{ item.name }}</v-list-item-title>
                <v-list-item-action class="d-none d-sm-flex">
                  <v-btn icon @click.stop="editReport(item.id)">
                    <v-icon color="primary">$ayiEdit</v-icon>
                  </v-btn>
                </v-list-item-action>
              </v-list-item>
            </v-list>
          </v-card-text>

          <v-divider></v-divider>

          <v-card-actions>
            <v-btn
              v-if="rights.change"
              color="primary"
              text
              @click.native="newReport"
              data-cy="reportselector:ok"
              class="d-none d-sm-flex"
              >{{ $ay.t("New") }}</v-btn
            >
            <v-spacer v-if="!$vuetify.breakpoint.xs"></v-spacer>
            <v-btn
              color="primary"
              text
              @click.native="cancel"
              data-cy="reportselector:cancel"
              >{{ $ay.t("Cancel") }}</v-btn
            >
          </v-card-actions>
        </v-card>
      </v-dialog>
    </v-row>
  </div>
</template>
<script>
export default {
  data: () => ({
    rights: window.$gz.role.getRights(window.$gz.type.Report),
    reportDataOptions: {},
    isVisible: false,
    resolve: null,
    reject: null,
    options: {
      width: 290,
      zIndex: 200
    },
    reportList: [],
    selectedReport: null,
    rendering: false,
    preSelectReportId: null
  }),
  methods: {
    editReport(reportid) {
      this.isVisible = false;
      this.resolve(null);
      this.$router.push({
        name: "ay-report-edit",
        params: {
          recordid: reportid,
          reportDataOptions: this.reportDataOptions
        }
      });
    },
    async immediateRenderReport(reportId, reportName) {
      if (this.$route.params.recordid == 0) {
        return;
      }

      const reportDataOptions = this.reportDataOptions;
      if (!reportDataOptions) {
        this.reject("Missing report data unable to render report");
      }
      reportDataOptions.ReportId = reportId;
      //Meta data from client for use by report script
      reportDataOptions.ClientMeta = window.$gz.api.reportClientMetaData();
      this.rendering = true;

      const res = await window.$gz.api.upsert(
        "report/render",
        reportDataOptions
      );
      this.rendering = false;

      if (res.error) {
        this.reject(res);
      } else {
        //special handling for timeout response at the server
        if (res.data && res.data.timeout) {
          await window.$gz.dialog.displayNoTranslationModalNotificationMessage(
            window.$gz.translation
              .get("ReportRenderTimeOut")
              .replace("{0}", res.data.timeoutconfigminutes),
            null,
            "error",
            `${this.$store.state.helpUrl}/ay-report-timeout`
          );
        } else {
          //all ok show report
          const reportUrl = window.$gz.api.reportDownloadUrl(res.data);
          if (window.open(reportUrl, "Report") == null) {
            this.reject(
              "Problem displaying report in new window.  Browser must allow pop-ups to view reports; check your browser setting"
            );
          }
        }
      }

      this.isVisible = false;
      if (reportName != null) {
        this.resolve({ name: reportName, id: reportId });
      } else {
        this.resolve(null);
      }
    },
    async renderReport(reportId, reportName) {
      if (this.$route.params.recordid == 0) {
        return;
      }

      const reportDataOptions = this.reportDataOptions;
      if (!reportDataOptions) {
        this.reject("Missing report data unable to render report");
      }
      reportDataOptions.ReportId = reportId;
      //Meta data from client for use by report script
      reportDataOptions.ClientMeta = window.$gz.api.reportClientMetaData();
      this.rendering = true;
      const reportUrl = null;
      try {
        let jobId = await window.$gz.api.upsert(
          "report/render-job",
          reportDataOptions
        );
        if (jobId.error) {
          throw new Error(window.$gz.errorHandler.errorToString(jobId, this));
        }
        jobId = jobId.jobId;
        this.jobActive = true;

        let jobStatus = 1;
        while (this.jobActive == true) {
          await window.$gz.util.sleepAsync(500);
          jobStatus = await window.$gz.api.get(
            `job-operations/status/${jobId}`
          );
          if (jobStatus.error) {
            throw new Error(
              window.$gz.errorHandler.errorToString(jobStatus, this)
            );
          }
          jobStatus = jobStatus.data;
          if (jobStatus == 4 || jobStatus == 0) {
            throw new Error("Job failed");
          }
          if (jobStatus == 3) {
            //success, get the report url name
            const jobLogRes = await window.$gz.api.get(
              `job-operations/logs/${jobId}`
            );
            //console.log(jobLogRes);
            //todo:look for reportfilename property in job log here and then put in reportUrl
            //debugger;
            if (Array.isArray(jobLogRes.data)) {
              //walk the array backwards as it's probably the final entry in the log
              for (var i = jobLogRes.data.length - 1; i >= 0; i--) {
                var v = jobLogRes.data[i].statusText;
                //console.log("value type is:", typeof v);
                if (v.includes("reportfilename")) {
                  console.log("Parsing:", v);
                  const o = JSON.parse(v);
                  reportUrl = window.$gz.api.reportDownloadUrl(
                    o.reportFileName
                  );
                }
              }
            }
            /*
[
  {
    "created": "2021-12-27T20:23:54.145758Z",
    "statusText": "LT:ProcessingJob \"LT:Report id: \"60\" LT:WorkOrder (1) LT:User AyaNova SuperUser - RenderReport\"",
    "jobId": "62f78eb6-7744-4bbc-bd93-00848110219c"
  },
  {
    "created": "2021-12-27T20:23:54.156294Z",
    "statusText": "LT:StartJob RenderReport",
    "jobId": "62f78eb6-7744-4bbc-bd93-00848110219c"
  },
  {
    "created": "2021-12-27T20:23:55.820618Z",
    "statusText": "{reportfilename:\"4jpsvserib2.pdf\"}",
    "jobId": "62f78eb6-7744-4bbc-bd93-00848110219c"
  }
]
*/
            this.jobActive = false;
          }
        }
        //job ran to completion, get the report file name and fetch it
        if (reportUrl) {
          if (window.open(reportUrl, "Report") == null) {
            this.reject(
              "Problem displaying report in new window.  Browser must allow pop-ups to view reports; check your browser setting"
            );
          }
        }
        this.isVisible = false;
        if (reportName != null) {
          this.resolve({ name: reportName, id: reportId });
        } else {
          this.resolve(null);
        }
      } catch (error) {
        this.jobActive = false;
        this.reject(error);
        //window.$gz.errorHandler.handleFormError(error, this);
        //window.$gz.eventBus.$emit("notify-error", this.$ay.t("JobFailed"));
      }
    },
    async open(reportDataOptions, preSelectReportId) {
      const vm = this;
      if (reportDataOptions == null) {
        throw new Error("report-selector:Open missing reportDataOptions");
      }
      if (reportDataOptions.AType == null) {
        throw new Error("report-selector:Open - AType is missing or empty");
      }

      this.reportDataOptions = reportDataOptions;
      this.preSelectReportId = preSelectReportId;
      if (!preSelectReportId) {
        //get report list from server
        const res = await window.$gz.api.get(
          `report/list/${reportDataOptions.AType}`
        );
        if (res.error) {
          // throw new Error(res.error);
          throw new Error(window.$gz.errorHandler.errorToString(res, vm));
        } else {
          this.reportList = res.data;
        }
        this.isVisible = true;
      } else {
        this.renderReport(this.preSelectReportId);
      }
      return new Promise((resolve, reject) => {
        this.resolve = resolve;
        this.reject = reject;
      });
    },
    cancel() {
      this.isVisible = false;
      this.resolve(null);
    },
    newReport() {
      this.isVisible = false;
      this.resolve(null);
      this.$router.push({
        name: "ay-report-edit",
        params: {
          recordid: 0,
          reportDataOptions: this.reportDataOptions
        }
      });
    }
  }
};
</script>
