<template>
  <div>
    <gz-report-selector ref="reportSelector"></gz-report-selector>
    <div v-if="formState.ready">
      <gz-error :error-box-message="formState.errorBoxMessage"></gz-error>
      <v-form ref="form">
        <v-row>
          <v-col cols="12" sm="6" lg="4" xl="3">
            <v-text-field
              v-model="obj.name"
              :readonly="formState.readOnly"
              :label="$ay.t('ContractName')"
              :rules="[form().required(this, 'name')]"
              :error-messages="form().serverErrors(this, 'name')"
              ref="name"
              data-cy="name"
              @input="fieldValueChanged('name')"
            ></v-text-field>
          </v-col>

          <v-col cols="12" sm="6" lg="4" xl="3">
            <gz-duration-picker
              v-model="obj.responseTime"
              :readonly="formState.readOnly"
              :label="$ay.t('ContractDefaultResponseTime')"
              :show-seconds="false"
              ref="responseTime"
              data-cy="responseTime"
              :error-messages="form().serverErrors(this, 'responseTime')"
              @input="fieldValueChanged('responseTime')"
            ></gz-duration-picker>
          </v-col>
          <v-col cols="12">
            <span class="text-h6">
              {{ $ay.t("ContractDefaultAdjustments") }}</span
            >
          </v-col>

          <v-col cols="12">
            <v-row>
              <v-col>
                <gz-percent
                  v-model="obj.partsOverridePct"
                  :readonly="formState.readOnly"
                  :label="$ay.t('PartList')"
                  ref="partsOverridePct"
                  data-cy="partsOverridePct"
                  :rules="[
                    form().decimalValid(this, 'partsOverridePct'),
                    form().required(this, 'partsOverridePct')
                  ]"
                  :error-messages="
                    form().serverErrors(this, 'partsOverridePct')
                  "
                  @input="fieldValueChanged('partsOverridePct')"
                ></gz-percent>
              </v-col>

              <v-col>
                <v-select
                  v-model="obj.partsOverrideType"
                  :items="selectLists.overrideTypes"
                  item-text="name"
                  item-value="id"
                  :readonly="formState.readOnly"
                  :label="$ay.t('ContractOverrideType')"
                  ref="partsOverrideType"
                  data-cy="partsOverrideType"
                  :rules="[form().integerValid(this, 'partsOverrideType')]"
                  :error-messages="
                    form().serverErrors(this, 'partsOverrideType')
                  "
                  @input="fieldValueChanged('partsOverrideType')"
                ></v-select>
              </v-col>
            </v-row>
            <v-row>
              <v-col>
                <gz-percent
                  v-model="obj.serviceRatesOverridePct"
                  :readonly="formState.readOnly"
                  :label="$ay.t('ServiceRateList')"
                  ref="serviceRatesOverridePct"
                  data-cy="serviceRatesOverridePct"
                  :rules="[
                    form().decimalValid(this, 'serviceRatesOverridePct'),
                    form().required(this, 'serviceRatesOverridePct')
                  ]"
                  :error-messages="
                    form().serverErrors(this, 'serviceRatesOverridePct')
                  "
                  @input="fieldValueChanged('serviceRatesOverridePct')"
                ></gz-percent>
              </v-col>

              <v-col>
                <v-select
                  v-model="obj.serviceRatesOverrideType"
                  :items="selectLists.overrideTypes"
                  item-text="name"
                  item-value="id"
                  :readonly="formState.readOnly"
                  :label="$ay.t('ContractOverrideType')"
                  ref="serviceRatesOverrideType"
                  data-cy="serviceRatesOverrideType"
                  :rules="[
                    form().integerValid(this, 'serviceRatesOverrideType')
                  ]"
                  :error-messages="
                    form().serverErrors(this, 'serviceRatesOverrideType')
                  "
                  @input="fieldValueChanged('serviceRatesOverrideType')"
                ></v-select>
              </v-col>
            </v-row>

            <v-row>
              <v-col>
                <gz-percent
                  v-model="obj.travelRatesOverridePct"
                  :readonly="formState.readOnly"
                  :label="$ay.t('TravelRateList')"
                  ref="travelRatesOverridePct"
                  data-cy="travelRatesOverridePct"
                  :rules="[
                    form().decimalValid(this, 'travelRatesOverridePct'),
                    form().required(this, 'travelRatesOverridePct')
                  ]"
                  :error-messages="
                    form().serverErrors(this, 'travelRatesOverridePct')
                  "
                  @input="fieldValueChanged('travelRatesOverridePct')"
                ></gz-percent>
              </v-col>

              <v-col>
                <v-select
                  v-model="obj.travelRatesOverrideType"
                  :items="selectLists.overrideTypes"
                  item-text="name"
                  item-value="id"
                  :readonly="formState.readOnly"
                  :label="$ay.t('ContractOverrideType')"
                  ref="travelRatesOverrideType"
                  data-cy="travelRatesOverrideType"
                  :rules="[
                    form().integerValid(this, 'travelRatesOverrideType')
                  ]"
                  :error-messages="
                    form().serverErrors(this, 'travelRatesOverrideType')
                  "
                  @input="fieldValueChanged('travelRatesOverrideType')"
                ></v-select>
              </v-col>
            </v-row>
          </v-col>

          <v-col cols="12" class="mt-10">
            <span class="text-h6">
              {{ $ay.t("ContractTaggedAdjustments") }}</span
            >
          </v-col>
          <!-- ################################ TAGGED PARTS TABLE ############################### -->
          <v-col cols="12" sm="6" lg="4" xl="3" class="mb-10">
            <span class="text-subtitle-2"> {{ $ay.t("PartList") }}</span
            ><v-btn large icon @click="addContractPartOverrideItem()">
              <v-icon small color="primary">$ayiPlus</v-icon>
            </v-btn>
            <v-simple-table>
              <template v-slot:default>
                <thead>
                  <tr>
                    <th class="text-right">
                      {{ $ay.t("ContractAdjustment") }}
                    </th>
                    <th class="text-left">
                      {{ $ay.t("ContractOverrideType") }}
                    </th>
                    <th class="text-left">
                      {{ $ay.t("Tags") }}
                    </th>
                    <th class="text-right">
                      <!-- CONTROL PANEL -->
                    </th>
                  </tr>
                </thead>

                <tbody>
                  <tr
                    v-for="(item, index) in obj.contractPartOverrideItems"
                    :key="item.Id"
                    :class="
                      form().childRowErrorClass(
                        thisVm(),
                        'ContractPartOverrideItems',
                        index
                      )
                    "
                  >
                    <td class="text-right">{{ item.overridePct }}%</td>
                    <td class="text-left">
                      {{
                        selectLists.overrideTypes.find(
                          z => z.id == item.overrideType
                        ).name
                      }}
                    </td>
                    <td class="text-left">
                      {{ $ay.util().formatTags(item.tags) }}
                    </td>
                    <td class="text-right">
                      <v-btn
                        large
                        icon
                        @click="editContractPartOverrideItem(index)"
                        class="ml-4"
                      >
                        <v-icon small>
                          $ayiEdit
                        </v-icon>
                      </v-btn>
                    </td>
                  </tr>
                </tbody>
              </template>
            </v-simple-table>
          </v-col>

          <!-- ################################ TAGGED SERVICE RATES TABLE ############################### -->
          <v-col cols="12" sm="6" lg="4" xl="3" class="mb-10">
            <span class="text-subtitle-2"> {{ $ay.t("ServiceRateList") }}</span
            ><v-btn large icon @click="addContractServiceRateOverrideItem()">
              <v-icon small color="primary">$ayiPlus</v-icon>
            </v-btn>
            <v-simple-table>
              <template v-slot:default>
                <thead>
                  <tr>
                    <th class="text-right">
                      {{ $ay.t("ContractAdjustment") }}
                    </th>
                    <th class="text-left">
                      {{ $ay.t("ContractOverrideType") }}
                    </th>
                    <th class="text-left">
                      {{ $ay.t("Tags") }}
                    </th>
                    <th class="text-right">
                      <!-- CONTROL PANEL -->
                    </th>
                  </tr>
                </thead>

                <tbody>
                  <tr
                    v-for="(item,
                    index) in obj.contractServiceRateOverrideItems"
                    :key="item.Id"
                    :class="
                      form().childRowErrorClass(
                        thisVm(),
                        'ContractServiceRateOverrideItems',
                        index
                      )
                    "
                  >
                    <td class="text-right">{{ item.overridePct }}%</td>
                    <td class="text-left">
                      {{
                        selectLists.overrideTypes.find(
                          z => z.id == item.overrideType
                        ).name
                      }}
                    </td>
                    <td class="text-left">
                      {{ $ay.util().formatTags(item.tags) }}
                    </td>
                    <td class="text-right">
                      <v-btn
                        large
                        icon
                        @click="editContractServiceRateOverrideItem(index)"
                        class="ml-4"
                      >
                        <v-icon small>
                          $ayiEdit
                        </v-icon>
                      </v-btn>
                    </td>
                  </tr>
                </tbody>
              </template>
            </v-simple-table>
          </v-col>

          <!-- ################################ TAGGED TRAVEL RATES TABLE ############################### -->
          <v-col cols="12" sm="6" lg="4" xl="3" class="mb-10">
            <span class="text-subtitle-2"> {{ $ay.t("TravelRateList") }}</span
            ><v-btn large icon @click="addContractTravelRateOverrideItem()">
              <v-icon small color="primary">$ayiPlus</v-icon>
            </v-btn>
            <v-simple-table>
              <template v-slot:default>
                <thead>
                  <tr>
                    <th class="text-right">
                      {{ $ay.t("ContractAdjustment") }}
                    </th>
                    <th class="text-left">
                      {{ $ay.t("ContractOverrideType") }}
                    </th>
                    <th class="text-left">
                      {{ $ay.t("Tags") }}
                    </th>
                    <th class="text-right">
                      <!-- CONTROL PANEL -->
                    </th>
                  </tr>
                </thead>

                <tbody>
                  <tr
                    v-for="(item, index) in obj.contractTravelRateOverrideItems"
                    :key="item.Id"
                    :class="
                      form().childRowErrorClass(
                        thisVm(),
                        'ContractTravelRateOverrideItems',
                        index
                      )
                    "
                  >
                    <td class="text-right">{{ item.overridePct }}%</td>
                    <td class="text-left">
                      {{
                        selectLists.overrideTypes.find(
                          z => z.id == item.overrideType
                        ).name
                      }}
                    </td>
                    <td class="text-left">
                      {{ $ay.util().formatTags(item.tags) }}
                    </td>
                    <td class="text-right">
                      <v-btn
                        large
                        icon
                        @click="editContractTravelRateOverrideItem(index)"
                        class="ml-4"
                      >
                        <v-icon small>
                          $ayiEdit
                        </v-icon>
                      </v-btn>
                    </td>
                  </tr>
                </tbody>
              </template>
            </v-simple-table>
          </v-col>
          <!-- ################################ CONTRACT RATES ############################### -->
          <v-col cols="12" class="mt-10">
            <span class="text-h6"> {{ $ay.t("ContractRateList") }}</span>
          </v-col>

          <!-- ################################ SERVICE RATES ############################### -->
          <v-col cols="12" sm="6" lg="4" xl="3" class="mb-10">
            <v-checkbox
              v-model="obj.contractServiceRatesOnly"
              :readonly="formState.readOnly"
              :label="$ay.t('ContractServiceRatesOnly')"
              ref="contractServiceRatesOnly"
              data-cy="contractServiceRatesOnly"
              :error-messages="
                form().serverErrors(this, 'contractServiceRatesOnly')
              "
              @change="fieldValueChanged('contractServiceRatesOnly')"
            ></v-checkbox>
            <span class="text-subtitle-2"> {{ $ay.t("ServiceRateList") }}</span
            ><v-btn large icon @click="addServiceRateItem()">
              <v-icon small color="primary">$ayiPlus</v-icon>
            </v-btn>

            <v-simple-table>
              <template v-slot:default>
                <tbody>
                  <tr
                    v-for="(item, index) in obj.serviceRateItems"
                    :key="item.Id"
                    :class="
                      form().childRowErrorClass(
                        thisVm(),
                        'ServiceRateItems',
                        index
                      )
                    "
                  >
                    <td class="text-left">
                      {{ item.serviceRateViz }}
                    </td>

                    <td class="text-right">
                      <v-btn
                        large
                        icon
                        @click="editServiceRateItem(index)"
                        class="ml-4"
                      >
                        <v-icon small>
                          $ayiEdit
                        </v-icon>
                      </v-btn>
                    </td>
                  </tr>
                </tbody>
              </template>
            </v-simple-table>
          </v-col>

          <!-- ################################ TRAVEL RATES ############################### -->
          <v-col cols="12" sm="6" lg="4" xl="3" class="mb-10">
            <v-checkbox
              v-model="obj.contractTravelRatesOnly"
              :readonly="formState.readOnly"
              :label="$ay.t('ContractTravelRatesOnly')"
              ref="contractTravelRatesOnly"
              data-cy="contractTravelRatesOnly"
              :error-messages="
                form().serverErrors(this, 'contractTravelRatesOnly')
              "
              @change="fieldValueChanged('contractTravelRatesOnly')"
            ></v-checkbox>
            <span class="text-subtitle-2"> {{ $ay.t("TravelRateList") }}</span
            ><v-btn large icon @click="addTravelRateItem()">
              <v-icon small color="primary">$ayiPlus</v-icon>
            </v-btn>

            <v-simple-table>
              <template v-slot:default>
                <tbody>
                  <tr
                    v-for="(item, index) in obj.travelRateItems"
                    :key="item.Id"
                    :class="
                      form().childRowErrorClass(
                        thisVm(),
                        'TravelRateItems',
                        index
                      )
                    "
                  >
                    <td class="text-left">
                      {{ item.travelRateViz }}
                    </td>

                    <td class="text-right">
                      <v-btn
                        large
                        icon
                        @click="editTravelRateItem(index)"
                        class="ml-4"
                      >
                        <v-icon small>
                          $ayiEdit
                        </v-icon>
                      </v-btn>
                    </td>
                  </tr>
                </tbody>
              </template>
            </v-simple-table>
          </v-col>
          <v-col cols="12" sm="6" lg="4" xl="3">
            <v-checkbox
              v-model="obj.active"
              :readonly="formState.readOnly"
              :label="$ay.t('Active')"
              ref="active"
              data-cy="active"
              :error-messages="form().serverErrors(this, 'active')"
              @change="fieldValueChanged('active')"
            ></v-checkbox>
          </v-col>
          <v-col v-if="form().showMe(this, 'AlertNotes')" cols="12">
            <v-textarea
              v-model="obj.alertNotes"
              :readonly="formState.readOnly"
              :label="$ay.t('AlertNotes')"
              :error-messages="form().serverErrors(this, 'alertNotes')"
              ref="alertNotes"
              data-cy="alertNotes"
              @input="fieldValueChanged('alertNotes')"
              auto-grow
            ></v-textarea>
          </v-col>
          <!-- --------------------------------- -->
          <v-col v-if="form().showMe(this, 'Notes')" cols="12">
            <v-textarea
              v-model="obj.notes"
              :readonly="formState.readOnly"
              :label="$ay.t('ContractNotes')"
              :error-messages="form().serverErrors(this, 'notes')"
              ref="notes"
              data-cy="notes"
              @input="fieldValueChanged('notes')"
              auto-grow
            ></v-textarea>
          </v-col>

          <v-col v-if="form().showMe(this, 'Tags')" cols="12">
            <gz-tag-picker
              v-model="obj.tags"
              :readonly="formState.readOnly"
              ref="tags"
              data-cy="tags"
              :error-messages="form().serverErrors(this, 'tags')"
              @input="fieldValueChanged('tags')"
            ></gz-tag-picker>
          </v-col>

          <v-col cols="12">
            <gz-custom-fields
              v-model="obj.customFields"
              :form-key="formCustomTemplateKey"
              :readonly="formState.readOnly"
              :parent-v-m="this"
              ref="customFields"
              data-cy="customFields"
              :error-messages="form().serverErrors(this, 'customFields')"
              @input="fieldValueChanged('customFields')"
            ></gz-custom-fields>
          </v-col>

          <v-col v-if="form().showMe(this, 'Wiki')" cols="12">
            <gz-wiki
              :aya-type="ayaType"
              :aya-id="obj.id"
              ref="wiki"
              v-model="obj.wiki"
              :readonly="formState.readOnly"
              @input="fieldValueChanged('wiki')"
            ></gz-wiki
          ></v-col>

          <v-col v-if="form().showMe(this, 'Attachments') && obj.id" cols="12">
            <gz-attachments
              :readonly="formState.readOnly"
              :aya-type="ayaType"
              :aya-id="obj.id"
            ></gz-attachments
          ></v-col>
        </v-row>
      </v-form>
    </div>
    <template v-if="!formState.ready">
      <v-progress-circular
        indeterminate
        color="primary"
        :size="60"
      ></v-progress-circular>
    </template>
    <!-- #################################################################################################-->
    <!-- ########################## CONTRACT PART OVERRIDE ITEM EDIT FORM  ###############################-->
    <!-- #################################################################################################-->
    <template
      v-if="
        obj.contractPartOverrideItems.length &&
          editContractPartOverrideItemIndex != -1
      "
    >
      <v-row justify="center">
        <v-dialog v-model="editContractPartOverrideItemDialog">
          <v-card>
            <v-card-title> </v-card-title>
            <v-card-text>
              <v-row>
                <v-col cols="12" sm="6" lg="4" xl="3">
                  <gz-percent
                    v-model="
                      obj.contractPartOverrideItems[
                        editContractPartOverrideItemIndex
                      ].overridePct
                    "
                    :readonly="formState.readOnly"
                    :label="$ay.t('ContractAdjustment')"
                    ref="ContractPartOverrideItems.OverridePct"
                    data-cy="ContractPartOverrideItems.OverridePct"
                    :rules="[
                      form().decimalValid(
                        this,
                        'ContractPartOverrideItems.OverridePct'
                      ),
                      form().required(
                        this,
                        'ContractPartOverrideItems.OverridePct'
                      )
                    ]"
                    :error-messages="
                      form().serverErrors(
                        this,
                        `ContractPartOverrideItems[${editContractPartOverrideItemIndex}].OverridePct`
                      )
                    "
                    @input="
                      fieldValueChanged(
                        `ContractPartOverrideItems[${editContractPartOverrideItemIndex}].OverridePct`
                      )
                    "
                  ></gz-percent>
                </v-col>
                <v-col cols="12" sm="6" lg="4" xl="3">
                  <v-select
                    v-model="
                      obj.contractPartOverrideItems[
                        editContractPartOverrideItemIndex
                      ].overrideType
                    "
                    :items="selectLists.overrideTypes"
                    item-text="name"
                    item-value="id"
                    :readonly="formState.readOnly"
                    :label="$ay.t('ContractOverrideType')"
                    ref="ContractPartOverrideItems.OverrideType"
                    data-cy="ContractPartOverrideItems.OverrideType"
                    :rules="[
                      form().integerValid(
                        this,
                        'ContractPartOverrideItems.OverrideType'
                      )
                    ]"
                    :error-messages="
                      form().serverErrors(
                        this,
                        `ContractPartOverrideItems[${editContractPartOverrideItemIndex}].OverrideType`
                      )
                    "
                    @input="
                      fieldValueChanged(
                        `ContractPartOverrideItems[${editContractPartOverrideItemIndex}].OverrideType`
                      )
                    "
                  ></v-select>
                </v-col>

                <v-col cols="12" sm="6" lg="4" xl="3">
                  <gz-tag-picker
                    v-model="
                      obj.contractPartOverrideItems[
                        editContractPartOverrideItemIndex
                      ].tags
                    "
                    :readonly="formState.readOnly"
                    ref="ContractPartOverrideItems.Tags"
                    data-cy="ContractPartOverrideItems.Tags"
                    :rules="[
                      form().required(this, 'ContractPartOverrideItems.Tags')
                    ]"
                    :error-messages="
                      form().serverErrors(
                        this,
                        `ContractPartOverrideItems[${editContractPartOverrideItemIndex}].Tags`
                      )
                    "
                    @input="
                      fieldValueChanged(
                        `ContractPartOverrideItems[${editContractPartOverrideItemIndex}].Tags`
                      )
                    "
                  ></gz-tag-picker>
                </v-col>
              </v-row>
            </v-card-text>
            <v-card-actions>
              <template v-if="!$vuetify.breakpoint.xs">
                <v-btn
                  color="red darken-1"
                  text
                  @click="deleteContractPartOverrideItem()"
                  >{{ $ay.t("Delete") }}</v-btn
                >
                <v-spacer></v-spacer>

                <v-btn
                  color="blue darken-1"
                  text
                  @click="addContractPartOverrideItem()"
                  class="ml-4"
                  >{{ $ay.t("New") }}</v-btn
                >

                <v-btn
                  color="blue darken-1"
                  text
                  @click="editContractPartOverrideItemDialog = false"
                  class="ml-4"
                  >{{ $ay.t("OK") }}</v-btn
                >
              </template>
              <template v-else>
                <!-- MOBILE FORMAT -->
                <v-row>
                  <v-btn
                    class="mt-4"
                    block
                    text
                    color="blue darken-1"
                    @click="editContractPartOverrideItemDialog = false"
                    >{{ $ay.t("OK") }}</v-btn
                  >
                  <v-btn
                    class="mt-4"
                    block
                    text
                    color="blue darken-1"
                    @click="addContractPartOverrideItem()"
                    >{{ $ay.t("New") }}</v-btn
                  >

                  <v-btn
                    class="mt-8 mb-6"
                    block
                    text
                    color="red darken-1"
                    @click="deleteContractPartOverrideItem()"
                    >{{ $ay.t("Delete") }}</v-btn
                  >
                </v-row>
              </template>
            </v-card-actions>
          </v-card>
        </v-dialog>
      </v-row>
    </template>

    <!-- #########################################################################################################-->
    <!-- ########################## CONTRACT SERVICE RATE OVERRIDE ITEM EDIT FORM  ###############################-->
    <!-- #########################################################################################################-->
    <template
      v-if="
        obj.contractServiceRateOverrideItems.length &&
          editContractServiceRateOverrideItemIndex != -1
      "
    >
      <v-row justify="center">
        <v-dialog v-model="editContractServiceRateOverrideItemDialog">
          <v-card>
            <v-card-title> </v-card-title>
            <v-card-text>
              <v-row>
                <v-col cols="12" sm="6" lg="4" xl="3">
                  <gz-percent
                    v-model="
                      obj.contractServiceRateOverrideItems[
                        editContractServiceRateOverrideItemIndex
                      ].overridePct
                    "
                    :readonly="formState.readOnly"
                    :label="$ay.t('ContractAdjustment')"
                    ref="ContractServiceRateOverrideItems.OverridePct"
                    data-cy="ContractServiceRateOverrideItems.OverridePct"
                    :rules="[
                      form().decimalValid(
                        this,
                        'ContractServiceRateOverrideItems.OverridePct'
                      ),
                      form().required(
                        this,
                        'ContractServiceRateOverrideItems.OverridePct'
                      )
                    ]"
                    :error-messages="
                      form().serverErrors(
                        this,
                        `ContractServiceRateOverrideItems[${editContractServiceRateOverrideItemIndex}].OverridePct`
                      )
                    "
                    @input="
                      fieldValueChanged(
                        `ContractServiceRateOverrideItems[${editContractServiceRateOverrideItemIndex}].OverridePct`
                      )
                    "
                  ></gz-percent>
                </v-col>
                <v-col cols="12" sm="6" lg="4" xl="3">
                  <v-select
                    v-model="
                      obj.contractServiceRateOverrideItems[
                        editContractServiceRateOverrideItemIndex
                      ].overrideType
                    "
                    :items="selectLists.overrideTypes"
                    item-text="name"
                    item-value="id"
                    :readonly="formState.readOnly"
                    :label="$ay.t('ContractOverrideType')"
                    ref="ContractServiceRateOverrideItems.OverrideType"
                    data-cy="ContractServiceRateOverrideItems.OverrideType"
                    :rules="[
                      form().integerValid(
                        this,
                        'ContractServiceRateOverrideItems.OverrideType'
                      )
                    ]"
                    :error-messages="
                      form().serverErrors(
                        this,
                        `ContractServiceRateOverrideItems[${editContractServiceRateOverrideItemIndex}].OverrideType`
                      )
                    "
                    @input="
                      fieldValueChanged(
                        `ContractServiceRateOverrideItems[${editContractServiceRateOverrideItemIndex}].OverrideType`
                      )
                    "
                  ></v-select>
                </v-col>

                <v-col cols="12" sm="6" lg="4" xl="3">
                  <gz-tag-picker
                    v-model="
                      obj.contractServiceRateOverrideItems[
                        editContractServiceRateOverrideItemIndex
                      ].tags
                    "
                    :readonly="formState.readOnly"
                    ref="ContractServiceRateOverrideItems.Tags"
                    data-cy="ContractServiceRateOverrideItems.Tags"
                    :rules="[
                      form().required(
                        this,
                        'ContractServiceRateOverrideItems.Tags'
                      )
                    ]"
                    :error-messages="
                      form().serverErrors(
                        this,
                        `ContractServiceRateOverrideItems[${editContractServiceRateOverrideItemIndex}].Tags`
                      )
                    "
                    @input="
                      fieldValueChanged(
                        `ContractServiceRateOverrideItems[${editContractServiceRateOverrideItemIndex}].Tags`
                      )
                    "
                  ></gz-tag-picker>
                </v-col>
              </v-row>
            </v-card-text>
            <v-card-actions>
              <template v-if="!$vuetify.breakpoint.xs">
                <v-btn
                  color="red darken-1"
                  text
                  @click="deleteContractServiceRateOverrideItem()"
                  >{{ $ay.t("Delete") }}</v-btn
                >
                <v-spacer></v-spacer>

                <v-btn
                  color="blue darken-1"
                  text
                  @click="addContractServiceRateOverrideItem()"
                  class="ml-4"
                  >{{ $ay.t("New") }}</v-btn
                >

                <v-btn
                  color="blue darken-1"
                  text
                  @click="editContractServiceRateOverrideItemDialog = false"
                  class="ml-4"
                  >{{ $ay.t("OK") }}</v-btn
                >
              </template>
              <template v-else>
                <!-- MOBILE FORMAT -->
                <v-row>
                  <v-btn
                    class="mt-4"
                    block
                    text
                    color="blue darken-1"
                    @click="editContractServiceRateOverrideItemDialog = false"
                    >{{ $ay.t("OK") }}</v-btn
                  >
                  <v-btn
                    class="mt-4"
                    block
                    text
                    color="blue darken-1"
                    @click="addContractServiceRateOverrideItem()"
                    >{{ $ay.t("New") }}</v-btn
                  >

                  <v-btn
                    class="mt-8 mb-6"
                    block
                    text
                    color="red darken-1"
                    @click="deleteContractServiceRateOverrideItem()"
                    >{{ $ay.t("Delete") }}</v-btn
                  >
                </v-row>
              </template>
            </v-card-actions>
          </v-card>
        </v-dialog>
      </v-row>
    </template>

    <!-- ########################################################################################################-->
    <!-- ########################## CONTRACT TRAVEL RATE OVERRIDE ITEM EDIT FORM  ###############################-->
    <!-- ########################################################################################################-->
    <template
      v-if="
        obj.contractTravelRateOverrideItems.length &&
          editContractTravelRateOverrideItemIndex != -1
      "
    >
      <v-row justify="center">
        <v-dialog v-model="editContractTravelRateOverrideItemDialog">
          <v-card>
            <v-card-title> </v-card-title>
            <v-card-text>
              <v-row>
                <v-col cols="12" sm="6" lg="4" xl="3">
                  <gz-percent
                    v-model="
                      obj.contractTravelRateOverrideItems[
                        editContractTravelRateOverrideItemIndex
                      ].overridePct
                    "
                    :readonly="formState.readOnly"
                    :label="$ay.t('ContractAdjustment')"
                    ref="ContractTravelRateOverrideItems.OverridePct"
                    data-cy="ContractTravelRateOverrideItems.OverridePct"
                    :rules="[
                      form().decimalValid(
                        this,
                        'ContractTravelRateOverrideItems.OverridePct'
                      ),
                      form().required(
                        this,
                        'ContractTravelRateOverrideItems.OverridePct'
                      )
                    ]"
                    :error-messages="
                      form().serverErrors(
                        this,
                        `ContractTravelRateOverrideItems[${editContractTravelRateOverrideItemIndex}].OverridePct`
                      )
                    "
                    @input="
                      fieldValueChanged(
                        `ContractTravelRateOverrideItems[${editContractTravelRateOverrideItemIndex}].OverridePct`
                      )
                    "
                  ></gz-percent>
                </v-col>
                <v-col cols="12" sm="6" lg="4" xl="3">
                  <v-select
                    v-model="
                      obj.contractTravelRateOverrideItems[
                        editContractTravelRateOverrideItemIndex
                      ].overrideType
                    "
                    :items="selectLists.overrideTypes"
                    item-text="name"
                    item-value="id"
                    :readonly="formState.readOnly"
                    :label="$ay.t('ContractOverrideType')"
                    ref="ContractTravelRateOverrideItems.OverrideType"
                    data-cy="ContractTravelRateOverrideItems.OverrideType"
                    :rules="[
                      form().integerValid(
                        this,
                        'ContractTravelRateOverrideItems.OverrideType'
                      )
                    ]"
                    :error-messages="
                      form().serverErrors(
                        this,
                        `ContractTravelRateOverrideItems[${editContractTravelRateOverrideItemIndex}].OverrideType`
                      )
                    "
                    @input="
                      fieldValueChanged(
                        `ContractTravelRateOverrideItems[${editContractTravelRateOverrideItemIndex}].OverrideType`
                      )
                    "
                  ></v-select>
                </v-col>

                <v-col cols="12" sm="6" lg="4" xl="3">
                  <gz-tag-picker
                    v-model="
                      obj.contractTravelRateOverrideItems[
                        editContractTravelRateOverrideItemIndex
                      ].tags
                    "
                    :readonly="formState.readOnly"
                    ref="ContractTravelRateOverrideItems.Tags"
                    data-cy="ContractTravelRateOverrideItems.Tags"
                    :rules="[
                      form().required(
                        this,
                        'ContractTravelRateOverrideItems.Tags'
                      )
                    ]"
                    :error-messages="
                      form().serverErrors(
                        this,
                        `ContractTravelRateOverrideItems[${editContractTravelRateOverrideItemIndex}].Tags`
                      )
                    "
                    @input="
                      fieldValueChanged(
                        `ContractTravelRateOverrideItems[${editContractTravelRateOverrideItemIndex}].Tags`
                      )
                    "
                  ></gz-tag-picker>
                </v-col>
              </v-row>
            </v-card-text>
            <v-card-actions>
              <template v-if="!$vuetify.breakpoint.xs">
                <v-btn
                  color="red darken-1"
                  text
                  @click="deleteContractTravelRateOverrideItem()"
                  >{{ $ay.t("Delete") }}</v-btn
                >
                <v-spacer></v-spacer>

                <v-btn
                  color="blue darken-1"
                  text
                  @click="addContractTravelRateOverrideItem()"
                  class="ml-4"
                  >{{ $ay.t("New") }}</v-btn
                >

                <v-btn
                  color="blue darken-1"
                  text
                  @click="editContractTravelRateOverrideItemDialog = false"
                  class="ml-4"
                  >{{ $ay.t("OK") }}</v-btn
                >
              </template>
              <template v-else>
                <!-- MOBILE FORMAT -->
                <v-row>
                  <v-btn
                    class="mt-4"
                    block
                    text
                    color="blue darken-1"
                    @click="editContractTravelRateOverrideItemDialog = false"
                    >{{ $ay.t("OK") }}</v-btn
                  >
                  <v-btn
                    class="mt-4"
                    block
                    text
                    color="blue darken-1"
                    @click="addContractTravelRateOverrideItem()"
                    >{{ $ay.t("New") }}</v-btn
                  >

                  <v-btn
                    class="mt-8 mb-6"
                    block
                    text
                    color="red darken-1"
                    @click="deleteContractTravelRateOverrideItem()"
                    >{{ $ay.t("Delete") }}</v-btn
                  >
                </v-row>
              </template>
            </v-card-actions>
          </v-card>
        </v-dialog>
      </v-row>
    </template>

    <!-- #########################################################################################################-->
    <!-- ########################## SERVICE RATE ITEM EDIT FORM  ###############################-->
    <!-- #########################################################################################################-->
    <template
      v-if="obj.serviceRateItems.length && editServiceRateItemIndex != -1"
    >
      <v-row justify="center">
        <v-dialog v-model="editServiceRateItemDialog">
          <v-card>
            <v-card-title> </v-card-title>
            <v-card-text>
              <v-row>
                <v-col cols="12" sm="6" lg="4" xl="3">
                  <gz-pick-list
                    :allow-no-selection="false"
                    :can-clear="false"
                    :aya-type="ayaTypes().ServiceRate"
                    :variant="'contractrates'"
                    :show-edit-icon="true"
                    v-model="
                      obj.serviceRateItems[editServiceRateItemIndex]
                        .serviceRateId
                    "
                    :readonly="formState.readOnly"
                    :label="$ay.t('ServiceRate')"
                    ref="userid"
                    data-cy="userid"
                    :rules="[
                      form().integerValid(
                        this,
                        'ServiceRateItems.ServiceRateId'
                      ),
                      form().required(this, 'ServiceRateItems.ServiceRateId')
                    ]"
                    :error-messages="
                      form().serverErrors(
                        this,
                        `ServiceRateItems[${editServiceRateItemIndex}].ServiceRateId`
                      )
                    "
                    @input="
                      fieldValueChanged(
                        `ServiceRateItems[${editServiceRateItemIndex}].ServiceRateId`
                      )
                    "
                    :name.sync="
                      obj.serviceRateItems[editServiceRateItemIndex]
                        .serviceRateViz
                    "
                  ></gz-pick-list>
                </v-col>
              </v-row>
            </v-card-text>
            <v-card-actions>
              <template v-if="!$vuetify.breakpoint.xs">
                <v-btn
                  color="red darken-1"
                  text
                  @click="deleteServiceRateItem()"
                  >{{ $ay.t("Delete") }}</v-btn
                >
                <v-spacer></v-spacer>

                <v-btn
                  color="blue darken-1"
                  text
                  @click="addServiceRateItem()"
                  class="ml-4"
                  >{{ $ay.t("New") }}</v-btn
                >

                <v-btn
                  color="blue darken-1"
                  text
                  @click="editServiceRateItemDialog = false"
                  class="ml-4"
                  >{{ $ay.t("OK") }}</v-btn
                >
              </template>
              <template v-else>
                <!-- MOBILE FORMAT -->
                <v-row>
                  <v-btn
                    class="mt-4"
                    block
                    text
                    color="blue darken-1"
                    @click="editServiceRateItemDialog = false"
                    >{{ $ay.t("OK") }}</v-btn
                  >
                  <v-btn
                    class="mt-4"
                    block
                    text
                    color="blue darken-1"
                    @click="addServiceRateItem()"
                    >{{ $ay.t("New") }}</v-btn
                  >

                  <v-btn
                    class="mt-8 mb-6"
                    block
                    text
                    color="red darken-1"
                    @click="deleteServiceRateItem()"
                    >{{ $ay.t("Delete") }}</v-btn
                  >
                </v-row>
              </template>
            </v-card-actions>
          </v-card>
        </v-dialog>
      </v-row>
    </template>

    <!-- #########################################################################################################-->
    <!-- ########################## TRAVEL RATE ITEM EDIT FORM  ###############################-->
    <!-- #########################################################################################################-->
    <template
      v-if="obj.travelRateItems.length && editTravelRateItemIndex != -1"
    >
      <v-row justify="center">
        <v-dialog v-model="editTravelRateItemDialog">
          <v-card>
            <v-card-title> </v-card-title>
            <v-card-text>
              <v-row>
                <v-col cols="12" sm="6" lg="4" xl="3">
                  <gz-pick-list
                    :allow-no-selection="false"
                    :can-clear="false"
                    :aya-type="ayaTypes().TravelRate"
                    :variant="'contractrates'"
                    :show-edit-icon="true"
                    v-model="
                      obj.travelRateItems[editTravelRateItemIndex].travelRateId
                    "
                    :readonly="formState.readOnly"
                    :label="$ay.t('TravelRate')"
                    ref="userid"
                    data-cy="userid"
                    :rules="[
                      form().integerValid(this, 'TravelRateItems.TravelRateId'),
                      form().required(this, 'TravelRateItems.TravelRateId')
                    ]"
                    :error-messages="
                      form().serverErrors(
                        this,
                        `TravelRateItems[${editTravelRateItemIndex}].TravelRateId`
                      )
                    "
                    @input="
                      fieldValueChanged(
                        `TravelRateItems[${editTravelRateItemIndex}].TravelRateId`
                      )
                    "
                    :name.sync="
                      obj.travelRateItems[editTravelRateItemIndex].travelRateViz
                    "
                  ></gz-pick-list>
                </v-col>
              </v-row>
            </v-card-text>
            <v-card-actions>
              <template v-if="!$vuetify.breakpoint.xs">
                <v-btn
                  color="red darken-1"
                  text
                  @click="deleteTravelRateItem()"
                  >{{ $ay.t("Delete") }}</v-btn
                >
                <v-spacer></v-spacer>

                <v-btn
                  color="blue darken-1"
                  text
                  @click="addTravelRateItem()"
                  class="ml-4"
                  >{{ $ay.t("New") }}</v-btn
                >

                <v-btn
                  color="blue darken-1"
                  text
                  @click="editTravelRateItemDialog = false"
                  class="ml-4"
                  >{{ $ay.t("OK") }}</v-btn
                >
              </template>
              <template v-else>
                <!-- MOBILE FORMAT -->
                <v-row>
                  <v-btn
                    class="mt-4"
                    block
                    text
                    color="blue darken-1"
                    @click="editTravelRateItemDialog = false"
                    >{{ $ay.t("OK") }}</v-btn
                  >
                  <v-btn
                    class="mt-4"
                    block
                    text
                    color="blue darken-1"
                    @click="addTravelRateItem()"
                    >{{ $ay.t("New") }}</v-btn
                  >

                  <v-btn
                    class="mt-8 mb-6"
                    block
                    text
                    color="red darken-1"
                    @click="deleteTravelRateItem()"
                    >{{ $ay.t("Delete") }}</v-btn
                  >
                </v-row>
              </template>
            </v-card-actions>
          </v-card>
        </v-dialog>
      </v-row>
    </template>
  </div>
