<template>
  <div class="container" v-loading="loading.page">
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="110px"
      label-position="right">
      <div class="content">
        <div class="section-title">POINTS CONFIGURATION</div>
        <el-form-item
          label="Name:"
          prop="dynamicPointsName"
          class="flex1">
          <el-input
            class="add-text"
            v-model="form.dynamicPointsName"
            maxlength="50"/>
        </el-form-item>
        <el-form-item
          label="Country:"
          prop="countryCode"
          class="flex1">
          <el-select
            class="add-text"
            v-model="form.countryCode"
            @change="changeCountry">
            <el-option
              v-for="(item, index) in options.country"
              :key="index"
              :label="item.countryName"
              :value="item.countryCode"/>
          </el-select>
        </el-form-item>
        <el-form-item
          label="Valid Period:"
          prop="periods"
          class="flex1">
          <el-date-picker
            v-model="form.periods"
            class="add-text"
            type="datetimerange"
            format="yyyy-MM-dd HH:mm"
            value-format="yyyy-MM-dd HH:mm"
            range-separator="-"
            start-placeholder="Start Date"
            end-placeholder="End Date"/>
        </el-form-item>
      </div>
      <div class="content">
        <div class="section-title">GROUP CONFIGURATION</div>
        <el-table
          :data="form.pointsItems"
          class="config-item-table"
          header-row-class-name="customer-row"
          row-class-name="customer-row">
          <el-table-column
            label="USER TYPE:"
            prop="label"
            min-width="120">
            <template slot-scope="{row}">
              <el-select
                v-model="row.userType"
                @change="v => getGroupOptions(v, row)">
                <el-option
                  v-for="item in options.uTypes"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            label="GROUP NAME:"
            prop="label"
            min-width="140">
            <template slot-scope="{row}">
              <el-select
                v-model="row.groupPk"
                @change="getGroupOptions"
                :disabled="groupOptions[row.userType].length == 0"
                v-if="groupOptions[row.userType]">
                <el-option
                  v-for="(item, index) in groupOptions[row.userType]"
                  :key="index"
                  :label="item.key"
                  :value="item.value">
                </el-option>
              </el-select>
              <div class="center" v-else-if="row.userType">
                <i class="el-icon-loading"/>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="CONNECTOR TYPE:"
            prop="label"
            min-width="160">
            <template slot-scope="{row}">
              <el-select
                v-model="row.connectorType">
                <el-option
                  v-for="item in options.cTypes"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            label="POINTS EARNING FORMULA:"
            prop="label"
            min-width="300">
            <template slot-scope="{row}">
              <div class="flexc">
                <el-input
                  class="input-text"
                  type="number"
                  v-model="row.earningValue"/>
                <div class="unit-text">{{currency}} =</div>
                <el-input
                  class="input-text"
                  type="number"
                  v-model="row.earningPoints"/>
                <div class="unit-text">POINTS</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="POINTS OFFSET FORMULA:"
            prop="label"
            min-width="300">
            <template slot-scope="{row}">
              <div class="flexc">
                <el-input
                  class="input-text"
                  type="number"
                  v-model="row.offsetPoints"/>
                <div class="unit-text">POINTS =</div>
                <el-input
                  class="input-text"
                  type="number"
                  v-model="row.offsetValue"/>
                <div class="unit-text">{{currency}}</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="Action"
            prop="label"
            min-width="60">
            <template slot="header">
              <div class="flexcc">
                <img
                  class="list-item-icon"
                  @click="addConfigItem"
                  src="../../assets/form-list-add.png"/>
              </div>
            </template>
            <template slot-scope="{row, $index}">
              <div class="flexcc">
                <img
                  class="list-item-icon"
                  @click="removeConfigItem(row, $index)"
                  src="../../assets/form-list-sub.png"/>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="content flexcr">
        <div class="buttons">
          <el-button
            @click="onBack"
            type="primary"
            class="cancel-button">
            CANCEL
          </el-button>
          <el-button
            @click="onClickSave"
            type="primary"
            :loading="loading.save">
            &nbsp; &nbsp;SAVE&nbsp; &nbsp;
          </el-button>
        </div>
        <audit-view :audit="form.audit"/>
      </div>
    </el-form>
  </div>
