<template>
  <div class="card-container">
    <el-form
      :model="addForm"
      :rules="rule"
      v-loading="loading"
      ref="addForm"
      label-position="right"
      label-width="180px">
      <div class="card-content">
        <div class="section-title">Monthly Credit Limit:</div>
        <el-row :gutter="20">
          <el-col :xs="24" :md="12">
            <el-form-item
              label="Group:"
              prop="groupPk">
              <el-select
                class="add-text"
                remote
                filterable
                :remote-method="filterCompany"
                v-model="addForm.groupPk"
                placeholder="Select with search"
                @blur="clearWords">
                <el-option
                  v-for="(item, index) in companyOptions"
                  :key="index"
                  :label="item.groupName"
                  :value="item.groupPk"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-form-item
              label="Status:"
              prop="dataStatus">
              <el-select
                class="add-text"
                v-model="addForm.dataStatus"
                placeholder="Select">
                <el-option
                  v-for="(item, index) in statusOptions"
                  :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="Monthly Credit Limit:"
              prop="creditLimitAmount">
              <span class="item-unit">(S$)</span>
              <el-input
                class="add-text"
                v-model="addForm.creditLimitAmount"
                placeholder="Add text"
                maxlength="10"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-form-item
              label="Effective Start Date:"
              prop="effectiveStartDate">
              <el-date-picker
                class="add-text"
                v-model="addForm.effectiveStartDate"
                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="Used Credit Limit:">
              <span class="item-unit">(S$)</span>
              <el-input
                class="add-text"
                v-model="addForm.usedCreditLimitAmount"
                placeholder="Add text"
                maxlength="10"
                readonly/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-form-item
              label="Effective End Date:"
              prop="effectiveEndDate">
              <el-date-picker
                class="add-text"
                v-model="addForm.effectiveEndDate"
                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="Remaining Credit Limit:">
              <span class="item-unit">(S$)</span>
              <el-input
                class="add-text"
                v-model="addForm.creditLimitRemainingAmount"
                placeholder="Add text"
                readonly
                maxlength="10"/>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-form-item
              label="Deposit Received:"
              prop="depositReceivedAmount">
              <span class="item-unit">(S$)</span>
              <el-input
                class="add-text"
                v-model="addForm.depositReceivedAmount"
                placeholder="Add text"
                maxlength="10"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :xs="24" :md="12">
            <el-form-item
              label="Service Provider:"
              prop="providerPk">
              <el-select
                class="add-text"
                v-model="addForm.providerPk"
                placeholder="Select">
                <el-option
                  v-for="(item, index) in providerOptions"
                  :key="index"
                  :label="item.providerName"
                  :value="''+item.providerPk"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </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="flex1"
          style="margin-left: 20px;"
          v-if="isEdit">
          <span
            class="add-text"
            :title='"CREATED BY " + addForm.createdBy + " ON " + addForm.createdOn'>
            LAST UPDATED BY {{addForm.updatedBy}} TIMESTAMP: {{addForm.updatedOn}}
          </span>
        </div>
      </div>
    </el-form>
  </div>
</template>

<script>
  import limit from '../../http/api/limit.js'
  import provider from '../../http/api/provider'
  import group from '@/http/api/group'
  export default {
    data() {
      return {
        loading: false,
        companyOptions: [],
        statusOptions: [],
        providerOptions: [],
        rule: {
          "groupPk": {
            required: true,
            trigger: 'change',
            message: 'Please select a group'
          },
          "dataStatus": {
            required: true,
            trigger: 'change',
            message: 'Please select a status'
          },
          "creditLimitAmount": [{
            required: true,
            trigger: 'blur',
            message: 'Please type Monthly Credit Limit'
          }, {
            pattern: /^\d+(.{0,1}\d{1,})?$/,
            trigger: 'blur',
            message: 'Please type a number of amount'
          }],
          "effectiveStartDate": {
            required: true,
            trigger: 'change',
            message: 'Please select effective start date'
          },
          "effectiveEndDate": {
            required: true,
            trigger: 'change',
            message: 'Please select effective end date'
          },
          "depositReceivedAmount": [{
            required: true,
            trigger: 'blur',
            message: 'Please type deposit received'
          }, {
            pattern: /^\d+(.{0,1}\d{1,})?$/,
            trigger: 'blur',
            message: 'Please type a number of amount'
          }],
          "providerPk": {
            required: true,
            trigger: 'change',
            message: 'Please select a provider'
          },
        },
        addForm: {
          groupPk: '',
          creditLimitAmount: '',
          depositReceivedAmount: '',
          effectiveStartDate: "",
          effectiveEndDate: "",
          dataStatus: "",
          providerPk: "",
          usedCreditLimitAmount: "0",
          creditLimitRemainingAmount: '0'
        },
        companyParams: {
          "pageSize": 20,
          "pageNo": 1,
          "pageVo": {
            "criteria": ""
          }
        },
        isEdit: false
      }
    },
    created() {
      this.loading = true;
      this.getCompanyList()
      if (this.$route.params.id) {
        this.isEdit = true;
        this.getLimitInfo()
      }
    },
    methods: {
      clearWords() {
        this.companyParams.pageVo.criteria = "";
        this.getCompanyList();
      },
      filterCompany(word) {
        this.companyParams.pageVo.criteria = word;
        this.getCompanyList();
      },
      getLimitInfo() {
        limit.viewCreditLimit(this.$route.params.id).then(res => {
          if (res.data) {
            this.addForm = res.data
          }
        }).catch(err => {
          this.loading = false;
          this.$message({
            message: err,
            type: 'error'
          })
        });
      },
      getCompanyList() {
        group.getGroupPages(this.companyParams).then(res => {
          if (res.data) {
            this.companyOptions = res.data
          }
        }).catch(err => {
          this.$message({
            message: err,
            type: 'error'
          })
        }).finally(() => {
          this.getLimitStatus();
        });
      },
      getLimitStatus() {
        limit.getLimitStatus().then(res => {
          if (res.data) {
            this.statusOptions = res.data
          }
        }).catch(err => {
          this.$message({
            message: err,
            type: 'error'
          })
        }).finally(() => {
          this.getAllProvider()
        });
      },
      getAllProvider() {
        provider.getAllServiceProvider().then(res => {
          if (res.data && res.data.length > 0) {
            this.providerOptions = res.data
            if (!this.addForm.providerPk)
              this.addForm.providerPk = res.data[0].providerPk + ""
          }
        }).finally(() => {
          this.loading = false;
        });
      },
      handleClickCancleButton() {
        this.$nextTick(() => {
          this.$router.push({
            path: "/partnership-management/monthly-credit-management"
          })
        })
      },
      handleClickSaveButton() {
        this.$refs['addForm'].validate(result => {
          if (result) {
            this.isEdit ? this.updateLimites() : this.addLimites();
          }
        })
      },
      addLimites() {
        this.loading = true;
        limit.addCreditLimit(this.addForm).then(res => {
          this.loading = false;
          this.$message({
            message: 'Add credit limit successfully',
            type: 'success'
          })
          this.handleClickCancleButton();
        }).catch(err => {
          this.loading = false;
          this.$message({
            message: err,
            type: 'error'
          })
        });
      },
      updateLimites() {
        this.loading = true;
        limit.updateCreditLimit(this.addForm).then(res => {
          this.loading = false;
          this.$message({
            message: 'Update credit limit successfully',
            type: 'success'
          })
          this.handleClickCancleButton();
        }).catch(err => {
          this.loading = false;
          this.$message({
            message: err,
            type: 'error'
          })
        });
      }
    }
  }
</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%;
    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;
    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>
