<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 dense>
          <v-col cols="12" sm="6" lg="4" xl="3">
            <v-text-field
              ref="name"
              v-model="obj.name"
              dense
              :readonly="formState.readOnly"
              :label="$ay.t('ContractName')"
              :rules="[form().required(this, 'name')]"
              :error-messages="form().serverErrors(this, '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
              ref="responseTime"
              v-model="obj.responseTime"
              :readonly="formState.readOnly"
              :label="$ay.t('ContractDefaultResponseTime')"
              :show-seconds="false"
              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 dense>
              <v-col>
                <gz-percent
                  ref="partsOverridePct"
                  v-model="obj.partsOverridePct"
                  :readonly="formState.readOnly"
                  :label="$ay.t('PartList')"
                  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
                  ref="partsOverrideType"
                  v-model="obj.partsOverrideType"
                  dense
                  :items="selectLists.overrideTypes"
                  item-text="name"
                  item-value="id"
                  :readonly="formState.readOnly"
                  :label="$ay.t('ContractOverrideType')"
                  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 dense>
              <v-col>
                <gz-percent
                  ref="serviceRatesOverridePct"
                  v-model="obj.serviceRatesOverridePct"
                  :readonly="formState.readOnly"
                  :label="$ay.t('ServiceRateList')"
                  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
                  ref="serviceRatesOverrideType"
                  v-model="obj.serviceRatesOverrideType"
                  dense
                  :items="selectLists.overrideTypes"
                  item-text="name"
                  item-value="id"
                  :readonly="formState.readOnly"
                  :label="$ay.t('ContractOverrideType')"
                  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 dense>
              <v-col>
                <gz-percent
                  ref="travelRatesOverridePct"
                  v-model="obj.travelRatesOverridePct"
                  :readonly="formState.readOnly"
                  :label="$ay.t('TravelRateList')"
                  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
                  ref="travelRatesOverrideType"
                  v-model="obj.travelRatesOverrideType"
                  dense
                  :items="selectLists.overrideTypes"
                  item-text="name"
                  item-value="id"
                  :readonly="formState.readOnly"
                  :label="$ay.t('ContractOverrideType')"
                  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
                        class="ml-4"
                        @click="editContractPartOverrideItem(index)"
                      >
                        <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
                        class="ml-4"
                        @click="editContractServiceRateOverrideItem(index)"
                      >
                        <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
                        class="ml-4"
                        @click="editContractTravelRateOverrideItem(index)"
                      >
                        <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
              ref="contractServiceRatesOnly"
              v-model="obj.contractServiceRatesOnly"
              dense
              :readonly="formState.readOnly"
              :label="$ay.t('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
                        class="ml-4"
                        @click="editServiceRateItem(index)"
                      >
                        <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
              ref="contractTravelRatesOnly"
              v-model="obj.contractTravelRatesOnly"
              dense
              :readonly="formState.readOnly"
              :label="$ay.t('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
                        class="ml-4"
                        @click="editTravelRateItem(index)"
                      >
                        <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
              ref="active"
              v-model="obj.active"
              dense
              :readonly="formState.readOnly"
              :label="$ay.t('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
              ref="alertNotes"
              v-model="obj.alertNotes"
              dense
              :readonly="formState.readOnly"
              :label="$ay.t('AlertNotes')"
              :error-messages="form().serverErrors(this, 'alertNotes')"
              data-cy="alertNotes"
              auto-grow
              @input="fieldValueChanged('alertNotes')"
            ></v-textarea>
          </v-col>
          <!-- --------------------------------- -->
          <v-col v-if="form().showMe(this, 'Notes')" cols="12">
            <v-textarea
              ref="notes"
              v-model="obj.notes"
              dense
              :readonly="formState.readOnly"
              :label="$ay.t('ContractNotes')"
              :error-messages="form().serverErrors(this, 'notes')"
              data-cy="notes"
              auto-grow
              @input="fieldValueChanged('notes')"
            ></v-textarea>
          </v-col>

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

          <v-col cols="12">
            <gz-custom-fields
              ref="customFields"
              v-model="obj.customFields"
              :form-key="formCustomTemplateKey"
              :readonly="formState.readOnly"
              :parent-v-m="this"
              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
              ref="wiki"
              v-model="obj.wiki"
              :aya-type="ayaType"
              :aya-id="obj.id"
              :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>
    <v-overlay :value="!formState.ready || formState.loading">
      <v-progress-circular indeterminate :size="64" />
    </v-overlay>
    <!-- #################################################################################################-->
    <!-- ########################## CONTRACT PART OVERRIDE ITEM EDIT FORM  ###############################-->
    <!-- #################################################################################################-->
    <template
      v-if="
        obj.contractPartOverrideItems.length &&
          editContractPartOverrideItemIndex != -1
      "
    >
      <v-row dense justify="center">
        <v-dialog
          v-model="editContractPartOverrideItemDialog"
          max-width="800px"
        >
          <v-card>
            <v-card-title> </v-card-title>
            <v-card-text>
              <v-row dense>
                <v-col>
                  <gz-percent
                    ref="ContractPartOverrideItems.OverridePct"
                    v-model="
                      obj.contractPartOverrideItems[
                        editContractPartOverrideItemIndex
                      ].overridePct
                    "
                    :readonly="formState.readOnly"
                    :label="$ay.t('ContractAdjustment')"
                    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-select
                    ref="ContractPartOverrideItems.OverrideType"
                    v-model="
                      obj.contractPartOverrideItems[
                        editContractPartOverrideItemIndex
                      ].overrideType
                    "
                    dense
                    :items="selectLists.overrideTypes"
                    item-text="name"
                    item-value="id"
                    :readonly="formState.readOnly"
                    :label="$ay.t('ContractOverrideType')"
                    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>

                  <gz-tag-picker
                    ref="ContractPartOverrideItems.Tags"
                    v-model="
                      obj.contractPartOverrideItems[
                        editContractPartOverrideItemIndex
                      ].tags
                    "
                    :readonly="formState.readOnly"
                    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
                  class="ml-4"
                  @click="addContractPartOverrideItem()"
                  >{{ $ay.t("New") }}</v-btn
                >

                <v-btn
                  color="blue darken-1"
                  text
                  class="ml-4"
                  @click="editContractPartOverrideItemDialog = false"
                  >{{ $ay.t("OK") }}</v-btn
                >
              </template>
              <template v-else>
                <!-- MOBILE FORMAT -->
                <v-row dense>
                  <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 dense justify="center">
        <v-dialog
          v-model="editContractServiceRateOverrideItemDialog"
          max-width="800px"
        >
          <v-card>
            <v-card-title> </v-card-title>
            <v-card-text>
              <v-row>
                <v-col>
                  <gz-percent
                    ref="ContractServiceRateOverrideItems.OverridePct"
                    v-model="
                      obj.contractServiceRateOverrideItems[
                        editContractServiceRateOverrideItemIndex
                      ].overridePct
                    "
                    :readonly="formState.readOnly"
                    :label="$ay.t('ContractAdjustment')"
                    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-select
                    ref="ContractServiceRateOverrideItems.OverrideType"
                    v-model="
                      obj.contractServiceRateOverrideItems[
                        editContractServiceRateOverrideItemIndex
                      ].overrideType
                    "
                    dense
                    :items="selectLists.overrideTypes"
                    item-text="name"
                    item-value="id"
                    :readonly="formState.readOnly"
                    :label="$ay.t('ContractOverrideType')"
                    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>

                  <gz-tag-picker
                    ref="ContractServiceRateOverrideItems.Tags"
                    v-model="
                      obj.contractServiceRateOverrideItems[
                        editContractServiceRateOverrideItemIndex
                      ].tags
                    "
                    :readonly="formState.readOnly"
                    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
                  class="ml-4"
                  @click="addContractServiceRateOverrideItem()"
                  >{{ $ay.t("New") }}</v-btn
                >

                <v-btn
                  color="blue darken-1"
                  text
                  class="ml-4"
                  @click="editContractServiceRateOverrideItemDialog = false"
                  >{{ $ay.t("OK") }}</v-btn
                >
              </template>
              <template v-else>
                <!-- MOBILE FORMAT -->
                <v-row dense>
                  <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 dense justify="center">
        <v-dialog
          v-model="editContractTravelRateOverrideItemDialog"
          max-width="800px"
        >
          <v-card>
            <v-card-title> </v-card-title>
            <v-card-text>
              <v-row>
                <v-col>
                  <gz-percent
                    ref="ContractTravelRateOverrideItems.OverridePct"
                    v-model="
                      obj.contractTravelRateOverrideItems[
                        editContractTravelRateOverrideItemIndex
                      ].overridePct
                    "
                    :readonly="formState.readOnly"
                    :label="$ay.t('ContractAdjustment')"
                    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-select
                    ref="ContractTravelRateOverrideItems.OverrideType"
                    v-model="
                      obj.contractTravelRateOverrideItems[
                        editContractTravelRateOverrideItemIndex
                      ].overrideType
                    "
                    dense
                    :items="selectLists.overrideTypes"
                    item-text="name"
                    item-value="id"
                    :readonly="formState.readOnly"
                    :label="$ay.t('ContractOverrideType')"
                    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>

                  <gz-tag-picker
                    ref="ContractTravelRateOverrideItems.Tags"
                    v-model="
                      obj.contractTravelRateOverrideItems[
                        editContractTravelRateOverrideItemIndex
                      ].tags
                    "
                    :readonly="formState.readOnly"
                    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
                  class="ml-4"
                  @click="addContractTravelRateOverrideItem()"
                  >{{ $ay.t("New") }}</v-btn
                >

                <v-btn
                  color="blue darken-1"
                  text
                  class="ml-4"
                  @click="editContractTravelRateOverrideItemDialog = false"
                  >{{ $ay.t("OK") }}</v-btn
                >
              </template>
              <template v-else>
                <!-- MOBILE FORMAT -->
                <v-row dense>
                  <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 dense justify="center">
        <v-dialog v-model="editServiceRateItemDialog" max-width="800px">
          <v-card>
            <v-card-title> </v-card-title>
            <v-card-text>
              <v-row>
                <v-col>
                  <gz-pick-list
                    ref="userid"
                    v-model="
                      obj.serviceRateItems[editServiceRateItemIndex]
                        .serviceRateId
                    "
                    :allow-no-selection="false"
                    :can-clear="false"
                    :aya-type="ayaTypes().ServiceRate"
                    :variant="'contractrates'"
                    show-edit-icon
                    :readonly="formState.readOnly"
                    :label="$ay.t('ServiceRate')"
                    data-cy="userid"
                    :rules="[
                      form().integerValid(
                        this,
                        'ServiceRateItems.ServiceRateId'
                      ),
                      form().required(this, 'ServiceRateItems.ServiceRateId')
                    ]"
                    :error-messages="
                      form().serverErrors(
                        this,
                        `ServiceRateItems[${editServiceRateItemIndex}].ServiceRateId`
                      )
                    "
                    :name.sync="
                      obj.serviceRateItems[editServiceRateItemIndex]
                        .serviceRateViz
                    "
                    @input="
                      fieldValueChanged(
                        `ServiceRateItems[${editServiceRateItemIndex}].ServiceRateId`
                      )
                    "
                  ></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
                  class="ml-4"
                  @click="addServiceRateItem()"
                  >{{ $ay.t("New") }}</v-btn
                >

                <v-btn
                  color="blue darken-1"
                  text
                  class="ml-4"
                  @click="editServiceRateItemDialog = false"
                  >{{ $ay.t("OK") }}</v-btn
                >
              </template>
              <template v-else>
                <!-- MOBILE FORMAT -->
                <v-row dense>
                  <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 dense justify="center">
        <v-dialog v-model="editTravelRateItemDialog" max-width="800px">
          <v-card>
            <v-card-title> </v-card-title>
            <v-card-text>
              <v-row>
                <v-col>
                  <gz-pick-list
                    ref="userid"
                    v-model="
                      obj.travelRateItems[editTravelRateItemIndex].travelRateId
                    "
                    :allow-no-selection="false"
                    :can-clear="false"
                    :aya-type="ayaTypes().TravelRate"
                    :variant="'contractrates'"
                    show-edit-icon
                    :readonly="formState.readOnly"
                    :label="$ay.t('TravelRate')"
                    data-cy="userid"
                    :rules="[
                      form().integerValid(this, 'TravelRateItems.TravelRateId'),
                      form().required(this, 'TravelRateItems.TravelRateId')
                    ]"
                    :error-messages="
                      form().serverErrors(
                        this,
                        `TravelRateItems[${editTravelRateItemIndex}].TravelRateId`
                      )
                    "
                    :name.sync="
                      obj.travelRateItems[editTravelRateItemIndex].travelRateViz
                    "
                    @input="
                      fieldValueChanged(
                        `TravelRateItems[${editTravelRateItemIndex}].TravelRateId`
                      )
                    "
                  ></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
                  class="ml-4"
                  @click="addTravelRateItem()"
                  >{{ $ay.t("New") }}</v-btn
                >

                <v-btn
                  color="blue darken-1"
                  text
                  class="ml-4"
                  @click="editTravelRateItemDialog = false"
                  >{{ $ay.t("OK") }}</v-btn
                >
              </template>
              <template v-else>
                <!-- MOBILE FORMAT -->
                <v-row dense>
                  <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>