</template>

<script>
import apiBase from '@/api/apiBase';
import points from '@/api/points';
import settings from '../../settings';
import AuditView from "@/components/AuditView"
export default {
  data() {
    return {
      loading: {
        page: true,
        save: false
      },
      isEdit: false,
      currency: "SGD",
      form: {
        dynamicPointsId: "",
        dynamicPointsName: "",
        countryCode: settings.defaultCountry,
        periods: ["", ""],
        pointsItems: []
      },
      pointsItem: {
        groupPk: "",
        userType: "",
        connectorType: "",
        earningValue: "",
        earningPoints: "",
        offsetValue: "",
        offsetPoints: "",
        dynamicPointsItemId: ""
      },
      options: {
        cTypes: [],
        uTypes: [],
        country: []
      },
      groupOptions: {
        PUBLIC: []
      },
      rules: {
        dynamicPointsName: {
          required: true,
          trigger: "blur",
          message: "Please enter name"
        },
        countryCode: {
          required: true,
          trigger: "change",
          message: "Please select country"
        },
        periods: {
          required: true,
          trigger: "change",
          validator: (rule, value, callback) => {
            if (value && value.length > 0) {
              if (value[0] && value[1]) {
                callback()
              } else {
                callback("Please select valid period")
              }
            } else {
              callback("Please select valid period")
            }
          }
        },
      }
    };
  },
  components: {AuditView},
  created() {
    this.getCountryOptions(() => {
      if (this.$route.params.id) {
        this.isEdit = true;
        this.getPointsConfigInfo();
      } else {
        this.addConfigItem();
        this.changeCountry();
      }
    });
  },
  methods: {
    init() {
      if (!this.form.pointsItems || this.form.pointsItems.length == 0) {
        this.form.pointsItems = [];
        this.addConfigItem();
      } else {
        this.form.pointsItems.forEach(item => {
          this.getGroupOptions(item.userType, item, true)
        });
      }
      this.changeCountry();
    },
    onBack() {
      this.$nextTick(() => {
        this.$router.replace({
          path: "/points-management/setting"
        })
      })
    },
    changeCountry() {
      if (this.options.country && this.options.country.length > 0) {
        for(let country of this.options.country) {
          if (country.countryCode == this.form.countryCode) {
            this.currency = country.currency;
            break;
          }
        }
      }
    },
    getCountryOptions(back) {
      apiBase.getCountryList().then(res => {
        if (res.data) {
          this.options.country = res.data
        } else {
          this.options.country = []
        }
      }).catch(() => {
        this.$message({
          message: err,
          type: 'error',
          duration: 3000,
        })
        this.options.country = []
      }).finally(() => {
        back();
        this.getChargeTypeOptions();
        this.getUserTypeOptions();
      })
    },
    getChargeTypeOptions() {
      apiBase.getChargerTypeOptions().then(res => {
        if (res.data) {
          this.options.cTypes = res.data
        } else {
          this.options.cTypes = []
        }
      }).catch(() => {
        this.$message({
          message: err,
          type: 'error',
          duration: 3000,
        })
        this.options.cTypes = []
      });
    },
    getUserTypeOptions() {
      apiBase.getUserTypeOptions().then(res => {
        if (res.data) {
          this.options.uTypes = res.data
        } else {
          this.options.uTypes = []
        }
      }).catch(() => {
        this.$message({
          message: err,
          type: 'error',
          duration: 3000,
        })
        this.options.uTypes = []
      }).finally(() => {
        this.loading.page = false;
      });
    },
    getGroupOptions(userType, row, init) {
      if (!init) {
        row.groupPk = "";
      }
      if (this.groupOptions[userType]) {
        return;
      }
      apiBase.getUserGroupOptions(userType).then(res => {
        if (res.data) {
          this.groupOptions[userType] = res.data
        } else {
          this.groupOptions[userType] = []
        }
      }).catch(err => {
        this.$message({
          message: err,
          type: 'error'
        })
        this.groupOptions[userType] = []
      }).finally(() => {
        row.userType = "";
        this.$nextTick(() => {
          row.userType = userType;
          this.$forceUpdate();
        });
      })
    },
    getPointsConfigInfo() {
      points.viewPointsConfig(this.$route.params.id).then(res => {
        if (res.data) {
          for (let k in this.form) {
            if (res.data[k]) {
              this.form[k] = res.data[k];
            }
          }
          if (res.data.periodStart && res.data.periodEnd) {
            this.form.periods = [
              res.data.periodStart,
              res.data.periodEnd
            ]
          }
          this.init();
        }
      }).catch(err => {
        this.$message({
          type: 'error',
          message: err
        })
      }).finally(() => {
        this.loading.page = false;
      })
    },
    addConfigItem() {
      this.form.pointsItems.push({
        ...this.pointsItem
      });
    },
    removeConfigItem(item, index) {
      if (item.dynamicPointsItemId) {
        this.$confirm('Are you sure you want to remove this configuration item?', 'Delete', {
          confirmButtonText: 'Confirm',
          cancelButtonText: 'Cancel',
          type: 'warning',
        }).then(() => {
          this.deleteConfigItem(item, index);
        })
      } else {
        this.form.pointsItems.splice(index, 1);
        if (this.form.pointsItems.length == 0) {
          this.addConfigItem()
        }
      }
    },
    deleteConfigItem(item, index) {
      points.deletePointsConfigItem(item.dynamicPointsItemId).then(res => {
        this.form.pointsItems.splice(index, 1);
        if (this.form.pointsItems.length == 0) {
          this.addConfigItem()
        }
      }).catch(error => {
        this.$notify({
          type: 'error',
          message: error,
          title: 'Delete failed'
        })
      })
    },
    onClickSave() {
      this.$refs.form.validate(result => {
        if (result) {
          this.loading.save = true;
          this.isEdit ? this.updateConfig() : this.createConfig();
        }
      });
    },
    createConfig() {
      points.createPointsConfig(this.form).then(res => {
        this.$message({
          type: 'success',
          message: "Successfully Created"
        });
        this.onBack();
      }).catch(err => {
        this.$message({
          type: 'error',
          message: err
        });
      }).finally(() => {
        this.loading.save = false;
      });
    },
    updateConfig() {
      points.updatePointsConfig(this.form).then(res => {
        this.$message({
          type: 'success',
          message: "Successfully Updated"
        });
        this.onBack();
      }).catch(err => {
        this.$message({
          type: 'error',
          message: err
        });
      }).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 {
    min-width: 400px;
    margin: 0 8px 16px;
    padding: 15px 60px;
    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%;
    min-width: 200px;
    max-width: 350px;
  }
  
  .area-text {
    width: 100%;
    min-width: 200px;
    max-width: 350px;
  }
  
  .input-text {
    flex: 1;
  }
  
  .unit-text {
    color: #333;
    padding: 0 8px;
    font-size: 12px;
    font-weight: bold;
    white-space: nowrap;
  }
  
  .add-text ::v-deep .el-textarea__inner,
  .area-text ::v-deep .el-textarea__inner {
    font-family: sans-serif;
  }
  .buttons {
    padding-top: 15px;
    padding-bottom: 15px;
  }
  @media screen and (max-width: 500px) {
    .container {
      padding: 0px;
    }
    .content {
      padding: 15px 30px;
    }
  }
  .list-item-icon {
    width: 30px;
    height: 30px;
    cursor: pointer;
    font-size: 26px;
    font-weight: 500;
    user-select: none;
  }
  .config-item-table {
    width: 100%;
    padding-bottom: 10px;
  }
  .config-item-table:before {
    height: 0;
  }
  ::v-deep .customer-row {
    th,td {
      padding: 0 0 10px;
      min-height: 30px;
      background: #fff;
      border-bottom: none;
    }
    .time-picker {
      width: 100%;
    }
  }
</style>