<template>
  <gz-dash
    icon="$ayiUser"
    :show-context-button="true"
    :update-frequency="900000"
    v-bind="[$props, $attrs]"
    @dash-refresh="getDataFromApi()"
    @dash-context="showContext()"
    v-on="$listeners"
  >
    <template slot="main">
      <v-sheet
        v-if="obj.length == 0"
        height="400"
        class="ml-6 mt-6 text-h4 grey--text text--lighten-1"
      >
        {{ $ay.t("NoData") }}
      </v-sheet>
      <gz-chart-line v-else :chart-data="chartData" :options="chartOptions" />
    </template>

    <template slot="settings">
      <div></div>
      <v-col v-if="context" cols="12">
        <v-dialog
          v-model="context"
          scrollable
          max-width="600px"
          data-cy="dashSettings"
          @keydown.esc="cancel"
        >
          <v-card elevation="24">
            <v-card-title class="text-h5 lighten-2" primary-title>
              <span> {{ $ay.t("Settings") }} </span>
            </v-card-title>

            <v-card-text>
              <v-select
                v-model="localSettings.timeSpan"
                class="mt-4"
                :items="selectLists.dateFilterTokens"
                item-text="name"
                item-value="id"
                :label="$ay.t('TimeSpan')"
              ></v-select>

              <v-select
                v-model="localSettings.interval"
                class="mt-4"
                :items="selectLists.units"
                item-text="name"
                item-value="id"
                :label="$ay.t('Interval')"
              ></v-select>

              <gz-pick-list
                v-model="localSettings.userid"
                class="mt-4"
                allow-no-selection
                :aya-type="$ay.ayt().User"
                variant="tech"
                :label="$ay.t('WorkOrderItemLaborUserID')"
              ></gz-pick-list>

              <gz-tag-picker
                v-model="localSettings.techtags"
                class="mt-4"
                :label="$ay.t('Tags') + ' - ' + $ay.t('User')"
              ></gz-tag-picker>
              <v-radio-group
                v-if="localSettings.techtags.length > 1"
                v-model="localSettings.techtagsany"
                row
                class="mt-n3"
              >
                <v-radio
                  :label="$ay.t('GridFilterDialogAndRadioText')"
                  :value="false"
                ></v-radio>
                <v-radio
                  :label="$ay.t('GridFilterDialogOrRadioText')"
                  :value="true"
                ></v-radio>
              </v-radio-group>

              <gz-tag-picker
                v-model="localSettings.wotags"
                class="mt-4"
                :label="$ay.t('Tags') + ' - ' + $ay.t('WorkOrder')"
              ></gz-tag-picker>
              <v-radio-group
                v-if="localSettings.wotags.length > 1"
                v-model="localSettings.wotagsany"
                row
                class="mt-n3"
              >
                <v-radio
                  :label="$ay.t('GridFilterDialogAndRadioText')"
                  :value="false"
                ></v-radio>
                <v-radio
                  :label="$ay.t('GridFilterDialogOrRadioText')"
                  :value="true"
                ></v-radio>
              </v-radio-group>

              <gz-tag-picker
                v-model="localSettings.woitemtags"
                class="mt-4"
                :label="$ay.t('Tags') + ' - ' + $ay.t('WorkOrderItem')"
              ></gz-tag-picker>
              <v-radio-group
                v-if="localSettings.woitemtags.length > 1"
                v-model="localSettings.woitemtagsany"
                row
                class="mt-n3"
              >
                <v-radio
                  :label="$ay.t('GridFilterDialogAndRadioText')"
                  :value="false"
                ></v-radio>
                <v-radio
                  :label="$ay.t('GridFilterDialogOrRadioText')"
                  :value="true"
                ></v-radio>
              </v-radio-group>
              <v-text-field
                v-model="localSettings.customTitle"
                class="mt-4"
                :label="$ay.t('Name')"
              ></v-text-field>
            </v-card-text>

            <v-divider></v-divider>
            <v-card-actions>
              <v-btn color="primary" text @click.native="context = false">{{
                $ay.t("Cancel")
              }}</v-btn>
              <v-spacer></v-spacer>
              <v-btn
                color="primary"
                text
                class="ml-4"
                @click="updateSettings"
                >{{ $ay.t("Save") }}</v-btn
              >
            </v-card-actions>
          </v-card>
        </v-dialog>
      </v-col>
    </template>
  </gz-dash>
