<template>
  <div class="card-container">
    <el-form
      :model="editForm"
      :rules="rule"
      v-loading="loading"
      ref="editForm"
      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="editForm.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="editForm.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="editForm.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="editForm.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="editForm.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="editForm.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="editForm.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="editForm.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="editForm.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="editForm.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="editForm.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="editForm.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 editForm.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="editForm.schedulePeriod.length > 1"
              class="list-item-icon" src="../../assets/form-list-sub.png"
              @click="delSchedule(index)"/>
            <img
              v-if="index == editForm.schedulePeriod.length-1"
              class="list-item-icon" src="../../assets/form-list-add.png"
              @click="addSchedule"/>
          </div>
        </div>
      </div>
      
      <div class="card-content flexcr">
        <div class="buttons">
          <el-button
            type="primary"
            class="cancel-button"
            @click="handleClickCancleButton">
            Cancel
          </el-button>
          <el-button
            style="margin-left: 20px;"
            type="primary"
            v-if="!isView"
            @click="handleClickConfigUpateButton">
            Save
          </el-button>
        </div>
        <div class="update-by">
          <span
            class="add-text"
            :title='"CREATED BY " + editForm.createdBy + " ON " + editForm.createdOn'>
            LAST UPDATED BY {{editForm.updatedBy}} TIMESTAMP: {{editForm.updatedOn}}
          </span>
        </div>
      </div>
    </el-form>
  </div>
</template>

<script>
  import { mapState } from 'vuex'
  import api from '../../http/api/chargingProfile.js'
  export default {
    data() {
      return {
        loading: true,
        autosize: {
          minRows: 3,
          maxRows: 6
        },
        editForm: {
          stackLevel: 0,
          description: "",
          durationInSeconds: "24",
          validFrom: "",
          validTo: "",
          startSchedule: "",
          note: "",
          chargingProfilePk: "",
          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'
            }]
          }
        },
        defScheduleInfo: {
          startPeriod: "",
          numberPhases: "",
          powerLimitInAmperes: ""
        },
        isView: false
      }
    },
    computed: {
      ...mapState('charge', ['profileId'])
    },
    created() {
      this.editForm.chargingProfilePk = this.profileId;
      if (this.$route.params.id) {
        this.editForm.chargingProfilePk = this.$route.params.id;
        this.isView = true;
      }
      this.addSchedule();
      this.getProfileInfo();
    },
    methods: {
      async getProfileInfo() {
        const res = await api.getChargingProfileById(this.editForm.chargingProfilePk)
        if (res.success) {
          const editForm = res.data
          editForm.durationInSeconds = parseInt(editForm.durationInSeconds / 3600);
          editForm.schedulePeriod.forEach((item, index) => {
            if (item.startPeriodInSeconds && item.startPeriodInSeconds > 60) {
              let minitues = item.startPeriodInSeconds / 60;
              let min = minitues % 60;
              let hor = parseInt(minitues / 60);
              if (hor == 0) hor = '00';
              item.startPeriod = hor + ":" + (min == 0 ? '00' : min);
            } else {
              item.startPeriod = '00:00';
            }
          })
          this.editForm = editForm
          this.getRecurrencyOptions();
        }
      },
      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.editForm.schedulePeriod.push(Object.assign({}, this.defScheduleInfo));
      },
      delSchedule(index) {
        this.editForm.schedulePeriod.splice(index, 1);
      },
      handleClickConfigUpateButton() {
        this.$refs['editForm'].validate(result => {
          if (result) {
            this.editChargingProfile();
          }
        })
      },
      editChargingProfile() {
        this.loading = true;
        api.updateChargingProfile(this.editForm).then(res => {
          this.$message({
            message: 'Edit charging profile successfully',
            type: 'success'
          })
          this.handleClickCancleButton()
        }).catch(err => {
          this.loading = false;
          this.$message({
            message: err,
            type: 'error'
          })
        });
      },
      handleClickCancleButton() {
        if (this.isView) {
          this.$router.push({
            path: "/smart-energy-management/config-stations"
          })
        } else {
          this.$router.push({
            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;
    font-size: 14px;
    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>
