<template>
  <div class="card-container" v-loading="loading.page">
    <div class="flexr">
      <el-form
        :model="form"
        :rules="rule"
        ref="mailForm"
        label-position="right"
        label-width="110px"
        class="card-content flex1">
        <div class="section-title">
          <span style="padding-right: 30px;text-transform: uppercase;">Mail Notification Settings</span>
          <el-checkbox v-model="form.enable">Enable notifications</el-checkbox>
        </div>
        <el-form-item
          label="Protocol:"
          prop="protocol">
          <el-select
            class="add-text"
            v-model="form.protocol">
            <el-option
              v-for="item in protocolTypes"
              :key="item"
              :label="item"
              :value="item"/>
          </el-select>
        </el-form-item>
        <el-form-item
          label="Host:"
          prop="host">
          <el-input
            class="add-text"
            v-model="form.host"
            placeholder=""
            maxlength="50"
            placeholder="Add text"/>
        </el-form-item>
        <el-form-item
          label="Port:"
          prop="port">
          <el-input
            class="add-text"
            v-model="form.port"
            placeholder=""
            maxlength="5"
            placeholder="Add text"/>
        </el-form-item>
        <el-form-item
          label="From:"
          prop="emailFrom">
          <el-input
            class="add-text"
            v-model="form.emailFrom"
            placeholder=""
            maxlength="80"
            placeholder="Add text"/>
        </el-form-item>
        <el-form-item
          label="Username:"
          prop="username">
          <el-input
            class="add-text"
            v-model="form.username"
            placeholder=""
            maxlength="80"
            placeholder="Add text"/>
        </el-form-item>
        <el-form-item
          label="Password:"
          prop="password">
          <el-input
            ref="password"
            class="add-text"
            type="password"
            v-model="form.password"
            placeholder="Add text"
            maxlength="128"/>
        </el-form-item>
        <el-form-item
          label="Security:"
          prop="password">
          <div class="flexc">
            <el-checkbox
              v-model="form.enableSsl">SSL</el-checkbox>
            <div style="margin-left: 30px;">
              <el-checkbox
                v-model="form.enableStarttls">TLS</el-checkbox>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <el-form
        :model="this"
        :rules="rule"
        ref="recipForm"
        label-width="90px"
        label-position="right"
        class="card-content flex1">
        <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="Add text"
                maxlength="50"
                @keyup.enter.native="addRecipient"/>
            </div>
            <div class="divide10"></div>
            <el-button
              type="primary"
              icon="el-icon-plus"
              @click="addRecipient"
              style="margin: 5px 0;"
              :loading="loading.add"
              :disabled="recipient.length == 0">
              Add
            </el-button>
          </div>
        </el-form-item>
        <div v-loading="loading.table">
          <el-table :data="table.list">
            <el-table-column
              align="center"
              label="Email"
              prop="recipientEmail"
              min-width="150"/>
            <el-table-column
              align="center"
              label="Notification Types"
              prop="userPk"
              min-width="150">
              <template slot-scope="{row}" >
                <span
                  class="link-type"
                  @click="assignReceipt(row)">
                  {{ row.notifyTypeCountStr }}
                </span>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="Action"
              min-width="70"
              v-if="!$route.meta.onlyView">
              <template v-slot="{ row }">
                <el-dropdown
                  class="action-dropdown"
                  @command="(v) => handleCommand(v, row)">
                  <i class="el-icon-more icon-action"></i>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item
                      command="sendTestMail">
                      Send Test Email
                    </el-dropdown-item>
                    <el-dropdown-item
                      command="deleteReceipt">
                      Delete
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="right">
          <pagination
            v-show="table.total > 0"
            :total="table.total"
            :page.sync="filter.pageNum"
            :limit.sync="filter.pageSize"
            @pagination="getReceiptTable" />
        </div>
      </el-form>
    </div>
    <div class="card-content flexcr">
      <div class="buttons">
        <el-button
          type="primary"
          @click="onSave"
          :loading="loading.save">
          &nbsp;SAVE&nbsp;
        </el-button>
      </div>
      <audit-view :audit="form.audit"/>
    </div>
    <EmailAssignment
      v-bind="dialogAssign"
      @hide="hideAssignDialog"/>
  </div>
</template>

