<template>
  <div class="container" v-loading="loading.page">
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="170px"
      label-position="right">
      <div class="content">
        <div class="section-title">VOUCHER DETAILS</div>
        <div class="flexcr">
          <el-form-item
            label="Name:"
            prop="voucherName"
            class="flex1">
            <el-input
              class="add-text"
              v-model="form.voucherName"
              maxlength="50"/>
          </el-form-item>
          <el-form-item
            label="Validity Period:"
            prop="validityPeriod"
            class="flex1">
            <el-date-picker
              :value="form.validityPeriod"
              type="daterange"
              value-format="yyyy-MM-dd"
              start-placeholder="Start Date"
              end-placeholder="End Date"
              clearable
              class="add-text"
              @change="changeDatePeriod"
              @input="changeDatePeriod"/>
          </el-form-item>
        </div>
        <div class="flexcr">
          <el-form-item
            label="Redemption Method:"
            prop="redemptionMethod"
            class="flex1">
            <el-select
              class="add-text"
              v-model="form.redemptionMethod">
              <el-option
                v-for="(item, index) in options.redemp"
                :key="index"
                :label="item"
                :value="item"/>
            </el-select>
          </el-form-item>
          <el-form-item
            label="Quantity:"
            prop="voucherQuantity"
            class="flex1">
            <el-input
              class="add-text"
              v-model="form.voucherQuantity"
              type="number"
              min="1"
              max="999999"
              maxlength="6"/>
          </el-form-item>
        </div>
        <div class="flexcr">
          <el-form-item
            label="Voucher Type:"
            prop="voucherType"
            class="flex1">
            <el-select
              class="add-text"
              v-model="form.voucherType"
              @change="changeVoucherType">
              <el-option
                v-for="(item, index) in options.type"
                :key="index"
                :label="item"
                :value="item"/>
            </el-select>
          </el-form-item>
          <el-form-item
            label="Points Value:"
            prop="purchasePoints"
            class="flex1"
            v-if="form.redemptionMethod != 'Manual Issue'">
            <el-input
              class="add-text"
              v-model="form.purchasePoints"
              type="number"
              min="0"
              max="999999"
              maxlength="6"/>
          </el-form-item>
          <el-form-item
            label="Points Value:"
            class="flex1"
            v-else>
            <el-input
              class="add-text"
              disabled/>
          </el-form-item>
        </div>
        <div class="flexr">
          <el-form-item
            label="Country:"
            prop="countryCode"
            class="flex1">
            <el-select
              class="add-text"
              v-model="form.countryCode">
              <el-option
                v-for="item in options.country"
                :key="item.value"
                :label="item.name"
                :value="item.value"/>
            </el-select>
          </el-form-item>
          <el-form-item
            label="Description:"
            prop="voucherDesc"
            class="flex1">
            <el-input
              class="add-text"
              v-model="form.voucherDesc"
              type="textarea"
              maxlength="500"
              :autosize="autoSize"/>
          </el-form-item>
        </div>
      </div>
      <div class="content" v-if="form.voucherType !== 'Free Charging'">
        <div class="section-title">VOUCHER CONFIGURATION</div>
        <div class="flexcr">
          <el-form-item
            :label="'Set ' + (form.voucherType || 'Voucher Value') + ':'"
            prop="voucherValue"
            class="flex1">
            <el-input
              class="add-text"
              v-model="form.voucherValue"
              type="number"
              min="0"
              max="999999"
              maxlength="6"/>
          </el-form-item>
          <el-form-item
            label="Redemption Code:"
            prop="redemptionCode"
            class="flex1">
            <el-input
              class="add-text"
              v-model="form.redemptionCode"
              readonly>
              <el-button
                slot="append"
                icon="el-icon-refresh"
                :loading="loading.redem"
                title="Refresh New Redemption Code"
                @click="refreshVoucherCode"/>
            </el-input>
          </el-form-item>
        </div>
      </div>
      <div class="content">
        <div class="section-title">VOUCHER CONDITIONS</div>
        <div class="flexcr">
          <el-form-item
            label="Specific Sites:"
            prop="sitePks"
            class="flex1">
            <el-select
              style="width: 100%;"
              v-model="form.sitePks"
              filterable
              remote
              multiple
              clearable
              :remote-method="getAllSite"
              placeholder="Select with search">
              <el-option
                v-for="(item, index) in options.site"
                :key="index"
                :label="item.siteName"
                :value="item.sitePk"/>
            </el-select>
          </el-form-item>
        </div>
        <div class="flexcr">
          <el-form-item
            label="Time Period:"
            prop="timePeriod"
            class="flex1">
            <el-time-picker
              :value="form.timePeriod"
              is-range
              format="HH:mm"
              value-format="HH:mm"
              start-placeholder="Start Time"
              end-placeholder="End Time"
              clearable
              class="add-text"
              @change="changeTimePeriod"
              @input="changeTimePeriod"/>
          </el-form-item>
          <el-form-item
            label="Charge Types:"
            prop="chargeType"
            class="flex1">
            <el-select
              class="add-text"
              v-model="form.chargeType"
              clearable>
              <el-option
                v-for="(item, index) in options.charge"
                :key="index"
                :label="item"
                :value="item"/>
            </el-select>
          </el-form-item>
        </div>
        <div class="flexcr">
          <el-form-item
            label="Spend Range:"
            prop="minSpend"
            class="flex1">
            <div class="add-text flexc">
              <el-input
                class="flex1"
                v-model="form.minSpend"
                type="number"
                min="0"
                max="99999"
                maxlength="6"
                placeholder="Minimum Spend"/>
              <span style="padding: 0 5px;">-</span>
              <el-input
                class="flex1"
                v-model="form.maxSpend"
                type="number"
                min="1"
                max="999999"
                maxlength="6"
                placeholder="Maximum Spend"/>
            </div>
          </el-form-item>
          <el-form-item
            label="Day Selection:"
            prop="days"
            class="flex1">
            <el-select
              class="add-text"
              v-model="form.days"
              multiple
              clearable>
              <el-option
                v-for="(item, index) in options.weeks"
                :key="index"
                :label="item.key"
                :value="item.value"/>
            </el-select>
          </el-form-item>
        </div>
      </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 api from '../../http/api/voucher.js';
