<template>
  <div class="card-container">
    <el-form
      :model="form"
      :rules="rule"
      v-loading="loading"
      ref="addForm"
      label-position="right"
      label-width="130px">
      <div class="card-content">
        <div class="section-title">RFID CARD DETAILS</div>
        <el-form-item
          label="RFID No.:"
          prop="rfidNumber">
          <el-input
            class="add-text"
            v-model="form.rfidNumber"
            placeholder="Add text"
            maxlength="20"/>
        </el-form-item>
        <el-form-item
          label="Email Address:"
          prop="email">
          <el-select
            class="add-text"
            v-model="form.email"
            filterable
            remote
            :remote-method="filterEmail"
            placeholder="Search with user email"
            @change="changeEmail">
            <el-option
              v-for="(item, index) in userList"
              :key="index"
              :label="item.email"
              :value="item"/>
          </el-select>
        </el-form-item>
        <el-form-item
          label="User Name:"
          v-if="form.userName">
          <span>{{form.userName}}</span>
        </el-form-item>
        <el-form-item
          label="User Contact No:"
          v-if="form.phone">
          <span>{{form.phone}}</span>
        </el-form-item>
        <el-form-item
          label="User Type:"
          v-if="form.userType">
          <span>{{form.userType}}</span>
        </el-form-item>
        <el-form-item
          label="Group (If any):"
          v-if="form.groupName">
          <span>{{form.groupName}}</span>
        </el-form-item>
        <el-form-item
          label="Card Type:"
          prop="cardType">
          <el-select
            class="add-text"
            v-model="form.cardType"
            placeholder="Select">
            <el-option
              v-for="(item, index) in cardTypeOptions"
              :key="index"
              :label="item"
              :value="item"/>
          </el-select>
        </el-form-item>
        <el-form-item
          label="Valid Till:"
          prop="validTill">
          <el-date-picker
            class="add-text"
            v-model="form.validTill"
            type="date"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            placeholder="Select date"/>
        </el-form-item>
      </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"
            @click="handleClickSaveButton">
            Save
          </el-button>
        </div>
        <div
          class="update-by"
          v-if="isEdit">
          <span
            class="add-text"
            :title='"CREATED BY " + form.createdBy + " ON " + form.createdOn'>
            LAST UPDATED BY {{form.updatedBy}} TIMESTAMP: {{form.updatedOn}}
          </span>
        </div>
      </div>
    </el-form>
  </div>
</template>

<script>
import api from '../../http/api/rfid.js'
export default {
  data() {
    return {
      loading: false,
      showProvider: false,
      form: {
        userPk: "",
        rfidNumber: '',
        email: '',
        validTill: '',
        cardType: []
      },
      rule: {
        rfidNumber: [{
          required: true,
          trigger: 'blur',
          message: 'Please input RFID No.'
        }/*,{
          pattern: /^\d{1,}$/,
          trigger: 'blur',
          message: 'Please type a number'
        }*/],
        email: {
          required: true,
          trigger: 'change',
          message: 'Please input user email address'
        }
      },
      userList: [],
      cardTypeOptions: [],
      isEdit: false
    }
  },
  async created() {
    this.loading = true;
    this.getCardTypeOptions();
    if (this.$route.params.id) {
      this.isEdit = true;
      await this.getCardDetails(this.$route.params.id)
    } else {
      
    }
  },
  methods: {
    filterEmail(email) {
      api.getRfidUserList(email).then(res => {
        if (res.data) {
          this.userList = res.data
        }
      }).catch(err => {
        this.userList = []
      })
    },
    changeEmail(email) {
      console.log(email);
      this.form.email = email.email
      this.form.userPk = email.userPk
    },
    getCardTypeOptions() {
      api.getCardTypeList().then(res => {
        if (res.data) {
          this.cardTypeOptions = res.data
        }
      }).finally(() => {
        this.loading = false;
      })
    },
    getCardDetails(id) {
      api.viewRfidCard({
        ocppTagPk: id
      }).then(res => {
        if (res.data) {
          this.form = res.data
        }
      }).catch(err => {
        this.$message({
          message: err,
          type: 'error'
        })
      });
    },
    addRfidCard() {
      this.loading = true;
      api.addRfidCard(this.form).then(res => {
        this.loading = false;
        this.$message({
          message: 'Add user successfully!',
          type: 'success'
        });
        setTimeout(() => {
          this.handleClickCancleButton()
        }, 500);
      }).catch(err => {
        this.loading = false;
        this.$message({
          message: err,
          type: 'error'
        })
      });
    },
    editRfidCard() {
      this.loading = true;
      api.updateRfidCard(this.form).then(res => {
        this.loading = false;
        this.$message({
          message: 'Update user successfully!',
          type: 'success'
        });
        setTimeout(() => {
          this.handleClickCancleButton()
        }, 500);
      }).catch(err => {
        this.loading = false;
        this.$message({
          message: err,
          type: 'error'
        })
      });
    },
    handleClickCancleButton() {
      this.$nextTick(() => {
        this.$router.push({
          path: '/rfid-card-management'
        });
      });
    },
    handleClickSaveButton() {
      this.$refs['addForm'].validate(result => {
        if (result) {
          if (this.isEdit) {
            this.editRfidCard()
          } else {
            this.addRfidCard()
          }
        }
      })
    }
  }
}
</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 80px;
    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: bold;
    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;
  }
  .hr {
    height: 2px;
    margin: 10px -40px;
    background-color: #F0F5FC;
  }
  .hr-full {
    height: 2px;
    margin: 80px -80px 30px;
    background-color: #F0F5FC;
  }
  .rate-list-view {
    display: flex;
    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;
  }
  @media screen and (max-width: 500px) {
    .card-container {
      padding: 0px;
    }
    .card-content {
      padding: 15px 30px;
    }
  }
  .item-unit {
    top: 12px;
    left: -40px;
    font-size: 12px;
    user-select: none;
    position: absolute;
  }
</style>
