<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"
                :disabled="form.onlyView"
                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"
                :disabled="form.onlyView">
                <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"
                :disabled="form.onlyView"/>
            </el-form-item>
            <el-form-item
              label="Monthly Credit Limit:"
              prop="creditLimitAmount"
              v-if="false">
              <span class="item-unit">(S$)</span>
              <el-input
                class="add-text"
                v-model="form.creditLimitAmount"
                placeholder=""
                maxlength="10"
                :readonly="form.onlyView"/>
            </el-form-item>
            <el-form-item
              label="Monthly Credit Limit:"
              v-if="isEdit">
              <span class="item-unit">(S$)</span>
              <el-input
                class="add-text"
                v-model="form.totalCreditLimitAmount"
                readonly/>
            </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.overallBalance"
                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">
            <template slot-scope="{row}">
              <el-input
                class="add-text credit-input"
                v-model="form.creditLimitAmount"
                maxlength="10"
                :readonly="form.onlyView"/>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="Group Credit 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.groupCurrentConsumption}}</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"
          :canEdit="!form.onlyView"
          :canDelete="form.canDelete"
          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
            v-if="!form.onlyView"
            style="margin-left: 15px;"
            type="primary"
            :loading="loading.save"
            @click="onSaveClick">
            &nbsp;Save&nbsp;
          </el-button>
        </div>
        <audit-view :audit="form.audit"/>
      </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'
import AuditView from "@/components/AuditView"
export default {
  name: "LimitDetailV2",
  data() {
    return {
      isEdit: false,
      loading: {
        page: true,
        save: false
      },
      form: {
        groupCreditPk: "",
        groupPk: "",
        providerPk: "",
        effectivePeriod: ["", ""],
        creditLimitAmount: "0",
        onlyView: false,
        canDelete: true
      },
      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: {AuditView, 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;
  }
  .add-text.credit-input ::v-deep .el-input__inner {
    border: none;
    padding: 0;
    width: 150px;
    border-radius: 0;
    text-align: center;
    border-bottom: 1px solid #aaa;
    &:focus {
      border-bottom: 1px solid $itemActiveBg;
    }
  }
  .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>