<template>
  <div class="view-container">
    <div class="view-content" v-loading="pageLoading">
      <el-form
        ref="updateSiteForm"
        :rules="rules"
        :model="updateSiteModel"
        :inline="false"
        label-position="left"
        label-width="100px"
        style="width: 100%;">

        <el-row :gutter="20">
          <el-col :span="12">
            <div class="section-title">
              SITE INFORMATION
            </div>
            <el-form-item
              label="Site Name:"
              prop="siteInformation.siteName">
                <el-input
                  :disabled="isMCSTUser"
                  v-model="updateSiteModel.siteInformation.siteName"
                  class="input-text"
                  @keyup.enter.native="handleFilter" />
            </el-form-item>
            <el-form-item
              prop="siteInformation.latitude"
              label="Latitude:">
                <el-input
                  :disabled="isMCSTUser"
                  v-model="updateSiteModel.siteInformation.latitude"
                  class="input-text"
                  @keyup.enter.native="handleFilter" />
            </el-form-item>
            <el-form-item
              prop="siteInformation.longitude"
              label="Longitude:">
                <el-input
                  :disabled="isMCSTUser"
                  v-model="updateSiteModel.siteInformation.longitude"
                  class="input-text"
                  @keyup.enter.native="handleFilter" />
            </el-form-item>
            <!--el-form-item
              prop="siteInformation.type"
              label="Type">
              <el-select
                v-model="updateSiteModel.siteInformation.type"
                class="input-text">
                  <el-option
                    v-for="item in siteTypeOptions"
                    :key="item.name"
                    :label="item.name"
                    :value="item.value" />
              </el-select>
            </el-form-item-->
          </el-col>

          <el-col :span="12">
            <div class="section-title">
              ADDITIONAL INFORMATION
            </div>
            <div style="display: flex; ">
              <el-form-item
                label-width="130px"
                label="Operating Hours:"
                class="flex-item">
                  <el-input
                    v-model="updateSiteModel.additionalInformation.operatingHours"
                    :disabled="isMCSTUser || !!updateSiteModel.additionalInformation.endlessService"
                    class="input-text"
                    @keyup.enter.native="handleFilter" />
              </el-form-item>
              <el-switch
                :disabled="isMCSTUser"
                @change="endlessServiceSwitchChange"
                style="margin-left: 10px"
                inactive-text="24/7"
                v-model="updateSiteModel.additionalInformation.endlessService">
              </el-switch>
            </div>
            <div style="display: flex; ">
              <el-form-item
                label-width="130px"
                label="Parking Fee:"
                class="flex-item">
                  <el-input
                    :disabled="isMCSTUser || !!updateSiteModel.additionalInformation.free"
                    v-model="updateSiteModel.additionalInformation.parkingFee"
                    class="input-text"
                    @keyup.enter.native="handleFilter" />
              </el-form-item>
              <el-switch
                :disabled="isMCSTUser"
                @change="freeSwitchChange"
                style="margin-left: 10px"
                inactive-text="Free"
                v-model="updateSiteModel.additionalInformation.free">
              </el-switch>
            </div>
            <div class="flex">
              <el-form-item
                label-width="130px"
                label="Additional Notes:"
                class="flex-item flex">
                  <el-input
                    :disabled="isMCSTUser"
                    v-model="updateSiteModel.additionalInformation.additionalNotes"
                    type="textarea"
                    :autosize="additionalNotesAutosize"
                    class="input-text" />
              </el-form-item>
              <div class="flexl" style="font-size: 13px; margin-left: 10px;">
                <span>Enable</span>
                <span>Idle Fee</span>
              </div>
              <el-switch
                style="margin-left: 5px;"
                v-model="updateSiteModel.idle.enableIdleFee"/>
            </div>
          </el-col>
        </el-row>
        <div class="sparator"></div>
        <div class="section-title">
          TIME CONFIGURATION
        </div>
        <el-table
          :data="siteTypeTable"
          fit
          style="width: 100%; max-width: 1000px;">
          <el-table-column
            label="Site Type With Schedule"
            prop="label"/>
          <el-table-column
            label="All Day"
            width="150px">
            <template slot-scope="{row, $index}">
              <el-switch v-model="row.allDay" :disabled="isSiteTypeEnable($index, true)"></el-switch>
            </template>
          </el-table-column>
          <el-table-column
            label="Start Time">
            <template slot-scope="{row, $index}">
              <el-time-picker
                v-model="row.startTime"
                format="HH:mm"
                value-format="HH:mm"
                placeholder="Start Time"
                :disabled="isSiteTypeEnable($index)">
              </el-time-picker>
            </template>
          </el-table-column>
          <el-table-column
            label="End Time">
            <template slot-scope="{row, $index}">
              <el-time-picker
                v-model="row.endTime"
                format="HH:mm"
                value-format="HH:mm"
                placeholder="End Time"
                :disabled="isSiteTypeEnable($index)">
              </el-time-picker>
            </template>
          </el-table-column>
        </el-table>
        <div class="sparator"></div>
        <div class="section-title">
          ADDRESS
        </div>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item
              prop="address.country"
              label="Country:">
              <el-select
                v-model="updateSiteModel.address.country"
                class="input-text">
                <el-option
                  v-for="item in countryOptions"
                  :key="item.name"
                  :label="item.name"
                  :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              prop="address.street"
              label-width="130px"
              label="Street:">
              <el-input
                v-model="updateSiteModel.address.street"
                class="input-text"
                @keyup.enter.native="handleFilter" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item
              prop="address.city"
              label="City:">
                <el-input
                  v-model="updateSiteModel.address.city"
                  class="input-text"
                  @keyup.enter.native="handleFilter" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label-width="130px"
              prop="address.postalCode"
              label="Postal Code:">
                <el-input
                  v-model="updateSiteModel.address.postalCode"
                  class="input-text"
                  @keyup.enter.native="handleFilter" />
            </el-form-item>
          </el-col>
        </el-row>

        <div class="sparator"></div>
        <div class="section-title">
          CHARGE RATE
        </div>
        <div
          class="rate-list-view"
          v-for="(item, index) in updateSiteModel.chargeRates"
          :key="item.ratePk">
          <el-form-item
            label="Type"
            label-width="50px"
            :prop="'chargeRates.' + index + '.chargeTypePk'"
            :rules="rules.chargeRate.chargeTypePk">
              <el-select
                :disabled="isMCSTUser"
                v-model="item.chargeTypePk"
                class="rate-text">
                  <el-option
                    v-for="item in chargeTypeOptions"
                    :key="item.chargeTypePk"
                    :label="item.chargeType"
                    :value="item.chargeTypePk" />
              </el-select>
          </el-form-item>
          <el-form-item
            label="Rate"
            label-width="50px"
            :prop="'chargeRates.' + index + '.rate'"
            :rules="rules.chargeRate.rate">
            <el-input
              :disabled="isMCSTUser"
              v-model="item.rate"
              class="rate-text" />
          </el-form-item>
          <div class="ratePunit">/</div>
          <el-form-item
            label-width="0px">
            <el-select
              :disabled="isMCSTUser"
              v-model="item.rateType"
              class="rate-type">
                <el-option
                  v-for="item in rateTypeOptions"
                  :key="item.name"
                  :label="item.value"
                  :value="item.value" />
            </el-select>
          </el-form-item>
          <img
            v-if="!isMCSTUser"
            class="list-item-icon"
            @click="handleClickSubChargeRateButton(item, index)"
            src="../../assets/form-list-sub.png"/>
          <img
            class="list-item-icon"
            v-if="!isMCSTUser && (index === updateSiteModel.chargeRates.length - 1)"
            @click="handleClickAddChargeRateButton"
            src="../../assets/form-list-add.png"/>
        </div>

        <div class="sparator" ></div>
        <div class="specialChangeRate">
          <div class="section-title">
            SPECIAL CHARGE RATE
            <el-switch v-model="swtSpecialRate"/>
          </div>
          <div
            v-for="(item, index) in updateSiteModel.specialChargeRates"
            :key="index"
            v-if="swtSpecialRate"
            class="rate-list-view">
            <el-form-item
              label="Company:"
              label-width="90px"
              :prop="'specialChargeRates.' + index + '.fleetCompanyId'"
              :rules="rules.specialChargeRates.fleetCompanyId">
              <el-select
                v-model="item.fleetCompanyId"
                class="rate-text-max">
                <el-option
                  v-for="item in companyOptions"
                  :key="item.fleetCompanyId"
                  :label="item.fleetCompanyName"
                  :value="item.fleetCompanyId">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              label="Type:"
              label-width="55px"
              :prop="'specialChargeRates.' + index + '.chargeTypePk'"
              :rules="rules.specialChargeRates.chargeTypePk">
              <el-select v-model="item.chargeTypePk" class="rate-text">
                <el-option
                  v-for="item in chargeTypeOptions"
                  :key="item.chargeTypePk"
                  :label="item.chargeType"
                  :value="item.chargeTypePk">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              label="Rate:"
              label-width="55px"
              :prop="'specialChargeRates.' + index + '.rate'"
              :rules="rules.specialChargeRates.rate">
              <el-input v-model="item.rate" class="rate-text"></el-input>
            </el-form-item>
            <div class="ratePunit">/</div>
            <el-form-item
              label=""
              label-width="0px"
              :prop="'specialChargeRates.' + index + '.rateType'"
              :rules="rules.specialChargeRates.rateType">
              <el-select v-model="item.rateType" class="rate-type">
                <el-option
                  v-for="item in rateTypeOptions"
                  :key="item.name"
                  :label="item.value"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
            <img
              class="list-item-icon"
              @click="handleClickSubSpecialRateButton(item, index)"
              src="../../assets/form-list-sub.png"
            />
            <img
              v-if="updateSiteModel.specialChargeRates.length - 1 === index"
              class="list-item-icon"
              @click="handleClickAddSpecialRateButton"
              src="../../assets/form-list-add.png"
            />
          </div>
        </div>

        <reservation
          :enable="updateSiteModel.reservation.enable"
          :timeLimit="updateSiteModel.reservation.timeLimit"
          @enable="reservationTimeLimitEnable"
          @time-limit-change="reservationTimeLimitChange"
        />
        
        <div class="sparator" ></div>
        <div class="specialChangeRate">
          <div class="section-title">
            LOAD BALANCING
          </div>
          <el-row
            :gutter="20"
            v-for="(item, index) in updateSiteModel.siteChargingProfiles"
            :key="index"
          >
            <el-col :span="6" :offset="0">
              <el-form-item
                label="Chargers In-Use:"
                label-width="150px">
                <!--:prop="'siteChargingProfiles.' + index + '.boxInUse'"
                :rules="rules.siteChargingProfiles.boxInUse"
              -->
                <el-select v-model="item.boxInUse">
                  <el-option
                    v-for="(item,index) in boxUseOptions"
                    :key="index"
                    :label="item"
                    :value="item"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8" :offset="1">
              <el-form-item
                label="Charging Profile:"
                label-width="150px">
                <!--:prop="'siteChargingProfiles.' + index + '.chargingProfilePk'"
                :rules="rules.siteChargingProfiles.chargingProfilePk"
              -->
                <el-select v-model="item.chargingProfilePk" filterable>
                  <el-option
                    v-for="(item,index) in chargingProfileOPtions"
                    :key="index"
                    :label="item.description"
                    :value="item.chargingProfilePk"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4" :offset="0">
              <img
                class="list-item-icon"
                @click="handelSubSiteChargingProfiles(index)"
                src="../../assets/form-list-sub.png"
              />
              <img
                v-if="updateSiteModel.siteChargingProfiles.length - 1 === index"
                class="list-item-icon"
                @click="handleAddSiteChargingProfiles"
                src="../../assets/form-list-add.png"
              />
            </el-col>
          </el-row>
        </div>
        <div v-if="enableFleetWhiteList()">
          <div class="sparator"></div>
          <div class="section-title">
            WHITELIST FLEET
          </div>
          <div
            class="rate-list-view"
            v-for="(item, index) in updateSiteModel.fleetWhitelist"
            :key="index">
            <el-form-item
              label-width="50px"
              label="Fleet">
              <el-select
                v-model="item.fleetCompanyId"
                style="margin-right: 10px;">
                <el-option
                  v-for="item in companyOptions"
                  :key="item.fleetCompanyId"
                  :label="item.fleetCompanyName"
                  :value="item.fleetCompanyId">
                </el-option>
              </el-select>
            </el-form-item>
            <img
              class="list-item-icon"
              @click="handleClickSubWhiteFleetButton(item, index)"
              src="../../assets/form-list-sub.png"/>
            <img
              v-if="index === updateSiteModel.fleetWhitelist.length - 1"
              class="list-item-icon"
              @click="handleClickAddWhiteFleetButton"
              src="../../assets/form-list-add.png"/>
          </div>
        </div>
        <div
          class="additional"
          v-if="enableUserWhiteList()">
          <div class="sparator"></div>
          <div class="section-title">
            WHITELIST USERS
          </div>
          <div
            class="rate-list-view"
            v-for="(item, index) in updateSiteModel.whitelistUser"
            :key="index">
            <el-form-item
              label-width="130px"
              label="Mobile Number"
              :prop="'whitelistUser.' + index + '.mobileNumber'"
              :rules="rules.whitelistUser.mobileNumber">
              <el-input
                v-model="item.mobileNumber"
                class="rate-text" />
            </el-form-item>
            <el-form-item
              label-width="140px"
              label="Licence Number"
              :prop="'whitelistUser.' + index +'.licenceNumber'"
              :rules="rules.whitelistUser.licenceNumber">
              <el-input
                v-model="item.licenceNumber"
                class="rate-text" />
            </el-form-item>
            <img
              class="list-item-icon"
              @click="handleClickSubWhiteUserButton(item, index)"
              src="../../assets/form-list-sub.png"/>
            <img
              v-if="index === updateSiteModel.whitelistUser.length - 1"
              class="list-item-icon"
              @click="handleClickAddWhiteUserButton"
              src="../../assets/form-list-add.png"/>
          </div>
        </div>
        <div v-if="updateSiteModel.idle.enableIdleFee">
          <div class="sparator"></div>
          <div class="section-title">Idle Fee SETTINGS</div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item
                label="Effective From:"
                label-width="130px"
                prop="idle.effectiveFrom">
                <el-time-picker
                  v-model="updateSiteModel.idle.effectiveFrom"
                  class="input-text"
                  format="HH:mm"
                  value-format="HH:mm"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="Effective To:"
                label-width="130px"
                prop="idle.effectiveTo">
                <el-time-picker
                  v-model="updateSiteModel.idle.effectiveTo"
                  class="input-text"
                  format="HH:mm"
                  value-format="HH:mm"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="Idle Fee:"
                label-width="130px"
                prop="idle.idleFee">
                <el-input
                  v-model="updateSiteModel.idle.idleFee"
                  class="input-text"
                  oninput="value=value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')"
                  maxlength="6"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="Every (minute):"
                label-width="130px"
                prop="idle.everyMinute">
                <el-input
                  maxlength="4"
                  v-model.number="updateSiteModel.idle.everyMinute"
                  class="input-text"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="Effective Date:"
                label-width="130px"
                prop="idle.effectiveDate">
                <el-date-picker
                  v-model="updateSiteModel.idle.effectiveDate"
                  class="input-text"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"/>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <div class="sparator" style="margin: 10px -80px;"></div>
        <div class="buttons">
          <el-button
            class="cancel-button"
            type="primary"
            @click="handleClickCancleButton">
              Cancel
          </el-button>
          <el-button
            class="confirm-button"
            type="primary"
            @click="handleClickConfigUpateButton">
              Save
          </el-button>
        </div>

      </el-form>
    </div>
  </div>
