<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=""
                    :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"
                        class="full-input"
                        ref="ttl"
                        v-model="rvwMttrVO['ttl']"
                        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>
              <td>
                <div class="gd-12 pr0">
                  <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=""
                    :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"
                        class="full-input"
                        ref="clr"
                        v-model="rvwMttrVO['clrNm']"
                        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>
              <td>
                <div class="gd-12 pr0">
                  <label
                    for=""
                    :class="{
                      'form-title mb10': true,
                      'point-font2': pageRole == 'adm',
                      'point-font': pageRole == 'government',
                    }"
                  >
                    접수일자
                  </label>
                  <input
                    type="date"
                    class="half-input"
                    style="display: block"
                    ref="rcptDt"
                    v-model="rvwMttrVO['rcptDt']"
                  />
                </div>
              </td>
            </tr>
            <tr>
              <td colspan="2">
                <div class="gd-12 pl0">
                  <label
                    for=""
                    :class="{
                      'form-title mb10': true,
                      'point-font2': pageRole == 'adm',
                      'point-font': pageRole == 'government',
                    }"
                  >
                    접수내용
                  </label>
                  <textarea
                    class="content"
                    ref="rcptCn"
                    v-model="rvwMttrVO['rcptCn']"
                    placeholder="접수내용을 입력하세요."
                  ></textarea>
                </div>
              </td>
            </tr>
            <tr>
              <td colspan="2">
                <div class="gd-12 pl0 pr0">
                  <label
                    :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>
          </table>
        </div>
      </details>
      <details open class="form-table-style mb30">
        <summary
          :class="{
            'point-font2': pageRole == 'adm',
            'point-font': pageRole == 'government',
          }"
        >
          <div class="flex justify-between align-center no-gutters">
            <p class="summary-style pl10">진행단계 및 지원방안</p>
            <div class="gd-1" v-if="isActive">
              <button
                :class="{
                  'large-btn': true,
                  'blue-border-btn': pageRole == 'adm',
                  'green-border-btn': pageRole == 'government',
                }"
                @click="fnTableAdd"
              >
                추가
              </button>
            </div>
          </div>
        </summary>
        <div class="pt10 pb10">
          <div v-for="(prgrs, index) of rvwMttrVO.prgrsList" :key="index">
            <table class="form-table">
              <colgroup>
                <col width="50%" />
                <col width="50%" />
              </colgroup>
              <tr>
                <td>
                  <div class="gd-12 pl0">
                    <label for="" class="point-font mb10">담당자</label>
                    <div class="flex align-center no-gutters">
                      <div class="gd-9 mr10">
                        <input
                          type="text"
                          class="full-input"
                          ref="picId"
                          v-model="prgrs['picNm']"
                          placeholder="담당자를 선택하세요."
                          readonly
                        />
                      </div>
                      <div class="gd-2">
                        <button
                          :class="{
                            'large-btn': true,
                            'blue-border-btn': pageRole == 'adm',
                            'green-border-btn': pageRole == 'government',
                          }"
                          @click="fnModalOpen('담당자', index)"
                        >
                          찾기
                        </button>
                      </div>
                    </div>
                  </div>
                </td>
                <td>
                  <div class="gd-12 pr0">
                    <label for="" class="point-font mb10">진행단계</label>
                    <select
                      class="full-select"
                      ref="prgrsCrs"
                      v-model="prgrs['prgrsCrs']"
                      @change="fnChangePrgrsCrs()"
                    >
                      <option value="">진행단계를 선택하세요.</option>
                      <option value="0">접수전</option>
                      <option value="1">처리중</option>
                      <option value="2">완료</option>
                    </select>
                  </div>
                </td>
              </tr>
              <tr>
                <td colspan="2">
                  <div class="gd-12 pl0">
                    <label for="" class="point-font mb10">진행날짜</label>
                    <input
                      type="date"
                      class="half-input"
                      style="display: block"
                      ref="prgrsDt"
                      v-model="prgrs['prgrsDt']"
                    />
                  </div>
                </td>
              </tr>
              <tr>
                <td colspan="2">
                  <div class="gd-12 pl0">
                    <label for="" class="point-font mb10">지원방향</label>
                    <textarea
                      class="content"
                      ref="sprtMthd"
                      v-model="prgrs['sprtMthd']"
                      placeholder="지원방향을 입력하세요."
                    ></textarea>
                  </div>
                </td>
              </tr>
            </table>
            <div class="flex justify-end align-center no-gutters">
              <div class="gd-1" v-show="index != 0">
                <button
                  class="large-btn red-border-btn"
                  @click="fnTableDelete(index)"
                >
                  삭제
                </button>
              </div>
            </div>
          </div>
        </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>{{ modal["title"] }}</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="40%" />
          </colgroup>
          <thead>
            <tr>
              <th class="text-ct">내용</th>
              <th class="text-ct">비고</th>
            </tr>
          </thead>
          <tr v-for="(item, index) of modal['list']" :key="index">
            <td>{{ item["name"] }}</td>
            <td>
              <button
                type="button"
                :class="{
                  'large-btn': true,
                  'blue-border-btn': pageRole == 'adm',
                  'green-border-btn point-font': pageRole == 'government',
                }"
                @click="fnModalInsert(item)"
              >
                선택
              </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 { rvwMttrDetailProc } from "../../../../../../resources/api/rvwMttr";
