<template>
  <div class="card-container">
    <el-form
      :model="addForm"
      :rules="rule"
      v-loading="loading"
      ref="addForm"
      label-width="150px"
      label-position="right">
      <div class="card-content">
        <div class="section-title">Charging Profile Information</div>
        <el-row :gutter="20">
          <el-col :xs="24" :md="12">
            <el-form-item
              label="Description:"
              prop="description">
              <el-input
                class="add-text"
                v-model="addForm.description"
                placeholder="Add text"
                maxlength="100"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-form-item
              label="Recurrency Kind:">
              <el-select
                class="add-text"
                v-model="addForm.recurrencyKind"
                placeholder="Select">
                <el-option
                  v-for="(item, index) in recurrencyOptions"
                  :key="index"
                  :label="item.name"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :xs="24" :md="12">
            <el-form-item
              label="Stack Level:"
              prop="stackLevel">
              <el-input
                class="add-text"
                v-model.number="addForm.stackLevel"
                placeholder="Add text"
                type="number"
                min="0"
                max="99"
                maxlength="2"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-form-item
              label="Valid From:">
              <el-date-picker
                class="add-text"
                v-model="addForm.validFrom"
                type="date"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                placeholder="Select date"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :xs="24" :md="12">
            <el-form-item
              label="Purpose:"
              prop="chargingProfilePurpose">
              <el-select
                class="add-text"
                v-model="addForm.chargingProfilePurpose"
                placeholder="Add text">
                <el-option
                  v-for="(item, index) in purposeOptions"
                  :key="index"
                  :label="item.name"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-form-item
              label="Valid To:">
              <el-date-picker
                class="add-text"
                v-model="addForm.validTo"
                type="date"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                placeholder="Select date"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :xs="24" :md="12">
            <el-form-item
              label="Kind:"
              prop="chargingProfileKind">
              <el-select
                class="add-text"
                v-model="addForm.chargingProfileKind"
                placeholder="Add text">
                <el-option
                  v-for="(item, index) in kindOptions"
                  :key="index"
                  :label="item.name"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-form-item
              label="Duration:"
              prop="registrationStatus"
              class="form-unit">
              <span class="item-unit">(Hours)</span>
              <el-select
                class="add-text"
                v-model="addForm.durationInSeconds"
                placeholder="Add text">
                <el-option
                  v-for="item in 24"
                  :key="item"
                  :label="item"
                  :value="item"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :xs="24" :md="12">
            <el-form-item
              label="Charge Rate Unit:"
              prop="chargingRateUnit">
              <el-select
                class="add-text"
                v-model="addForm.chargingRateUnit"
                placeholder="Add text">
                <el-option
                  v-for="(item, index) in rateUnitOptions"
                  :key="index"
                  :label="item.name"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-form-item
              label="Start Date:"
              prop="startSchedule">
              <el-date-picker
                class="add-text"
                v-model="addForm.startSchedule"
                type="date"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                placeholder="Select date"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :xs="24" :md="12">
            <el-form-item
              label="Min Charging Rate:"
              class="form-unit">
              <span class="item-unit" style="left: -150px;">(Decimal, Multiple Of 0.1)</span>
              <el-input
                class="add-text"
                v-model="addForm.minChargingRate"
                placeholder="Add text"
                maxlength="30"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-form-item
              label="Additional Notes:">
              <el-input
                class="add-text"
                type="textarea"
                v-model="addForm.note"
                :autosize="autosize"
                placeholder="Add text"
                maxlength="300"/>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
      <div class="card-content">
        <div class="section-title">Schedule Period</div>
        <div class="rate-list-view" v-for="(item, index) in addForm.schedulePeriod" :key="index">
          <el-form-item
            label="Start Time:"
            label-width="115px"
            :prop="'schedulePeriod.' + index + '.startPeriod'"
            :rules="rule.schedulePeriod.startPeriod">
            <el-time-select
              class="rate-text"
              :picker-options="pickerOptions"
              :editable="false"
              placeholder="Select time"
              v-model="item.startPeriod"/>
          </el-form-item>
          <el-form-item
            label="Power Limit:"
            label-width="115px"
            :prop="'schedulePeriod.' + index + '.powerLimitInAmperes'"
            :rules="rule.schedulePeriod.powerLimitInAmperes">
            <el-input
              class="rate-text"
              style="min-width: 160px;"
              v-model.number="item.powerLimitInAmperes"
              type="number"
              maxlength="10"
              placeholder="Add text"/>
            <!--span class="limit-unit">A</span-->
          </el-form-item>
          <el-form-item
            label="No. Of Phase:"
            label-width="115px"
            :prop="'schedulePeriod.' + index + '.numberPhases'"
            :rules="rule.schedulePeriod.numberPhases">
            <el-select
              class="rate-text"
              v-model="item.numberPhases"
              placeholder="Select">
              <el-option 
                v-for="(item, index) in numberPhasesOptions"
                :key="index"
                :label="item"
                :value="item"/>
            </el-select>
          </el-form-item>
          <div>
            <img
              v-if="addForm.schedulePeriod.length > 1"
              class="list-item-icon" src="../../assets/form-list-sub.png"
              @click="delSchedule(index)"/>
            <img
              v-if="index == addForm.schedulePeriod.length-1"
              class="list-item-icon" src="../../assets/form-list-add.png"
              @click="addSchedule"/>
          </div>
        </div>
      </div>
      <div class="card-content">
        <div class="buttons">
          <el-button
            type="primary"
            class="cancel-button"
            @click="handleClickCancleButton">
            Cancel
          </el-button>
          <el-button
            style="margin-left: 20px;"
            type="primary"
            native-type="submit"
            @click="handleClickConfigUpateButton">
            Save
          </el-button>
        </div>
      </div>
    </el-form>
  </div>
