<template>
    <div>
        <b-table
        :items="postFileManagementList"
        :fields="fields"
        select-mode="multi"
        responsive="md"
        ref="selectableTable"
        >
        <template #cell(請勾選)="row">
          <b-form-checkbox v-model="row.item.selected" class="checkbox-custom"></b-form-checkbox>
        </template>
        <template #cell(name)="data">
            <span style="font-weight:normal;color:black;font-size:15px">{{data.item.docFile[0].name}}</span>
        </template>
        <template #cell(postDay)="data">
            <span style="font-weight:normal;color:black;font-size:15px">{{ getFormattedDate(data.value) }}</span>
        </template>
  
      </b-table>
      <b-button @click="deleteOne" variant="primary" size="sm" class="float-right">確認</b-button>
    </div>
  </template>
  
  <script>
  import { mapState, mapActions } from 'vuex'
  import moment from 'moment'
  export default {
    data () {
      return {
        fields: [
          '請勾選',
          {
            key: 'name',
            label: '檔案名稱',
            tdClass: 'align-right'
          },
          {
            key: 'postDay',
            label: '發文日期',
            tdClass: 'align-right'
          }
        ],
        fileList: []
      }
    },
    async mounted () {
      await this.$store.dispatch('tenders/getPostFileManagement', this.currentUser.defaultTender)
    },
    methods: {
      ...mapActions('tenders', ['deletePostFile', 'getPostFileManagement']),
      getFormattedDate (date) {
        let d = null
        if (date) {
          return moment(date).format('YYYY-MM-DD')
        } else {
          return d
        }
      },
      async deleteOne () {
        if (!confirm('確定要刪除選擇的發文文件?')) return
        const selectedPostFileManagement = this.postFileManagementList.filter((postFileManagement) => postFileManagement.selected)
        console.log('Selected Files:', selectedPostFileManagement)
        for (let index = 0; index < selectedPostFileManagement.length; index++) {
          const postFileManagement = selectedPostFileManagement[index]
          console.log('Deleting File:', postFileManagement._id)
          await this.$store.dispatch('tenders/deletePostFile', postFileManagement._id)
          this.$emit('closeEvent')
        }
        await this.$store.dispatch('tenders/getPostFileManagement', this.currentUser.defaultTender)
        console.log('Post File Management List:', this.postFileManagementList)
        alert('刪除成功')
      }
    },
    computed: {
      ...mapState({
        currentUser: state => state.user.current,
        postFileManagementList: state => state.tenders.postFileManagementList
      }),
      row () {
        return this.postFileList.length
      }
    }
  }
  </script>
  
  <style>
  .checkbox-custom {
    margin-left: 10px
  }
  </style>
  