<template>
  <div class="view-container">
    <div class="view-content" v-loading="pageLoading">
      <el-form
        ref="addSiteForm"
        :rules="rules"
        :model="siteForm"
        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
                v-model="siteForm.siteInformation.siteName"
                class="input-text" />
            </el-form-item>
            <el-form-item
              prop="siteInformation.latitude"
              label="Latitude:">
                <el-input
                  v-model="siteForm.siteInformation.latitude"
                  class="input-text" />
            </el-form-item>
            <el-form-item
              prop="siteInformation.longitude"
              label="Longitude:">
                <el-input
                  v-model="siteForm.siteInformation.longitude"
                  class="input-text" />
            </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
                    :disabled="siteForm.additionalInformation.endlessService"
                    v-model="siteForm.additionalInformation.operatingHours"
                    class="input-text" />
              </el-form-item>
              <el-switch
                style="margin-left: 10px"
                inactive-text="24/7"
                @change="endlessServiceSwitchChange"
                v-model="siteForm.additionalInformation.endlessService">
              </el-switch>
            </div>
            <div style="display: flex; ">
              <el-form-item
                label-width="130px"
                label="Parking Fee:"
                class="flex-item">
                  <el-input
                    :disabled="siteForm.additionalInformation.free"
                    v-model="siteForm.additionalInformation.parkingFee"
                    class="input-text" />
              </el-form-item>
              <el-switch
                style="margin-left: 10px"
                inactive-text="Free"
                @change="freeSwitchChange"
                v-model="siteForm.additionalInformation.free">
              </el-switch>
            </div>
            <div class="flex">
              <el-form-item
                label-width="130px"
                label="Additional Notes:"
                class="flex-item flex">
                <el-input
                  v-model="siteForm.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="siteForm.idle.enableIdleFee"/>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item
              prop="siteInformation.type"
              label="Type:">
              <div class="type-row" v-for="(item, index) in siteTypeTable">
                <el-time-picker
                  v-model="item.startTime"
                  format="HH:mm"
                  value-format="HH:mm"
                  :placeholder="item.label"
                  :disabled="isSiteTypeEnable(index)"/>
                <el-time-picker
                  v-model="item.endTime"
                  format="HH:mm"
                  value-format="HH:mm"
                  placeholder="End Time"
                  :disabled="isSiteTypeEnable(index)"/>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="sparator"></div>
        <div class="section-title">
          EMAIL
        </div>
        <el-form
          :model="this"
          :rules="rule"
          ref="recipForm"
          label-position="left"
          label-width="150px">
          <el-row :gutter="20">
            <el-col :xs="24" :sm="16" :md="10" :lg="9">
              <el-form-item
                label="Recipients:"
                prop="recipient">
                <el-input
                  class="add-text"
                  v-model="recipient"
                  placeholder="Add text"
                  maxlength="50"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-button
                type="primary"
                icon="el-icon-plus"
                @click="addRecipient">
                Add
              </el-button>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item
                label="Added Recipients:">
                <div class="receip-item" v-for="(item, index) in recipients" :key="index">
                  <span>{{item}}</span>
                  <i class="el-icon-close" @click="deleteRecipient(index)"></i>
                </div>
                <div
                  class="link-button"
                  v-if="recipients.length > 0"
                  @click="clearAllRecipient">Clear All</div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      <!-- <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> -->
        <!-- prop="siteInformation.type"
        label="Type">
        <el-select
          v-model="siteForm.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> -->
      <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="siteForm.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="siteForm.address.street"
                class="input-text" />
          </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="siteForm.address.city"
                class="input-text"
                @keyup.enter.native="handleFilter" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            prop="address.postalCode"
            label-width="130px"
            label="Postal Code:">
              <el-input
                v-model="siteForm.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 siteForm.chargeRates"
        :key="item.ratePk">
        <el-form-item
          label="Type"
          label-width="60px"
          :prop="'chargeRates.' + index + '.chargeTypePk'"
          :rules="rules.chargeRate.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-select>
        </el-form-item>
        <el-form-item
          label="Rate"
          label-width="60px"
          :prop="'chargeRates.' + index + '.rate'"
          :rules="rules.chargeRate.rate">
          <el-input
            v-model="item.rate"
            class="rate-text" />
        </el-form-item>
        <div class="ratePunit">/</div>
        <el-form-item
          label-width="0px"
          prop="type">
          <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="handleClickSubChargeRateButton(item, index)"
          src="../../assets/form-list-sub.png"/>
      </div>
      <div class="rate-list-view">
        <el-form-item
          label="Type"
          label-width="50px"
          prop="tempChargeRate.chargeTypePk"
          :rules="rules.chargeRate.chargeTypePk">
          <el-select
            v-model="siteForm.tempChargeRate.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="tempChargeRate.rate"
          :rules="rules.chargeRate.rate">
            <el-input
              v-model="siteForm.tempChargeRate.rate"
              class="rate-text" />
        </el-form-item>
        <div class="ratePunit">/</div>
        <el-form-item
          label-width="0px">
          <el-select
            v-model="siteForm.tempChargeRate.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="handleClickSubTempChargeRateButton"
          src="../../assets/form-list-sub.png"/>
        <img
          class="list-item-icon"
          @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 siteForm.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="siteForm.specialChargeRates.length - 1 === index"
            class="list-item-icon"
            @click="handleClickAddSpecialRateButton"
            src="../../assets/form-list-add.png"/>
        </div>
      </div>
      <reservation
        :enable="siteForm.reservation.enable"
        :timeLimit="siteForm.reservation.timeLimit"
        @enable="reservationTimeLimitEnable"
        @time-limit-change="reservationTimeLimitChange"
      />
      
      <div class="sparator" ></div>
      <div class="specialChangeRate">
        <div class="section-title">
          LOAD BALANCING
        </div>
        <Balancing v-model="balancingForm" title="Add"/>
        <!-- <el-row
          :gutter="20"
          v-for="(item, index) in balancingForm.siteChargingProfiles"
          :key="index">
          <el-col :span="6" :offset="0">
            <el-form-item
              label="Chargers In-Use:"
              label-width="150px">
              <el-select v-model="item.boxInUse">
                <el-option
                  v-for="(item,index) in [1,2]"
                  :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">
              <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="balancingForm.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 siteForm.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 === siteForm.fleetWhitelist.length - 1"
            class="list-item-icon"
            @click="handleClickAddWhiteFleetButton"
            src="../../assets/form-list-add.png"/>
        </div>
      </div>
      <div v-if="enableUserWhiteList()">
        <div class="sparator"></div>
        <div class="section-title">
          WHITELIST USERS
        </div>
        <div
          class="rate-list-view"
          v-for="(item, index) in siteForm.whitelistUser"
          :key="index">
          <el-form-item
            label-width="130px"
            label="Mobile Number"
            :rules="rules.whitelistUser.mobileNumber"
            :prop="'whitelistUser.' + index + '.mobileNumber'">
            <el-input
              v-model="item.mobileNumber"
              class="rate-text" />
          </el-form-item>
          <el-form-item
            label-width="140px"
            label="Licence Number"
            :rules="rules.whitelistUser.licenceNumber"
            :prop="'whitelistUser.' + index + '.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 === siteForm.whitelistUser.length - 1"
            class="list-item-icon"
            @click="handleClickAddWhiteUserButton"
            src="../../assets/form-list-add.png"/>
        </div>
      </div>
      
      <div v-if="siteForm.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="siteForm.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="siteForm.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="siteForm.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="siteForm.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="siteForm.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 Balancing from './components/Balancing'
