<template>
  <div>
    <v-toolbar dark>
      <v-spacer />
      <v-toolbar-title>포인트 정책</v-toolbar-title>
      <v-spacer />
    </v-toolbar>

    <br>

    <v-container>
      <v-row>
        <v-col cols="10" />
        <v-col>
          <v-btn
            block
            color="#3bb9f1"
            dark
            depressed
            @click="showWriteDialog"
          >
            포인트 정책 등록
          </v-btn>
        </v-col>
      </v-row>

      <v-row>
        <v-col>
          <v-data-table
            :headers="headers"
            :items="point_policy_list"
            :loading="is_loading"
            :items-per-page="-1"
            item-key="id"
            class="elevation-1"
            hide-default-footer
          >
            <template v-slot:item.title="{ item }">
              {{ item.title }}
            </template>

            <template v-slot:item.policyType="{ item }">
              {{ policy_type_map[item.policyType] }}
            </template>

            <template v-slot:item.actionType="{ item }">
              {{ action_type_map[item.actionType] }}
            </template>

            <template v-slot:item.threshold="{ item }">
              {{ item.threshold }} 번
            </template>

            <template v-slot:item.availableCount="{ item }">
              {{ item.availableCount }} 번
            </template>

            <template v-slot:item.period="{ item }">
              {{ item.startDate }} ~ {{ item.endDate }}
            </template>

            <template v-slot:item.point="{ item }">
              {{ item.pointAmount }}
            </template>

            <template v-slot:item.isActive="{ item }">
              <div v-if="item.isActive">
                O
              </div>
              <div v-else>
                X
              </div>
            </template>

            <template v-slot:item.management="{ item }">
              <v-btn
                :disabled="is_loading"
                @click="showModifyDialog(item)"
              >
                수정
              </v-btn>
            </template>
          </v-data-table>
        </v-col>
      </v-row>
      <v-row class="text-center">
        <v-col>
          <v-pagination
            v-model="page"
            :length="total_page"
            circle
            @input="next"
          />
        </v-col>
      </v-row>
    </v-container>
    <v-row>
      <v-dialog
        v-model="show_write_dialog"
        max-width="1000px"
        persistent
      >
        <v-card>
          <v-card-title>포인트 정책 등록</v-card-title>
          <v-card-text>
            <v-text-field
              v-model="point_policy.title"
              label="제목"
              required
            />
          </v-card-text>
          <v-card-text v-if="selected_point_policy === null">
            <v-radio-group
              v-model="point_policy.policy_type"
              label="지급 유형 선택"
            >
              <v-radio
                v-for="item in policy_type_list"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              />
            </v-radio-group>
          </v-card-text>
          <v-card-text v-if="selected_point_policy === null">
            <v-radio-group
              v-model="point_policy.action_type"
              label="액션 선택"
            >
              <v-radio
                v-for="item in action_type_list"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              />
            </v-radio-group>
          </v-card-text>
          <v-card-text v-if="selected_point_policy === null">
            <v-text-field
              v-model="point_policy.threshold"
              label="참여해야 하는 횟수"
              required
            />
          </v-card-text>
          <v-card-text v-if="selected_point_policy === null">
            <v-text-field
              v-model="point_policy.point"
              label="포인트"
              required
            />
          </v-card-text>
          <v-card-text v-if="selected_point_policy === null">
            <v-text-field
              v-model="point_policy.available_count"
              label="참여 가능 횟수"
              required
            />
          </v-card-text>
          <v-card-text>
            <v-row align="center">
              <v-col cols="4">
                기간
              </v-col>
              <v-col
                cols="8"
                class="datepicker-wrapper"
              >
                <datetime
                  v-model="point_policy.start_date"
                  class="datepicker"
                  format="YYYY-MM-DD H:i"
                />
                <div> ~</div>
                <datetime
                  v-model="point_policy.end_date"
                  class="datepicker"
                  format="YYYY-MM-DD H:i"
                />
              </v-col>
            </v-row>
          </v-card-text>
          <v-card-text v-show="selected_point_policy !== null">
            <v-row align="center">
              <v-col cols="4">
                활성화
              </v-col>
              <v-col cols="8">
                <input
                  v-model="point_policy.is_active"
                  type="checkbox"
                >
              </v-col>
            </v-row>
          </v-card-text>
          <v-card-actions v-show="!is_loading">
            <v-spacer />
            <v-btn
              color="blue darken-1"
              text
              @click="cancel"
            >
              취소
            </v-btn>
            <v-btn
              v-if="selected_point_policy !== null"
              color="blue darken-1"
              text
              @click="modify"
            >
              수정
            </v-btn>
            <v-btn
              v-else
              color="blue darken-1"
              text
              @click="validate"
            >
              등록
            </v-btn>
          </v-card-actions>
        </v-card>
      </v-dialog>
    </v-row>
  </div>