import { ivstDscsnListProc } from "../../../../../../resources/api/ivstDscsn";
import { mbrListProc } from "../../../../../../resources/api/mbrInfo";

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

      rvwMttrVO: {},
      rvwMttrTypeList: [],

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

      // 모달 객체
      isOpen: false,
      modal: {
        title: null,
        index: null,
        list: [],
      },

      // 모달 데이터 (투자상담)
      ivstDscsnList: [],

      // 모달 데이터 (접수자/담당자)
      mbrSearch: [],

      // 진행단계 추가 가능 여부
      isActive: true,

      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() {
      // 데이터 삽입
      let data = {
        rvwMttrId: this.pageId,
        ivstDscsnId: this.$route.query.ivstDscsnId,
        ttl: this.$route.query.ttl,
      };
      // 실행
      try {
        const response = await rvwMttrDetailProc(data);
        this.rvwMttrVO = response.data.data.rvwMttrVO;
        this.rvwMttrTypeList = response.data.data.rvwMttrTypeList;
        this.fileList = response.data.data.rvwMttrVO.fileList;

        let today = new Date().toISOString().substring(0, 10);

        let dscsnOtln = this.rvwMttrVO.type;
        if (
          dscsnOtln != "" &&
          dscsnOtln != "투자협의" &&
          dscsnOtln != "건의사항"
        ) {
          this.dscsnOtln.select = "self";
          this.dscsnOtln.detail = this.rvwMttrVO.type;
        } else {
          this.dscsnOtln.select = this.rvwMttrVO.type;
        }

        // 기본정보
        if (this.rvwMttrVO.rvwMttrId == null) {
          this.rvwMttrVO.clr = this.$store.state.mbrId;
          this.rvwMttrVO.clrNm = this.$store.state.mbrNm;
          this.rvwMttrVO.rcptDt = today;
        }
        // 진행단계
        if (this.rvwMttrVO.prgrsList[0].rvwMttrPrgrsId == null) {
          this.rvwMttrVO.prgrsList[0].picId = this.$store.state.mbrId;
          this.rvwMttrVO.prgrsList[0].picNm = this.$store.state.mbrNm;
          this.rvwMttrVO.prgrsList[0].prgrsDt = today;
        }
        // 진행단계 완료 여부
        this.fnChangePrgrsCrs();
      } catch (error) {
        alert("에러가 발생했습니다.\n관리자에게 문의해주세요.");
      }
    },

    // 모달 열기
    fnModalOpen(type, index) {
      this.isOpen = true;
      this.modal["title"] = type;
      this.modal["index"] = index;
      this.fnModalViewList();
    },
    fnModalViewList() {
      const type = this.modal["title"];
      const index = this.modal["index"];
      if (type == "투자상담명") {
        this.axiosIvstDscsnList();
      } else if (type == "접수자" || type == "담당자") {
        this.axiosMbrList(type, index);
      }
    },
    // 모달 선택
    fnModalInsert(data) {
      if (data["type"] == "ivstDscsn") {
        this.rvwMttrVO["ivstDscsnId"] = data["id"];
        this.rvwMttrVO["ttl"] = data["name"];
        if (this.rvwMttrVO.rcptCn == null || this.rvwMttrVO.rcptCn == "") {
          this.rvwMttrVO.rcptCn = data.mainCn;
        }
      } else if (data["type"] == "clr") {
        this.rvwMttrVO["clr"] = data["id"];
        this.rvwMttrVO["clrNm"] = data["name"];
      } else if (data["type"] == "picId") {
        let index = data["index"];
        this.rvwMttrVO.prgrsList[index]["picId"] = data["id"];
        this.rvwMttrVO.prgrsList[index]["picNm"] = data["name"];
      }
      this.fnModalClose();
    },
    // 모달 닫기
    fnModalClose() {
      this.isOpen = false;
      this.modal = {
        title: null,
        index: null,
        list: [],
      };
      this.search = { ...defaultSearchParams };
    },
    // axios: 모달 데이터 조회(투자상담)
    async axiosIvstDscsnList() {
      // 데이터 삽입
      let data = this.search;
      data.searchType = "ttl";
      // 실행
      try {
        const response = await ivstDscsnListProc(data);
        let dataList = [];
        for (let item of response.data["data"]["list"]) {
          dataList.push({
            type: "ivstDscsn",
            name: item["ttl"],
            id: item["ivstDscsnId"],
            mainCn: item["mainCn"],
          });
        }
        this.modal["list"] = dataList;
        this.search = response.data["data"]["pagination"];
      } catch (error) {
        alert("에러가 발생했습니다.\n관리자에게 문의해주세요.");
      }
    },
    // axios: 모달 데이터 조회(접수자/담당자)
    async axiosMbrList(type, index) {
      // 데이터 삽입
      let data = { ...this.search, authrtCd: "" };
      data.searchType = "mbr_nm";
      // 실행
      try {
        const response = await mbrListProc(data);
        let dataList = [];
        if (type == "접수자") {
          for (let item of response.data.data.list) {
            dataList.push({
              type: "clr",
              name: item["mbrNm"],
              id: item["mbrId"],
            });
          }
        } else if (type == "담당자") {
          for (let item of response.data.data.list) {
            dataList.push({
              type: "picId",
              name: item["mbrNm"],
              id: item["mbrId"],
              index: index,
            });
          }
        }
        this.modal["list"] = dataList;
        this.search = response.data["data"]["pagination"];
      } catch (error) {
        alert("에러가 발생했습니다.\n관리자에게 문의해주세요.");
      }
    },

    // 진행단계 추가
    fnTableAdd() {
      this.rvwMttrVO.prgrsList.push({
        rvwMttrId: this.pageId,
        picId: this.$store.state.mbrId,
        picNm: this.$store.state.mbrNm,
        prgrsCrs: "",
        prgrsDt: new Date().toISOString().substring(0, 10),
        sprtMthd: null,
        rgtr: null,
        regDt: null,
        mdfr: null,
        mdfcnDt: null,
      });
    },
    // 진행단계 삭제
    fnTableDelete(index) {
      var isDelete = confirm("해당 진행단계 및 지원방안을 삭제하시겠습니까?");
      if (isDelete) {
        this.rvwMttrVO.deleteList.push(this.rvwMttrVO.prgrsList[index]);
        this.rvwMttrVO.prgrsList.splice(index, 1);
      } else {
        return;
      }
    },
    // 진행단계 완료
    fnChangePrgrsCrs() {
      this.isActive = true;
      for (let prgrs of this.rvwMttrVO.prgrsList) {
        if (prgrs.prgrsCrs == 2) {
          this.isActive = false;
          return;
        }
      }
    },

    // 유효성 검사
    valiadtion() {
      if (this.rvwMttrVO["ttl"] == null || this.rvwMttrVO["ttl"] == "") {
        alert("투자상담명을 선택해주세요.");
        this.$refs.ttl.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;
        }
      }

      if (this.rvwMttrVO["clrNm"] == null || this.rvwMttrVO["clrNm"] == "") {
        alert("접수자를 선택해주세요.");
        this.$refs.clr.focus();
        return false;
      }

      if (this.rvwMttrVO["rcptDt"] == null || this.rvwMttrVO["rcptDt"] == "") {
        alert("접수일자를 선택해주세요.");
        this.$refs.rcptDt.focus();
        return false;
      }

      if (this.rvwMttrVO["rcptCn"] == null || this.rvwMttrVO["rcptCn"] == "") {
        alert("접수내용을 입력해주세요.");
        this.$refs.rcptCn.focus();
        return false;
      }

      if (this.rvwMttrVO.prgrsList.length > 0) {
        for (let i = 0; i < this.rvwMttrVO.prgrsList.length; i++) {
          if (
            this.rvwMttrVO.prgrsList[i].prgrsCrs == null ||
            this.rvwMttrVO.prgrsList[i].prgrsCrs == ""
          ) {
            alert("진행단계를 입력해주세요.");
            this.$refs.prgrsCrs[i].focus();
            return false;
          }
          if (
            this.rvwMttrVO.prgrsList[i].prgrsDt == null ||
            this.rvwMttrVO.prgrsList[i].prgrsDt == ""
          ) {
            alert("진행날짜를 입력해주세요.");
            this.$refs.prgrsDt[i].focus();
            return false;
          }
          if (
            this.rvwMttrVO.prgrsList[i].sprtMthd == null ||
            this.rvwMttrVO.prgrsList[i].sprtMthd == ""
          ) {
            alert("지원방향을 입력해주세요.");
            this.$refs.sprtMthd[i].focus();
            return false;
          }
        }
      }
      return true;
    },
    // axios: 등록
    async fnUpsert() {
      // 유효성 검사
      if (this.valiadtion() == false) {
        return;
      }
      // 상담요지 포멧 변경
      let data = this.rvwMttrVO;
      if (this.dscsnOtln.select == "self") {
        data.type = this.dscsnOtln.detail;
      } else {
        data.type = this.dscsnOtln.select;
      }
      data.deleteFileList = this.deleteFileList;
      // 데이터 세팅
      let formData = new FormData();
      const paramsToBlob = new Blob([JSON.stringify(data)], {
        type: "application/json; charset=UTF-8",
      });
      formData.append("rvwMttrVO", paramsToBlob);
      if (this.insertFileList.length > 0) {
        for (const file of this.insertFileList) {
          formData.append("insertFileList", file);
        }
      }
      // 실행
      defaultAxios({
        url:
          this.pageId == null
            ? "/government/rvwMttr/insertProc.file"
            : "/government/rvwMttr/updateProc.file",
        method: "post",
        headers: {
          "Content-Type": "multipart/form-data; charset=UTF-8",
          Authorization: this.$store.state.authorization,
        },
        data: formData,
      })
        .then((response) => {
          alert(response.data["message"]);
          this.$router.push({
            path: this.routerPaths["view"],
            query: {
              pageId:
                this.pageId == null
                  ? response.data.data.rvwMttrId
                  : this.pageId,
            },
          });
        })
        .catch((error) => {
          const errorData = error.response.data;
          if (errorData.message != null && errorData.message != "") {
            alert(error.response.data.message);
          } else {
            alert("에러가 발생했습니다.\n관리자에게 문의해주세요.");
          }
        });
    },

    // 취소
    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;
    },
  },
  watch: {
    fileList: {
      deep: true,
      handler() {
        this.fnFileList();
      },
    },
  },
};
</script>