</template>

<script>
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*  Xeslint-disable    */
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
const FORM_KEY = "contract-edit";
const API_BASE_URL = "contract/";
const FORM_CUSTOM_TEMPLATE_KEY = "Contract"; //<-- Should always be CoreBizObject AyaType name here where possible

export default {
  async created() {
    let vm = this;

    try {
      await initForm(vm);

      vm.rights = window.$gz.role.getRights(window.$gz.type.Contract);
      vm.formState.readOnly = !vm.rights.change;
      window.$gz.eventBus.$on("menu-click", clickHandler);

      let setDirty = false;
      let setValid = true;

      //id 0 means create or duplicate to new
      if (vm.$route.params.recordid != 0) {
        //is there already an obj from a prior operation?
        if (this.$route.params.obj) {
          //yes, no need to fetch it
          this.obj = this.$route.params.obj;
        } else {
          await vm.getDataFromApi(vm.$route.params.recordid); //let getdata handle loading
        }
      } else {
        //Might be a duplicate and contain another record
        if (this.$route.params.obj) {
          this.obj = this.$route.params.obj;
          this.obj.concurrency = undefined;
          this.obj.id = 0;
          this.obj.name = `${this.obj.name} - ${window.$gz.translation.get(
            "Copy"
          )}`;
          this.obj.serviceRateItems.forEach(z => (z.id = 0));
          this.obj.travelRateItems.forEach(z => (z.id = 0));
          this.obj.contractPartOverrideItems.forEach(z => (z.id = 0));
          this.obj.contractServiceRateOverrideItems.forEach(z => (z.id = 0));
          this.obj.contractTravelRateOverrideItems.forEach(z => (z.id = 0));

          setDirty = true;
        }
      }

      window.$gz.form.setFormState({
        vm: vm,
        loading: false,
        dirty: setDirty,
        valid: setValid
      });

      generateMenu(vm);
    } catch (error) {
      window.$gz.errorHandler.handleFormError(error, vm);
    } finally {
      vm.formState.ready = true;
    }
  },
  async beforeRouteLeave(to, from, next) {
    if (!this.formState.dirty || JUST_DELETED) {
      next();
      return;
    }
    if ((await window.$gz.dialog.confirmLeaveUnsaved()) === true) {
      next();
    } else {
      next(false);
    }
  },
  beforeDestroy() {
    window.$gz.eventBus.$off("menu-click", clickHandler);
  },
  data() {
    return {
      formCustomTemplateKey: FORM_CUSTOM_TEMPLATE_KEY,
      obj:
        //IMPORTANT NOTE: Fields that are NON NULLABLE in the schema for the table but *are* hideable **MUST** have a default value set here or else there will be no way to save the record
        //I.E. Serial, usertype fields, ACTIVE
        //Also, if it's a non-nullable Enum backed field then it should have a valid selection i.e. not zero if there is no zero
        {
          id: 0,
          concurrency: 0,
          name: null,
          active: true,
          notes: null,
          wiki: null,
          customFields: "{}",
          tags: [],
          responseTime: "00:00:00",
          contractServiceRatesOnly: false,
          contractTravelRatesOnly: false,
          partsOverridePct: 0,
          partsOverrideType: 1,
          serviceRatesOverridePct: 0,
          serviceRatesOverrideType: 1,
          travelRatesOverridePct: 0,
          travelRatesOverrideType: 1,
          alertNotes: null,
          serviceRateItems: [],
          travelRateItems: [],
          contractPartOverrideItems: [],
          contractTravelRateOverrideItems: [],
          contractServiceRateOverrideItems: []
        },
      formState: {
        ready: false,
        dirty: false,
        valid: true,
        readOnly: false,
        loading: true,
        errorBoxMessage: null,
        appError: null,
        serverError: {}
      },
      rights: window.$gz.role.defaultRightsObject(),
      ayaType: window.$gz.type.Contract,
      selectLists: {
        overrideTypes: []
      },
      editContractPartOverrideItemDialog: false,
      editContractPartOverrideItemIndex: 0,
      editContractServiceRateOverrideItemDialog: false,
      editContractServiceRateOverrideItemIndex: 0,
      editContractTravelRateOverrideItemDialog: false,
      editContractTravelRateOverrideItemIndex: 0,
      editServiceRateItemDialog: false,
      editServiceRateItemIndex: 0,
      editTravelRateItemDialog: false,
      editTravelRateItemIndex: 0
    };
  },
  //WATCHERS
  watch: {
    formState: {
      handler: function(val) {
        //,oldval is available here too if necessary
        if (this.formState.loading) {
          return;
        }

        //enable / disable save button
        if (val.dirty && val.valid && !val.readOnly) {
          window.$gz.eventBus.$emit("menu-enable-item", FORM_KEY + ":save");
        } else {
          window.$gz.eventBus.$emit("menu-disable-item", FORM_KEY + ":save");
        }

        //enable / disable duplicate / new button
        if (!val.dirty && val.valid && !val.readOnly) {
          window.$gz.eventBus.$emit(
            "menu-enable-item",
            FORM_KEY + ":duplicate"
          );
          window.$gz.eventBus.$emit("menu-enable-item", FORM_KEY + ":new");
        } else {
          window.$gz.eventBus.$emit(
            "menu-disable-item",
            FORM_KEY + ":duplicate"
          );
          window.$gz.eventBus.$emit("menu-disable-item", FORM_KEY + ":new");
        }
      },
      deep: true
    }
  },
  methods: {
    editContractPartOverrideItem: function(index) {
      this.editContractPartOverrideItemIndex = index;
      if (this.editContractPartOverrideItemIndex != -1) {
        this.editContractPartOverrideItemDialog = true;
      }
    },
    addContractPartOverrideItem: function() {
      this.obj.contractPartOverrideItems.push({
        id: 0,
        contractId: 0,
        overridePct: 0,
        overrideType: 1,
        tags: []
      });

      this.editContractPartOverrideItemIndex =
        this.obj.contractPartOverrideItems.length - 1;
      this.editContractPartOverrideItemDialog = true;
      this.formState.dirty = true;
    },
    deleteContractPartOverrideItem: function() {
      this.editContractPartOverrideItemDialog = false;
      this.obj.contractPartOverrideItems.splice(
        this.editContractPartOverrideItemIndex,
        1
      );
      this.editContractPartOverrideItemIndex = -1;
      this.formState.dirty = true;
    },

    editContractServiceRateOverrideItem: function(index) {
      this.editContractServiceRateOverrideItemIndex = index;
      if (this.editContractServiceRateOverrideItemIndex != -1) {
        this.editContractServiceRateOverrideItemDialog = true;
      }
    },
    addContractServiceRateOverrideItem: function() {
      this.obj.contractServiceRateOverrideItems.push({
        id: 0,
        contractId: 0,
        overridePct: 0,
        overrideType: 1,
        tags: []
      });

      this.editContractServiceRateOverrideItemIndex =
        this.obj.contractServiceRateOverrideItems.length - 1;
      this.editContractServiceRateOverrideItemDialog = true;
      this.formState.dirty = true;
    },
    deleteContractServiceRateOverrideItem: function() {
      this.editContractServiceRateOverrideItemDialog = false;
      this.obj.contractServiceRateOverrideItems.splice(
        this.editContractServiceRateOverrideItemIndex,
        1
      );
      this.editContractServiceRateOverrideItemIndex = -1;
      this.formState.dirty = true;
    },

    editContractTravelRateOverrideItem: function(index) {
      this.editContractTravelRateOverrideItemIndex = index;
      if (this.editContractTravelRateOverrideItemIndex != -1) {
        this.editContractTravelRateOverrideItemDialog = true;
      }
    },
    addContractTravelRateOverrideItem: function() {
      this.obj.contractTravelRateOverrideItems.push({
        id: 0,
        contractId: 0,
        overridePct: 0,
        overrideType: 1,
        tags: []
      });

      this.editContractTravelRateOverrideItemIndex =
        this.obj.contractTravelRateOverrideItems.length - 1;
      this.editContractTravelRateOverrideItemDialog = true;
      this.formState.dirty = true;
    },
    deleteContractTravelRateOverrideItem: function() {
      this.editContractTravelRateOverrideItemDialog = false;
      this.obj.contractTravelRateOverrideItems.splice(
        this.editContractTravelRateOverrideItemIndex,
        1
      );
      this.editContractTravelRateOverrideItemIndex = -1;
      this.formState.dirty = true;
    },
    addServiceRateItem: function() {
      this.editServiceRateItemIndex =
        this.obj.serviceRateItems.push({
          id: 0,
          contractId: this.obj.id,
          serviceRateId: null
        }) - 1;

      this.editServiceRateItemDialog = true;
      this.formState.dirty = true;
    },
    editServiceRateItem: function(index) {
      this.editServiceRateItemIndex = index;
      this.editServiceRateItemDialog = true;
    },
    deleteServiceRateItem: function() {
      this.editServiceRateItemDialog = false;
      this.obj.serviceRateItems.splice(this.editServiceRateItemIndex, 1);
      this.editServiceRateItemIndex = -1;
      this.formState.dirty = true;
    },
    addTravelRateItem: function() {
      this.editTravelRateItemIndex =
        this.obj.travelRateItems.push({
          id: 0,
          contractId: this.obj.id,
          travelRateId: null
        }) - 1;

      this.editTravelRateItemDialog = true;
      this.formState.dirty = true;
    },
    editTravelRateItem: function(index) {
      this.editTravelRateItemIndex = index;
      this.editTravelRateItemDialog = true;
    },
    deleteTravelRateItem: function() {
      this.editTravelRateItemDialog = false;
      this.obj.travelRateItems.splice(this.editTravelRateItemIndex, 1);
      this.editTravelRateItemIndex = -1;
      this.formState.dirty = true;
    },

    canSave: function() {
      return this.formState.valid && this.formState.dirty;
    },
    canDuplicate: function() {
      return this.formState.valid && !this.formState.dirty;
    },
    ayaTypes: function() {
      return window.$gz.type;
    },
    form() {
      return window.$gz.form;
    },
    thisVm() {
      return this;
    },
    fieldValueChanged(ref) {
      if (
        this.formState.ready &&
        !this.formState.loading &&
        !this.formState.readOnly
      ) {
        window.$gz.form.fieldValueChanged(this, ref);
      }
    },
    async getDataFromApi(recordId) {
      let vm = this;
      window.$gz.form.setFormState({
        vm: vm,
        loading: true
      });
      if (!recordId) {
        throw new Error(FORM_KEY + "::getDataFromApi -> Missing recordID!");
      }
      let url = API_BASE_URL + recordId;
      try {
        window.$gz.form.deleteAllErrorBoxErrors(vm);

        let res = await window.$gz.api.get(url);

        if (res.error) {
          //Not found?
          if (res.error.code == "2010") {
            window.$gz.form.handleObjectNotFound(vm);
          }
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        } else {
          vm.obj = res.data;
          //modify the menu as necessary
          generateMenu(vm);
          //Update the form status
          window.$gz.form.setFormState({
            vm: vm,
            dirty: false,
            valid: true,
            loading: false
          });
        }
      } catch (error) {
        window.$gz.errorHandler.handleFormError(error, vm);
      } finally {
        window.$gz.form.setFormState({
          vm: vm,
          loading: false
        });
      }
    },
    async submit() {
      let vm = this;
      if (vm.canSave == false) {
        return;
      }

      try {
        window.$gz.form.setFormState({
          vm: vm,
          loading: true
        });
        let url = API_BASE_URL; // + vm.$route.params.recordid;
        //clear any errors vm might be around from previous submit
        window.$gz.form.deleteAllErrorBoxErrors(vm);
        vm.editTravelRateItemIndex = -1;
        vm.editServiceRateItemIndex = -1;
        vm.editContractPartOverrideItemIndex = -1;
        vm.editContractTravelRateOverrideItemIndex = -1;
        vm.editContractServiceRateOverrideItemIndex = -1;

        let res = await window.$gz.api.upsert(url, vm.obj);

        if (res.error) {
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        } else {
          //POST or PUT - whole new object returned which is a little different than other objects
          //so if it's new then need to navigate to it to update url with id
          if (vm.$route.params.recordid != 0) {
            //update of existing record
            vm.obj = res.data;
          } else {
            this.$router.replace({
              name: "contract-edit",
              params: {
                recordid: res.data.id,
                obj: res.data // Pass data object to new form will prevent fetch
              }
            });
          }

          //Update the form status
          window.$gz.form.setFormState({
            vm: vm,
            dirty: false,
            valid: true
          });
        }
      } catch (ex) {
        window.$gz.errorHandler.handleFormError(ex, vm);
      } finally {
        window.$gz.form.setFormState({
          vm: vm,
          loading: false
        });
      }
    },
    async remove() {
      let vm = this;
      try {
        let dialogResult = await window.$gz.dialog.confirmDelete();
        if (dialogResult != true) {
          return;
        }

        //do the delete
        window.$gz.form.setFormState({
          vm: vm,
          loading: true
        });
        //No need to delete a new record, just abandon it...
        if (vm.$route.params.recordid == 0) {
          //this should not get offered for delete but to be safe and clear just in case:
          JUST_DELETED = true;
          // navigate backwards
          vm.$router.go(-1);
        } else {
          let url = API_BASE_URL + vm.$route.params.recordid;

          window.$gz.form.deleteAllErrorBoxErrors(vm);
          let res = await window.$gz.api.remove(url);
          if (res.error) {
            vm.formState.serverError = res.error;
            window.$gz.form.setErrorBoxErrors(vm);
          } else {
            //workaround to prevent warning about leaving dirty record
            //For some reason I couldn't just reset isdirty in formstate
            JUST_DELETED = true;
            // navigate backwards
            vm.$router.go(-1);
          }
        }
      } catch (error) {
        //Update the form status
        window.$gz.form.setFormState({
          vm: vm,
          loading: false
        });
        window.$gz.errorHandler.handleFormError(error, vm);
      }
    },

    duplicate() {
      //Navigate to new record
      this.$router.push({
        name: "contract-edit",
        params: {
          recordid: 0,
          obj: this.obj
        }
      });
    }

    //end methods
  }
};

