<template>
  <div class="container" v-loading="loading.page">
    <el-form
      ref="limitForm"
      :model="form"
      :rules="rules"
      label-width="165px"
      label-position="right">
      <div class="content">
        <div class="section-title">CREDIT LIMIT CONTRACT</div>
        <div class="flexr">
          <div class="form-left">
            <el-form-item
              label="Group:"
              prop="groupPk">
              <el-select
                class="add-text"
                v-model="form.groupPk"
                placeholder="Select with search">
                <el-option
                  v-for="(item, index) in options.group"
                  :key="index"
                  :label="item.groupName"
                  :value="item.groupPk"/>
              </el-select>
            </el-form-item>
            <el-form-item
              label="Service Provider:"
              prop="providerPk">
              <el-select
                class="add-text"
                v-model="form.providerPk"
                placeholder="Select">
                <el-option
                  v-for="(item, index) in options.provider"
                  :key="index"
                  :label="item.key"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
            <el-form-item
              label="Effective Period:"
              prop="effectivePeriod">
              <el-date-picker
                class="add-text"
                v-model="form.effectivePeriod"
                type="daterange"
                format="dd/MM/yyyy"
                value-format="dd/MM/yyyy"
                placeholder="Select date"/>
            </el-form-item>
            <el-form-item
              label="Monthly Credit Limit:"
              prop="creditLimitAmount">
              <span class="item-unit">(S$)</span>
              <el-input
                class="add-text"
                v-model="form.creditLimitAmount"
                placeholder=""
                maxlength="10"/>
            </el-form-item>
          </div>
          <div class="form-right" v-if="isEdit">
            <el-form-item
              label="Status:"
              prop="dataStatus">
              <el-select
                class="add-text"
                v-model="form.dataStatus"
                placeholder="Select"
                disabled>
                <el-option
                  v-for="(item, index) in options.status"
                  :key="index"
                  :label="item.key"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
            <el-form-item
              label="Approved Users:">
              <el-input
                class="add-text"
                v-model="form.approvedUsers"
                readonly/>
            </el-form-item>
            <el-form-item
              label="Overall Balance:">
              <el-input
                class="add-text"
                :value="form.individualCredit + '/' + form.groupCredit"
                readonly/>
            </el-form-item>
          </div>
        </div>
      </div>
      <div class="content" v-if="isEdit">
        <div class="section-title">Group Credit</div>
        <el-table
          :data="[form]">
          <el-table-column
            align="center"
            label="Amount"
            prop="groupCredit"
            min-width="100"/>
          <el-table-column
            align="center"
            label="Assigned Users"
            min-width="120">
            <template slot-scope="{row}">
              <span>{{row.approvedUsers-row.individualApprovedUsers}}</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="Current Consumption"
            prop="currentConsumptionCredit"
            min-width="140">
            <template slot-scope="{row}">
              <span>{{row.creditLimitRemainingAmount}}/{{row.groupCredit}}</span>
            </template>
          </el-table-column>
        </el-table>
        <p></p>
      </div>
      <div class="content" v-if="isEdit">
        <div class="section-title">Individual Plans</div>
        <plans
          :id="form.groupCreditPk"
          :groupPk="form.groupPk"
          v-if="form.groupCreditPk"
          @refresh="getLimitInfo"/>
        <p></p>
      </div>
      <div class="content flexcr">
        <div class="buttons">
          <el-button
            type="primary"
            class="cancel-button"
            @click="onBack">
            Cancel
          </el-button>
          <el-button
            style="margin-left: 20px;"
            type="primary"
            :loading="loading.save"
            @click="onSaveClick">
            Save
          </el-button>
        </div>
        <div
          class="flex1"
          style="margin-left: 20px;"
          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 apiBase from '@/api/apiBase';
