<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="8" />
        <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="items"
            :loading="is_loading"
            :items-per-page="-1"
            item-key="id"
            class="elevation-1"
            hide-default-footer
          >
            <template v-slot:item.id="{ item }">
              {{ item.id }}
            </template>

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

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

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

            <template v-slot:item.type="{ item }">
              <span v-if="item.type === 'SERIES'">시리즈(오리지널 콘텐츠)</span>
              <span v-else-if="item.type === 'CONTENT'">개별 콘텐츠</span>
              <span v-else-if="item.type === 'LIVE'">라이브</span>
              <span v-else-if="item.type === 'CHANNEL'">채널</span>
              <span v-else>메인</span>
            </template>

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

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

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

            <template v-slot:item.link="{ item }">
              <v-btn @click="copyLink(item.link)">
                링크복사
              </v-btn>
            </template>

            <template v-slot:item.isActive="{ item }">
              <div v-if="item.isActive">
                사용
              </div>
              <div v-else>
                미사용
              </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-row>
        <v-dialog
          v-model="show_write_dialog"
          max-width="1000px"
          persistent
        >
          <v-card>
            <v-card-title>매체 파트너 코드 등록</v-card-title>

            <v-card-text>
              <v-row align="center">
                <v-col cols="4">
                  매체 그룹
                </v-col>
                <v-col cols="8">
                  <v-text-field
                    v-model="media_group"
                    label="매체 그룹"
                    required
                  />
                </v-col>
              </v-row>
            </v-card-text>

            <v-card-text>
              <v-row align="center">
                <v-col cols="4">
                  PID
                </v-col>
                <v-col cols="8">
                  <v-text-field
                    v-model="pid"
                    label="PID"
                    required
                  />
                </v-col>
              </v-row>
            </v-card-text>

            <v-card-text>
              <v-row align="center">
                <v-col cols="4">
                  PID 명
                </v-col>
                <v-col cols="8">
                  <v-text-field
                    v-model="pid_name"
                    label="PID 명"
                    required
                  />
                </v-col>
              </v-row>
            </v-card-text>

            <v-card-text>
              <v-row align="center">
                <v-col cols="4">
                  구분
                </v-col>
                <v-col cols="8">
                  <v-radio-group
                    v-model="type"
                    row
                  >
                    <v-radio
                      v-for="item in type_list"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </v-radio-group>
                </v-col>
              </v-row>
            </v-card-text>

            <v-card-text>
              <v-row align="center">
                <v-col cols="4">
                  utm_source
                </v-col>
                <v-col cols="8">
                  <v-text-field
                    v-model="utm_source"
                    label="UTM_SOURCE"
                    required
                  />
                </v-col>
              </v-row>
            </v-card-text>

            <v-card-text>
              <v-row align="center">
                <v-col cols="4">
                  utm_medium
                </v-col>
                <v-col cols="8">
                  <v-text-field
                    v-model="utm_medium"
                    label="UTM_MEDIUM"
                    required
                  />
                </v-col>
              </v-row>
            </v-card-text>

            <v-card-text v-show="selected_media_partner_code !== null">
              <v-row align="center">
                <v-col cols="4">
                  사용여부
                </v-col>
                <v-col cols="8">
                  <v-radio-group
                    v-model="is_active"
                    row
                  >
                    <v-radio
                      key="1"
                      label="사용"
                      :value="true"
                    />

                    <v-radio
                      key="2"
                      label="미사용"
                      :value="false"
                    />
                  </v-radio-group>
                </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_media_partner_code !== 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>
    </v-container>
  </div>
</template>

<script>
import * as api from "@/api/marketing";