import site from '../../http/api/site'
import settings from '../../settings.js'
import apiBase from '@/api/apiBase.js';
import AuditView from "@/components/AuditView"
export default {
  data() {
    return {
      loading: {
        page: true,
        save: false,
        redem: false
      },
      isEdit: false,
      form: {
        voucherId: "",
        voucherName: "",
        voucherDesc: "",
        voucherType: "",
        datePeriodStart: "",
        datePeriodEnd: "",
        voucherQuantity: "1",
        redemptionMethod: "",
        purchasePoints: "",
        voucherValue: "",
        redemptionCode: "",
        countryCode: settings.defaultCountry,
        timePeriodStart: "",
        timePeriodEnd: "",
        minSpend: "",
        maxSpend: "",
        chargeType: "",
        sitePks: [],
        days: [],
        timePeriod: ["",""],
        validityPeriod: []
      },
      options: {
        days: [],
        site: [],
        type: [],
        weeks: [],
        charge: ["AC", "DC"],
        redemp: [],
        country: []
      },
      rules: {
        voucherName: {
          required: true,
          trigger: "blur",
          message: "Please input voucher name",
        },
        validityPeriod: {
          required: true,
          trigger: "change",
          message: "Please select validity date"
        },
        voucherQuantity: {
          required: true,
          trigger: "blur",
          message: "Please input quantity",
        },
        redemptionMethod: {
          required: true,
          trigger: "change",
          message: "Please select redemption method"
        },
        voucherType: {
          required: true,
          trigger: "change",
          message: "Please select voucher type"
        },
        purchasePoints: {
          required: true,
          trigger: "blur",
          message: "Please input points value",
        },
        voucherValue: {
          required: true,
          trigger: "blur",
          message: "Please input voucher value",
        },
        redemptionCode: {
          required: true,
          trigger: "change",
          message: "Please click the refresh button on the right to generate code",
        },
        countryCode: {
          required: true,
          trigger: "change",
          message: "Please select country"
        },
        chargeType: {
          required: true,
          trigger: "change",
          message: "Please select charge type"
        },
        sitePks: {
          required: true,
          trigger: "change",
          message: "Please select sites"
        },
        timePeriod: {
          required: true,
          trigger: "change",
          validator: (rule, value, callback) => {
            if (value && value.length > 0) {
              if (value[0] && value[1]) {
                callback()
              } else {
                callback("Please select time period")
              }
            } else {
              callback("Please select time period")
            }
          }
        },
      },
      autoSize: {
        minRows: 4,
        maxRows: 4
      }
    };
  },
  components: {AuditView},
  created() {
    this.getCountryOptions();
    if (this.$route.params.id) {
      this.isEdit = true;
      this.getVoucherDetail();
    }
  },
  methods: {
    init() {
      if (this.form.datePeriodStart && this.form.datePeriodEnd) {
        this.form.validityPeriod = [
          this.form.datePeriodStart,
          this.form.datePeriodEnd
        ]
      }
      if (this.form.timePeriodStart && this.form.timePeriodEnd) {
        this.form.timePeriod = [
          this.form.timePeriodStart,
          this.form.timePeriodEnd
        ]
      }
      //this.changeTimePeriod();
    },
    onBack() {
      this.$nextTick(() => {
        this.$router.replace({
          path: "/voucher-management/voucher"
        })
      })
    },
    getCountryOptions() {
      /*this.options.days = [];
      for (let i = 1; i <= 31; i++) {
        this.options.days.push(i);
      }*/
      site.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(() => {
        this.getWeekOptions();
        this.getChargeTypeOptions();
        this.getRedemTypeOptions();
        this.getVoucherTypeOptions();
        this.getAllSite();
      })
    },
    getWeekOptions() {
      api.getWeekOptions().then(res => {
        if (res.data) {
          this.options.weeks = res.data
        } else {
          this.options.weeks = []
        }
      }).catch(() => {
        this.$message({
          message: err,
          type: 'error',
          duration: 3000,
        })
        this.options.weeks = []
      })
    },
    getRedemTypeOptions() {
      api.getRedemMethodOptions().then(res => {
        if (res.data) {
          this.options.redemp = res.data
        } else {
          this.options.redemp = []
        }
      }).catch(() => {
        this.$message({
          message: err,
          type: 'error',
          duration: 3000,
        })
        this.options.redemp = []
      })
    },
    getVoucherTypeOptions() {
      api.getVoucherTypeOptions().then(res => {
        if (res.data) {
          this.options.type = res.data
        } else {
          this.options.type = []
        }
      }).catch(() => {
        this.$message({
          message: err,
          type: 'error',
          duration: 3000,
        })
        this.options.type = []
      }).finally(() => {
        this.loading.page = false;
      })
    },
    getAllSite(word) {
      site.getAllSiteList({siteName: word}).then(res => {
        if (res.data && res.data.length > 0) {
          this.options.site = res.data
        } else {
          this.options.site = []
        }
      }).catch(() => {
        this.$message({
          message: err,
          type: 'error',
          duration: 3000,
        })
        this.options.site = []
      });
    },
    getChargeTypeOptions() {
      apiBase.getChargerTypeOptions().then(res => {
        if (res.data) {
          this.options.charge = res.data
        } else {
          this.options.charge = []
        }
      }).catch(() => {
        this.$message({
          message: err,
          type: 'error',
          duration: 3000,
        })
        this.options.charge = []
      });
    },
    getVoucherDetail() {
      api.viewVoucher(this.$route.params.id).then(res => {
        if (res.data) {
          this.form = res.data;
          this.init();
        }
      }).catch(err => {
        this.$message({
          type: 'error',
          message: err
        })
      }).finally(() => {
        this.loading.page = false;
      })
    },
    refreshVoucherCode() {
      this.loading.redem = true;
      api.getVoucherRedemCode().then(res => {
        if (res.data) {
          this.form.redemptionCode = res.data
        }
      }).catch(() => {
        this.$message({
          message: err,
          type: 'error',
          duration: 3000,
        })
        this.form.redemptionCode = ""
      }).finally(() => {
        this.loading.redem = false;
      })
    },
    changeDatePeriod(date) {
      console.log("changeDatePeriod", date);
      if (date) {
        this.form.validityPeriod = date;
      } else {
        this.form.validityPeriod = [];
      }
      this.$nextTick(() => {
        this.$forceUpdate();
      })
    },
    changeTimePeriod(time) {
      console.log("changeTimePeriod", time);
      if (time) {
        this.form.timePeriod = time;
      } else {
        this.form.timePeriod = ["", ""];
      }
      this.$nextTick(() => {
        this.$forceUpdate();
      })
    },
    changeVoucherType() {
      if (this.form.voucherType == 'Free Charging') {
        this.form.voucherValue = "";
        this.form.redemptionCode = "";
      }
    },
    onClickSave() {
      this.$refs.form.validate(result => {
        if (result) {
          this.loading.save = true;
          if (this.form.validityPeriod.length == 2) {
            this.form.datePeriodStart = this.form.validityPeriod[0]
            this.form.datePeriodEnd = this.form.validityPeriod[1]
          }
          if (this.form.timePeriod.length == 2) {
            this.form.timePeriodStart = this.form.timePeriod[0]
            this.form.timePeriodEnd = this.form.timePeriod[1]
          }
          if (this.form.redemptionMethod == 'Manual Issue') {
            this.form.purchasePoints = "";
          }
          this.isEdit ? this.updateVoucher() : this.createVoucher();
        }
      });
    },
    createVoucher() {
      api.createVoucher(this.form).then(res => {
        this.$message({
          type: 'success',
          message: "Successfully added"
        });
        this.onBack();
      }).catch(err => {
        this.$message({
          type: 'error',
          message: err
        });
      }).finally(() => {
        this.loading.save = false;
      });
    },
    updateVoucher() {
      api.updateVoucher(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 {
    margin: 0 8px 16px;
    padding: 15px 80px;
    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: 150px;
    max-width: 300px;
  }
  .add-text ::v-deep .el-textarea__inner {
    font-family: sans-serif;
  }
  .form-photo {
    flex: 1;
    ::v-deep .el-form-item__label {
      padding: 12px;
      line-height: 16px;
    }
    .photo-uploader {
      margin-right: 10px;
      .uploader-image {
        width: 180px;
        height: 120px;
        text-align: left;
      }
      ::v-deep img {
        object-fit: cover;
      }
      .avatar-uploader-icon {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        font-size: 28px;
        color: #8c939d;
        width: 120px;
        height: 120px;
        line-height: 120px;
        text-align: center;
      }
    }
  }
  .hr {
    height: 2px;
    margin: 10px -40px;
    background-color: #F0F5FC;
  }
  .buttons {
    padding-top: 15px;
    padding-bottom: 15px;
  }
  @media screen and (max-width: 500px) {
    .container {
      padding: 0px;
    }
    .content {
      padding: 15px 30px;
    }
  }
</style>