import Reservation from './components/Reservation'
import waves from '@/directive/waves' // waves directive
import site from '../../http/api/site'
import { fetchFleetCompanyOptions } from '@/http/api/driver'

export default {
  name: 'AddSite',
  directives: { waves },
  components: { Balancing, Reservation },
  async created() {
    this.pageLoading = true;
    this.getChargeTypeOptions()
    this.getRateTypeOptions()
    this.getSiteTypeOptions()
    this.getCountryOptions()
    await this.getCompanyOptions()
    //this.getChargingProfileOPtions()
    this.pageLoading = false;
  },
  data() {
    return {
      pageLoading: false,
      rateTypeOptions: [],
      chargeTypeOptions: [],
      siteTypeOptions: [],
      countryOptions: [],
      companyOptions: [],
      chargingProfileOPtions: [],
      
      recipient: '',
      recipients: [],
      siteTypeTable: [{
        siteType: "",
        allDay: false,
        startTime: "",
        endTime: ""
      }],
      additionalNotesAutosize: {
        minRows: 3,
        maxRows: 6,
      },
      balancingForm: {
        loadBalancing: 'dynamic',
        staticMaxAmpere: 0,
        siteChargingProfiles: [{
          boxInUse: '',
          chargingProfilePk: ''
        }],
      },
      siteForm: {
        specialChargeRates: [
          {
            fleetCompanyId: '',
            chargeTypePk: '',
            rate: '',
            rateType: '',
          }
        ],
        siteInformation: {
          siteName: '',
          latitude: '',
          longitude: '',
          type: 'PUBLIC',
        },
        additionalInformation: {
          operatingHours: '',
          parkingFee: '',
          additionalNotes: '',
          endlessService: false,
          free: false,
        },

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

        tempChargeRate: {
          chargeTypePk: '',
          rate: '',
          rateType: '',
        },
        chargeRates: [],

        whitelistUser: [{
          licenceNumber: '',
          mobileNumber: '',
        }],
        fleetWhitelist: [{
          //siteFleetId: "",
          fleetCompanyId: ''
        }],
        reservation: {
          enable: false,
          timeLimit: 15,
        },
        idle: {
          enableIdleFee: false,
          idleFee: '',
          effectiveDate: '',
          effectiveFrom: '',
          effectiveTo: '',
          everyMinute: ''
        }
      },
      rule: {
        "recipient": {
          pattern: /^[a-zA-Z0-9]+[\S]+@[a-zA-Z0-9_-]+[\.][\Sa-zA-Z]+$/,
          trigger: 'blur',
          message: 'Please type a correct recipient'
        }
      },
      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'
          }]
        }
      },
      swtSpecialRate: false
    }
  },
  methods: {
    handleClickAddSpecialRateButton() {
      this.siteForm.specialChargeRates.push(
        {
          fleetCompanyId: this.companyOptions[0].fleetCompanyId,
          chargeTypePk: this.chargeTypeOptions[0].chargeTypePk,
          rate: '',
          rateType: this.rateTypeOptions[0].value,
        }
      )
    },
    handleClickSubSpecialRateButton(specialRate, index) {
      this.siteForm.specialChargeRates.splice(index, 1)
      if (this.siteForm.specialChargeRates.length === 0) {
        this.siteForm.specialChargeRates.push(
          {
            fleetCompanyId: this.companyOptions[0].fleetCompanyId,
            chargeTypePk: this.chargeTypeOptions[0].chargeTypePk,
            rate: '',
            rateType: this.rateTypeOptions[0].value,
          }
        )
      }
    },
    reservationTimeLimitEnable(enable) {
      this.siteForm.reservation.enable = enable
    },
    reservationTimeLimitChange(timeLimit) {
      this.siteForm.reservation.timeLimit = timeLimit
    },
    endlessServiceSwitchChange(value) {
      if (value) {
        this.siteForm.additionalInformation.operatingHours = ""
      }
    },
    freeSwitchChange(value) {
      if (value) {
        this.siteForm.additionalInformation.parkingFee = ""
      }
    },
    getChargeTypeOptions() {
      site.getChargeTypeList().then((response) => {
        const { data = [] } = response
        this.chargeTypeOptions = data
        this.setTempChargeTypeDefaultValue()
        this.siteForm.specialChargeRates[0].chargeTypePk = data[0].chargeTypePk
      });
    },
    setTempChargeTypeDefaultValue() {
      if (this.chargeTypeOptions.length > 0) {
        const defaultValue = this.chargeTypeOptions[0].chargeTypePk
        this.siteForm.tempChargeRate.chargeTypePk = defaultValue
      }
    },
    getRateTypeOptions() {
      site.getRateTypeList().then((response) => {
        const { data = [] } = response
        this.rateTypeOptions = data
        this.setTempRateTypeDefaultValue()
        this.siteForm.specialChargeRates[0].rateType = data[0].value
      });
    },
    setTempRateTypeDefaultValue() {
      if (this.rateTypeOptions.length > 0) {
        const defaultValue = this.rateTypeOptions[0].value
        this.siteForm.tempChargeRate.rateType = defaultValue
      }
    },
    getSiteTypeOptions() {
      site.getSiteTypeList().then((response) => {
        this.siteTypeOptions = response.data
        const { data } = response;
        if (data && data.length > 0) {
          this.siteTypeTable = [];
          data.forEach(item => {
            this.siteTypeTable.push({
              label: item.name,
              siteType: item.value,
              allDay: false,
              startTime: "",
              endTime: ""
            })
          })
          //this.siteForm.siteInformation.type = data[0].value
        }
      });
    },
    getCompanyOptions() {
      fetchFleetCompanyOptions().then((response) => {
        const { data, success } = response
        if (success) {
          this.companyOptions = data
          if (data && data.length > 0) {
            this.siteForm.specialChargeRates[0].fleetCompanyId = data[0].fleetCompanyId
          }
        }
      })
    },
    getCountryOptions() {
      site.getCountryList().then(({ data }) => {
        this.countryOptions = data
        if (data && data.length > 0) {
          this.siteForm.address.country = data[0].value
        }
      })
    },
    getChargingProfileOPtions() {
      site.getChargingProfiles().then(({ data }) => {
        this.chargingProfileOPtions = data
      })
    },
    handleClickSubChargeRateButton(chargeRate, index) {
      this.siteForm.chargeRates.splice(index, 1)
    },
    handleClickSubTempChargeRateButton() {
      if (this.siteForm.chargeRates.length > 0) {
        const {
          rate,
          rateType,
          chargeTypePk,
        } = this.siteForm.chargeRates.pop()
        this.siteForm.tempChargeRate.chargeTypePk = chargeTypePk
        this.siteForm.tempChargeRate.rateType = rateType
        this.siteForm.tempChargeRate.rate = rate
      } else {
        this.resetTempChargeRate()
      }
    },
    handleClickAddChargeRateButton() {
      this.siteForm.chargeRates.push({
        ...this.siteForm.tempChargeRate
      })
      this.resetTempChargeRate()
    },
    resetTempChargeRate() {
      this.setTempRateTypeDefaultValue()
      this.siteForm.tempChargeRate.rate = ''
      this.setTempChargeTypeDefaultValue()
    },
    handleClickAddWhiteUserButton() {
      this.siteForm.whitelistUser.push({
        mobileNumber: '',
        licenceNumber: '',
      })
    },
    handleClickSubWhiteUserButton(user, index) {
      this.siteForm.whitelistUser.splice(index, 1)
      if (this.siteForm.whitelistUser.length === 0) {
        this.siteForm.whitelistUser.push({
          mobileNumber: '',
          licenceNumber: '',
        })
      }
    },
    handleClickAddWhiteFleetButton() {
      this.siteForm.fleetWhitelist.push({
        fleetCompanyId: ''
      })
    },
    handleClickSubWhiteFleetButton(fleet, index) {
      this.siteForm.fleetWhitelist.splice(index, 1)
      if (this.siteForm.fleetWhitelist.length === 0) {
        this.siteForm.fleetWhitelist.push({
          fleetCompanyId: ''
        })
      }
    },
    handleClickCancleButton() {
      this.$router.go(-1)
    },
    handleClickConfigUpateButton() {
      this.$refs['addSiteForm'].validate(result => {
        if (result) {
          this.addSiteWithForm();
        }
      })
    },
    addRecipient() {
      if (this.recipient) {
        this.$refs["recipForm"].validate(result => {
          if (result) {
            this.recipients.push(this.recipient);
            this.recipient = "";
          }
        });
      }
    },
    deleteRecipient(index) {
      this.recipients.splice(index, 1);
    },
    clearAllRecipient() {
      this.$confirm('Clear all recipients?', 'Prompt', {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }).then(res => {
        this.recipients = [];
      })
    },
    addSiteWithForm() {
      const {
        siteName,
        //type: siteType,
        latitude: locationLatitude,
        longitude: locationLongitude,
      } = this.siteForm.siteInformation

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

      const chargeRates = [...this.siteForm.chargeRates]
      const chargeProfiles = []
      const {
        chargeTypePk,
        rate,
        rateType,
      } = this.siteForm.tempChargeRate
      if (chargeTypePk && rate && rateType) {
        chargeRates.push({
          chargeTypePk,
          rate,
          rateType,
        })
      }
      if (this.swtSpecialRate) {
        this.siteForm.specialChargeRates.forEach(({
            fleetCompanyId,
            chargeTypePk,
            rate,
            rateType,
          }) => {
            if (chargeTypePk && fleetCompanyId && rate && rateType) {
              chargeRates.push({
                fleetCompanyId,
                chargeTypePk,
                rate,
                rateType,
              })
            }
        })
      }

      this.balancingForm.siteChargingProfiles.forEach(item => {
        if (item.boxInUse && item.chargingProfilePk)
          chargeProfiles.push(item)
      })

      const {
        free,
        parkingFee,
        endlessService,
        additionalNotes,
        operatingHours,
      } = this.siteForm.additionalInformation

      const { whitelistUser, fleetWhitelist, siteChargingProfiles } = this.siteForm
      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 data = {
        siteName,
        siteTypes,
        locationLatitude,
        locationLongitude,
        enableReservation: this.siteForm.reservation.enable,
        timeLimit: this.siteForm.reservation.timeLimit,
        address: {
          street,
          city,
          country,
          countryCode: country,
          zipCode: postalCode
        },
        chargeRates,
        whitelistUser,
        fleetWhitelist,
        siteChargingProfiles: chargeProfiles,
        free,
        endlessService,
        operatingHours,
        parkingFee,
        additionalNotes,
        loadBalancing: this.balancingForm.loadBalancing,
        staticMaxAmpere: this.balancingForm.staticMaxAmpere,
        ...this.siteForm.idle,
        emails: this.recipients
      };

      site.addSite(data)
        .then(() => {
          this.$router.go(-1)
          this.$notify({
            title: "add site success",
            type: 'success',
            duration: 5000,
          })
        })
        .catch((error) => {
          this.$message({
            message: error,
            type: "error",
            duration: 5 * 1000,
          })
          this.pageLoading = false;
        })
    },
    siteTypeSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex == 2) {
        return [1,2]
      } else if (columnIndex == 3) {
        return [0,0]
      }
    },
    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 scoped lang='scss'>
  @import '../../styles/element-ui.scss';
  @import '../../styles/variables.scss';

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

  .view-content {
    padding: 15px 60px;
    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: 5px 10px 22px;
  }

  .cancel-button {
    width: 94px;
    height: 40px;
  }

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

  ::v-deep .el-switch__label.el-switch__label--left span {
    font-size: 14px;
    color: black;
  }
  .ratePunit {
    height: 39px;
    font-size: 20px;
    margin-left: -5px;
    padding-right: 10px;
  }
  .type-row {
    display: flex;
    align-items: center;
    padding-bottom: 10px;
  }
  .type-row > div {
    margin-right: 10px;
  }
  .link-button {
    color: #3179E4;
    font-size: 14px;
    cursor: pointer;
    margin: 0 -10px;
    padding: 0 10px;
    display: inline-block;
    white-space: nowrap;
    text-decoration: underline;
  }
  .receip-item {
    display: flex;
    align-items: center;
    font-size: 14px;
    line-height: 1em;
    padding-top: 10px;
  }
  .receip-item i {
    color: #666;
    padding: 0 10px;
    cursor: pointer;
  }
  .receip-item i:hover,
  .receip-item i:active,
  .link-button:hover {
    color: #ff5500;
  }
</style>
