<template>
  <div class="card-container">
    <el-form
      :model="settingsForm"
      :rules="rule"
      v-loading="loading"
      ref="settingsForm"
      label-position="right"
      label-width="110px">
      <div class="flexr">
        <div class="card-content">
          <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-form-item
            label="Protocol:"
            prop="protocol">
            <el-input
              class="add-text"
              v-model="settingsForm.protocol"
              placeholder=""
              maxlength="10"/>
          </el-form-item>
          <el-form-item
            label="Host:"
            prop="host">
            <el-input
              class="add-text"
              v-model="settingsForm.host"
              placeholder=""
              maxlength="30"/>
          </el-form-item>
          <el-form-item
            label="Port:"
            prop="port">
            <el-input
              class="add-text"
              v-model="settingsForm.port"
              placeholder=""
              maxlength="5"/>
          </el-form-item>
          <el-form-item
            label="From:"
            prop="from">
            <el-input
              class="add-text"
              v-model="settingsForm.from"
              placeholder=""
              maxlength="50"/>
          </el-form-item>
          <el-form-item
            label="Username:"
            prop="username">
            <el-input
              class="add-text"
              v-model="settingsForm.username"
              placeholder=""
              maxlength="30"/>
          </el-form-item>
          <el-form-item
            label="Password:"
            prop="password">
            <div class="add-text flexcr" style="margin: -5px 0;">
              <div class="flex1">
                <el-input
                  ref="password"
                  class="add-text"
                  :type="passwordType"
                  v-model="settingsForm.password"
                  placeholder="Email password"
                  maxlength="128"/>
                <span class="show-pwd" @click="showPwd">
                  <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
                </span>
              </div>
              <div class="divide10"></div>
              <el-button
                type="primary"
                @click="sendTestMail"
                style="margin: 5px 0;">
                Send Test Mail
              </el-button>
            </div>
          </el-form-item>
          <el-form
            :model="this"
            :rules="rule"
            ref="recipForm"
            label-width="110px"
            label-position="right">
            <el-form-item
              label="Recipients:"
              prop="recipient">
              <div class="add-text flexcr" style="margin: -5px 0;">
                <div class="flex1">
                  <el-input
                    class="add-text"
                    v-model="recipient"
                    placeholder=""
                    maxlength="50"/>
                </div>
                <div class="divide10"></div>
                <el-button
                  type="primary"
                  icon="el-icon-plus"
                  @click="addRecipient"
                  style="margin: 5px 0;">
                  Add
                </el-button>
              </div>
            </el-form-item>
          </el-form>
          <el-form-item
            label=""
            prop="chargeBoxId"
            label-width="0">
            <label class="el-form-item__label">Added Recipients:</label>
            <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>
        </div>
        <div class="card-content">
          <div class="section-title">
            <span style="padding-right: 10px;">Notification Types</span>
          </div>
          <el-checkbox-group
            class="features-group"
            v-model="settingsForm.enabledFeatures">
            <template v-for="(item, index) in features">
              <el-checkbox
                :key="index"
                :label="item.value">{{item.name}}</el-checkbox>
            </template>
          </el-checkbox-group>
        </div>
      </div>
      <div class="card-content">
        <div class="buttons">
          <el-button
            type="primary"
            class="cancel-button"
            @click="clearAllField">
            Clear All
          </el-button>
          <el-button
            style="margin-left: 20px;"
            type="primary"
            @click="handleUpateButton">
            Update Changes
          </el-button>
        </div>
      </div>
    </el-form>
  </div>
</template>

<script>
  import api from '@/http/api/settings'
  import site from '@/http/api/site'
  export default {
    data() {
      return {
        loading: true,
        settingsForm: {
          enabled: false,
          recipients: [],
          //chargeTypes: [],
          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 username'
          },
          "password": {
            required: true,
            trigger: 'blur',
            message: 'Please type password'
          },
          "protocol": {
            required: true,
            trigger: 'blur',
            message: 'Please type protocol'
          },
          "port": {
            required: true,
            trigger: 'blur',
            message: 'Please type port'
          },
          "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": [],
          //chargeTypes: [],
          "enabledFeatures": []
        },
        features: [],
        manualValid: false,
        //chargeTypeOptions: [],
        passwordType: "password"
      }
    },
    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.getChargeTypeOptions()
        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.addChargeType()
        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.getSettings();
              this.$message({
                message: 'Save settings successfully',
                type: 'success'
              });
            }).catch(err => {
              this.loading = false;
              this.$message({
                message: err,
                type: 'error'
              })
            });
          }
        });
      },
      showPwd() {
        if (this.passwordType === 'password') {
          this.passwordType = 'text'
        } else {
          this.passwordType = 'password'
        }
        this.$nextTick(() => {
          this.$refs.password.focus()
        })
      },
    }
  }
</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;
  }
  .card-content {
    flex: 1;
    min-width: 500px;
    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: 14px;
    user-select: none;
    line-height: 24px;
    font-weight: 700;
    font-family: sans-serif;
    /* text-transform: uppercase; */
  }
  .add-text {
    width: 100%;
    min-width: 150px;
    max-width: 400px;
  }
  .add-text ::v-deep .el-textarea__inner {
    font-family: sans-serif;
  }
  .add-text.pwd ::v-deep .el-input__inner {
    padding-right: 30px;
  }
  .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: 15px;
  }
  .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: $buttonText;
  }
  .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;
  }
  .divide10 {
    width: 10px;
  }
  .features-group {
    min-width: 400px;
  }
  @media screen and (max-width: 800px) {
    .card-container {
      padding: 10px 20px;
    }
    .card-content {
      min-width: auto;
      padding: 15px 30px;
    }
  }
  
  @media screen and (max-width: 500px) {
    .card-container {
      padding: 0px;
    }
    .card-content {
      padding: 15px 20px;
    }
    .divide10 {
      display: none;
    }
    .features-group {
      min-width: 80vw;
    }
  }
  .el-checkbox-group .el-checkbox {
    display: flex;
    align-items: center;
  }
  .el-checkbox >>> .el-checkbox__input {
    height: 14px;
    line-height: 14px;
  }
  .el-checkbox >>> .el-checkbox__label {
    word-break: break-all;
    white-space: normal;
  }
  .show-pwd {
    width: 15px;
    color: #666;
    cursor: pointer;
    font-size: 14px;
    position: relative;
    margin-left: -24px;
  }
</style>