/////////////////////////////
//
//
async function clickHandler(menuItem) {
  if (!menuItem) {
    return;
  }
  let m = window.$gz.menu.parseMenuItem(menuItem);
  if (m.owner == FORM_KEY && !m.disabled) {
    switch (m.key) {
      case "save":
        m.vm.submit();
        break;
      case "delete":
        m.vm.remove();
        break;
      case "new":
        m.vm.$router.push({
          name: "contract-edit",
          params: { recordid: 0 }
        });
        break;
      case "duplicate":
        m.vm.duplicate();
        break;
      case "report":
        if (m.id != null) {
          //last report selected is in m.id
          m.vm.$router.push({
            name: "ay-report",
            params: { recordid: m.id, ayatype: window.$gz.type.Contract }
          });
        } else {
          //general report selector chosen

          let res = await m.vm.$refs.reportSelector.open({
            AType: window.$gz.type.Contract,
            selectedRowIds: [m.vm.obj.id]
          });

          //if null for no selection
          //just bail out
          if (res == null) {
            return;
          }
          //persist last report selected
          window.$gz.form.setLastReport(FORM_KEY, res);

          //Now open the report viewer...
          m.vm.$router.push({
            name: "ay-report",
            params: { recordid: res.id, ayatype: window.$gz.type.Contract }
          });
        }
        break;

      default:
        window.$gz.eventBus.$emit(
          "notify-warning",
          FORM_KEY + "::context click: [" + m.key + "]"
        );
    }
  }
}