const FORM_KEY = "contract-edit";
const API_BASE_URL = "contract/";
const FORM_CUSTOM_TEMPLATE_KEY = "Contract";
export default {
  data() {
    return {
      formCustomTemplateKey: FORM_CUSTOM_TEMPLATE_KEY,
      obj: {
        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
    };
  },
  watch: {
    formState: {
      handler: function(val) {
        if (this.formState.loading) {
          return;
        }
        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");
        }
        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
    }
  },
  async created() {
    const 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;
      //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);
        }
      } 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: true
      });
      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);
  },
  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) {
      const vm = this;
      window.$gz.form.setFormState({
        vm: vm,
        loading: true
      });
      if (!recordId) {
        throw new Error(FORM_KEY + "::getDataFromApi -> Missing recordID!");
      }
      try {
        window.$gz.form.deleteAllErrorBoxErrors(vm);
        const res = await window.$gz.api.get(API_BASE_URL + recordId);
        if (res.error) {
          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;
          generateMenu(vm);
          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() {
      const vm = this;
      if (vm.canSave == false) {
        return;
      }
      try {
        window.$gz.form.setFormState({
          vm: vm,
          loading: true
        });
        window.$gz.form.deleteAllErrorBoxErrors(vm);
        vm.editTravelRateItemIndex = -1;
        vm.editServiceRateItemIndex = -1;
        vm.editContractPartOverrideItemIndex = -1;
        vm.editContractTravelRateOverrideItemIndex = -1;
        vm.editContractServiceRateOverrideItemIndex = -1;
        const res = await window.$gz.api.upsert(API_BASE_URL, vm.obj);
        if (res.error) {
          vm.formState.serverError = res.error;
          window.$gz.form.setErrorBoxErrors(vm);
        } else {
          //POST or PUT 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) {
            vm.obj = res.data;
          } else {
            this.$router.replace({
              name: "contract-edit",
              params: {
                recordid: res.data.id,
                obj: res.data
              }
            });
          }
          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() {
      try {
        const dialogResult = await window.$gz.dialog.confirmDelete();
        if (dialogResult != true) {
          return;
        }
        window.$gz.form.setFormState({
          vm: this,
          loading: true
        });

        if (this.$route.params.recordid == 0) {
          JUST_DELETED = true;

          this.$router.go(-1);
        } else {
          window.$gz.form.deleteAllErrorBoxErrors(this);
          const res = await window.$gz.api.remove(
            API_BASE_URL + this.$route.params.recordid
          );
          if (res.error) {
            this.formState.serverError = res.error;
            window.$gz.form.setErrorBoxErrors(this);
          } else {
            JUST_DELETED = true;
            this.$router.go(-1);
          }
        }
      } catch (error) {
        window.$gz.errorHandler.handleFormError(error, this);
      } finally {
        window.$gz.form.setFormState({
          vm: this,
          loading: false
        });
      }
    },

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

/////////////////////////////
//
//
async function clickHandler(menuItem) {
  if (!menuItem) {
    return;
  }
  const 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":
        {
          const res = await m.vm.$refs.reportSelector.open(
            {
              AType: window.$gz.type.Contract,
              selectedRowIds: [m.vm.obj.id]
            },
            m.id
          );
          if (res == null) {
            return;
          }
          window.$gz.form.setLastReportMenuItem(FORM_KEY, res, m.vm);
        }
        break;
      default:
        window.$gz.eventBus.$emit(
          "notify-warning",
          FORM_KEY + "::context click: [" + m.key + "]"
        );
    }
  }
}

//////////////////////
//
//
function generateMenu(vm) {
  const 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
    });
  }

  menuOptions.menuItems.push({
    title: "Report",
    icon: "$ayiFileAlt",
    key: FORM_KEY + ":report",
    vm: vm
  });

  const lastReport = window.$gz.form.getLastReport(FORM_KEY);
  if (lastReport != null) {
    menuOptions.menuItems.push({
      title: lastReport.name,
      notrans: true,
      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
    });
  }

  if (vm.rights.delete && vm.$route.params.recordid != 0) {
    menuOptions.menuItems.push({
      title: "Delete",
      icon: "$ayiTrashAlt",
      surface: false,
      key: FORM_KEY + ":delete",
      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();
  await window.$gz.formCustomTemplate.get(FORM_CUSTOM_TEMPLATE_KEY, vm);
  await populateSelectionLists(vm);
}

//////////////////////////////////////////////////////////
//
// Ensures UI translated text is available
//
async function fetchTranslatedText() {
  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) {
  await window.$gz.enums.fetchEnumList("contractoverridetype");
  vm.selectLists.overrideTypes = window.$gz.enums.getSelectionList(
    "contractoverridetype"
  );
}
</script>
