<template>
  <div class="card-container">
    <div class="card-content">
      <el-form
        :model="settingsForm"
        :rules="rule"
        v-loading="loading"
        ref="settingsForm"
        label-position="left"
        label-width="150px"
        style="width: 100%;">
        <div class="section-title">OPCC Settings</div>
        <el-row :gutter="20">
          <el-col :xs="24" :sm="16" :md="12" :lg="9">
            <div class="flexc">
              <el-form-item
                label="Heartbeat Interval:"
                prop="heartbeat"
                class="flex1">
                <el-input
                  class="value-text"
                  v-model="settingsForm.heartbeat"
                  placeholder="Add text"
                  maxlength="5"/>
              </el-form-item>
              <span class="el-form-item">&nbsp;&nbsp;Minutes</span>
            </div>
            <div class="tips">The time interval in <i>minutes</i> for how often a charge point should request the current time from the CSMS.</div>
          </el-col>
          <el-col :xs="4" :sm="8" :md="2" :lg="6">
            <p></p>
          </el-col>
          <el-col :xs="24" :sm="16" :md="10" :lg="8">
            <div class="flexc">
              <el-form-item
                label="Expiration:"
                prop="expiration"
                label-width="95px"
                class="flex1">
                <el-input
                  class="value-text"
                  v-model="settingsForm.expiration"
                  placeholder="Add text"
                  maxlength="5"/>
              </el-form-item>
              <span class="el-form-item">&nbsp;&nbsp;Hours</span>
            </div>
            <div class="tips" style="padding-left: 95px;">The amount of time in <i>hours</i> for how long a charge point should cache the authorization info of an idTag in its local white list, if an expiry date is not explicitly set. 
            The value 0 disables this functionality 
              (i.e.no expiry date will be set).</div>
          </el-col>
        </el-row>
        <div class="hr"></div>
        <div class="section-title">
          <span style="padding-right: 30px;">Mail Notification Settings</span>
          <el-checkbox v-model="settingsForm.enabled">Enable notifications</el-checkbox>
        </div>
        <el-row :gutter="20">
          <el-col :xs="24" :sm="16" :md="10" :lg="9">
            <el-form-item
              label="Protocol:"
              prop="protocol">
              <el-input
                class="add-text"
                v-model="settingsForm.protocol"
                placeholder="Add text"
                maxlength="10"/>
            </el-form-item>
          </el-col>
          <el-col :xs="4" :sm="8" :md="4" :lg="6" :xl="6">
            <p></p>
          </el-col>
          <el-col :xs="24" :sm="16" :md="10" :lg="9" :xl="9" v-if="featuresGroup >= 1" style="overflow: hidden;">
            <el-checkbox-group v-model="settingsForm.enabledFeatures">
              <template v-for="(item, index) in features">
                <el-checkbox
                  :key="index"
                  v-if="index < 2"
                  :label="item.value">{{item.name}}</el-checkbox>
              </template>
            </el-checkbox-group>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :xs="24" :sm="16" :md="10" :lg="9">
            <el-form-item
              label="Host:"
              prop="host">
              <el-input
                class="add-text"
                v-model="settingsForm.host"
                placeholder="Add text"
                maxlength="30"/>
            </el-form-item>
          </el-col>
          <el-col :xs="4" :sm="8" :md="4" :lg="6" :xl="6">
            <p></p>
          </el-col>
          <el-col :xs="24" :sm="16" :md="10" :lg="9" :xl="9" v-if="featuresGroup >= 2" style="overflow: hidden;">
            <el-checkbox-group v-model="settingsForm.enabledFeatures">
              <template v-for="(item, index) in features">
                <el-checkbox
                  :key="index"
                  v-if="index >= 2 && index < 4"
                  :label="item.value">{{item.name}}</el-checkbox>
              </template>
            </el-checkbox-group>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :xs="24" :sm="16" :md="10" :lg="9">
            <el-form-item
              label="Port:"
              prop="port">
              <el-input
                class="add-text"
                v-model="settingsForm.port"
                placeholder="Add text"
                maxlength="5"/>
            </el-form-item>
          </el-col>
          <el-col :xs="4" :sm="8" :md="4" :lg="6" :xl="6">
            <p></p>
          </el-col>
          <el-col :xs="24" :sm="16" :md="10" :lg="9" :xl="9" v-if="featuresGroup >= 3" style="overflow: hidden;">
            <el-checkbox-group v-model="settingsForm.enabledFeatures">
              <template v-for="(item, index) in features">
                <el-checkbox
                  :key="index"
                  v-if="index >= 4 && index < 6"
                  :label="item.value">{{item.name}}</el-checkbox>
              </template>
            </el-checkbox-group>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :xs="24" :sm="16" :md="10" :lg="9">
            <el-form-item
              label="From:"
              prop="from">
              <el-input
                class="add-text"
                v-model="settingsForm.from"
                placeholder="Add text"
                maxlength="50"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :xs="24" :sm="16" :md="10" :lg="9">
            <el-form-item
              label="Username:"
              prop="username">
              <el-input
                class="add-text"
                v-model="settingsForm.username"
                placeholder="Add text"
                maxlength="30"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :xs="24" :sm="16" :md="10" :lg="9">
            <el-form-item
              label="Password:"
              prop="password">
              <el-input
                class="add-text"
                type="password"
                v-model="settingsForm.password"
                placeholder="Add text"
                maxlength="20"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-button
              type="primary"
              @click="sendTestMail">
              Send Test Mail
            </el-button>
          </el-col>
        </el-row>
        <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-form>
        <el-row :gutter="20">
          <el-col :xs="24" :sm="16" :md="10" :lg="9">
            <el-form-item
              label="Added Recipients:"
              prop="chargeBoxId">
              <div class="receip-item" v-for="(item, index) in settingsForm.recipients" :key="index">
                <span>{{item}}</span>
                <i class="el-icon-close" @click="deleteRecipient(index)"></i>
              </div>
              <div
                class="link-button"
                v-if="settingsForm.recipients.length > 0"
                @click="clearAllRecipient">Clear All</div>
              <div class="el-form-item__error" v-else-if="manualValid">Please add at least one recipient</div>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="hr-full"></div>
        <div class="buttons">
          <el-button
            type="primary"
            class="cancel-button"
            @click="clearAllField">
            Clear All
          </el-button>
          <el-button
            style="margin-left: 20px;"
            type="primary"
            native-type="submit"
            @click="handleUpateButton">
            Update Changes
          </el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
  import api from '../http/api/settings'
  export default {
    data() {
      return {
        loading: true,
        settingsForm: {
          recipients: [],
          enabledFeatures: []
        },
        rule: {
          "heartbeat": {
            required: true,
            trigger: 'blur',
            message: 'Please type heartbeat'
          },
          "expiration": {
            required: true,
            trigger: 'blur',
            message: 'Please type expiration'
          },
          "from": {
            required: true,
            trigger: 'blur',
            message: 'Please type from'
          },
          "host": {
            required: true,
            trigger: 'blur',
            message: 'Please type host'
          },
          "username": {
            required: true,
            trigger: 'blur',
            message: 'Please type host'
          },
          "password": {
            required: true,
            trigger: 'blur',
            message: 'Please type host'
          },
          "protocol": {
            required: true,
            trigger: 'blur',
            message: 'Please type host'
          },
          "port": {
            required: true,
            trigger: 'blur',
            message: 'Please type host'
          },
          "recipient": {
            pattern: /^[a-zA-Z0-9]+[\S]+@[a-zA-Z0-9_-]+[\.][\Sa-zA-Z]+$/,
            trigger: 'blur',
            message: 'Please type a correct recipient'
          }
        },
        recipient: '',
        clearForm: {
          "heartbeat": '',
          "expiration": '',
          "enabled": false,
          "from": "",
          "host": "",
          "username": "",
          "password": "",
          "protocol": "",
          "port": '',
          "recipients": [],
          "enabledFeatures": []
        },
        features: [],
        featuresGroup: 0,
        manualValid: false
      }
    },
    created() {
      //this.init();
      this.getCheckList();
    },
    methods: {
      async getCheckList() {
        const res = await api.getFeatures();
        if (res.data && res.data.length > 0) {
          this.features = res.data;
          this.featuresGroup = res.data.length / 2
        }
        this.getSettings();
      },
      async getSettings() {
        const res = await api.getSettings();
        if (res.data) {
          this.settingsForm = res.data;
        }
        this.loading = false;
      },
      init() {
        this.recipient = "";
        const info = JSON.parse(JSON.stringify(this.clearForm));
        this.settingsForm = info;
        this.manualValid = false;
        this.$forceUpdate();
      },
      checkedChange(checked, value) {
        const enabledFeatures = this.settingsForm.enabledFeatures;
        if (checked) {
          enabledFeatures.push(value)
        } else {
          const index = enabledFeatures.indexOf(value)
          if (index >= 0) {
            enabledFeatures.splice(index, 1)
          }
        }
        this.settingsForm.enabledFeatures = enabledFeatures;
      },
      addRecipient() {
        if (this.recipient) {
          this.$refs["recipForm"].validate(result => {
            if (result) {
              this.settingsForm.recipients.push(this.recipient);
              this.recipient = "";
            }
          });
        }
      },
      deleteRecipient(index) {
        this.settingsForm.recipients.splice(index, 1);
      },
      clearAllRecipient() {
        this.$confirm('Clear all recipients?', 'Prompt', {
          confirmButtonText: 'Confirm',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(res => {
          this.settingsForm.recipients = [];
        })
      },
      clearAllField() {
        this.$confirm('Clear all fields?', 'Prompt', {
          confirmButtonText: 'Confirm',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(res => {
          this.init();
          this.$refs['settingsForm'].clearValidate();
          this.$refs["recipForm"].clearValidate();
        });
      },
      sendTestMail() {
        this.$refs['settingsForm'].validate(result => {
          if (this.settingsForm.recipients.length == 0) {
            this.manualValid = true;
            return;
          }
          if (result) {
            this.loading = true;
            api.testMail(this.settingsForm).then(res => {
              this.loading = false;
              this.$message({
                message: 'Send test mail successfully',
                type: 'success'
              });
            }).catch(err => {
              this.loading = false;
              this.$message({
                message: err,
                type: 'error'
              })
            });
          }
        });
      },
      handleUpateButton() {
        this.$refs['settingsForm'].validate(result => {
          if (this.settingsForm.recipients.length == 0) {
            this.manualValid = true;
            return;
          }
          if (result) {
            this.loading = true;
            api.updateSettings(this.settingsForm).then(res => {
              this.loading = false;
              this.$message({
                message: 'Save settings successfully',
                type: 'success'
              });
            }).catch(err => {
              this.loading = false;
              this.$message({
                message: err,
                type: 'error'
              })
            });
          }
        });
      }
    }
  }
</script>
<style lang='scss' scoped="scoped">
  @import '../styles/variables.scss';
  .card-container {
    width: 100%;
    padding: 20px 60px;
    min-height: $mainAppMinHeight;
    overflow-x: auto;
    background-color: #F0F5FC;
  }
</style>
<style scoped="scoped">
  .card-content {
    min-width: 500px;
    padding: 15px 80px;
    border-radius: 6px;
    background-color: white;
  }
  .section-title {
    color: #333;
    margin-top: 20px;
    margin-bottom: 30px;
    font-size: 16px;
    user-select: none;
    line-height: 24px;
    font-weight: 500;
    font-family: sans-serif;
    /* text-transform: uppercase; */
  }
  .add-text {
    width: 100%;
    max-width: 300px;
  }
  .add-text ::v-deep .el-textarea__inner {
    font-family: sans-serif;
  }
  .value-text {
    width: 100%;
    max-width: 280px;
  }
  .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: 150px;
    padding-right: 14px;
  }
  .list-item-icon {
    width: 30px;
    height: 30px;
    cursor: pointer;
    margin: 0 10px 22px;
  }
  .buttons {
    padding-top: 15px;
    padding-bottom: 30px;
  }
  .tips {
    color: #999;
    font-size: 12px;
    padding-left: 150px;
    padding-bottom: 20px;
  }
  .tips i {
    color: #333;
    font-weight: 500;
    font-style: normal;
  }
  ::v-deep .el-checkbox__input.is-checked + .el-checkbox__label {
    color: #333;
  }
  ::v-deep .el-checkbox__input.is-checked .el-checkbox__inner::after {
    border-color: #fff;
  }
  .el-checkbox + .el-checkbox {
    margin: 12px 0;
  }
  .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;
  }
  @media screen and (max-width: 500px) {
    .card-container {
      padding: 0px;
    }
    .card-content {
      padding: 15px 40px;
    }
  }
</style>