</template>

<script>
import waves from '@/directive/waves' // waves directive
import site from '../../http/api/site'
import { mapState } from 'vuex'
import Reservation from './components/Reservation'
import { getRoleName } from '@/utils/auth'
import { fetchFleetCompanyOptions } from '@/http/api/driver'

export default {
  components: { Reservation },
  name: 'AddSite',
  directives: { waves },
  data() {
    return {
      additionalNotesAutosize: {
        minRows: 3,
        maxRows: 6,
      },
      pageLoading: false,
      siteTypeTable: [{
        siteType: "",
        allDay: false,
        startTime: "",
        endTime: ""
      }],
      companyOptions: [],
      rateTypeOptions: [],
      chargeTypeOptions: [],
      siteTypeOptions: [],
      countryOptions: [],
      chargingProfileOPtions: [],
      boxUseOptions: [1,2,3,4,5,6,7,8,9,10],
      
      updateSiteModel: {
        specialChargeRates: [],
        siteInformation: {
          siteName: '',
          latitude: '',
          longitude: '',
          type: '',
        },
        siteChargingProfiles: [
          {
            boxInUse: '',
            chargingProfilePk: ''
          }
        ],

        additionalInformation: {
          operatingHours: '',
          parkingFee: '',
          additionalNotes: '',
          endlessService: false,
          free: false,
        },

        address: {
          street: '',
          postalCode: '',
          city: '',
          country: '',
        },

        tempChargeRate: {
          ratePk: '',
          chargeTypePk: '',
          rate: '',
          rateType: '',
        },
        chargeRates: [],
        fleetWhitelist: [],
        whitelistUser: [],
        reservation: {
          enable: true,
          timeLimit: 15,
        },
        idle: {
          enableIdleFee: false,
          idleFee: '',
          effectiveDate: '',
          effectiveFrom: '',
          effectiveTo: '',
          everyMinute: ''
        }
      },

      rules: {
        siteInformation: {
          siteName: {
            required: true,
            trigger: 'blur',
            message: 'Site Name is required',
          },
          latitude: [{
            required: true,
            trigger: 'blur',
            message: 'Latitude is required',
          }, {
            pattern: /^[\-\+]?((0|([1-8]\d?))(\.\d{1,8})?|90(\.0{1,8})?)$/,
            trigger: 'blur',
            message: 'Please type a correct latitude',
          }],
          longitude: [{
            required: true,
            trigger: 'blur',
            message: 'Longitude is required',
          }, {
            pattern: /^[\-\+]?(0(\.\d{1,8})?|([1-9](\d)?)(\.\d{1,8})?|1[0-7]\d{1}(\.\d{1,8})?|180\.0{1,8})$/,
            trigger: 'blur',
            message: 'Please type a correct longitude',
          }],
          type: {
            required: true,
            trigger: 'change',
            message: 'Site Type is required',
          },
        },
        siteChargingProfiles: {
          boxInUse: [{
            required: true,
            trigger: 'change',
            message: 'Chargers In-Use is required',
          }, {
            type: 'number',
            message: 'Chargers In-Use is a number',
          }],
          chargingProfilePk: {
            required: true,
            trigger: 'change',
            message: 'Charging Profileis required',
          },
        },
        address: {
          street: {
            required: true,
            trigger: 'blur',
            message: 'Address is required',
          },
          postalCode: {
            required: true,
            trigger: 'blur',
            message: 'Postal Code is required',
          },
          city: {
            required: true,
            trigger: 'blur',
            message: 'City is required',
          },
          country: {
            required: true,
            trigger: 'blur',
            message: 'Country is required',
          },
        },
        chargeRate: {
          chargeTypePk: {
            required: true,
            trigger: 'change',
            message: 'Charge Type is required',
          },
          rate: [{
            required: true,
            trigger: 'blur',
            message: 'Rate is required',
          }, {
            pattern: /^\d+(\.\d+)?$/,
            trigger: 'blur',
            message: 'Please type a correct rate',
          }],
          rateType: {
            required: true,
            trigger: 'change',
            message: 'Rate Type is required',
          }
        },
        specialChargeRates: {
          fleetCompanyId: {
            required: true,
            trigger: 'change',
            message: 'Fleet Company is required',
          },
          chargeTypePk: {
            required: true,
            trigger: 'change',
            message: 'Charge Type is required',
          },
          rate: [{
            required: true,
            trigger: 'blur',
            message: 'Rate is required',
          }, {
            pattern: /^\d+(\.\d+)?$/,
            trigger: 'blur',
            message: 'Please type a correct rate',
          }],
          rateType: {
            required: true,
            trigger: 'change',
            message: 'Rate Type is required',
          }
        },
        whitelistUser: {
          licenceNumber: {
            required: true,
            trigger: 'blur',
            message: 'Licence Number is required',
          },
          mobileNumber: {
            required: true,
            trigger: 'blur',
            message: 'Mobile Number is required',
          },
        },
        idle: {
          idleFee: {
            required: true,
            trigger: 'blur',
            message: 'Idle fee is required'
          },
          effectiveDate: {
            required: true,
            trigger: 'change',
            message: 'Effective Date is required'
          },
          effectiveFrom: {
            required: true,
            trigger: 'change',
            message: 'Effective From is required'
          },
          effectiveTo: {
            required: true,
            trigger: 'change',
            message: 'Effective To is required'
          },
          everyMinute: [{
            required: true,
            trigger: 'blur',
            message: 'Every is required'
          }, {
            type: 'number',
            message: 'Every is a number'
          }]
        }
      },
      isMCSTUser: false,
      swtSpecialRate: false
    }
  },
  computed: {
    ...mapState('site', ['selectedSite']),
  },
  async created() {
    this.pageLoading = true;
    this.getRateTypeOptions()
    this.getChargeTypeOptions()
    await this.getCompanyOptions()
    await this.getSiteInfo()
    this.getCountryOptions()
    this.getChargingProfileOPtions()
    this.isMCSTUser = getRoleName() === "MCST"
    //this.pageLoading = false;
  },
  methods: {
    handleClickAddSpecialRateButton() {
      this.updateSiteModel.specialChargeRates.push(
        {
          fleetCompanyId: this.companyOptions[0].fleetCompanyId,
          chargeTypePk: this.chargeTypeOptions[0].chargeTypePk,
          rate: '',
          rateType: this.rateTypeOptions[0].value,
        }
      )
    },
    handleClickSubSpecialRateButton(specialRate, index) {
      this.$confirm(
        'Are you sure you want to delete this charge rate ?',
        'Delete',
        {
          confirmButtonText: 'Ok',
          cancelButtonText: 'Cancel',
          type: 'warning',
        },
      ).then(() => {
        const { ratePk } = specialRate;
        if (ratePk) {
          site.deleteChargeRate({ ratePk })
            .then(() => {
              this.updateSiteModel.specialChargeRates.splice(index, 1)
              if (this.updateSiteModel.specialChargeRates.length === 0) {
                this.updateSiteModel.specialChargeRates.push(
                  {
                    fleetCompanyId: this.companyOptions[0].fleetCompanyId,
                    chargeTypePk: this.chargeTypeOptions[0].chargeTypePk,
                    rate: '',
                    rateType: this.rateTypeOptions[0].value,
                  }
                )
              }
            })
            .catch((error) => {
              this.$notify({
                title: 'Delete Charge Rate Error',
                message: error,
                type: 'error',
              })
            })
        } else {
          this.updateSiteModel.specialChargeRates.splice(index, 1)
          if (this.updateSiteModel.specialChargeRates.length === 0) {
            this.updateSiteModel.specialChargeRates.push(
              {
                fleetCompanyId: this.companyOptions[0].fleetCompanyId,
                chargeTypePk: this.chargeTypeOptions[0].chargeTypePk,
                rate: '',
                rateType: this.rateTypeOptions[0].value,
              }
            )
          }
        }
      })
    },
    handelSubSiteChargingProfiles(index) {
      const item = this.updateSiteModel.siteChargingProfiles[index]
      this.$confirm(
        'Are you sure you want to delete this config?',
        'Delete', {
          confirmButtonText: 'Ok',
          cancelButtonText: 'Cancel',
          type: 'warning',
        }
      ).then(() => {
        if (item.siteChargingProfileId) {
          site.deleteChargingProfile(item.siteChargingProfileId).then(res => {
            
          })
          this.updateSiteModel.siteChargingProfiles.splice(index, 1)
          if (this.updateSiteModel.siteChargingProfiles.length === 0) {
            this.handleAddSiteChargingProfiles()
          }
        } else {
          this.updateSiteModel.siteChargingProfiles.splice(index, 1)
          if (this.updateSiteModel.siteChargingProfiles.length === 0) {
            this.handleAddSiteChargingProfiles()
          }
        }
      })
    },
    handleAddSiteChargingProfiles() {
      this.updateSiteModel.siteChargingProfiles.push({
        boxInUse: '',
        chargingProfilePk: ''
      })
    },
    reservationTimeLimitEnable(enable) {
      this.updateSiteModel.reservation.enable = enable
    },
    reservationTimeLimitChange(timeLimit) {
      this.updateSiteModel.reservation.timeLimit = timeLimit
    },
    endlessServiceSwitchChange(value) {
      if (value) {
        this.updateSiteModel.additionalInformation.operatingHours = ""
      }
    },
    freeSwitchChange(value) {
      if (value) {
        this.updateSiteModel.additionalInformation.parkingFee = ""
      }
    },
    getSiteInfo() {
      const { sitePk } = this.selectedSite;
      if (sitePk) {
        site.getSiteInfo({ sitePk })
          .then(({ data }) => {
            const {
              free,
              parkingFee,
              endlessService,
              additionalNotes,
              operatingHours,

              siteName,
              //siteType,
              siteTypes,
              locationLatitude,
              locationLongitude,

              enableReservation,
              timeLimit,
              address = {},
              chargeRates = [],
              whitelistUser = [],
              fleetWhitelist = []
            } = data

            this.updateSiteModel.reservation.enable = enableReservation
            this.updateSiteModel.reservation.timeLimit = timeLimit

            this.updateSiteModel.siteInformation.siteName = siteName
            //this.updateSiteModel.siteInformation.type = siteType
            if (siteTypes) {
              this.siteTypeOptions = siteTypes
            }
            this.updateSiteModel.siteInformation.longitude = locationLongitude
            this.updateSiteModel.siteInformation.latitude = locationLatitude

            this.updateSiteModel.additionalInformation.free = free
            this.updateSiteModel.additionalInformation.parkingFee = parkingFee
            this.updateSiteModel.additionalInformation.endlessService = endlessService
            this.updateSiteModel.additionalInformation.additionalNotes = additionalNotes
            this.updateSiteModel.additionalInformation.operatingHours = operatingHours

            this.updateSiteModel.address.street = address.street
            this.updateSiteModel.address.postalCode = address.zipCode
            this.updateSiteModel.address.country = address.country
            this.updateSiteModel.address.city = address.city
            
            this.updateSiteModel.idle.idleFee = data.idleFee
            this.updateSiteModel.idle.everyMinute = data.everyMinute
            this.updateSiteModel.idle.effectiveTo = data.effectiveTo
            this.updateSiteModel.idle.effectiveFrom = data.effectiveFrom
            this.updateSiteModel.idle.effectiveDate = data.effectiveDate
            this.updateSiteModel.idle.enableIdleFee = data.enableIdleFee

            chargeRates.forEach(item => {
              if (item.fleetCompanyId) {
                const index = this.updateSiteModel.specialChargeRates.length - 1
                this.updateSiteModel.specialChargeRates.splice(index, 0, item)
              } else {
                this.updateSiteModel.chargeRates.push(item)
              }
            })
            if (this.updateSiteModel.specialChargeRates.length == 0) {
              setTimeout(() => {
                this.handleClickAddSpecialRateButton();
              }, 2000);
            } else {
              this.swtSpecialRate = true;
            }
            this.updateSiteModel.siteChargingProfiles = data.siteChargingProfiles || []
            if (this.updateSiteModel.siteChargingProfiles.length == 0) {
              this.handleAddSiteChargingProfiles()
            }
            
            if (whitelistUser.length) {
              this.updateSiteModel.whitelistUser = whitelistUser
            } else {
              this.updateSiteModel.whitelistUser.push({
                licenceNumber: '',
                mobileNumber: '',
              })
            }
            if (fleetWhitelist.length) {
              this.updateSiteModel.fleetWhitelist = fleetWhitelist
            } else {
              this.updateSiteModel.fleetWhitelist.push({
                fleetCompanyId: '',
              })
            }
            this.getSiteTypeOptions()
          }).catch(err => {
            this.pageLoading = false;
            this.$message({
              message: err,
              type: "error",
              duration: 5 * 1000,
            })
          });
      }
    },
    getChargeTypeOptions() {
      site.getChargeTypeList().then((response) => {
        const { data = [] } = response
        this.chargeTypeOptions = data
        this.setTempChargeTypeDefaultValue()
        //this.setLastSpecialChargeTypeDefaultValue()
      });
    },
    setLastSpecialChargeTypeDefaultValue() {
      if (this.chargeTypeOptions.length > 0) {
        const lastIndex = this.updateSiteModel.specialChargeRates.length - 1
        this.updateSiteModel.specialChargeRates[lastIndex].chargeTypePk = this.chargeTypeOptions[0].chargeTypePk
      }
    },
    setTempChargeTypeDefaultValue() {
      if (this.chargeTypeOptions.length > 0) {
        const defaultValue = this.chargeTypeOptions[0].chargeTypePk
        this.updateSiteModel.tempChargeRate.chargeTypePk = defaultValue
      }
    },
    getRateTypeOptions() {
      site.getRateTypeList().then((response) => {
        const { data = [] } = response
        this.rateTypeOptions = data
        this.setTempRateTypeDefaultValue()
      });
    },
    setTempRateTypeDefaultValue() {
      if (this.rateTypeOptions.length > 0) {
        const defaultValue = this.rateTypeOptions[0].value
        this.updateSiteModel.tempChargeRate.rateType = defaultValue
      }
    },
    getSiteTypeOptions() {
      site.getSiteTypeList().then((response) => {
        //this.siteTypeOptions = response.data
        const { data } = response;
        if (data && data.length) {
          this.siteTypeTable = [];
          data.forEach(item => {
            console.log("this.siteTypeOptions", this.siteTypeOptions);
            if (this.siteTypeOptions && this.siteTypeOptions.length) {
              this.siteTypeOptions.forEach(t => {
                if (item.value == t.siteType) {
                  this.siteTypeTable.push({
                    label: item.name,
                    siteType: item.value,
                    allDay: t.allDay,
                    startTime: t.startTime,
                    endTime: t.endTime
                  })
                }
              })
            } else {
              this.siteTypeTable.push({
                label: item.name,
                siteType: item.value,
                allDay: false,
                startTime: "",
                endTime: ""
              })
            }
          })
        }
      }).finally(() => {
        this.pageLoading = false;
      })
    },
    getCompanyOptions() {
      fetchFleetCompanyOptions().then((response) => {
        const { data, success } = response
        if (success) {
          this.companyOptions = data
          /*if (data && data.length > 0) {
            const lastIndex = this.updateSiteModel.specialChargeRates.length - 1
            this.updateSiteModel.specialChargeRates[lastIndex].fleetCompanyId = data[0].fleetCompanyId
          }*/
        }
      })
    },
    getCountryOptions() {
      site.getCountryList().then(({ data }) => {
        this.countryOptions = data
      })
    },
    getChargingProfileOPtions() {
      site.getChargingProfiles().then(({ data }) => {
        this.chargingProfileOPtions = data
      })
    },
    handleClickSubChargeRateButton(chargeRate, index) {
      this.$confirm(
        'Are you sure you want to delete this charge rate ?',
        'Delete',
        {
          confirmButtonText: 'Ok',
          cancelButtonText: 'Cancel',
          type: 'warning',
        },
      ).then(() => {
        const { ratePk } = chargeRate;
        if (ratePk) {
          site.deleteChargeRate({ ratePk })
            .then(() => {
              this.updateSiteModel.chargeRates.splice(index, 1)
            })
            .catch((error) => {
              this.$notify({
                title: 'Delete Charge Rate Error',
                message: error,
                type: 'error',
              })
            })
        } else {
          this.updateSiteModel.chargeRates.splice(index, 1)
        }
      })
    },
    handleClickSubTempChargeRateButton() {

      const callback = () => {
        if (this.updateSiteModel.chargeRates.length > 0) {
          const lastChargeRate = this.updateSiteModel.chargeRates.pop()
          const {
            rate,
            rateType,
            chargeTypePk,
            ratePk,
          } = lastChargeRate
          this.updateSiteModel.tempChargeRate.chargeTypePk = chargeTypePk
          this.updateSiteModel.tempChargeRate.rateType = rateType
          this.updateSiteModel.tempChargeRate.rate = rate
          this.updateSiteModel.tempChargeRate.ratePk = ratePk
        } else {
          this.resetTempChargeRate()
        }
      }

      this.$confirm(
        'Are you sure you want to delete this charge rate ?',
        'Delete',
        {
          confirmButtonText: 'Ok',
          cancelButtonText: 'Cancel',
          type: 'warning',
        },
      ).then(() => {
        const { ratePk } = this.updateSiteModel.tempChargeRate
        if (ratePk) {
          site.deleteChargeRate({ ratePk })
            .then(() => {
              callback()
            })
            .catch((error) => {
              this.$notify({
                title: 'Delete Charge Rate Error',
                message: error,
                type: 'error',
              })
            })
        } else {
          callback()
        }
      })
    },
    handleClickAddChargeRateButton() {
      this.updateSiteModel.chargeRates.push({
        ...this.updateSiteModel.tempChargeRate
      })
      this.resetTempChargeRate()
    },
    resetTempChargeRate() {
      this.setTempRateTypeDefaultValue()
      this.updateSiteModel.tempChargeRate.rate = ''
      this.updateSiteModel.tempChargeRate.ratePk = ''
      this.setTempChargeTypeDefaultValue()
    },
    handleClickAddWhiteUserButton() {
      this.updateSiteModel.whitelistUser.push({
        licenceNumber: '',
        mobileNumber: '',
      })
    },
    handleClickSubWhiteUserButton(user, index) {
      this.$confirm(
        'Are you sure you want to delete this user ?',
        'Delete',
        {
          confirmButtonText: 'Ok',
          cancelButtonText: 'Cancel',
          type: 'warning',
        }
      ).then(() => {
        const { whitelistPk } = user
        if (whitelistPk) {
          site.deleteWhitelistUser({ whitelistPk  })
            .then(() => {
              this.updateSiteModel.whitelistUser.splice(index, 1)
            })
            .catch((error) => {
              this.$notify({
                type: 'error',
                message: error,
                title: 'delete user error'
              })
            })
            .finally(() => {
              if (this.updateSiteModel.whitelistUser.length === 0) {
                this.updateSiteModel.whitelistUser.push({
                  licenceNumber: '',
                  mobileNumber: '',
                })
              }
            })
        } else {
          this.updateSiteModel.whitelistUser.splice(index, 1)
          if (this.updateSiteModel.whitelistUser.length === 0) {
            this.updateSiteModel.whitelistUser.push({
              licenceNumber: '',
              mobileNumber: '',
            })
          }
        }
      })
    },
    handleClickAddWhiteFleetButton() {
      this.updateSiteModel.fleetWhitelist.push({
        fleetCompanyId: ''
      })
    },
    handleClickSubWhiteFleetButton(fleet, index) {
      this.$confirm('Are you sure you want to delete this fleet?','Delete', {
        confirmButtonText: 'Ok',
        cancelButtonText: 'Cancel',
        type: 'warning',
      }).then(() => {
        if (fleet.siteFleetId) {
          site.deleteWhitelistFleet({siteFleetId: fleet.siteFleetId}).then(res => {
            this.updateSiteModel.fleetWhitelist.splice(index, 1)
            if (this.updateSiteModel.fleetWhitelist.length === 0) {
              this.updateSiteModel.fleetWhitelist.push({
                fleetCompanyId: ''
              })
            }
          }).catch(err => {
            this.$notify({
              type: 'error',
              message: error,
              title: 'delete fleet error'
            })
          })
        } else {
          this.updateSiteModel.fleetWhitelist.splice(index, 1)
          if (this.updateSiteModel.fleetWhitelist.length === 0) {
            this.updateSiteModel.fleetWhitelist.push({
              fleetCompanyId: ''
            })
          }
        }
      })
    },
    handleClickCancleButton() {
      this.$router.go(-1)
    },
    handleClickConfigUpateButton() {
      this.$refs['updateSiteForm'].validate(result => {
        if (result) {
          this.pageLoading = true;
          this.editSiteWithForm();
        }
      })
    },
    editSiteWithForm() {
      const {
        siteName,
        //type: siteType,
        latitude: locationLatitude,
        longitude: locationLongitude,
      } = this.updateSiteModel.siteInformation
      
      const siteTypes = [];
      if (this.isSiteTypeEnable(0, false)) {
        this.siteTypeTable.forEach(item => {
          siteTypes.push({
            siteType: item.siteType,
            allDay: item.allDay,
            startTime: "",
            endTime: ""
          })
        })
      } else {
        siteTypes.push(...this.siteTypeTable);
      }

      const {
        streetPk,
        street,
        postalCode,
        city,
        country,
      } = this.updateSiteModel.address;

      let chargeRates = [
        ...this.updateSiteModel.chargeRates, {
        ...this.updateSiteModel.tempChargeRate
      }].filter(({ ratePk, chargeTypePk, rate, rateType }) => (ratePk || (chargeTypePk && rate && rateType)))
      
      if (this.swtSpecialRate) {
        this.updateSiteModel.specialChargeRates.forEach(({
          fleetCompanyId,
          chargeTypePk,
          rateType,
          rate,
          ratePk,
        }) => {
          if (ratePk || (fleetCompanyId && chargeTypePk && rateType && rate)) {
            chargeRates.push({
              ratePk,
              rate,
              rateType,
              chargeTypePk,
              fleetCompanyId,
            })
          }
        })
      }

      const whitelistUser = this.updateSiteModel.whitelistUser
        .filter(({ whitelistPk, mobileNumber, licenceNumber }) => (whitelistPk || (mobileNumber && licenceNumber)))
      const fleetWhitelist = this.updateSiteModel.fleetWhitelist
        .filter(({fleetCompanyId}) => (fleetCompanyId))
      const chargeProfiles = []
      this.updateSiteModel.siteChargingProfiles.forEach(item => {
        if (item.boxInUse && item.chargingProfilePk)
          chargeProfiles.push(item)
      })
      const {
        free,
        parkingFee,
        endlessService,
        additionalNotes,
        operatingHours,
      } = this.updateSiteModel.additionalInformation
      const data = {
        sitePk: this.selectedSite.sitePk, 
        free,
        parkingFee,
        endlessService,
        additionalNotes,
        operatingHours,
        siteName,
        siteTypes,
        enableReservation: this.updateSiteModel.reservation.enable,
        timeLimit: this.updateSiteModel.reservation.timeLimit,
        locationLatitude,
        locationLongitude,
        address: {
          streetPk,
          street,
          city,
          country,
          zipCode: postalCode,
        },
        chargeRates,
        whitelistUser,
        fleetWhitelist,
        siteChargingProfiles: chargeProfiles,
        ...this.updateSiteModel.idle
      };

      site.updateSite(data)
        .then(() => {
          this.$router.go(-1)
          this.$notify({
            title: "Update site success",
            type: 'success',
            duration: 5000,
          })
        })
        .catch((error) => {
          this.$message({
            message: error,
            type: 'error',
            duration: 5 * 1000,
          })
          this.pageLoading = false;
        })
    },
    enableUserWhiteList() {
      for (let type of this.siteTypeTable) {
        if (type.siteType == "PRI_USR_WHI") {
          return (type.allDay || (type.startTime && type.endTime))
        } else {
          continue;
        }
      }
      return false;
    },
    enableFleetWhiteList() {
      for (let type of this.siteTypeTable) {
        if (type.siteType == "PRI_FLE_WHI") {
          return (type.allDay || (type.startTime && type.endTime))
        } else {
          continue;
        }
      }
      return false;
    },
    isSiteTypeEnable(index, isSwitch) {
      for (let i = 0; i < this.siteTypeTable.length; i++) {
        let type = this.siteTypeTable[i];
        if (type.allDay) {
          if (index == i && isSwitch) {
            return false;
          } else {
            return true;
          }
        } else {
          continue;
        }
      }
      return false;
    }
  }
}

