<template>
  <div
    :class="{
      content: true,
      'admin-style overflow-y': pageRole == 'adm',
      'pt50 pb50': pageRole == 'government',
    }"
  >
    <div
      :class="{
        'w1200 ': pageRole == 'government',
      }"
    >
      <div
        :class="{
          'admin-page-title point-font2 mb30': pageRole == 'adm',
          'page-title point-font mb30': pageRole == 'government',
        }"
      >
        <p>투자상담</p>
      </div>
      <details open class="form-table-style mb30">
        <summary
          :class="{
            'point-font2': pageRole == 'adm',
            'point-font': pageRole == 'government',
          }"
        >
          <p class="summary-style pl10">기본정보</p>
        </summary>
        <div class="pt10 pb10">
          <table class="form-table">
            <colgroup>
              <col width="50%" />
              <col width="50%" />
            </colgroup>
            <tr>
              <td>
                <div class="gd-12 pl0">
                  <label
                    for="ttl"
                    :class="{
                      'form-title mb10': true,
                      'point-font2': pageRole == 'adm',
                      'point-font': pageRole == 'government',
                    }"
                  >
                    상담요지
                  </label>
                  <div class="flex align-center">
                    <div class="gd-6 pl0">
                      <select
                        class="full-input"
                        v-model="dscsnOtln.select"
                        @change="fnChangeSelect"
                      >
                        <option value="">상담요지를 선택하세요.</option>
                        <option value="투자협의">투자협의</option>
                        <option value="건의사항">건의사항</option>
                        <option value="self">직접입력</option>
                      </select>
                    </div>
                    <div class="gd-6 pr0" v-show="dscsnOtln.select == 'self'">
                      <input
                        type="text"
                        class="full-input"
                        ref="detail"
                        v-model="dscsnOtln.detail"
                        placeholder="상담요지를 직접 입력하세요."
                      />
                    </div>
                  </div>
                </div>
              </td>
            </tr>
            <tr>
              <td>
                <div class="gd-12 pl0">
                  <label
                    for="ttl"
                    :class="{
                      'form-title mb10': true,
                      'point-font2': pageRole == 'adm',
                      'point-font': pageRole == 'government',
                    }"
                  >
                    제목
                  </label>
                  <input
                    type="text"
                    id="ttl"
                    class="full-input"
                    ref="ttl"
                    v-model="ivstDscsnVO['ttl']"
                    placeholder="제목을 입력하세요."
                  />
                </div>
              </td>
              <td>
                <div class="gd-12 pr0">
                  <label
                    for="dt"
                    :class="{
                      'form-title mb10': true,
                      'point-font2': pageRole == 'adm',
                      'point-font': pageRole == 'government',
                    }"
                  >
                    일시
                  </label>
                  <input
                    type="date"
                    id="dt"
                    class="half-input"
                    style="display: block"
                    ref="dt"
                    v-model="ivstDscsnVO['dt']"
                  />
                </div>
              </td>
            </tr>
            <tr>
              <td>
                <div class="gd-12 pl0">
                  <label
                    for="plc"
                    :class="{
                      'form-title mb10': true,
                      'point-font2': pageRole == 'adm',
                      'point-font': pageRole == 'government',
                    }"
                  >
                    장소
                  </label>
                  <input
                    type="text"
                    id="plc"
                    class="full-input"
                    ref="plc"
                    v-model="ivstDscsnVO['plc']"
                    placeholder="장소를 입력하세요."
                  />
                </div>
              </td>
              <td>
                <div class="gd-12 pr0">
                  <label
                    for="entNm"
                    :class="{
                      'form-title mb10': true,
                      'point-font2': pageRole == 'adm',
                      'point-font': pageRole == 'government',
                    }"
                  >
                    기업명
                  </label>
                  <div class="flex align-center no-gutters">
                    <div class="gd-9 mr10">
                      <input
                        type="text"
                        id="entNm"
                        class="full-input"
                        ref="entNm"
                        v-model="ivstDscsnVO['entNm']"
                        placeholder="기업명을 선택하세요."
                        readonly
                      />
                    </div>
                    <div class="gd-2">
                      <button
                        :class="{
                          'large-btn': true,
                          'blue-border-btn': pageRole == 'adm',
                          'green-border-btn': pageRole == 'government',
                        }"
                        @click="fnModalOpen"
                      >
                        찾기
                      </button>
                    </div>
                  </div>
                </div>
              </td>
            </tr>
            <tr>
              <td>
                <div class="gd-12 pl0">
                  <label
                    for="prtpnt"
                    :class="{
                      mb10: true,
                      'point-font2': pageRole == 'adm',
                      'point-font': pageRole == 'government',
                    }"
                    >참석자</label
                  >
                  <input
                    type="text"
                    id="prtpnt"
                    class="full-input"
                    v-model="ivstDscsnVO['prtpnt']"
                    placeholder="참석자를 입력하세요."
                  />
                </div>
              </td>
              <td>
                <div class="gd-12 pr0">
                  <label
                    for="dscsnPbofc"
                    :class="{
                      'form-title mb10': true,
                      'point-font2': pageRole == 'adm',
                      'point-font': pageRole == 'government',
                    }"
                  >
                    상담공무원
                  </label>
                  <input
                    type="text"
                    id="dscsnPbofc"
                    class="full-input"
                    ref="dscsnPbofc"
                    v-model="ivstDscsnVO['dscsnPbofc']"
                    placeholder="상담공무원을 입력하세요."
                  />
                </div>
              </td>
            </tr>
            <tr>
              <td colspan="2">
                <div class="gd-12 pl0 pr0">
                  <label
                    for=""
                    :class="{
                      mb10: true,
                      'point-font2': pageRole == 'adm',
                      'point-font': pageRole == 'government',
                    }"
                    >주요내용</label
                  >
                  <textarea
                    name=""
                    id=""
                    class="mainCn"
                    v-model="ivstDscsnVO['mainCn']"
                    placeholder="내용을 입력하세요."
                  ></textarea>
                </div>
              </td>
            </tr>
            <tr>
              <td colspan="2">
                <div class="gd-12 pl0 pr0">
                  <label
                    for=""
                    :class="{
                      mb10: true,
                      'point-font2': pageRole == 'adm',
                      'point-font': pageRole == 'government',
                    }"
                  >
                    첨부파일
                  </label>
                  <div class="flex">
                    <div class="gd-10 pl0">
                      <div class="filebox">
                        <input
                          class="upload-name full-input"
                          v-model="viewFiles"
                          placeholder="첨부파일이 없습니다."
                          readonly
                        />
                      </div>
                      <div>
                        <div
                          v-for="(file, index) of fileList"
                          :key="index"
                          class="file-wrap flex justify-between align-center border pd10 mt10"
                        >
                          <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"
                            />
                          </button>
                        </div>
                      </div>
                    </div>
                    <div class="gd-2 pr0">
                      <label
                        for="file"
                        :class="{
                          'large-btn text-ct cursor': true,
                          'blue-border-btn': pageRole == 'adm',
                          'green-border-btn': pageRole == 'government',
                        }"
                      >
                        파일찾기
                      </label>
                      <input
                        type="file"
                        id="file"
                        ref="file"
                        @change="fnFileInsert"
                        multiple
                        style="display: none"
                      />
                    </div>
                  </div>
                </div>
              </td>
            </tr>
            <tr>
              <td>
                <div class="gd-12 pl0">
                  <label
                    for=""
                    :class="{
                      mb10: true,
                      'point-font2': pageRole == 'adm',
                      'point-font': pageRole == 'government',
                    }"
                  >
                    입주의향
                  </label>
                  <div class="flex">
                    <div class="gd-4 pl0 flex align-center">
                      <input
                        class="mr5"
                        type="radio"
                        name="mvnInten"
                        id="mvnIntenTrue"
                        v-model="ivstDscsnVO['mvnInten']"
                        value="1"
                      />
                      <label for="mvnIntenTrue">의향있음</label>
                    </div>
                    <div class="gd-4 pl0 flex align-center">
                      <input
                        class="mr5"
                        type="radio"
                        name="mvnInten"
                        id="mvnIntenHalf"
                        v-model="ivstDscsnVO['mvnInten']"
                        value="2"
                      />
                      <label for="mvnIntenHalf">검토중</label>
                    </div>
                    <div class="gd-4 pl0 flex align-center">
                      <input
                        class="mr5"
                        type="radio"
                        name="mvnInten"
                        id="mvnIntenFalse"
                        v-model="ivstDscsnVO['mvnInten']"
                        value="0"
                      />
                      <label for="mvnIntenFalse">의향없음</label>
                    </div>
                  </div>
                </div>
              </td>
              <td>
                <div class="gd-12 pr0">
                  <label
                    for=""
                    :class="{
                      mb10: true,
                      'point-font2': pageRole == 'adm',
                      'point-font': pageRole == 'government',
                    }"
                  >
                    MOU의향
                  </label>
                  <div class="flex">
                    <div class="gd-4 pl0 flex align-center">
                      <input
                        class="mr5"
                        type="radio"
                        name="mouInten"
                        id="mouIntenTrue"
                        v-model="ivstDscsnVO['mouInten']"
                        value="1"
                      />
                      <label for="mouIntenTrue">의향있음</label>
                    </div>
                    <div class="gd-4 pl0 flex align-center">
                      <input
                        class="mr5"
                        type="radio"
                        name="mouInten"
                        id="mouIntenHalf"
                        v-model="ivstDscsnVO['mouInten']"
                        value="2"
                      />
                      <label for="mouIntenHalf">검토중</label>
                    </div>
                    <div class="gd-4 pl0 flex align-center">
                      <input
                        class="mr5"
                        type="radio"
                        name="mouInten"
                        id="mouIntenFalse"
                        v-model="ivstDscsnVO['mouInten']"
                        value="0"
                      />
                      <label for="mouIntenFalse">의향없음</label>
                    </div>
                  </div>
                </div>
              </td>
            </tr>
          </table>
        </div>
      </details>
      <div class="flex justify-end align-center no-gutters">
        <div class="gd-1 mr10">
          <button
            :class="{
              'large-btn': true,
              'blue-btn': pageRole == 'adm',
              'green-btn': pageRole == 'government',
            }"
            @click="fnUpsert"
          >
            {{ pageId == null ? "등록" : "수정" }}
          </button>
        </div>
        <div class="gd-1">
          <button class="large-btn gray-btn" @click="fnPrev">취소</button>
        </div>
      </div>
      <!-- 모달: 기업명 -->
      <Modal :showModal="isOpen">
        <template v-slot:header>
          <div
            :class="{
              'box-title': true,
              'point-font2': pageRole == 'adm',
              'point-font': pageRole == 'government',
            }"
          >
            <p>기업명</p>
          </div>
          <button class="close-btn" @click="fnModalClose">X</button>
        </template>
        <!-- 검색 -->
        <div class="search-bar mb15">
          <div class="flex">
            <div class="border gd-9 pl0">
              <input
                type="text"
                class="full-input border-none condition-input"
                v-model="search['searchText']"
                v-on:keyup.enter="fnModalViewList"
                placeholder="검색어를 입력하세요."
              />
            </div>
            <div class="gd-3 pr0">
              <button
                :class="{
                  'large-btn': true,
                  'blue-border-btn': pageRole == 'adm',
                  'green-border-btn': pageRole == 'government',
                }"
                @click="fnModalViewList"
              >
                검색
              </button>
            </div>
          </div>
        </div>
        <!-- 목록 -->
        <table class="form-table2 mb10">
          <colgroup>
            <col width="60%" />
            <col width="35%" />
          </colgroup>
          <thead>
            <tr>
              <th class="text-ct">제목</th>
              <th class="text-ct">비고</th>
            </tr>
          </thead>
          <tr v-for="(entInfo, index) of entInfolist" :key="index">
            <td>{{ entInfo.entNm }}</td>
            <td>
              <button
                type="button"
                :class="{
                  'large-btn': true,
                  'blue-border-btn': pageRole == 'adm',
                  'green-border-btn point-font': pageRole == 'government',
                }"
                @click="fnModalInsert(entInfo)"
              >
                선택
              </button>
            </td>
          </tr>
        </table>
        <template v-slot:footer>
          <div class="gd-2"></div>
          <div class="gd-8">
            <PaginationButton
              v-model:currentPage="search['currentPage']"
              :pagination="search"
              :click="fnModalViewList"
              :className="pageRole == 'adm' ? 'admin-pagination' : null"
            />
          </div>
          <div class="gd-2"></div>
        </template>
      </Modal>
    </div>
  </div>