</template>

<script>
import * as api from '@/api/point_policy'
import datetime from "vuejs-datetimepicker";

export default {
  name: "PointPolicyView",
  components: {datetime},

  data() {
    return {
      is_loading: false,
      show_write_dialog: false,

      action_type_list: [
        {
          name: '본인인증',
          value: 'USER_AUTHENTICATION'
        },
        {
          name: '콘텐츠 댓글',
          value: 'CONTENT_COMMENT'
        },
        {
          name: '구매한 콘텐츠 댓글',
          value: 'ORDER_CONTENT_COMMENT'
        },
        {
          name: '라이브 연속 청취 30분',
          value: 'LIVE_CONTINUOUS_LISTEN_30'
        },
      ],
      action_type_map: {
        'USER_AUTHENTICATION': '본인인증',
        'CONTENT_COMMENT': '콘텐츠 댓글',
        'ORDER_CONTENT_COMMENT': '구매한 콘텐츠 댓글',
        'LIVE_CONTINUOUS_LISTEN_30': '라이브 연속 청취 30분',
      },

      policy_type_list: [
        {
          name: '매일',
          value: 'DAILY'
        },
        {
          name: '전체',
          value: 'TOTAL'
        },
      ],
      policy_type_map: {
        'DAILY': '매일',
        'TOTAL': '전체',
      },

      point_policy: {
        title: '',
        policy_type: '',
        action_type: '',
        threshold: 0,
        available_count: 0,
        point: 0,
        start_date: '',
        end_date: ''
      },
      selected_point_policy: null,
      point_policy_list: [],

      page: 1,
      total_page: 0,

      headers: [
        {
          text: '제목',
          align: 'center',
          sortable: false,
          value: 'title',
        },
        {
          text: '지급유형',
          align: 'center',
          sortable: false,
          value: 'policyType',
        },
        {
          text: '액션',
          align: 'center',
          sortable: false,
          value: 'actionType',
        },
        {
          text: '참여해야 하는 횟수',
          align: 'center',
          sortable: false,
          value: 'threshold',
        },
        {
          text: '참여 가능 횟수',
          align: 'center',
          sortable: false,
          value: 'availableCount',
        },
        {
          text: '기간',
          align: 'center',
          sortable: false,
          value: 'period',
        },
        {
          text: '포인트',
          align: 'center',
          sortable: false,
          value: 'pointAmount',
        },
        {
          text: '활성화',
          align: 'center',
          sortable: false,
          value: 'isActive',
        },
        {
          text: '관리',
          align: 'center',
          sortable: false,
          value: 'management'
        }
      ],
    }
  },

  async created() {
    await this.getPointPolicyList()
  },

  methods: {
    notifyError(message) {
      this.$dialog.notify.error(message)
    },

    notifySuccess(message) {
      this.$dialog.notify.success(message)
    },

    showWriteDialog() {
      this.show_write_dialog = true
    },

    showModifyDialog(item) {
      this.selected_point_policy = item;
      this.point_policy = {
        title: item.title,
        policy_type: item.policyType,
        action_type: item.actionType,
        threshold: item.threshold,
        available_count: item.availableCount,
        point: item.pointAmount,
        start_date: item.startDate,
        end_date: item.endDate,
        is_active: item.isActive
      };
      this.show_write_dialog = true
    },

    validate() {
      if (this.point_policy.title.trim() === '') {
        this.notifyError('제목을 입력하세요.')
        return
      }

      if (this.point_policy.policy_type.trim() === '') {
        this.notifyError('지급유형을 선택하세요')
        return
      }

      if (this.point_policy.action_type.trim() === '') {
        this.notifyError('액션을 선택하세요')
        return
      }

      if (isNaN(this.point_policy.threshold)) {
        this.notifyError('참여 해야하는 횟수는 숫자만 입력 가능합니다.')
        return
      }

      if (this.point_policy.threshold <= 0) {
        this.notifyError('참여 해야하는 횟수는 1이상 입력 가능합니다.')
        return
      }

      if (isNaN(this.point_policy.point)) {
        this.notifyError('지급 포인트는 숫자만 입력 가능합니다.')
        return
      }

      if (isNaN(this.point_policy.available_count)) {
        this.notifyError('참여 가능 횟수는 숫자만 입력 가능합니다.')
        return
      }

      if (this.point_policy.available_count <= 0) {
        this.notifyError('참여 가능 횟수는 1이상 입력 가능합니다.')
        return
      }

      if (this.point_policy.start_date.trim() === '') {
        this.notifyError('정책 시작 날짜를 입력하세요')
        return
      }

      this.submit()
    },

    cancel() {
      this.point_policy = {
        title: '',
        policy_type: '',
        action_type: '',
        threshold: 0,
        available_count: 0,
        point: 0,
        start_date: '',
        end_date: ''
      }
      this.show_write_dialog = false
      this.selected_point_policy = null;
    },

    async submit() {
      if (this.is_loading) return;

      this.is_loading = true

      try {
        const request = {
          'title': this.point_policy.title,
          'policyType': this.point_policy.policy_type,
          'actionType': this.point_policy.action_type,
          'threshold': this.point_policy.threshold,
          'availableCount': this.point_policy.available_count,
          'pointAmount': this.point_policy.point,
          'startDate': this.point_policy.start_date,
          'endDate': this.point_policy.end_date
        }
        const res = await api.createPointPolicyList(request)

        if (res.status === 200 && res.data.success === true) {
          this.cancel()
          this.notifySuccess(res.data.message || '등록되었습니다.')

          this.page = 1
          this.point_policy_list = []
          await this.getPointPolicyList()
        } else {
          this.notifyError(res.data.message || '알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
        }
      } catch (e) {
        this.notifyError("알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.")
      }

      this.is_loading = false
    },

    async modify() {
      if (this.is_loading) return;

      try {
        const request = {}

        if (this.point_policy.title !== this.selected_point_policy.title) {
          request.title = this.point_policy.title
        }

        if (this.point_policy.start_date !== this.selected_point_policy.startDate) {
          request.startDate = this.point_policy.start_date
        }

        if (this.point_policy.end_date !== this.selected_point_policy.endDate) {
          request.endDate = this.point_policy.end_date
        }

        if (this.point_policy.is_active !== this.selected_point_policy.isActive) {
          request.isActive = this.point_policy.is_active
        }

        const res = await api.updatePointPolicyList(this.selected_point_policy.id, request)

        if (res.status === 200 && res.data.success === true) {
          this.cancel()
          this.notifySuccess(res.data.message || '수정되었습니다.')

          this.page = 1
          this.point_policy_list = []
          await this.getPointPolicyList()
        } else {
          this.notifyError(res.data.message || '알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
        }
      } catch (e) {
        this.notifyError("알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.")
      }

      this.is_loading = false
    },

    async getPointPolicyList() {
      if (this.is_loading) return;
      this.is_loading = true

      try {
        const res = await api.getPointPolicyList(this.page);

        if (res.status === 200 && res.data.success === true) {
          const data = res.data.data

          const total_page = Math.ceil(data.totalCount / 20)
          this.point_policy_list = data.items

          if (total_page <= 0)
            this.total_page = 1
          else
            this.total_page = total_page
        } else {
          this.notifyError(res.data.message || '알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
        }
      } catch (e) {
        this.notifyError('알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
      }

      this.is_loading = false
    },

    async next() {
      await this.getPointPolicyList()
    },
  }
}
</script>

<style scoped>
.datepicker {
  text-align: center;
}

.datepicker-wrapper {
  display: flex;
  flex-direction: row;
}

.datepicker-wrapper > div {
  margin: 20px;
}

.v-card__text {
  margin-top: 20px;
}

.v-card__actions {
  margin-top: 100px;
}

.v-card__actions > .v-btn {
  font-size: 20px;

}
</style>
