<template>
 <div class="content overflow-y">
    <div class="admin-page-title point-font2 mb30">
      <p>구독서비스 관리</p>
    </div>
    <div class="flex justify-between align-start  no-gutters">
      <div class="gd-5 no-gutters">
        <div class="gd-4">
          <select class="full-select ml0" v-model="search.authrtId" @change="fnViewList" style="border-radius: 3rem;">
            <option value="">전체</option>
            <option value="ROLE_CO">기업회원</option>
            <option value="ROLE_CO_USER">기업일반회원</option>
            <option value="ROLE_CO_MANAGER">기업관리자</option>
            <option value="ROLE_USER">일반회원</option>
            <option value="APPL_PRNMNT">출원예정사</option>
          </select>
        </div>
      </div>
      <div class="search-bar mb15 gd-7">
      <div class="flex justify-end align-center no-gutters">
        <div class="gd-9">
          <div class="flex align-center">
            <div class="gd-3 pl0">
              <select  class="full-select" v-model="search.searchType">
                <option v-for="(item, idx) in codeList" :key="idx" :value="item.cdId">{{ item.cdNm }}
                </option>
            </select>
            </div>
            <div class="gd-9 pl0">
              <input
              type="text"
              class="full-input condition-input"
              placeholder="검색어를 입력하세요."
              v-model="search.searchText" @keyup.enter="fnViewList" />
            </div>
          </div>
        </div>
        <div class="gd-2">
          <button class="large-btn blue-border-btn" @click="fnViewList">
            검색
          </button>
        </div>
      </div>
      <p class="text-rg small-text">보안을 위해, 이름 검색 시 전체 이름을 정확하게 입력해주세요.</p>
    </div>
    </div>
    <div class="table-zone mb10">
      <p class="small-text black mb10">총 <span style="font-weight: 700;">{{ listCnt }}건</span> | 선택 <span style="font-weight: 700;"> {{checkList.length}}명</span></p>
      <table class="list-table admin-list">
        <colgroup>
          <col width="5%" />
          <col width="10%" />
          <col width="20%" />
          <col width="10%" />
          <col width="20%" />
          <col width="20%" />
          <col width="15%" />
        </colgroup>
        <thead>
            <tr>
                <th><input type="checkbox" v-model="checkAll"  @click="allCheckClick"></th>                         
                <th>no</th>
                <th>아이디</th>
                <th>이름</th>
                <th>기업명</th>                            
                <th>이메일</th>
                <th>가입일</th>
            </tr>
        </thead>
        <tbody>
          <tr v-for="(item, indx) in list" :key="indx">
            <td class="text-ct"><input type="checkbox" :value="item.mbr_id" v-model="checkList" /></td>
            <td class="text-ct">   {{search.totalRecordCount - indx - (search.currentPage - 1) * this.search.pageSize}}</td>
            <td>{{ item.lgn_id }}</td>
            <td class="text-ct">{{ item.mbr_encpt_flnm }}</td>
            <td class="text-ct">{{ item.ent_nm == null ? "-" : item.ent_nm }}</td>
            <td>{{ item.mbr_encpt_emad }}</td>
            <td class="text-ct">{{ $filters.date(item.frst_reg_dt)}}</td>
          </tr>
          <tr v-if="list.length == 0" >
            <td  class="text-ct data-none" colspan="7">등록된 정보가 존재하지 않습니다.</td>
          </tr>
        </tbody>
      </table>
    </div>
    <div class="flex justify-between align-center no-gutters">
      <div class="gd-1"></div>
      <div class="gd-10">
        <PaginationButton
          :className="'admin-pagination'"
          v-model:currentPage="search.currentPage"
          :pagination="search"
          :click="fnViewList"
        />
        </div>
      <div class="gd-1"> 
        <button class="large-btn blue-btn" @click="mailFormDrow()">메일발송</button>
      </div>
    </div>    
  </div>
  <!-- 모달: 메일발송  -->
  <Modal :showModal="mailForm" :className="'large-modal'">
      <template v-slot:header>
        <p class="page-sub-title">메일 전송 내용</p>
        <button class="close-btn" @click="mailFormOff"><svg-icon type="mdi" :path="closePath"></svg-icon></button>
      </template>
      <div class="content">
          <p class="detail-text text-rg"><span class="detail-bold">선택 인원수 : {{checkList.length}}명</span></p>
          <div class="gd-12 pd10">
              <p class="from-title">제목</p>
              <input type="text" name="" id="newsTitle" class="full-input" v-model="email.email_title" />
          </div>
          <div class="gd-12 pd10 content-area">
              <p class="from-title">내용</p>
              <textarea name="smart" id="smart"  style="width:100%; height: 30rem;"></textarea>
          </div>
      </div>
      <template v-slot:footer>
        <div class="gd-2 pr0">
          <button class="large-btn gray-btn" @click="mailFormOff">
            취소
          </button>
        </div>
        <div class="gd-2 pr0">
          <button class="large-btn blue-border-btn" @click="emailCheck">
            발송하기
          </button>
        </div>
      </template>
    </Modal>
</template>

<script>
import PaginationButton from "../../../../component/pagination/PaginationButton.vue";
import Modal from "../../../../component/modal/Modal.vue";
import { find, allcheck} from '../../../../../resources/api/subsc.js'
import { sendEmail } from '../../../../../resources/api/sendMail.js'
import { toRaw } from "vue";
import queryParams from "../../../../../resources/js/queryParams";
import { defaultSearchParams } from "../../../../../resources/js/defaultSearchParams";
import COMMON_UTIL from '../../../../../resources/js/commonUtil';
import { mdiWindowClose } from "@mdi/js";