//////////////////////
//
//
function generateMenu(vm) {
  let menuOptions = {
    isMain: false,
    readOnly: vm.formState.readOnly,
    icon: "$ayiFileContract",
    title: "Contract",
    helpUrl: "svc-contracts",
    formData: {
      ayaType: window.$gz.type.Contract,
      recordId: vm.$route.params.recordid,
      formCustomTemplateKey: FORM_CUSTOM_TEMPLATE_KEY,
      recordName: vm.obj.name
    },
    menuItems: []
  };

  if (vm.rights.change) {
    menuOptions.menuItems.push({
      title: "Save",
      icon: "$ayiSave",
      surface: true,
      key: FORM_KEY + ":save",
      vm: vm
    });
  }

  if (vm.rights.delete && vm.$route.params.recordid != 0) {
    menuOptions.menuItems.push({
      title: "Delete",
      icon: "$ayiTrashAlt",
      surface: false,
      key: FORM_KEY + ":delete",
      vm: vm
    });
  }

  //REPORTS
  //Report not Print, print is a further option
  menuOptions.menuItems.push({
    title: "Report",
    icon: "$ayiFileAlt",
    key: FORM_KEY + ":report",
    vm: vm
  });

  //get last report selected
  let lastReport = window.$gz.form.getLastReport(FORM_KEY);
  if (lastReport != null) {
    menuOptions.menuItems.push({
      title: lastReport.name,
      icon: "$ayiFileAlt",
      key: FORM_KEY + ":report:" + lastReport.id,
      vm: vm
    });
  }

  if (vm.rights.change) {
    menuOptions.menuItems.push({
      title: "New",
      icon: "$ayiPlus",
      key: FORM_KEY + ":new",
      vm: vm
    });
  }

  if (vm.rights.change && vm.$route.params.recordid != 0) {
    menuOptions.menuItems.push({
      title: "Duplicate",
      icon: "$ayiClone",
      key: FORM_KEY + ":duplicate",
      vm: vm
    });
  }

  menuOptions.menuItems.push({ divider: true, inset: false });

  window.$gz.eventBus.$emit("menu-change", menuOptions);
}