</template>
<script>
import GzDash from "./dash-base.vue";
export default {
  components: {
    GzDash
  },
  props: {
    settings: { type: Object, default: null }
  },
  data() {
    return {
      obj: {},
      meta: [],
      context: false,
      localSettings: {},
      selectLists: {
        dateFilterTokens: [],
        units: []
      },
      chartOptions: {
        responsive: true,
        maintainAspectRatio: false,
        scales: {
          xAxes: [
            {
              type: "time",
              time: {
                unit: "day"
              },
              gridLines: {
                drawOnChartArea: false
              }
            }
          ],
          yAxes: [
            {
              gridLines: {
                drawOnChartArea: false
              },
              ticks: {
                beginAtZero: true
              }
            }
          ]
        }
      }
    };
  },
  computed: {
    chartData() {
      let ret = [];
      this.meta.forEach(m => {
        let userData = this.obj.filter(d => d.z == m.userid);
        if (userData.length > 0) {
          ret.push({
            label: m.name,
            borderColor: m.uicolor,
            fill: false,
            pointRadius: 2,
            pointHoverRadius: 6,
            pointHitRadius: 3,
            data: userData.map(d => {
              return { x: d.x, y: d.y };
            })
          });
        }
      });
      return { datasets: ret };
    }
  },
  async created() {
    await initWidget(this);
  },
  async mounted() {
    await this.getDataFromApi();
  },
  methods: {
    showContext: function() {
      this.localSettings = window.$gz.util.deepCopySkip(this.settings);
      this.context = true;
    },
    updateSettings: function() {
      this.settings.customTitle = this.localSettings.customTitle;
      this.settings.timeSpan = this.localSettings.timeSpan;
      this.settings.interval = this.localSettings.interval;
      this.settings.wotags = this.localSettings.wotags;
      this.settings.wotagsany = this.localSettings.wotagsany;
      this.settings.woitemtags = this.localSettings.woitemtags;
      this.settings.woitemtagsany = this.localSettings.woitemtagsany;
      this.settings.techtags = this.localSettings.techtags;
      this.settings.techtagsany = this.localSettings.techtagsany;
      this.settings.userid = this.localSettings.userid;

      this.$emit("dash-change");
      this.context = false;
      this.getDataFromApi();
    },

    async getDataFromApi() {
      try {
        this.errorMessage = null;
        const res = await window.$gz.api.post("kpi", {
          KPIName: "WorkOrderItemLaborQuantityEveryoneSummary",
          criteria: {
            timeSpan: this.settings.timeSpan,
            interval: this.settings.interval,
            wotags: this.settings.wotags,
            wotagsany: this.settings.wotagsany,
            woitemtags: this.settings.woitemtags,
            woitemtagsany: this.settings.woitemtagsany,
            techtags: this.settings.techtags,
            techtagsany: this.settings.techtagsany,
            userid: this.settings.userid
          },
          clientTimeStamp: window.$gz.locale.clientLocalZoneTimeStamp()
        });
        if (res.error) {
          this.errorMessage = res.error;
        } else {
          this.chartOptions.scales.xAxes[0].time.unit = this.settings.interval;
          res.data.forEach(z => {
            z.x = new Date(z.x) //convert to locale timezone and output in the closest thing to iso-8601 format
              .toLocaleString("sv-SE", {
                timeZone: this.timeZoneName
              });
          });
          this.meta = res.meta;
          this.meta.unshift({
            userid: null,
            name: "---",
            uicolor: "#eeeeeeff"
          });
          this.obj = res.data;
        }
      } catch (error) {
        this.errorMessage = error.toString();
      }
    }
  }
};

/////////////////////////////////
//
//
async function initWidget(vm) {
  await fetchTranslatedText();
  populateSelectionLists(vm);
}