</template>

<script>
  import api from '../../http/api/chargingProfile.js'
  export default {
    data() {
      return {
        loading: true,
        autosize: {
          minRows: 3,
          maxRows: 6
        },
        addForm: {
          stackLevel: 0,
          description: "",
          durationInSeconds: "24",
          validFrom: "",
          validTo: "",
          startSchedule: "",
          note: "",
          chargingProfilePurpose: "TX_DEFAULT_PROFILE",
          chargingProfileKind: "RECURRING",
          recurrencyKind: "DAILY",
          chargingRateUnit: "A",
          minChargingRate: "",
          schedulePeriod: []
        },
        pickerOptions: {
          start: '00:00',
          step: '00:30',
          end: '23:30'
        },
        purposeOptions: [],
        kindOptions: [],
        rateUnitOptions: [],
        recurrencyOptions: [],
        numberPhasesOptions: [1, 3],
        rule: {
          stackLevel: [{
            required: true,
            trigger: 'blur',
            message: 'Please input stack level'
          }, {
            type: 'number',
            min: 0,
            max: 99,
            message: 'Stack level range is 0-99'
          }],
          description: {
            required: true,
            trigger: 'blur',
            message: 'Please input description'
          },
          chargingProfilePurpose: {
            required: true,
            trigger: 'change',
            message: 'Please select purpose'
          },
          chargingProfileKind: {
            required: true,
            trigger: 'change',
            message: 'Please select kind'
          },
          chargingRateUnit: {
            required: true,
            trigger: 'change',
            message: 'Please select charging rate unit'
          },
          startSchedule: {
            required: true,
            trigger: 'change',
            message: 'Please select start date'
          },
          schedulePeriod: {
            startPeriod: {
              required: true,
              trigger: 'change',
              message: 'Please select start time'
            },
            numberPhases: {
              required: true,
              trigger: 'change',
              message: 'Please select No. of Phase'
            },
            powerLimitInAmperes: [{
              required: true,
              trigger: 'blur',
              message: 'Please input power limit'
            }/*, {
              type: 'number',
              min: 1,
              max: 999,
              message: 'Power Limit range is 1-999'
            }*/]
          }
        },
        defScheduleInfo: {
          startPeriod: "",
          numberPhases: "",
          powerLimitInAmperes: ""
        }
      }
    },
    created() {
      this.addSchedule();
      this.getRecurrencyOptions();
    },
    methods: {
      async getRecurrencyOptions() {
        const res = await api.getRecurrencyKindList();
        if (res.success) {
          this.recurrencyOptions = res.data
        }
        this.getPurposeOptions();
      },
      async getPurposeOptions() {
        const res = await api.getPurposeOptionList();
        if (res.success) {
          this.purposeOptions = res.data
        }
        this.getKindOptions();
      },
      async getKindOptions() {
        const res = await api.getKindOptionList();
        if (res.success) {
          this.kindOptions = res.data
        }
        this.getRateUnitOptions();
      },
      async getRateUnitOptions() {
        const res = await api.getChargingRateUnitList();
        if (res.success) {
          this.rateUnitOptions = res.data
        }
        this.loading = false;
      },
      addSchedule() {
        this.addForm.schedulePeriod.push(Object.assign({}, this.defScheduleInfo));
      },
      delSchedule(index) {
        this.addForm.schedulePeriod.splice(index, 1);
      },
      handleClickConfigUpateButton() {
        this.$refs['addForm'].validate(result => {
          if (result) {
            this.addChargingProfile();
          }
        })
      },
      addChargingProfile() {
        this.loading = true;
        api.addChargingProfile(this.addForm).then(res => {
          this.$message({
            message: 'Add charging profile successfully',
            type: 'success'
          })
          this.loading = false;
          this.handleClickCancleButton()
        }).catch(err => {
          this.loading = false;
          this.$message({
            message: err,
            type: 'error'
          })
        });
      },
      handleClickCancleButton() {
        this.$nextTick(() => {
          this.$router.replace({
            path: "/smart-energy-management/charging-profiles"
          })
        })
      }
    }
  }