let JUST_DELETED = false;

/////////////////////////////////
//
//
async function initForm(vm) {
  await fetchTranslatedText(vm);
  await window.$gz.formCustomTemplate.get(FORM_CUSTOM_TEMPLATE_KEY, vm);
  await populateSelectionLists(vm);
}

//////////////////////////////////////////////////////////
//
// Ensures UI translated text is available
//
async function fetchTranslatedText(vm) {
  await window.$gz.translation.cacheTranslations([
    "Contract",
    "ContractName",
    "ContractNotes",
    "AlertNotes",
    "ContractDefaultAdjustments",
    "ContractTaggedAdjustments",
    "ContractOverrideType",
    "ContractAdjustment",
    "ContractDefaultResponseTime",
    "PartList",
    "ServiceRateList",
    "TravelRateList",
    "ServiceRate",
    "TravelRate",
    "ContractRateList",
    "ContractServiceRatesOnly",
    "ContractTravelRatesOnly",
    "ContractCustom1",
    "ContractCustom2",
    "ContractCustom3",
    "ContractCustom4",
    "ContractCustom5",
    "ContractCustom6",
    "ContractCustom7",
    "ContractCustom8",
    "ContractCustom9",
    "ContractCustom10",
    "ContractCustom11",
    "ContractCustom12",
    "ContractCustom13",
    "ContractCustom14",
    "ContractCustom15",
    "ContractCustom16"
  ]);
}

//////////////////////
//
//
async function populateSelectionLists(vm) {
  //ensure the pick lists required are pre-fetched
  await window.$gz.enums.fetchEnumList("contractoverridetype");
  vm.selectLists.overrideTypes = window.$gz.enums.getSelectionList(
    "contractoverridetype"
  );
}
</script>