<script>
import api from "../../api/apiEmails.js";
import Pagination from '@/components/Pagination'
import AuditView from "@/components/AuditView"
import EmailAssignment from "./EmailAssignment.vue";
export default {
  data() {
    return {
      loading: {
        add: false,
        page: true,
        table: false,
        save: false
      },
      form: {
        emailId: "",
        enable: false,
        protocol: "smtp",
        host: "",
        port: "",
        emailFrom: "",
        username: "",
        password: ""
      },
      filter: {
        pageNum: 1,
        pageSize: 10,
        pageCriteria: {
          emailId: "",
          criteria: ""
        }
      },
      table: {
        list: [],
        total: 0
      },
      recipient: "",
      rule: {
        "emailFrom": {
          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: false,
          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'
        }
      },
      protocolTypes: [],
      dialogAssign: {
        item: {},
        visible: false
      }
    }
  },
  components: {EmailAssignment,Pagination,AuditView},
  created() {
    this.getProtocolTypes();
    this.getMailSettings();
  },
  methods: {
    getProtocolTypes() {
      api.getProtocolOptions().then(res => {
        if (res.data) {
          this.protocolTypes = res.data
        }
      }).catch(err => {
        
      })
    },
    getMailSettings() {
      api.getEmailConfiguration().then(res => {
        this.loading.page = false;
        if (res.data) {
          this.form = res.data;
          if (res.data.emailId) {
            this.filter.pageCriteria.emailId = res.data.emailId;
            this.getReceiptTable();
          }
        }
      }).catch(err => {
        this.loading.page = false;
        this.$message({
          message: err,
          type: 'error'
        })
      })
    },
    getReceiptTable() {
      this.loading.table = true;
      api.getRecipientPages(this.filter).then(res => {
        if (res.data.totalRow && res.data.records) {
          this.table.total = res.data.totalRow;
          this.table.list = res.data.records;
        } else {
          this.table.total = 0;
          this.table.list = [];
        }
      }).catch(err => {
        this.$message({
          type: 'error',
          message: err
        })
        this.table.total = 0;
        this.table.list = [];
      }).finally(() => {
        this.loading.table = false;
      })
    },
    addRecipient() {
      if (this.recipient) {
        this.$refs["recipForm"].validate(result => {
          if (result) {
            this.addRecipientEmail();
          }
        });
      }
    },
    addRecipientEmail() {
      this.loading.add = true;
      api.creatEmailRecipient({
        emailId: this.form.emailId,
        recipientEmail: this.recipient
      }).then(res => {
        this.$message({
          message: "Add successful",
          type: 'success'
        })
        this.getReceiptTable();
      }).catch(err => {
        this.$message({
          message: err,
          type: 'error'
        })
      }).finally(() => {
        this.recipient = "";
        this.loading.add = false;
      })
    },
    handleCommand(cb, item) {
      this[cb](item)
    },
    sendTestMail(row) {
      if (row.recipientId) {
        this.loading.table = true;
        api.sendTestMail({
          recipientId: row.recipientId,
        }).then(res => {
          this.loading.table = false;
          this.$message({
            message: 'Send test mail successfully',
            type: 'success'
          });
        }).catch(err => {
          this.loading.table = false;
          this.$message({
            message: err,
            type: 'error'
          })
        });
      }
    },
    deleteReceipt(row) {
      this.$confirm('Are you sure you want to delete this email?', 'Delete', {
        confirmButtonText: 'OK',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }).then(res => {
        this.deleteReceiptEmail(row.recipientId);
      })
    },
    assignReceipt(row) {
      if (row) {
        this.dialogAssign.item = row;
        this.dialogAssign.visible = true;
      }
    },
    hideAssignDialog(e) {
      this.dialogAssign.item = {};
      this.dialogAssign.visible = false;
      this.getReceiptTable();
    },
    deleteReceiptEmail(recipientId) {
      this.loading.table = true;
      api.deleteEmailRecipient(recipientId).then(res => {
        this.$message({
          message: "Delete successful",
          type: 'success'
        })
        this.getReceiptTable();
      }).catch(err => {
        this.loading.table = false;
        this.$message({
          message: err,
          type: 'error'
        })
      });
    },
    onSave() {
      this.$refs['mailForm'].validate(result => {
        if (result) {
          this.loading.save = true;
          api.saveEmailConfiguration(this.form).then(res => {
            this.loading.save = false;
            this.getMailSettings();
            this.$message({
              message: 'Save settings successfully',
              type: 'success'
            });
          }).catch(err => {
            this.loading.save = false;
            this.$message({
              message: err,
              type: 'error'
            })
          });
        }
      });
    }
  }
}
</script>

<style lang="scss" scoped>
@import '../../styles/variables.scss';
.card-container {
  width: 100%;
  padding: 20px 50px;
  min-height: $mainAppMinHeight;
  background-color: #F0F5FC;
}
.card-content {
  min-width: 35vw;
  margin: 0 8px 16px;
  padding: 20px 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;
}
.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;
}
.buttons {
  display: flex;
  padding: 15px;
  align-items: center;
  justify-content: center;
}
::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;
}
.divide10 {
  width: 10px;
}
@media screen and (max-width: 900px) {
  .card-container {
    padding: 10px 20px;
  }
  .card-content {
    min-width: 80vw;
    padding: 15px 30px;
  }
}

@media screen and (max-width: 500px) {
  .card-container {
    padding: 0px;
  }
  .card-content {
    margin: 8px;
    padding: 15px 20px;
  }
  .divide10 {
    display: none;
  }
  .features-group {
    min-width: 80vw;
  }
  .card-content + .card-content {
    margin: 0 8px 12px;
  }
}
.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;
}
</style>