<template>
  <div class="content-zone">
    <div class="content">
      <div class="scroll">
        <div class="form-box">
          <div class="form-box-title">
            <p>기본정보</p>
          </div>
          <div class="form-content">
            <div>
              <label class="form-title">제목</label>
              <input
                type="text"
                class="form-control sm"
                v-model="popup['popupTtl']"
                ref="popupTtl"
                placeholder="제목을 입력하세요."
              />
            </div>
            <div>
              <label class="form-title">게시일</label>
              <div class="input-group">
                  <VueDatePicker
                    v-model="popup['bgngDt']"
                    ref="bgngDt"
                    time-picker-inline
                    placeholder="시작일"
                    locale="ko"
                    inputFormat="yyyy-mm-dd"
                  />
                <div class="pd10">-</div>
                  <VueDatePicker
                    v-model="popup['endDt']"
                    ref="endDt"
                    time-picker-inline
                    placeholder="종료일"
                    locale="ko"
                    inputFormat="yyyy-mm-dd"
                  />
              </div>
            </div>
            <div>
              <label class="form-title">팝업크기</label>
              <div class="input-group">
                <select class="form-select sm fixed" v-model="popup['popupSizeType']">
                  <option value="fixed">고정값</option>
                  <option value="custom">사용자지정</option>
                </select>
              
                  <!-- 고정값 -->
                  <template v-if="popup['popupSizeType'] == 'fixed'">
                    <div
                      v-for="(popupSize, index) of popupSizes"
                      :key="index"
                      class="form-check"
                    >
                      <input
                        type="radio"
                        :id="popupSize['id']"
                        class="mr5"
                        v-model="popup['popupSize']"
                        :value="popupSize['id']"
                        ref="popupSize"
                      />
                      <label :for="popupSize['id']">
                        {{ popupSize["wdthLen"] }}X{{ popupSize["vrtcLen"] }}
                      </label>
                    </div>
                  </template>
                  <!-- 사용자 지정 -->
                  <template v-if="popup['popupSizeType'] == 'custom'">
                      <input
                        type="text"
                        class="form-control sm"
                        v-model="popup['wdthLen']"
                        placeholder="가로 길이를 입력하세요."
                      />
                    <div class="pd10">x</div>
                      <input
                        type="text"
                        class="form-control sm"
                        v-model="popup['vrtcLen']"
                        placeholder="세로 길이를 입력하세요."
                      />
                  </template>
              </div>
            </div>
            <div >
              <label class="form-title">업로드 형식</label>
              <div class="check-area">
                <div class="form-check">
                  <input
                    type="radio"
                    id="image"
                    class="mr5"
                    v-model="popup['popupType']"
                    value="image"
                  />
                  <label for="image">이미지</label>
                </div>
                <div class="form-check">
                  <input
                    type="radio"
                    id="video"
                    class="mr5"
                    v-model="popup['popupType']"
                    value="video"
                  />
                  <label for="video">영상</label>
                </div>
              </div>
            </div>
            <template v-if="popup['popupType'] == 'image'">
              <div>
                <label class="form-title">이미지 첨부파일</label>
    
                  <div
                    v-for="(file, index) of this.fileList"
                    :key="index"
                    class="input-group"
                    style="height: 100%"
                  >
                    <p v-if="file['fileId'] != null">
                      {{ file["fileNm"] }}.{{ file["extnNm"] }}
                    </p>
                    <p v-else>{{ file.name }}</p>
                    <button
                      class="icon-btn pd0"
                      @click="fnFileDelete(file, index)"
                    >
                      <svg-icon
                        type="mdi"
                        :width="15"
                        :height="15"
                        :path="path"
                      ></svg-icon>
                    </button>
                  </div>
                  <div v-if="fileList.length < 1">
                    <label
                      for="file"
                      class="large-btn blue-border-btn text-ct"
                    >
                      파일찾기
                    </label>
                    <input
                      type="file"
                      id="file"
                      ref="file"
                      @change="fnFileInsert"
                    />
                  </div>
              </div>
          
              <div>
                <label class="form-title">링크 URL</label>
                <input
                  type="text"
                  class="form-control sm"
                  placeholder="이미지 주소를 입력하세요."
                  v-model="popup['linkUrl']"
                  :disabled="popup['popupType'] != 'image'"
                  ref="linkUrl"
                />
              </div>
            </template>
            <template v-if="popup['popupType'] == 'video'">
                <div>
                  <label class="form-title">동영상 URL</label>
                  <input
                    type="text"
                    class="form-control"
                    placeholder="동영상 주소를 입력하세요."
                    v-model="popup['vdoUrl']"
                    :disabled="popup['popupType'] != 'video'"
                    ref="vdoUrl"
                  />
                </div>
            </template>
            <div>
              <label class="form-title">팝업 노출 페이지</label>
              <select
                class="form-select sm "
                v-model="popup['pageType']"
                ref="pageType"
              >
                <option value="">팝업을 노출할 페이지를 선택하세요.</option>
                <option
                  v-for="(item, index) of codeList"
                  :key="index"
                  :value="item.cd"
                >
                  {{ item.cdNm }}
                </option>
              </select>
            </div>
            <div>
              <label class="form-title">순서</label>
              <select class="form-select sm " v-model="popup['sn']" ref="sn">
                <option value="0">순서를 선택하세요.</option>
                <option value="1">1</option>
                <option value="2">2</option>
                <option value="3">3</option>
                <option value="4">4</option>
                <option value="5">5</option>
              </select>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="btn-wrap">
      <button class="btn sm primary" @click="fnUpsert">
        <span v-if="this.$route.query.pageId == null">저장</span>
        <span v-else>수정</span>
      </button>
      <button class="btn sm tertiary" @click="fnCancel">취소</button>
  </div>
