<template>
  <div>
    <b-row class="prize-list-wrapper">
      <b-col md="6">
        <b-card title="獎項列表" style="height:70vh;">
          <b-table responsive hover sticky-header=true :items="prizeList" bordered :fields="prizeTableFields"
            style="max-height: 52vh; overflow: auto;" @row-clicked="click">
            <template #cell(ICON)="data">
              <div class="text-center">
                <feather-icon :icon="data.value" />
              </div>
            </template>
          </b-table>
          <b-button v-ripple.400="'rgba(255, 255, 255, 0.15)'" class="mt-3" variant="outline-primary" block
            @click="showAddPrize">
            加碼
          </b-button>
        </b-card>
      </b-col>

      <b-col md="6">
        <b-card title="抽獎紀錄" style="height:70vh;">
          <b-table responsive sticky-header=true :items="recipientsList" bordered :fields="recipientsTableFields"
            style="max-height: 60vh; overflow: auto;">
            <template #cell(ICON)="data">
              <div class="text-center">
                <feather-icon :icon="data.value" />
              </div>
            </template>
          </b-table>
        </b-card>
      </b-col>

      <!--Model Start-->
      <b-modal ref="draw-modal" id="draw-modal" centered title="抽獎" no-stacking hide-footer>
        <label>獎品:</label>
        <b-form-input v-model="drawOption.prize_name" :disabled=true />
        <br>
        <label>地區: </label>
        <v-select multiple v-model="drawOption.region" :options="regionOption" />
        <br>
        <label>數量: </label>
        <div class="demo-inline-spacing">
          <b-form-radio v-model="drawOption.draw_one" name="some-radios" :value=true>
            單抽
          </b-form-radio>
          <b-form-radio v-model="drawOption.draw_one" name="some-radios" :value=false>
            全抽
          </b-form-radio>
        </div>

        <b-button v-ripple.400="'rgba(255, 255, 255, 0.15)'" class="mt-3" variant="outline-secondary" block
          @click="hideModal">
          Close
        </b-button>
        <b-button v-ripple.400="'rgba(255, 255, 255, 0.15)'" class="mt-2" variant="primary" block @click="draw">
          Accept
        </b-button>
      </b-modal>

      <b-modal ref="draw-error" centered title="抽獎錯誤" no-stacking hide-footer>
        <b-card-text class="my-1 text-center">
          抽獎錯誤
        </b-card-text>
        <b-button v-ripple.400="'rgba(255, 255, 255, 0.15)'" class="mt-3" variant="outline-secondary" block
          @click="hideModal">
          Close
        </b-button>
      </b-modal>

      <b-modal ref="draw-output" title="得獎者是......" centered no-stacking hide-footer>
        <br>
        <div :key="index" v-for="(item, index) in drawList" :class=counterId(index)>
          <i>{{ item.user_id }}</i>
          <span>{{ item.user_name }}</span>
          <span>{{ item.department_name }}</span>
        </div>

        <div v-if="drawOption.draw_one">
          <b-button v-ripple.400="'rgba(255, 255, 255, 0.15)'" class="mt-2" variant="outline-primary" block
            @click="donate">
            捐出
          </b-button>
        </div>

        <b-button v-ripple.400="'rgba(255, 255, 255, 0.15)'" class="mt-2" variant="primary" block @click="store">
          Accept
        </b-button>
      </b-modal>

      <b-modal ref="add-prize" centered title="加碼" no-stacking hide-footer>
        <label>獎品:</label>
        <b-form-input v-model="addPrizeOption.name" />
        <br>
        <label>加碼者: </label>
        <b-form-input v-model="addPrizeOption.provider" />
        <br>
        <label>數量: </label>
        <b-form-spinbutton v-model="addPrizeOption.count" min="1" />

        <b-button v-ripple.400="'rgba(255, 255, 255, 0.15)'" class="mt-3" variant="outline-secondary" block
          @click="hideModal">
          Close
        </b-button>
        <b-button v-ripple.400="'rgba(255, 255, 255, 0.15)'" class="mt-2" variant="primary" block @click="addPrize">
          Accept
        </b-button>
      </b-modal>
      <!--Model End-->
    </b-row>
  </div>
</template>

<script>
import { BRow, BCol, BCard, BCardText, BLink, BTable, BModal, BFormInput, BFormSpinbutton, BButton, BFormCheckbox, BFormRadio } from 'bootstrap-vue'
import useJwt from '@/auth/jwt/useJwt'
import { VueGoodTable } from 'vue-good-table'
import vSelect from 'vue-select'
import Ripple from 'vue-ripple-directive'
import 'vue-select/dist/vue-select.css';

