<template>
  <el-table
    :data="itemList"
    class="user-sub-item-table no-border">
    <el-table-column
      label="Card No:"
      min-width="90px">
      <template slot-scope="{row}">
        <el-input
          class="item-input"
          v-model="row.membershipNo" />
      </template>
    </el-table-column>
    <el-table-column
      label="Group:"
      min-width="90">
      <template slot-scope="{row}">
        <el-select
          class="item-input"
          v-model="row.groupPk">
          <el-option
            v-for="(item,index) in groupList"
            :key="index"
            :label="item.name"
            :value="item.value"/>
        </el-select>
      </template>
    </el-table-column>
    <el-table-column
      label="Card Photo:"
      min-width="90">
      <template slot-scope="{$index,row}">
        <el-upload
          v-if="isEdit"
          class="card-uploader"
          accept=".jpg,.jpeg,.png,.gif,.JPG,.JPEG"
          :action="action"
          :headers="headers"
          :show-file-list="false"
          :on-success="e => onUploadSuccess(e, $index)"
          :on-error="onUploadError"
          :before-upload="e => beforeUpload(e, $index)">
          <div
            v-loading="loading.upload && $index == loading.index"
            class="uploader-image">
            <el-image
              class="uploader-image"
              v-if="row.cardFront"
              :src="getImageSrc(row.cardFront)"/>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </div>
        </el-upload>
        <div class="card-uploader" v-else-if="row.cardFront">
          <el-image
            class="uploader-image"
            :src="getImageSrc(row.cardFront)"
            :preview-src-list="previewSrcList(row.cardFront)"/>
        </div>
      </template>
    </el-table-column>
    <el-table-column
      label="Status:"
      min-width="80">
      <template slot-scope="{$index,row}">
        <div class="flexc" v-loading="loading.action && $index == loading.index">
          <span>{{row.membershipStatus}}</span>
          <div class="flexl" v-if="row.membershipStatus=='Pending'">
            <div
              class="action-approve"
              @click="approveItem($index)">Approve</div>
            <div
              class="action-reject"
              @click="rejectItem($index)">Reject</div>
          </div>
        </div>
      </template>
    </el-table-column>
    <el-table-column
      label="Action:"
      min-width="100px">
      <template slot-scope="{$index,row}">
        <div v-loading="loading.subt">
          <img
            class="list-item-icon"
            @click="onSubtItem($index)"
            src="../../../assets/form-list-sub.png"/>
          <img
            v-if="$index === itemList.length - 1"
            class="list-item-icon"
            @click="onAddItem"
            src="../../../assets/form-list-add.png"/>
        </div>
      </template>
    </el-table-column>
  </el-table>
</template>

