<template>
  <div class="container" v-loading="loading">
    <el-form
      :model="form"
      :rules="rules"
      ref="form"
      label-position="right"
      label-width="180px">
      <div class="content">
        <div class="section-title">Group</div>
        <el-form-item
          prop="groupName"
          label="Group Name:">
          <el-input
            v-model="form.groupName"
            class="add-text"
            placeholder=""
            maxlength="100"/>
        </el-form-item>
        <el-form-item
          prop="groupType"
          label="Group Type:">
          <el-select
            v-model="form.groupType"
            class="add-text"
            placeholder="">
            <el-option
              v-for="item in options.groupType"
              :key="item.value"
              :label="item.name"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          prop="contactPerson"
          label="Contact Person:">
          <div class="add-text flexc">
            <el-select
              style="min-width: 75px; max-width: 80px;"
              v-model="form.callingCode">
              <el-option
                v-for="item in options.callingCode"
                :key="item.callingCode"
                :label="'+' + item.callingCode"
                :value="item.callingCode"
              />
            </el-select>
            <el-input
              style="margin-left: 10px;"
              v-model="form.contactPerson"
              maxlength="80"/>
          </div>
        </el-form-item>
        <el-form-item
          prop="contactNumber"
          label="Contact Number:">
          <el-input
            v-model="form.contactNumber"
            class="add-text"
            placeholder=""
            maxlength="20"/>
        </el-form-item>
        <!--el-form-item
          label="Login ID:">
          <el-input
            v-model="form.loginId"
            class="add-text"
            placeholder=""
            maxlength="50"/>
        </el-form-item>
        <el-form-item
          label="Password Set:">
          <el-input
            v-model="form.password"
            class="add-text"
            type="password"
            maxlength="20"/>
        </el-form-item-->
        <el-form-item
          label="Country:">
          <el-select
            v-model="form.countryCode"
            class="add-text"
            placeholder="">
            <el-option
              v-for="item in options.countryOptions"
              :key="item.value"
              :label="item.name"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          prop="discount"
          label="Discount:">
          <el-input
            v-model="form.discount"
            class="add-text"
            maxlength="5"/>
        </el-form-item>
      </div>
      <div class="content flexcr">
        <div class="buttons">
          <el-button
            @click="onClickCancelButton"
            type="primary"
            class="cancel-button">
            Cancel
          </el-button>
          <el-button
            @click="onClickConfirmButton"
            type="primary">
            Save
          </el-button>
        </div>
        <div
          class="update-by"
          v-if="isEdit">
          <span
            class="add-text"
            :title='"CREATED BY " + form.createdBy + " ON " + form.createdOn'>
            LAST UPDATED BY {{form.updatedBy}} TIMESTAMP: {{form.updatedOn}}
          </span>
        </div>
      </div>
    </el-form>
  </div>
</template>

<script>
import site from '@/http/api/site'
import api from '@/http/api/group'
import setting from '../../settings.js'
import {getCountryList} from '../../utils/index.js'
export default {
  name: "GroupDetail",
  data() {
    return {
      loading: false,
      form: {
        discount: "",
        groupPk: "",
        groupName: "",
        groupType: "",
        contactPerson: "",
        contactNumber: "",
        loginId: "",
        password: "",
        callingCode: setting.defaultCalling,
        countryCode: setting.defaultCountry
      },
      options: {
        callingCode: [],
        countryOptions: [],
        groupType: []
      },
      isEdit: false,
      rules: { 
        groupType: [{
          message: "Please select group type",
          trigger: "blur",
          required: true,
        }],
        groupName: [{
          message: "Please input group name",
          trigger: "blur",
          required: true,
        }],
        contactPerson: [{
          message: "required",
          trigger: "blur",
          required: false,
        }],
        contactNumber: [{
          message: "required",
          trigger: "blur",
          required: false,
        }, {
          pattern: /^\d{6,}$/,
          trigger: "blur",
          message: "Please enter the correct number",
        }],
        discount: [{
          trigger: "blur",
          validator: (rule, value, callback, source, options) => {
            let pattern = /^\d*(\.)?\d{1,2}$/
            if (pattern.test(value)) {
              const lang = Number(value);
              if (lang < 0 || lang > 100) {
                callback("Discount must to be between 0 and 100")
              } else {
                callback()
              }
            } else {
              callback("Please enter the correct discount")
            }
          }
        }]
      }
    }
  },
  created() {
    this.getCountryList()
    this.getGroupType()
    if (this.$route.params.id) {
      this.isEdit = true;
      this.getGroupDetail()
    }
  },
  methods: {
    getCountryList() {
      getCountryList(list => {
        this.options.callingCode = list
      })
      site.getCountryList().then(({ data }) => {
        this.options.countryOptions = data
      })
    },
    getGroupType() {
      this.loading = true;
      api.getUserGroupType().then(res => {
        if (res.data) {
          this.options.groupType = res.data
          if (!this.isEdit) {
            const defaultType = this.options.groupType[0].value
            this.form.groupType = defaultType
          }
        }
      }).catch(error => {
        this.$message({
          message: error,
          type: 'error'
        })
      }).finally(() => {
        this.loading = false;
      })
    },
    getGroupDetail() {
      api.getUserGroupInfo({
        groupPk: this.$route.params.id,
      }).then(res => {
        if (res.data) {
          this.form = Object.assign(this.form, res.data)
          if (!this.form.callingCode) {
            this.form.callingCode = setting.defaultCalling
          }
        }
      }).catch(err => {
        this.$message({
          message: err,
          type: 'error'
        })
      })
    },
    onClickCancelButton() {
      this.$nextTick(() => {
        this.$router.replace({
          path: "/partnership-management/group-management"
        })
      })
    },
    onClickConfirmButton() {
      this.$refs.form.validate(async (valid, fields) => {
        if (valid) {
          this.loading = true
          this.isEdit ? this.onUpdateGroup() : this.onAddGroup();
        }
      })
    },
    onAddGroup() {
      api.addUserGroup(this.form).then(res => {
        this.$message({
          type: 'success',
          message: "Add successfully!"
        })
        this.onClickCancelButton()
      }).catch(err => {
        this.$message({
          type: 'error',
          message: err
        })
      }).finally(() => {
        this.loading = false;
      })
    },
    onUpdateGroup() {
      api.updateUserGroup(this.form).then(res => {
        this.$message({
          type: 'success',
          message: "Update successfully!"
        })
        this.onClickCancelButton()
      }).catch(err => {
        this.$message({
          type: 'error',
          message: err
        })
      }).finally(() => {
        this.loading = 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%;
    max-width: 300px;
  }
  .add-text ::v-deep .el-textarea__inner {
    font-family: sans-serif;
  }
  .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>>