export default {
  mixins: [queryParams],
  components: {  
    'PaginationButton': PaginationButton,
    'Modal':Modal
  },
  data() {
    return {
      closePath:mdiWindowClose,
      // 페이지 권한 객체
      pageAuth: JSON.parse(localStorage.getItem("vuex")).pageAuth,
      // 검색 정보 담는 객체
      search: { ...defaultSearchParams },
      pagination: {},
      email: {
                email_title: null,
                email_content: null,              
            },
      codeList: [
            { cdNm: '회원명', cdId: 'mbr_nm' },
            { cdNm: '기업명', cdId: 'ent_nm' },
      ], // 검색 조건
      //검색 리스트
      list : [], 
      subscIdx: 0,
      checkList : [],
      listCnt: 0,
      checkAll : false,
      mailForm : false,
      oEditors: {}, // oEditors는 스마트에디터용
      editorCreate : false,
    };
  },
  created() {
    this.resotreQueryParams("queryParams");
    if(this.search.searchType == ''){
      this.search.searchType = 'mbr_nm';
    }
    this.fnViewList();
  },
  methods: {
    // 구독자 리스트 조회
    fnViewList : async function(){
        this.saveQueryParams('queryParams', this.search); // 검색조건 저장
        try {
            this.$setLoading(true);
            const res = await find(toRaw(this.search));           
            this.list = res.data.data.list; // 게시물 목록             
            this.listCnt = res.data.data.pagination.totalRecordCount; // 게시판 관리 목록 갯수
            this.search = res.data.data.pagination; // 페이징처리 및 검색 내용

        } catch (error) {           
            // alert('에러가 발생했습니다.\n시스템관리자에게 문의하세요.');
            alert(this.$getCmmnMessage('err005'));
        } finally {
            this.$setLoading(false);
        }
    },
    // 메일발송폼 오픈
    mailFormDrow : function(){            
        const vm = this;

        if(this.checkList.length == 0){
            alert('EMAIL 발송을 위한 구독자를 선택해 주세요');
            return false;
        }
        
        this.mailForm = true;
      
      //  if( this.editorCreate == false){           
            setTimeout(function(){
              nhn.husky.EZCreator.createInIFrame({             
               oAppRef: vm.oEditors,
                elPlaceHolder: "smart",
                sSkinURI: "/client/smarteditor2-2.8.2.3/SmartEditor2Skin.html",
                htParams: {
                    bUseToolbar: true,				// 툴바 사용 여부 (true:사용/ false:사용하지 않음)
                    bSkipXssFilter: true,
                    bUseVerticalResizer: true,
                    bUseModeChanger: true
                },
                fCreator: "createSEditor2"
              });
            }, 50);           
    //    }            

        this.editorCreate = true;
    },
    // 메일창 닫기 
    mailFormOff : function(){
        const oEditors = this.oEditors;
       // oEditors.getById["smart"].exec("SET_IR", [""]);
        this.mailForm = false;      
        this.email.email_content = '';
        this.email.email_title = '';
    },

    // 모든 유저 정보 가져오기
    allcheck : async function(){
      this.saveQueryParams('queryParams', this.search); // 검색조건 저장
      try {
            this.$setLoading(true);
            const res = await allcheck(toRaw(this.search));        
            this.checkList = res.data.data;
            this.checkAll = true;
        } catch (error) {       
            // alert('에러가 발생했습니다.\n시스템관리자에게 문의하세요.');
            alert(this.$getCmmnMessage('err005'));
        } finally {
            this.$setLoading(false);
        }
    },
    // 전체 클릭
    allCheckClick : function(){
      if(this.checkList.length == this.search.totalRecordCount){
        this.checkList = [];
      }else{
        this.allcheck();
      }
    },
     //등록 유효성 검사
    emailCheck: function () {
        this.oEditors.getById["smart"].exec("UPDATE_CONTENTS_FIELD", []);
        // 스마트에디터의 iframe에 있는 내용을 textarea로. 
        this.email.email_content = document.getElementById("smart").value;
        if (COMMON_UTIL.isEmpty(this.email.email_title) === false) {
            alert("제목을 입력해주세요.");
            return false;
        }
        if (COMMON_UTIL.isEmpty(this.email.email_content) === false || this.email.email_content === "<p><br></p>") {
            alert("내용을 입력해주세요.");
            return false;
        }

       // if(confirm(this.$getCmmnMessage("cnf010","현재 내용으로 메일을 "))){
        if(confirm("현재 내용으로 메일을 전송하시겠습니까?")){
          this.sendMail();
        }      
    },

    // 메일발송
    sendMail : async function(){
      const temp = {
                      'idList' : this.checkList,
                      'title' : this.email.email_title,
                      'contents' : this.email.email_content,
                      'eventCd' : 'm0101'
                   };
      try {
        this.$setLoading(true);
        const res = await sendEmail(temp);    
        alert(res.data.message);
        this.mailFormOff();
      } catch (error) {      
        // alert('에러가 발생했습니다.\n시스템관리자에게 문의하세요.');
        alert(this.$getCmmnMessage('err005'));
      } finally {
        this.$setLoading(false);
      }         
    }
  },
  watch: {
    checkList : function(v){
        // 첱체 체크 처리
        if(this.checkList.length == this.search.totalRecordCount){
            this.checkAll = true;
        }else{
            this.checkAll = false;
        }
    },
  },
  computed: {    
  },
  mounted() {},
};
</script>

<style scoped>
.ghost {
  height: 15px;
  color: transparent;
  border: 1px dashed var(--blue);
}
.ghost * {
  display: none;
}
</style>