<template>
  <div class="app-container">
    <div class="filter-container flexr" style="align-items: flex-end;overflow: hidden;">
      <div class="flex2">
        <div class="flexcr">
          <div class="section-title">
            BASE SETTING
            <span
              class="normal"
              v-if="baseConfig.lastUpdateTime">
              (LAST UPDATED: {{baseConfig.lastUpdateTime}})
            </span>
          </div>
          <div
            class="basic-edit"
            v-if='roleName == "ADMIN"'
            @click="editBaseConfig">
            <i class="el-icon-edit-outline"/>
            Edit
          </div>
        </div>
        <div
          class="basic-config"
          v-if="baseConfig.dynamicPointsId">
          <b>POINTS EARNING FORMULA:&nbsp;</b>
          <span>{{baseConfig.earningValue}} {{baseConfig.earningCurrency}} = {{baseConfig.earningPoints}} POINTS</span>
        </div>
        <div
          class="basic-config"
          v-if="baseConfig.dynamicPointsId">
          <b>POINTS OFFSET FORMULA:&nbsp;</b>
          <span>{{baseConfig.offsetPoints}} POINTS = {{baseConfig.offsetValue}} {{baseConfig.offsetCurrency}}</span>
        </div>
      </div>
      <div class="filter-flex-button" style="padding: 5px 0;">
        <el-button
          type="primary"
          @click="onClickAdd"
          icon="el-icon-plus"
          v-if="!$route.meta.onlyView">
          Add Point Config
        </el-button>
      </div>
    </div>
    <el-table
      v-loading="table.loading"
      :data="table.list">
      <el-table-column
        align="center"
        label="Name"
        min-width="150">
        <template slot-scope="{row}">
          <div
            class="link-type"
            @click="onClickEdit(row)"
            v-if="row.dataStatus != 'Inactive'">
            {{row.dynamicPointsName}}
          </div>
          <span v-else>{{ row.dynamicPointsName }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="Country"
        prop="countryName"
        min-width="100"/>
      <el-table-column
        align="center"
        label="Valid Period"
        min-width="150">
        <template slot-scope="{row}">
          <div>Start: {{row.periodStart}}</div>
          <div>End: {{row.periodEnd}}</div>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="Sites"
        prop="sites"
        min-width="100"/>
      <el-table-column
        align="center"
        label="Vehicle Types"
        prop="vehicleTypes"
        min-width="120"/>
      <el-table-column
        align="center"
        label="Status"
        prop="dataStatus"
        min-width="80"/>
      <el-table-column
        v-if="!$route.meta.onlyView"
        label="Action"
        align="center"
        min-width="70">
        <template slot-scope="{row, $index}">
          <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="onClickAssignSite">
                Assign Sites
              </el-dropdown-item>
              <el-dropdown-item
                command="onClickAssignVehicle">
                Assign Vehicles
              </el-dropdown-item>
              <el-dropdown-item
                command="onClickEdit">
                Edit
              </el-dropdown-item>
              <el-dropdown-item
                command="onClickDelete">
                Delete
              </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>
    <BaseConfigDialog
      :visible="showBasic"
      :config="baseConfig"
      @hide="hideBaseDialog"/>
    <AssignmentDialog
      v-bind="assignment"
      @hide="hideAssignment"/>
  </div>
</template>

<script>
import apiBase from '@/api/apiBase';
import points from '@/api/points';
import settings from '../../settings';
import AssignmentDialog from './AssignmentDialog';
import BaseConfigDialog from './BaseConfigDialog';
import Pagination from '@/components/Pagination';
import {getRoleName} from '../../utils/auth.js'
export default {
  data() {
    return {
      table: {
        list: [],
        total: 0,
        loading: false
      },
      filters: {
        pageNum: 1,
        pageSize: 10,
        pageCriteria: {
          criteria: "",
          countryCode: ""//settings.defaultCountry
        }
      },
      roleName: "",
      showBasic: false,
      baseConfig: {},
      assignment: {
        title: "",
        pointsId: "",
        visible: false,
        isVehicle: false
      }
    };
  },
  components: {Pagination, AssignmentDialog, BaseConfigDialog},
  created() {
    this.getBasicConfig();
    this.toSearch();
    this.roleName = getRoleName();
  },
  methods: {
    toSearch() {
      this.filters.pageNum = 1
      this.getTableData()
    },
    getBasicConfig() {
      points.getBasePointsConfig().then(res => {
        if (res.data && res.data.dynamicPointsId) {
          this.baseConfig = res.data
        }
      }).catch(err => {
        this.$message({
          type: 'error',
          message: err
        })
      })
    },
    getTableData() {
      this.table.loading = true;
      points.getPointsConfigPages(this.filters).then(res => {
        if (res.data.totalRow && res.data.records) {
          this.table.total = res.data.totalRow;
          this.table.list = res.data.records;
        } else {
          this.table.total = 0;
          this.table.list = [];
        }
      }).catch(err => {
        this.$message({
          type: 'error',
          message: err
        })
        this.table.total = 0;
        this.table.list = [];
      }).finally(() => {
        this.table.loading = false;
      })
    },
    editBaseConfig() {
      this.showBasic = true;
    },
    hideBaseDialog(e) {
      this.showBasic = false;
      if (e) {
        this.getBasicConfig();
      }
    },
    handleCommand(cb, item) {
      this[cb](item)
    },
    onClickAssignSite(item) {
      this.assignment.isVehicle = false;
      this.assignment.pointsId = item.dynamicPointsId;
      this.assignment.title = "ASSIGN SITES (" + item.dynamicPointsName +  ")";
      this.assignment.visible = true;
    },
    onClickAssignVehicle(item) {
      this.assignment.isVehicle = true;
      this.assignment.pointsId = item.dynamicPointsId;
      this.assignment.title = "ASSIGN VEHICLE TYPES (" + item.dynamicPointsName +  ")";
      this.assignment.visible = true;
    },
    hideAssignment() {
      this.assignment.visible = false;
      this.getTableData();
    },
    onClickAdd() {
      this.$router.push({
        path: '/points-management/create'
      });
    },
    onClickEdit(item) {
      this.$router.push({
        path: '/points-management/update/' + item.dynamicPointsId
      });
    },
    onClickDelete(item) {
      this.$confirm(
        'Are you sure you want to delete this points config?',
        'Delete', {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }).then(res => {
        this.deletePointsConfig(item.dynamicPointsId);
      });
    },
    deletePointsConfig(id) {
      this.table.loading = true;
      points.deletePointsConfig(id).then(res => {
        this.$message({
          message: 'Delete successfully!',
          type: 'success'
        });
        this.getTableData();
      }).catch(err => {
        this.$message({
          message: err,
          type: 'error'
        });
        this.table.loading = false;
      });
    }
  }
}
</script>

<style scoped>
.section-title {
  color: #333;
  margin-bottom: 20px;
  font-size: 16px;
  user-select: none;
  line-height: 24px;
  font-weight: bold;
  white-space: nowrap;
  font-family: sans-serif;
  text-overflow: ellipsis;
  text-transform: uppercase;
}
.section-title .normal {
  font-weight: normal;
}
.basic-config {
  color: #333;
  font-size: 14px;
  padding-bottom: 6px;
}
.basic-edit {
  color: #3179E4;
  cursor: pointer;
  font-size: 15px;
  margin-left: 15px;
  margin-bottom: 15px;
  user-select: none;
  white-space: nowrap;
}
.basic-edit:hover,
.basic-edit:active {
  color: #ff0000;
}
</style>