export default {
  components: {
    BRow,
    BCol,
    BCard,
    BCardText,
    BLink,
    BTable,
    BModal,
    BFormInput,
    BFormSpinbutton,
    BButton,
    BFormCheckbox,
    BFormRadio,
    VueGoodTable,
    vSelect,
  },
  directives: {
    Ripple,
  },
  data() {
    return {
      prizeList: [],
      recipientsList: [],

      prizeTableFields: ['name', 'provider', 'count'],
      recipientsTableFields: ['prize_name', 'user_id', 'user_name', 'created_at'],
      regionOption: ['北區', '中區', '南區', '來賓'],

      drawOption: {
        activity_id: this.$route.params.activity_id,
        prize_id: '0',
        prize_name: '',
        region: ['北區', '中區', '南區', '來賓'],
        draw_one: true,
      },
      addPrizeOption: {
        activity_id: this.$route.params.activity_id,
        name: '',
        provider: '',
        count: 1,
      },

      drawList: [],
    }
  },
  created() {
    useJwt.postData('/api/prize/index_by_activity', { activity_id: this.$route.params.activity_id }).then(res => {
      this.prizeList = res.data;
    });

    useJwt.postData('/api/recipients/index_by_activity', { activity_id: this.$route.params.activity_id }).then(res => {
      this.recipientsList = res.data;
      this.recipientsList.forEach(element => {
        element.created_at = this.dateFormat(element.created_at);
      });
    });
  },
  methods: {
    dateFormat(date) {
      var d = new Date(date);
      return d.getFullYear()
        + '/' + (d.getMonth() + 1).toString().padStart(2, '0')
        + '/' + d.getDate().toString().padStart(2, '0')
        + '/' + d.getHours().toString().padStart(2, '0')
        + ':' + d.getMinutes().toString().padStart(2, '0')
        + ':' + d.getSeconds().toString().padStart(2, '0');
    },
    counterId(id) {
      return 'counter_' + id;
    },
    showDraw() {
      this.$refs['draw-modal'].show();
    },
    showDrawOutput() {
      this.$refs['draw-output'].show();
    },
    showAddPrize() {
      this.$refs['add-prize'].show();
    },
    showDrawError() {
      this.$refs['draw-error'].show();
    },
    hideModal() {
      this.$refs['draw-modal'].hide();
      this.$refs['draw-error'].hide();
      this.$refs['draw-output'].hide();
      this.$refs['add-prize'].hide();
      this.updateDataset();
    },
    updateDataset() {
      useJwt.postData('/api/prize/index_by_activity', { activity_id: this.$route.params.activity_id }).then(res => {
        this.prizeList = res.data;
      });
      useJwt.postData('/api/recipients/index_by_activity', { activity_id: this.$route.params.activity_id }).then(res => {
        this.recipientsList = res.data;
        this.recipientsList.forEach(element => {
          element.created_at = this.dateFormat(element.created_at);
        });
      });
    },
    click(params) {
      this.drawList = [];
      if (params.count > 0) {
        this.drawOption.prize_name = params.name;
        this.drawOption.prize_id = params.id;
        this.showDraw();
      } else {
        this.showDrawError();
      }
    },
    draw() {
      useJwt.postData('/api/draw/draw', this.drawOption).then(res => {
        if (res.data[0]["user_id"]) {
          this.drawList = res.data;
          console.log("draw success");
          this.showDrawOutput();
        } else {
          this.showDrawError();
          console.log("draw error: " + res.data);
        }
      });
    },
    store() {
      var idList = [];
      this.drawList.forEach(element => {
        idList.push(element.user_id);
      });
      useJwt.postData('/api/draw/store', {
        users: idList,
        prize_id: this.drawOption.prize_id,
      }).then(res => {
        if (res.data) {
          console.log("store success");
        } else {
          console.log("store error");
        }
        this.hideModal();
      });
    },
    donate() {
      var idList = [];
      this.drawList.forEach(element => {
        idList.push(element.user_id);
      });
      useJwt.postData('/api/draw/donate', { users: idList }).then(res => {
        if (res.data) {
          console.log("donate success");
        } else {
          console.log("donate error");
        }
        this.hideModal();
      });
    },
    addPrize() {
      useJwt.postData('/api/prize/store', this.addPrizeOption).then(res => {
        if (res.data) {
          console.log("add prize success");
        } else {
          console.log("add prize error");
        }
        this.hideModal();
      });
    },
  },
}
</script>

<style lang="scss">
@import '~@resources/scss/vue/libs/vue-select.scss';
</style>