</script>

<style scoped="scoped" lang='scss'>
  @import '../../styles/variables.scss';
  
  .card-container {
    width: 100%;
    padding: 20px 60px;
    min-height: $mainAppMinHeight;
    background-color: #F0F5FC;
  }
  .card-content {
    margin: 0 8px 16px;
    padding: 15px 50px;
    border-radius: 6px;
    background-color: white;
  }
  .section-title {
    color: #333;
    margin-top: 20px;
    margin-bottom: 30px;
    font-size: 15px;
    user-select: none;
    line-height: 24px;
    font-weight: 700;
    font-family: sans-serif;
    text-transform: uppercase;
  }
  .add-text {
    width: 100% !important;
    max-width: 300px;
  }
  .add-text ::v-deep .el-textarea__inner {
    font-family: sans-serif;
  }
  .hr {
    height: 2px;
    margin: 10px -40px;
    background-color: #F0F5FC;
  }
  .hr-full {
    height: 2px;
    margin: 20px -80px;
    background-color: #F0F5FC;
  }
  .rate-list-view {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
  }
  .rate-text {
    max-width: 160px;
    padding-right: 14px;
  }
  .list-item-icon {
    width: 30px;
    height: 30px;
    cursor: pointer;
    margin: 0 10px 22px;
  }
  .buttons {
    padding-top: 15px;
    padding-bottom: 15px;
  }
  .form-unit ::v-deep .el-form-item__label {
    line-height: 30px;
  }
  .item-unit {
    top: 12px;
    left: -55px;
    font-size: 12px;
    user-select: none;
    position: absolute;
  }
  .limit-unit {
    right: 22px;
    font-size: 13px;
    user-select: none;
    position: absolute;
  }
  @media screen and (max-width: 500px) {
    .card-container {
      padding: 0px;
    }
    .card-content {
      padding: 15px 20px;
    }
  }
</style>