</template>

<script>
import defaultAxios from "../../../../../../resources/js/defaultAxios";
import { defaultSearchParams } from "../../../../../../resources/js/defaultSearchParams";
import defaultFileSystem from "../../../../../../resources/js/defaultFileSystem";
// COMPONENT
import Modal from "../../../../../component/modal/Modal.vue";
import PaginationButton from "../../../../../component/pagination/PaginationButton.vue";
// API
import { ivstDscsnDetailProc } from "../../../../../../resources/api/ivstDscsn";
import { entInfoListProc } from "../../../../../../resources/api/entInfo";

export default {
  mixins: [defaultFileSystem],
  components: {
    Modal: Modal,
    PaginationButton: PaginationButton,
  },
  data() {
    return {
      pageRole: this.$store.state.userType, // 유저 권한
      pageId: this.$route.query.pageId, // 페이지 아이디

      ivstDscsnVO: {},

      // 검색 정보 담는 객체
      search: { ...defaultSearchParams },

      // 모달 객체
      isOpen: false,
      entInfolist: [],

      dscsnOtln: {
        select: null,
        detail: null,
      },
    };
  },
  created() {
    this.fnViewDetail();
  },
  computed: {
    routerPaths() {
      return {
        list: this.$store.state.path + "/list.page",
        view: this.$store.state.path + "/view.page",
        insert: this.$store.state.path + "/insert.page",
      };
    },
  },
  methods: {
    // axios: 투자상담 조회(상세)
    async fnViewDetail() {
      // 데이터 세팅
      const data = { ivstDscsnId: this.pageId };
      // 실행
      try {
        const response = await ivstDscsnDetailProc(data);
        this.ivstDscsnVO = response.data.data;
        // 기업정보 기본값 추가
        if (this.ivstDscsnVO.ivstDscsnId == null) {
          this.ivstDscsnVO.entId = this.$route.query.entId;
          this.ivstDscsnVO.entNm = this.$route.query.entNm;
        }
        // 일시 기본값 추가
        let today = new Date().toISOString().substring(0, 10);
        if (this.ivstDscsnVO.dt == null) {
          this.ivstDscsnVO.dt = today;
        }
        // 상담요지 포멧 변경
        let dscsnOtln = this.ivstDscsnVO.dscsnOtln;
        if (
          dscsnOtln != "" &&
          dscsnOtln != "투자협의" &&
          dscsnOtln != "건의사항"
        ) {
          this.dscsnOtln.select = "self";
          this.dscsnOtln.detail = this.ivstDscsnVO.dscsnOtln;
        } else {
          this.dscsnOtln.select = this.ivstDscsnVO.dscsnOtln;
        }
        this.fileList = response.data.data.fileList;
      } catch (error) {
        alert("에러가 발생했습니다.\n관리자에게 문의해주세요.");
      }
    },

    // 모달 열기
    fnModalOpen() {
      this.isOpen = true;
      this.fnModalViewList();
    },
    // axios: 모달 데이터 조회(기업정보)
    async fnModalViewList() {
      // 데이터 세팅
      let data = this.search;
      // 실행
      try {
        const response = await entInfoListProc(data);
        this.entInfolist = response.data["data"]["list"];
        this.search = response.data["data"]["pagination"];
      } catch (error) {
        alert("에러가 발생했습니다.\n관리자에게 문의해주세요.");
      }
    },
    // 모달 선택
    fnModalInsert(data) {
      // 객체 삽입
      this.ivstDscsnVO["entId"] = data["entId"];
      this.ivstDscsnVO["entNm"] = data["entNm"];
      // 모달 닫기
      this.fnModalClose();
    },
    // 모달 닫기
    fnModalClose() {
      this.isOpen = false;
      this.search = { ...defaultSearchParams };
    },

    // 등록 및 수정
    fnUpsert() {
      // 유효성 검사
      if (this.valiadtion() == false) {
        return;
      }
      // 데이터 세팅
      let data = this.ivstDscsnVO;
      // 상담요지 포멧 변경
      if (this.dscsnOtln.select == "self") {
        data.dscsnOtln = this.dscsnOtln.detail;
      } else {
        data.dscsnOtln = this.dscsnOtln.select;
      }
      // 실행
      defaultAxios({
        url:
          this.pageId == null
            ? "/government/ivstDscsn/insertProc.file"
            : "/government/ivstDscsn/updateProc.file",
        method: "post",
        headers: {
          "Content-Type": "multipart/form-data; charset=UTF-8",
          Authorization: this.$store.state.authorization,
        },
        data: data,
      })
        .then((response) => {
          alert(response.data["message"]);
          this.$router.push({
            path: this.routerPaths["view"],
            query: {
              pageId:
                this.pageId == null
                  ? response.data.data.ivstDscsnId
                  : this.pageId,
            },
          });
        })
        .catch((error) => {
          const errorData = error.response.data;
          if (errorData.message != null && errorData.message != "") {
            alert(error.response.data.message);
          } else {
            alert("에러가 발생했습니다.\n관리자에게 문의해주세요.");
          }
        });
    },
    // 유효성 검사
    valiadtion() {
      if (this.ivstDscsnVO["ttl"] == null || this.ivstDscsnVO["ttl"] == "") {
        alert("제목을 입력해주세요.");
        this.$refs.ttl.focus();
        return false;
      }

      if (this.ivstDscsnVO["dt"] == null || this.ivstDscsnVO["dt"] == "") {
        alert("일시를 입력해주세요.");
        this.$refs.dt.focus();
        return false;
      }

      if (this.ivstDscsnVO["plc"] == null || this.ivstDscsnVO["plc"] == "") {
        alert("장소를 입력해주세요.");
        this.$refs.plc.focus();
        return false;
      }

      if (
        this.ivstDscsnVO["entNm"] == null ||
        this.ivstDscsnVO["entNm"] == ""
      ) {
        alert("기업명을 입력해주세요.");
        this.$refs.entNm.focus();
        return false;
      }

      if (
        this.ivstDscsnVO["dscsnPbofc"] == null ||
        this.ivstDscsnVO["dscsnPbofc"] == ""
      ) {
        alert("상담공무원을 입력해주세요.");
        this.$refs.dscsnPbofc.focus();
        return false;
      }

      if (this.dscsnOtln.select == null || this.dscsnOtln.select == "") {
        alert("상담요지를 선택해주세요.");
        return false;
      }
      if (this.dscsnOtln.select == "self") {
        if (this.dscsnOtln.detail == null || this.dscsnOtln.detail == "") {
          alert("상담요지를 입력해주세요.");
          this.$refs.detail.focus();
          return false;
        }
      }

      return true;
    },

    // 첨부파일 등록
    fnFileInsert() {
      this.files = this.$refs.file.files;
      this.fileList = [...this.fileList, ...Array.from(this.files)];
      this.ivstDscsnVO.insertFileList = [
        ...this.ivstDscsnVO.insertFileList,
        ...Array.from(this.files),
      ];
      this.$refs.file.value = "";
    },
    // 첨부파일 삭제
    fnFileDelete(file, index) {
      if (file["fileId"] != null) {
        this.ivstDscsnVO.deleteFileList.push(file);
      }
      this.fileList.splice(index, 1);
      this.ivstDscsnVO.insertFileList.splice(index, 1);
    },

    // 취소
    fnPrev() {
      let isCheck = confirm("작성을 취소하시겠습니까?");
      if (!isCheck) {
        return;
      }
      if (this.pageId != null) {
        this.$router.push({
          path: this.routerPaths["view"],
          query: { pageId: this.pageId },
        });
      } else {
        this.$router.push({
          path: this.routerPaths["list"],
        });
      }
    },

    // 상담요지 변경
    fnChangeSelect() {
      this.dscsnOtln.detail = null;
    },
  },
};
</script>