</template>

<script>
import defaultAxios from "../../../../resources/js/defaultAxios";
import { mdiClose } from "@mdi/js";

// API
import { detailProc } from "../../../../resources/api/popup";

export default {
  data() {
    return {
      path: mdiClose,

      file: null,

      // 팝업 객체
      popup: {},
      popupSizes: [
        { id: "PS1", wdthLen: 300, vrtcLen: 300 },
        { id: "PS2", wdthLen: 500, vrtcLen: 700 },
        { id: "PS3", wdthLen: 700, vrtcLen: 1000 },
        { id: "PS4", wdthLen: 1200, vrtcLen: 850 },
      ],

      // 파일 업로드
      files: null,
      fileList: [],
      deleteFileList: [],

      codeList: [], // 팝업 노출 페이지
    };
  },
  created() {
    this.fnViewDetail();
  },
  methods: {
    // 조회(상세)
    fnViewDetail() {
      let data = {
        popupId: this.$route.query.pageId,
      };
      this.axiosViewDetail(data);
    },
    // 등록 및 수정
    fnUpsert() {
      // 유효성 검사
      if (this.valiadtion() == false) {
        return;
      }

      // 팝업 크기 삽입
      if (this.popup.popupSizeType == "fixed") {
        for (let popupSize of this.popupSizes) {
          if (popupSize["id"] == this.popup["popupSize"]) {
            this.popup["wdthLen"] = popupSize["wdthLen"];
            this.popup["vrtcLen"] = popupSize["vrtcLen"];
          }
        }
      }

      this.popup["bgngDt"] = this.dateFormat(new Date(this.popup["bgngDt"]));
      this.popup["endDt"] = this.dateFormat(new Date(this.popup["endDt"]));

      var formData = new FormData();
      if (this.popup["popupId"] != null) {
        this.popup["deleteFileList"] = this.deleteFileList;
      }
      const paramsToBlob = new Blob([JSON.stringify(this.popup)], {
        type: "application/json; charset=UTF-8",
      });
      formData.append("popupVO", paramsToBlob);
      if (this.fileList != null && this.fileList.length > 0) {
        for (const file of this.fileList) {
          if (file["fileId"] == null) {
            formData.append("multipartFileList", file);
          }
        }
      }

      // URL 삽입
      let url = null;
      if (this.popup["popupId"] != null) {
        url = "/admin/popup/updateProc.file";
      } else {
        url = "/admin/popup/insertProc.file";
      }

      this.axiosUpsert(url, formData);
    },
    // 취소
    fnCancel() {
      if (!confirm("작성을 취소하시겠습니까?")) return;
      this.$router.push({
        name: "admPopupManagementSelectList",
      });
    },
    // 첨부파일 등록
    fnFileInsert() {
      this.files = null;
      this.fileList = [];
      this.files = this.$refs.file.files;
      this.fileList = Array.from(this.files);
    },
    // 첨부파일 삭제
    fnFileDelete(file, index) {
      if (file["fileId"] != null) {
        this.deleteFileList.push(file);
      }
      this.files = null;
      this.fileList = [];
      this.$refs.file.value = "";
    },

    // 날짜 형식 변경
    dateFormat(date) {
      return (
        date.getFullYear() +
        "-" +
        (date.getMonth() + 1 < 9
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) +
        "-" +
        (date.getDate() < 9 ? "0" + date.getDate() : date.getDate())
      );
    },

    // 유효성 검사
    valiadtion() {
      if (this.popup["popupTtl"] == null || this.popup["popupTtl"] == "") {
        alert("제목을 입력해주세요.");
        this.$refs.popupTtl.focus();
        return false;
      }
      if (this.popup["bgngDt"] == null || this.popup["bgngDt"] == "") {
        alert("시작일을 입력해주세요.");
        this.$refs.bgngDt.focus();
        return false;
      }
      if (this.popup["endDt"] == null || this.popup["endDt"] == "") {
        alert("종료일을 입력해주세요.");
        this.$refs.endDt.focus();
        return false;
      }
      if (
        this.popup["popupSizeType"] == "null" ||
        this.popup["popupSizeType"] == ""
      ) {
        alert("팝업 크기를 선택해주세요.");
        return false;
      }
      if (this.popup["popupSizeType"] == "fixed") {
        if (this.popup["popupSize"] == null || this.popup["popupSize"] == "") {
          alert("팝업 크기를 선택해주세요.");
          return false;
        }
      } else if (this.popup["popupSizeType"] == "custom") {
        if (this.popup["wdthLen"] == null || this.popup["wdthLen"] == "") {
          alert("팝업 가로 크기를 선택해주세요.");
          return false;
        }
        if (this.popup["vrtcLen"] == null || this.popup["vrtcLen"] == "") {
          alert("팝업 세로 크기를 선택해주세요.");
          return false;
        }
      }
      if (this.popup["popupType"] == null || this.popup["popupType"] == "") {
        alert("업로드 형식을 선택해주세요.");
        return false;
      }
      if (this.popup["popupType"] == "image") {
        if (this.fileList.length < 1) {
          alert("이미지 첨부파일을 선택해주세요.");
          return false;
        }
        if (this.popup["linkUrl"] == null || this.popup["linkUrl"] == "") {
          alert("링크 URL을 선택해주세요.");
          this.$refs.linkUrl.focus();
          return false;
        }
      } else if (this.popup["popupType"] == "video") {
        if (this.popup["vdoUrl"] == null || this.popup["vdoUrl"] == "") {
          alert("동영상 URL을 선택해주세요.");
          this.$refs.vdoUrl.focus();
          return false;
        }
      }
      if (this.popup["sn"] == null || this.popup["sn"] == "") {
        alert("순서를 선택해주세요.");
        this.$refs.sn.focus();
        return false;
      }
      if (this.popup["pageType"] == null || this.popup["pageType"] == "") {
        alert("팝업 노출 페이지를 선택해주세요.");
        return false;
      }
      if (this.popup["popupUseYn"] == null || this.popup["popupUseYn"] == "") {
        alert("사용 유무를 선택해주세요.");
        return false;
      }
    },

    //─────axios─────┐
    // 상세 조회
    async axiosViewDetail(data) {
      try {
        const response = await detailProc(data);
        this.popup = response.data["data"]["popupVO"];
        this.codeList = response.data["data"]["codeList"];
        this.fileList = response.data["data"]["fileList"];
        if (this.popup["wdthLen"] == 0 || this.popup["vrtcLen"] == 0) {
          this.popup["wdthLen"] = null;
          this.popup["vrtcLen"] = null;
        }
      } catch (error) {
        alert("에러가 발생했습니다.\n시스템관리자에게 문의하세요.");
      }
    },
    // 등록 및 수정
    axiosUpsert(url, formData) {
      defaultAxios({
        url: url,
        method: "post",
        headers: {
          "Content-Type": "multipart/form-data; charset=UTF-8",
          Authorization: this.$store.state.authorization,
        },
        data: formData,
      })
        .then((response) => {
          alert(response.data["message"]);
          if (response.status == 200) {
            this.$router.push({
              name: "admPopupManagementSelectOne",
              query: {
                pageId: this.popup["popupId"]
                  ? this.popup["popupId"]
                  : response.data.data["popupId"],
              },
            });
          }
        })
        .catch((error) => {
          const errorData = error.response.data;
          if (errorData.message != null && errorData.message != "") {
            alert(error.response.data.message);
          } else {
            alert("에러가 발생했습니다.\n관리자에게 문의해주세요.");
          }
        });
    },
    //─────axios─────┘
  },
  watch: {
    // 팝업 크기 셀렉트 박스 초기화
    "popup.popupSizeType"() {
      if (this.popup["popupSizeType"] == "fixed") {
        this.popup["wdthLen"] = null;
        this.popup["vrtcLen"] = null;
      }
      if (this.popup["popupSizeType"] == "custom") {
        this.popup["popupSize"] = "PS1";
      }
    },
    // 업로드 형식 라디오 초기화
    "popup.popupType"(oldValue, newValue) {
      if (oldValue == "image" && newValue == "video") {
        this.popup["vdoUrl"] = null;
        this.popup["linkUrl"] = null;
      }
      if (oldValue == "video" && newValue == "image") {
        this.popup["vdoUrl"] = null;
        this.popup["linkUrl"] = null;
        // 첨부파일 일괄 삭제
        if (this.fileList.length > 0) {
          for (let file of this.fileList) {
            if (file["fileId"] != null) {
              this.deleteFileList.push(file);
            }
          }
        }
        this.fileList = [];
      }
    },
  },
};
</script>