<template>
  <div
    class="container"
    v-loading="loading.page">
    <el-form
      class="content"
      ref="form"
      :model="form"
      :rules="rules"
      label-width="150px"
      label-position="right">
      <div class="section-title">Memberships</div>
      <div class="flexcr">
        <el-form-item
          label="Display Name:"
          prop="displayName"
          class="flex1">
          <el-input
            class="add-text"
            :readonly="isView"
            v-model="form.displayName"/>
        </el-form-item>
        <el-form-item
          label="Card No:"
          prop="cardNo"
          class="flex1">
          <el-input
            class="add-text"
            :readonly="isView"
            v-model="form.cardNo"/>
        </el-form-item>
      </div>
      <div class="flexcr">
        <el-form-item
          label="Email Address:"
          prop="emailAddress"
          class="flex1">
          <el-input
            class="add-text"
            :readonly="isView"
            v-model="form.emailAddress"/>
        </el-form-item>
        <el-form-item
          label="Group:"
          prop="groupPk"
          class="flex1">
          <el-select
            class="add-text"
            :disabled="isView"
            v-model="form.groupPk">
            <el-option
              v-for="(item, index) in options.groups"
              :key="index"
              :label="item.groupName"
              :value="''+item.groupPk"/>
          </el-select>
        </el-form-item>
      </div>
      <div class="flexcr">
        <el-form-item
          label="Country:"
          prop="countryCode"
          class="flex1">
          <el-select
            class="add-text"
            :disabled="isView"
            v-model="form.countryCode">
            <el-option
              v-for="item in options.countryList"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="Phone Number:"
          prop="phone"
          class="flex1">
          <div class="add-text flexc">
            <el-select
              style="min-width: 75px; max-width: 80px;"
              :disabled="isView"
              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;"
              :readonly="isView"
              v-model="form.phone"/>
          </div>
        </el-form-item>
      </div>
      <div class="flexcr">
        <el-form-item
          label="PDVL:"
          class="form-photo"
          prop="cardFront">
          <template v-slot:label>
            Card Photo:<br>(Front)&nbsp;
          </template>
          <div class="add-text">
            <el-upload
              v-if="isEdit || (!isEdit && !isView)"
              class="photo-uploader"
              accept=".jpg,.jpeg,.png,.gif,.JPG,.JPEG"
              :action="action"
              :headers="headers"
              :show-file-list="false"
              :on-success="onUploadSuccess"
              :on-error="onUploadError"
              :before-upload="beforeUpload">
              <div
                v-loading="loading.upload"
                class="uploader-image">
                <el-image
                  class="uploader-image"
                  v-if="form.cardFront"
                  :src="getImageSrc(form.cardFront)"/>
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </div>
            </el-upload>
            <div class="photo-uploader" v-else-if="form.cardFront">
              <el-image
                class="uploader-image"
                :src="getImageSrc(form.cardFront)"
                :preview-src-list="previewSrcList"/>
            </div>
          </div>
        </el-form-item>
      </div>
      <p></p>
    </el-form>
    <div class="content flexcr">
      <div class="buttons" v-if="isView">
        <el-button
          v-if="this.form.membershipStatus !== 'Reject'"
          @click="onClickReject"
          type="primary"
          class="cancel-button"
          :loading="loading.reject">
          &nbsp;Reject&nbsp;
        </el-button>
        <el-button
          v-if="this.form.membershipStatus !== 'Pass'"
          @click="onClickApprove"
          type="primary"
          :loading="loading.approve">
          Approve
        </el-button>
      </div>
      <div class="buttons" v-else-if="isEdit">
        <el-button
          @click="onBack"
          type="primary"
          class="cancel-button">
          Cancel
        </el-button>
        <el-button
          @click="onClickSave"
          type="primary"
          :loading="loading.save">
          &nbsp;Save&nbsp;
        </el-button>
      </div>
      <div class="buttons" v-else>
        <el-button
          @click="onBack"
          type="primary"
          class="cancel-button">
          &nbsp;Back&nbsp;
        </el-button>
        <el-button
          @click="onClickSave"
          type="primary"
          :loading="loading.save">
          &nbsp;Save&nbsp;
        </el-button>
      </div>
      <div class="update-by" v-if="isEdit || isView">
        <span
          class="add-text"
          :title='"CREATED BY " + form.createdBy + " ON " + form.createdOn'>
          LAST UPDATED BY {{form.updatedBy}} TIMESTAMP: {{form.updatedOn}}
        </span>
      </div>
    </div>
  </div>
</template>