export default {
  name: "MarketingMediaPartnerCodeView",

  data() {
    return {
      is_loading: false,
      page: 1,
      total_page: 0,
      show_write_dialog: false,

      selected_media_partner_code: null,
      media_group: null,
      pid: null,
      pid_name: null,
      type: 'MAIN',
      is_active: true,
      utm_source: null,
      utm_medium: null,

      type_list: [
        {
          label: '메인',
          value: 'MAIN'
        },
        {
          label: '시리즈(오리지널 콘텐츠 포함)',
          value: 'SERIES'
        },
        {
          label: '개별 콘텐츠',
          value: 'CONTENT'
        },
        {
          label: '라이브',
          value: 'LIVE'
        },
        {
          label: '채널',
          value: 'CHANNEL'
        },
      ],

      items: [],
      headers: [
        {
          text: '번호',
          align: 'center',
          sortable: false,
          value: 'id',
        },
        {
          text: '매체그룹',
          align: 'center',
          sortable: false,
          value: 'mediaGroup',
        },
        {
          text: 'Pid',
          align: 'center',
          sortable: false,
          value: 'pid',
        },
        {
          text: 'Pid명',
          align: 'center',
          sortable: false,
          value: 'pidName',
        },
        {
          text: '구분',
          align: 'center',
          sortable: false,
          value: 'type',
        },
        {
          text: '링크',
          align: 'center',
          sortable: false,
          value: 'link',
        },
        {
          text: '등록시간',
          align: 'center',
          sortable: false,
          value: 'createdAt',
        },
        {
          text: '기록추적(사용여부)',
          align: 'center',
          sortable: false,
          value: 'isActive',
        },
        {
          text: '관리',
          align: 'center',
          sortable: false,
          value: 'management',
        }
      ],
    }
  },

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

  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_media_partner_code = item;
      this.media_group = item.mediaGroup;
      this.pid = item.pid
      this.pid_name = item.pidName
      this.type = item.type
      this.utm_source = item.utmSource
      this.utm_medium = item.utmMedium
      this.is_active = item.isActive;
      this.show_write_dialog = true
    },

    cancel() {
      this.selected_media_partner_code = null
      this.media_group = null
      this.pid = null
      this.pid_name = null
      this.type = 'MAIN'
      this.is_active = true
      this.utm_source = null
      this.utm_medium = null
      this.show_write_dialog = false
    },

    async copyLink(link) {
      this.is_loading = true
      try {
          await navigator.clipboard.writeText(link)
          this.notifySuccess("링크가 복사되었습니다.")
      } catch (e) {
        this.notifyError("링크를 복사하지 못했습니다.")
      } finally {
        this.is_loading = false
      }
    },

    validate() {
      if (this.media_group === null) {
        this.notifyError('매체 그룹을 입력하세요')
        return
      }

      if (this.pid === null) {
        this.notifyError('PID를 입력하세요')
        return
      }

      if (this.pid_name === null) {
        this.notifyError('PID명을 입력하세요')
        return
      }

      if (
        this.type !== 'MAIN' &&
        this.type !== 'SERIES' &&
        this.type !== 'CONTENT' &&
        this.type !== 'LIVE' &&
        this.type !== 'CHANNEL'
      ) {
        this.notifyError('잘못된 광고타입입니다.')
        return
      }

      if (this.utm_source === null) {
        this.notifyError('utm_source를 입력하세요')
        return
      }

      if (this.utm_medium === null) {
        this.notifyError('utm_medium을 입력하세요')
        return
      }

      this.submit()
    },

    async getMediaPartnerCodeList() {
      this.is_loading = true

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

        if (res.status === 200 && res.data.success === true) {
          let data = res.data.data
          this.items = data.items

          const totalPage = Math.ceil(data.totalCount / 20)
          if (totalPage <= 0)
            this.total_page = 1
          else
            this.total_page = totalPage
        } else {
          this.notifyError('알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
        }

        this.is_loading = false
      } catch (e) {
        this.notifyError('알 수 없는 오류가 발생했습니다. 다시 시도해 주세요.')
        this.is_loading = false
      }
    },

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

      try {
        const request = {
          mediaGroup: this.media_group,
          pid: this.pid,
          pidName: this.pid_name,
          type: this.type,
          utmSource: this.utm_source,
          utmMedium: this.utm_medium
        };
        const res = await api.createMediaPartner(request)

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

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

      this.is_loading = false
    },

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

      try {
        const request = {
          id: this.selected_media_partner_code.id
        };

        if (this.media_group !== this.selected_media_partner_code.mediaGroup) {
          request.mediaGroup = this.media_group
        }

        if (this.pid !== this.selected_media_partner_code.pid) {
          request.pid = this.pid;
        }

        if (this.pid_name !== this.selected_media_partner_code.pidName) {
          request.pidName = this.pid_name;
        }

        if (this.type !== this.selected_media_partner_code.type) {
          request.type = this.type;
        }

        if (this.utm_source !== this.selected_media_partner_code.utmSource) {
          request.utmSource = this.utm_source;
        }

        if (this.utm_medium !== this.selected_media_partner_code.utmMedium) {
          request.utmMedium = this.utm_medium;
        }

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

        const res = await api.updateMediaPartner(request)

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

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

      this.is_loading = false
    },

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

<style scoped>

</style>