//////////////////////////////////////////////////////////
//
// Ensures UI translated text is available
//
async function fetchTranslatedText() {
  await window.$gz.translation.cacheTranslations([
    "DateRangeYesterday",
    "DateRangeToday",
    "DateRangeLastWeek",
    "DateRangeThisWeek",
    "DateRangeNextWeek",
    "DateRangeLastMonth",
    "DateRangeThisMonth",
    "DateRangeNextMonth",
    "DateRange14DayWindow",
    "DateRangePast",
    "DateRangeLastYear",
    "DateRangeThisYear",
    "DateRangeInTheLastThreeMonths",
    "DateRangeInTheLastSixMonths",
    "DateRangePastYear",
    "DateRangePast90Days",
    "DateRangePast30Days",
    "DateRangePast7Days",
    "DateRangePast24Hours",
    "DateRangePast6Hours",
    "DateRangeJanuary",
    "DateRangeFebruary",
    "DateRangeMarch",
    "DateRangeApril",
    "DateRangeMay",
    "DateRangeJune",
    "DateRangeJuly",
    "DateRangeAugust",
    "DateRangeSeptember",
    "DateRangeOctober",
    "DateRangeNovember",
    "DateRangeDecember",
    "DateRangePreviousYearThisMonth",
    "DateRangePreviousYearLastMonth",
    "DateRangePreviousYearNextMonth",
    "TimeSpanDays",
    "TimeSpanMonths",
    "Name",
    "TimeSpan",
    "Interval",
    "WorkOrder",
    "WorkOrderItem",
    "WorkOrderItemLaborUserID",
    "User",
    "GridFilterDialogAndRadioText",
    "GridFilterDialogOrRadioText"
  ]);
}

/////////////////////////////////
//
//
function populateSelectionLists(vm) {
  vm.selectLists.dateFilterTokens.push(
    ...[
      // { name: vm.$ay.t("DateRangeYesterday"), id: "*yesterday*" },
      // { name: vm.$ay.t("DateRangeToday"), id: "*today*" },
      { name: vm.$ay.t("DateRangeThisYear"), id: "*thisyear*" },
      { name: vm.$ay.t("DateRangeThisMonth"), id: "*thismonth*" },
      { name: vm.$ay.t("DateRangeThisWeek"), id: "*thisweek*" },
      { name: vm.$ay.t("DateRangeLastYear"), id: "*lastyear*" }, //prior year from jan to dec
      { name: vm.$ay.t("DateRangeLastMonth"), id: "*lastmonth*" },
      { name: vm.$ay.t("DateRangeLastWeek"), id: "*lastweek*" },
      //-------------------------- rando ones -------------------
      { name: vm.$ay.t("DateRange14DayWindow"), id: "*14daywindow*" },
      { name: vm.$ay.t("DateRangePast"), id: "*past*" },
      {
        name: vm.$ay.t("DateRangeInTheLastThreeMonths"),
        id: "*last3months*"
      },
      {
        name: vm.$ay.t("DateRangeInTheLastSixMonths"),
        id: "*last6months*"
      },
      { name: vm.$ay.t("DateRangePastYear"), id: "*pastyear*" }, //last 365 days
      { name: vm.$ay.t("DateRangePast90Days"), id: "*past90days*" },
      { name: vm.$ay.t("DateRangePast30Days"), id: "*past30days*" },
      { name: vm.$ay.t("DateRangePast7Days"), id: "*past7days*" },
      // { name: vm.$ay.t("DateRangePast24Hours"), id: "*past24hours*" },
      // { name: vm.$ay.t("DateRangePast6Hours"), id: "*past6hours*" },
      { name: vm.$ay.t("DateRangeJanuary"), id: "*january*" },
      { name: vm.$ay.t("DateRangeFebruary"), id: "*february*" },
      { name: vm.$ay.t("DateRangeMarch"), id: "*march*" },
      { name: vm.$ay.t("DateRangeApril"), id: "*april*" },
      { name: vm.$ay.t("DateRangeMay"), id: "*may*" },
      { name: vm.$ay.t("DateRangeJune"), id: "*june*" },
      { name: vm.$ay.t("DateRangeJuly"), id: "*july*" },
      { name: vm.$ay.t("DateRangeAugust"), id: "*august*" },
      { name: vm.$ay.t("DateRangeSeptember"), id: "*september*" },
      { name: vm.$ay.t("DateRangeOctober"), id: "*october*" },
      { name: vm.$ay.t("DateRangeNovember"), id: "*november*" },
      { name: vm.$ay.t("DateRangeDecember"), id: "*december*" },
      {
        name: vm.$ay.t("DateRangePreviousYearThisMonth"),
        id: "*lastyearthismonth*"
      },
      {
        name: vm.$ay.t("DateRangePreviousYearLastMonth"),
        id: "*lastyearlastmonth*"
      },
      {
        name: vm.$ay.t("DateRangePreviousYearNextMonth"),
        id: "*lastyearnextmonth*"
      }
    ]
  );

  vm.selectLists.units.push(
    ...[
      { name: vm.$ay.t("TimeSpanDays"), id: "day" },
      {
        name: vm.$ay.t("TimeSpanMonths"),
        id: "month"
      }
    ]
  );
}
</script>