<script>
import api from '@/http/api/group'
import site from '@/http/api/site'
import { baseURL } from '@/http/http'
import { getToken } from '@/utils/auth'
import settings from '../../settings.js'
import {getCountryList} from '../../utils/index.js'
export default {
  data() {
    return {
      loading: {
        page: true,
        upload: false,
        approve: false,
        reject: false,
        save: false
      },
      form: {
        membershipId: "",
        displayName: "",
        cardNo: "",
        countryCode: settings.defaultCountry,
        callingCode: settings.defaultCalling,
        emailAddress: "",
        groupPk: "",
        phone: "",
        cardFront: "",
        cardReverse: "",
        membershipStatus: "",
      },
      rules: {
        displayName: {
          required: true,
          trigger: "blur",
          message: "Please input display name",
        },
        emailAddress: {
          required: true,
          trigger: "blur",
          message: "Please input email address"
        },
        cardNo: {
          required: true,
          trigger: "blur",
          message: "Please input card number"
        },
        groupPk: {
          required: true,
          trigger: "change",
          message: "Please select a group"
        },
        countryCode: {
          required: true,
          trigger: "change",
          message: "Please select a country"
        },
        phone: {
          required: true,
          trigger: "blur",
          message: "Please input phone number"
        },
        cardFront: {
          required: true,
          trigger: "change",
          message: "Please upload card photo"
        }
      },
      options: {
        groups: [],
        callingCode: [],
        countryList: []
      },
      isView: false,
      isEdit: false
    }
  },
  computed: {
    action() {
      return baseURL + process.env.VUE_APP_API_PREFIX + '/picture/upload'
    },
    headers() {
      return {
        accessToken: getToken(),
        photoSubDir: "MEMBERSHIP",
      }
    },
    previewSrcList() {
      const imageSrc = []
      if (this.form.cardFront) {
        imageSrc.push(baseURL + this.form.cardFront)
      }
      return imageSrc
    },
    isFulfilled() {
      return this.form.membershipStatus !== 'Pending'
    },
  },
  created() {
    console.log("参数", );
    const params = this.$route.params
    if (params.user) {
      this.isView = true;
      this.form.membershipId = params.user;
    } else if (params.id) {
      this.isEdit = true;
      this.form.membershipId = params.id;
    }
    this.getCountryOptions()
    this.getGroupOptions()
    getCountryList(list => {
      this.options.callingCode = list
    })
  },
  methods: {
    onBack() {
      this.$nextTick(() => {
        this.$router.replace({
          path: "/user-management/group"
        })
      })
    },
    getImageSrc(path) {
      return baseURL + path
    },
    getCountryOptions() {
      site.getCountryList().then(res => {
        if (res.data) {
          this.options.countryList = res.data
        }
      }).catch(err => {
        this.loading.page = false;
        this.$message({
          message: err,
          type: 'error'
        })
      })
    },
    getGroupOptions() {
      api.getAllUserGroups().then(res => {
        if (res.data) {
          this.options.groups = res.data
        }
        if (this.isEdit || this.isView) {
          this.getGroupUserInfo();
        } else {
          setTimeout(() => {
            this.loading.page = false;
          }, 500)
        }
      }).catch(err => {
        this.loading.page = false;
        this.$message({
          message: err,
          type: 'error'
        })
      })
    },
    getGroupUserInfo() {
      api.getGroupUserInfo({
        membershipId: this.form.membershipId
      }).then(res => {
        this.loading.page = false;
        if (res.data) {
          this.form = res.data
        }
      }).catch(err => {
        this.loading.page = false;
        this.$message({
          message: err,
          type: 'error'
        })
      })
    },
    beforeUpload(file) {
      const IMAGE_TYPE_ARRAY = ['jpg', 'png', 'jpeg', 'gif']
      const fileExt = file.name.replace(/.+\./, '').toLowerCase()
      if (IMAGE_TYPE_ARRAY.indexOf(fileExt) === -1) {
        const msg = `Please select a file with ${IMAGE_TYPE_ARRAY.join(', ')}`
        this.$message.warning(msg)
        return false
      }
      if (file.size > 2097152) {
        this.$message.warning('The file cannot exceed 2MiB')
        return false
      }
      this.loading.upload = true;
    },
    onUploadSuccess(response) {
      this.form.cardFront = response.data.picturePath;
      this.loading.upload = false;
    },
    onUploadError(err) {
      this.$message({
        type: 'error',
        message: "" + err
      });
      this.loading.upload = false;
    },
    onClickReject() {
      this.loading.reject = true;
      api.rejectGroupUser({
        membershipId: this.form.membershipId
      }).then(res => {
        this.$message({
          type: 'success',
          message: "Success"
        });
        this.onBack();
      }).catch(err => {
        this.$message({
          type: 'error',
          message: err
        });
      }).finally(() => {
        this.loading.reject = false;
      });
    },
    onClickApprove() {
      this.loading.approve = true;
      api.approveGroupUser({
        membershipId: this.form.membershipId
      }).then(res => {
        this.$message({
          type: 'success',
          message: "Success"
        });
        this.onBack();
      }).catch(err => {
        this.$message({
          type: 'error',
          message: err
        });
      }).finally(() => {
        this.loading.approve = false;
      });
    },
    onClickSave() {
      this.$refs.form.validate(result => {
        if (result) {
          this.loading.save = true;
          this.isEdit ? this.updateGroupuser() : this.addGroupUser();
        }
      });
    },
    addGroupUser() {
      api.addGroupUser(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;
      });
    },
    updateGroupuser() {
      api.updateGroupUser(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: 100px;
    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>