</script>

<style lang='scss' scoped>
  @import '../../styles/variables.scss';

  .view-container {
    width: 100%;
    padding: 20px 60px;
    min-height: $mainAppMinHeight;
    background-color: #F0F5FC;
  }

  .view-content {
    padding: 15px 80px;
    border-radius: 6px;
    background-color: white;
  }

  .sparator {
    margin: 10px -40px;
    height: 2px;
    background-color: #F0F5FC;
  }

  .section-title {
    color: #333333;
    margin-top: 20px;
    margin-bottom: 30px;
    font-size: 16px;
    line-height: 24px;
    font-weight: 500;
    font-family: sans-serif;
    text-transform: uppercase;
  }

  .input-text {
    width: 100%;
    max-width: 300px;
  }

  .input-text .el-textarea__inner {
    font-family: sans-serif;
  }

  .rate-list-view {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
  }
  
  .rate-text-max {
    max-width: 200px;
    padding-right: 14px;
  }

  .rate-text {
    max-width: 150px;
    padding-right: 14px;
  }
  
  .rate-type {
    max-width: 100px;
    padding-right: 14px;
  }

  .list-item-icon {
    width: 30px;
    height: 30px;
    cursor: pointer;
    margin: 0 10px 22px;
  }

  .cancel-button {
    width: 94px;
    height: 40px;
    color: #555;
    background: #FFFFFF;
    border: 1px solid #001489;
    box-sizing: border-box;
    border-radius: 4px;
  }

  .confirm-button {
    width: 94px;
    height: 40px;
    margin-left: 20px;
    background: #001489;
    border: 1px solid #001489;
    box-sizing: border-box;
    border-radius: 4px;
  }

  ::v-deep .el-switch__label.el-switch__label--left > span {
    font-size: 14px;
    color: #333;
  }

  .ratePunit {
    height: 39px;
    font-size: 20px;
    margin-left: -5px;
    padding-right: 10px;
  }
</style>