<script>
import api from '@/http/api/apiUser'
import group from '@/http/api/group'
import { baseURL } from '@/http/http'
import { getToken } from '@/utils/auth'
export default {
  name: "ListMember",
  props: {
    list: {
      type: Array,
      default: () => []
    },
    isEdit: {
      type: Boolean,
      default: true
    },
    isFleet: {
      type: Boolean,
      default: false
    }
  },
  model: {
    prop: 'list',
    event: 'change'
  },
  data() {
    return {
      loading: {
        subt: false,
        upload: false,
        action: false,
        index: -1
      },
      itemList: [{
        membershipId: "",
        membershipNo: "",
        groupPk: "",
        groupName: "",
        cardFront: "",
        cardReverse: "",
        membershipStatus: ""
      }],
      groupList: []
    };
  },
  watch: {
    list: {
      deep: true,
      handler(n, o) {
        this.itemList = n || [];
        if (this.itemList.length === 0) {
          this.onAddItem();
        } else {
          this.onChange()
        }
      }
    }
  },
  computed: {
    action() {
      return baseURL + process.env.VUE_APP_API_PREFIX + '/picture/upload'
    },
    headers() {
      return {
        accessToken: getToken(),
        photoSubDir: "MEMBERSHIP",
      }
    },
    previewSrcList(path) {
      const imageSrc = []
      if (path) {
        imageSrc.push(baseURL + path)
      }
      return imageSrc
    }
  },
  mounted() {
    this.getGroupOptions();
  },
  methods: {
    onChange() {
      this.$emit('change', this.itemList);
    },
    getImageSrc(path) {
      return baseURL + path
    },
    getGroupOptions() {
      api.getGroupByType(this.isFleet ? "FLEET" : "MEMBER").then(res => {
        if (res.data) {
          this.groupList = res.data
        }
      }).catch(err => {
        this.$message({
          message: err,
          type: 'error'
        })
      })
    },
    beforeUpload(file, index) {
      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;
      this.loading.index = index;
    },
    onUploadSuccess(response, index) {
      this.itemList[index].cardFront = response.data.picturePath;
      this.loading.upload = false;
      this.onChange();
    },
    onUploadError(err) {
      this.$message({
        type: 'error',
        message: "" + err
      });
      this.loading.upload = false;
    },
    onAddItem() {
      this.itemList.push({
        membershipId: "",
        membershipNo: "",
        groupPk: "",
        groupName: "",
        cardFront: "",
        cardReverse: "",
        membershipStatus: ""
      })
      this.onChange();
    },
    onSubtItem(index) {
      let item = this.itemList[index]
      if (item.membershipId) {
        this.$confirm("Are you sure you want to delete this vehicle ?", "Delete", {
          confirmButtonText: 'OK',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(() => {
          this.loading.subt = true
          this.deleteItem(item.membershipId, index);
        })
      } else {
        this.itemList.splice(index, 1)
        if (this.itemList.length === 0) {
          this.onAddItem();
        }
      }
    },
    deleteItem(id, index) {
      api.deleteUserMembership(id).then(() => {
        this.itemList.splice(index, 1);
        if (this.itemList.length === 0) {
          this.onAddItem();
        }
      }).catch((error) => {
        this.$message({
          message: error,
          type: 'error',
        })
      }).finally(() => {
        this.loading.subt = false;
      })
    },
    approveItem(index) {
      let item = this.itemList[index]
      if (item.membershipId) {
        this.loading.index = index;
        this.loading.action = true;
        api.approveUserMembership(item.membershipId).then(res => {
          this.itemList[index].membershipStatus = "Pass";
        }).catch((error) => {
          this.$message({
            message: error,
            type: 'error',
          })
        }).finally(() => {
          this.loading.action = false;
        })
      }
    },
    rejectItem(index) {
      let item = this.itemList[index]
      if (item.membershipId) {
        this.loading.index = index;
        this.loading.action = true;
        api.rejectUserMembership(item.membershipId).then(res => {
          this.itemList[index].membershipStatus = "Reject";
        }).catch((error) => {
          this.$message({
            message: error,
            type: 'error',
          })
        }).finally(() => {
          this.loading.action = false;
        })
      }
    }
  }
}
</script>

<style scoped>
  .user-sub-item-table >>> .el-table__header th {
    background: transparent;
    border: none;
    padding: 10px 0;
  }
  .user-sub-item-table >>> td {
    border: none;
    padding: 1px 0;
    background: #fff !important;
  }
  .user-sub-item-table >>> .cell {
    padding: 0 8px;
  }
  .user-sub-item-list {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
  }
  .item-input {
    min-width: 80px;
  }
  .list-item-icon {
    width: 30px;
    height: 30px;
    cursor: pointer;
    margin: 5px 0px;
  }
  .list-item-icon + .list-item-icon {
    margin-left: 15px;
  }
  .card-uploader {
    padding: 5px 0;
  }
  .uploader-image {
    width: 120px;
    height: 80px;
    text-align: left;
  }
  .uploader-image >>> img {
    object-fit: cover;
  }
  .avatar-uploader-icon {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    font-size: 28px;
    color: #8c939d;
    width: 80px;
    height: 80px;
    line-height: 80px;
    text-align: center;
  }
  .action-approve {
    color: #82CF08;
    cursor: pointer;
    font-size: 12px;
    padding: 2px 10px;
    line-height: 15px;
  }
  .action-reject {
    color: #ED3F3F;
    cursor: pointer;
    font-size: 12px;
    padding: 2px 10px;
    line-height: 15px;
  }
  .action-approve:hover,
  .action-reject:hover {
    text-decoration: underline;
  }
</style>