import limit from '@/api/limit.js'
import provider from '@/http/api/provider'
import group from '@/http/api/group'
import plans from './plans.vue'
export default {
  data() {
    return {
      isEdit: false,
      loading: {
        page: true,
        save: false
      },
      form: {
        groupCreditPk: "",
        groupPk: "",
        providerPk: "",
        effectivePeriod: ["", ""],
        creditLimitAmount: ""
      },
      rules: {
        groupPk: {
          required: true,
          trigger: 'change',
          message: 'Please select a group'
        },
        providerPk: {
          required: true,
          trigger: 'change',
          message: 'Please select a provider'
        },
        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'
        }],
        effectivePeriod: {
          required: true,
          trigger: 'change',
          validator: (rule, value, callback) => {
            if (value && value.length > 0) {
              if (value[0] && value[1]) {
                callback()
              } else {
                callback("Please select effective period")
              }
            } else {
              callback("Please select effective period")
            }
          }
        },
      },
      options: {
        group: [],
        status: [],
        provider: []
      },
      companyParams: {
        "pageSize": 50,
        "pageNo": 1,
        "pageVo": {
          "criteria": ""
        }
      },
    };
  },
  components: {plans},
  created() {
    this.getGroupOptions();
    if (this.$route.params.id) {
      this.isEdit = true;
      this.getStatusOptions();
      this.getLimitInfo();
    }
  },
  methods: {
    onBack() {
      this.$nextTick(() => {
        this.$router.push({
          path: "/partnership-management/monthly-credit-limit"
        })
      })
    },
    getStatusOptions() {
      apiBase.getDataStatusOptions().then(res => {
        if (res.data && res.data.length > 0) {
          this.options.status = res.data
        }
      }).catch(err => {
        this.$message.error(err);
      })
    },
    getGroupOptions() {
      group.getGroupPages(this.companyParams).then(res => {
        if (res.data) {
          this.options.group = res.data
        }
      }).catch(err => {
        this.$message({
          message: err,
          type: 'error'
        })
      }).finally(() => {
        this.getAllProvider();
      });
    },
    getAllProvider() {
      apiBase.getProviderList().then(res => {
        if (res.data && res.data.length > 0) {
          this.options.provider = res.data
          if (!this.form.providerPk)
            this.form.providerPk = res.data[0].value
        }
      }).finally(() => {
        this.loading.page = false;
      });
    },
    getLimitInfo() {
      limit.viewCreditLimit(this.$route.params.id).then(res => {
        if (res.data) {
          this.form = res.data
        }
      }).catch(err => {
        this.loading.page = false;
        this.$message({
          message: err,
          type: 'error'
        })
      });
    },
    onSaveClick() {
      this.$refs['limitForm'].validate(result => {
        if (result) {
          this.loading.save = true;
          this.isEdit ? this.updateLimites() : this.addLimites();
        }
      })
    },
    addLimites() {
      limit.addCreditLimit(this.form).then(res => {
        this.$message({
          message: 'Add credit limit successfully',
          type: 'success'
        })
        this.onBack();
      }).catch(err => {
        this.$message({
          message: err,
          type: 'error'
        })
      }).finally(() => {
        this.loading.save = false;
      });
    },
    updateLimites() {
      limit.updateCreditLimit(this.form).then(res => {
        this.$message({
          message: 'Update credit limit successfully',
          type: 'success'
        })
        this.onBack();
      }).catch(err => {
        this.$message({
          message: err,
          type: 'error'
        })
      }).finally(() => {
        this.loading.save = false;
      });
    }
  }
}
</script>

<style lang="scss" scoped>
  @import '../../styles/variables.scss';
  .container {
    width: 100%;
    padding: 20px 60px;
    min-height: $mainAppMinHeight;
    background-color: #F0F5FC;
  }
  .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: bold;
    font-family: sans-serif;
    text-transform: uppercase;
  }
  .add-text {
    width: 100% !important;
    min-width: 150px;
    max-width: 300px;
  }
  .add-text ::v-deep .el-textarea__inner {
    font-family: sans-serif;
  }
  .hr {
    height: 2px;
    margin: 10px -40px;
    background-color: #F0F5FC;
  }
  .buttons {
    padding-top: 15px;
    padding-bottom: 15px;
  }
  .form-left,.form-right {
    flex: 1;
    min-width: 300px;
  }
  .item-unit {
    top: 12px;
    left: -40px;
    font-size: 12px;
    user-select: none;
    position: absolute;
  }
  @media screen and (max-width: 500px) {
    .container {
      padding: 0px;
    }
    .content {
      padding: 15px 30px;
    }
    .form-left,.form-right {
      width: 100%;
      min-width: auto;
    }
  }
</style>