<template>
  <div class="app-container">
    <div class="filter-container filter-view">
      <el-select
        class="filter-view-item"
        clearable
        v-model="filters.pageCriteria.contractStatus"
        placeholder="Contract Status"
        @change="toSearch">
        <el-option
          v-for="(item, index) in statusContracts"
          :key="index"
          :label="item"
          :value="item"/>
      </el-select>
      <el-select
        class="filter-view-item"
        clearable
        v-model="filters.pageCriteria.auditStatus"
        placeholder="Approval Status"
        @change="toSearch">
        <el-option
          v-for="(item, index) in statusOptions"
          :key="index"
          :label="item.key"
          :value="item.value"/>
      </el-select>
      <div style="flex: 1; max-width: 300px;">
        <el-input
          v-model="filters.pageCriteria.criteria"
          class="filter-view-item"
          prefix-icon="el-icon-search"
          placeholder="Search by Group Name"
          @keyup.enter.native="toSearch"
          @change="toSearch"
          clearable/>
      </div>
      <div class="filter-flex-button">
        <el-button
          v-if="!$route.meta.onlyView"
          class="filter-item"
          type="primary"
          icon="el-icon-plus"
          @click="creatLimit">
          Credit Limit Contract
        </el-button>
      </div>
    </div>
    <el-table
      v-loading="table.loading"
      :data="table.list">
      <el-table-column
        align="center"
        label="Group"
        prop="groupName"
        min-width="120">
        <template slot-scope="{row}">
          <span
            class="link-type"
            @click="editLimit(row)"
            v-if="!$route.meta.onlyView">
            {{ row.groupName }}
          </span>
          <span v-else>{{ row.groupName }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="Service Provider"
        prop="providerName"
        min-width="140"/>
      <el-table-column
        align="center"
        label="Monthly Credit Set"
        prop="creditLimitAmount"
        min-width="150"/>
      <el-table-column
        align="center"
        label="Current Useage"
        prop="creditLimitUsagedAmount"
        min-width="140"/>
      <el-table-column
        align="center"
        label="Approved Users"
        prop="approvedUsers"
        min-width="140"/>
      <el-table-column
        align="center"
        label="Effective Period"
        prop="effectivePeriod"
        min-width="140"/>
      <el-table-column
        align="center"
        label="Contract Status"
        prop="contractStatus"
        min-width="130">
        <template slot-scope="{row}">
          <div :class="'status-' + row.contractStatus">
            {{row.contractStatus}}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="Approval Status"
        prop="auditStatusName"
        min-width="130">
        <template slot-scope="{row}">
          <div
            class="link-type"
            :class="'status-' + row.auditStatusName"
            @click="viewApproval(row)">
            {{row.auditStatusName}}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="Action"
        min-width="80"
        v-if="!$route.meta.onlyView">
        <template slot-scope="{row}">
          <el-dropdown
            class="action-dropdown"
            @command="(v) => handleCommand(v, row)"
            v-if="row.dataStatus == 'Active'">
            <i class="el-icon-more icon-action"></i>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                command="editLimit"
                v-if="row.auditStatusName != 'Approved'">
                Edit
              </el-dropdown-item>
              <el-dropdown-item
                command="editLimit"
                v-else>
                View
              </el-dropdown-item>
              <el-dropdown-item
                command="viewApproval">
                View Approval
              </el-dropdown-item>
              <el-dropdown-item
                command="deleteLimit">
                Set Inactive
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <div class="right">
      <Pagination
        v-show="table.total > 0"
        :total="table.total"
        :page.sync="filters.pageNum"
        :limit.sync="filters.pageSize"
        @pagination="getTableData" />
    </div>
    <approval
      v-bind="approvalDialog"
      @hide="hideApproval"/>
  </div>
</template>

<script>
import apiBase from '@/api/apiBase';
import limit from '@/api/limit';
import Approval from './approval.vue';
import Pagination from '@/components/Pagination';
export default {
  data() {
    return {
      table: {
        loading: false,
        total: 0,
        list: []
      },
      filters: {
        pageNum: 1,
        pageSize: 10,
        pageCriteria: {
          dataStatus: "A",
          auditStatus: "",
          contractStatus: "",
          criteria: ""
        }
      },
      statusOptions: [],
      statusContracts: [],
      approvalDialog: {
        id: "",
        visible: false,
        isApproval: false
      }
    };
  },
  components: { Approval, Pagination },
  created() {
    this.getStatusOptions();
    this.getContractStatus();
    this.toSearch();
  },
  methods: {
    toSearch() {
      this.filters.pageNum = 1;
      this.getTableData();
    },
    getStatusOptions() {
      apiBase.getAuditStatusOptions().then(res => {
        if (res.data && res.data.length > 0) {
          this.statusOptions = res.data
        }
      }).catch(err => {
        //this.$message.error(err);
      })
    },
    getContractStatus() {
      limit.getContractStatusOptions().then(res => {
        if (res.data && res.data.length > 0) {
          this.statusContracts = res.data
        }
      }).catch(err => {
        //this.$message.error(err);
      })
    },
    handleCommand(fuc, item) {
      this[fuc](item)
    },
    getTableData() {
      this.table.loading = true;
      limit.getCreditLimitPages(this.filters).then(res => {
        if (res.data.totalRow && res.data.records) {
          this.table.list = res.data.records
          this.table.total = res.data.totalRow
        } else {
          this.table.list = []
          this.table.total = 0
        }
      }).catch(err => {
        this.$message({
          type: 'error',
          message: err
        });
        this.table.list = []
        this.table.total = 0
      }).finally(() => {
        this.table.loading = false;
      });
    },
    creatLimit() {
      this.$router.push({
        path: '/partnership-management/monthly-credit-limit/add'
      });
    },
    editLimit(row) {
      this.$router.push({
        path: '/partnership-management/monthly-credit-limit/edit/' + row.groupCreditPk
      });
    },
    viewApproval(row) {
      this.approvalDialog.id = row.groupCreditPk;
      this.approvalDialog.visible = true;
    },
    hideApproval(e) {
      this.approvalDialog.id = "";
      this.approvalDialog.visible = false;
      if (e) {
        this.getTableData();
      }
    },
    deleteLimit(row) {
      this.$confirm('Are you sure you want set inactive to this credit limit?', 'Set Inactive', {
        confirmButtonText: 'OK',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }).then(res => {
        this.handleDeleteLimit(row.groupCreditPk)
      })
    },
    handleDeleteLimit(id) {
      limit.deleteCreditLimit(id).then(res => {
        this.$message({
          message: 'Set inactive credit limit successfully',
          type: 'success'
        });
        this.getTableData();
      }).catch(err => {
        this.$message({
          message: err,
          type: 'error'
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.status-Pending {
  color: #ffa028;
  &::before {
    background-color: #ffa028;
  }
}
.status-Approved,
.status-Active {
  color: #07a378;
  &::before {
    background-color: #07a378;
  }
}
.status-Rejected,
.status-Expired {
  color: #ed3f3f;
  &::before {
    background-color: #ed3f3f;
  }
}
</style>