<template>
	<!-- <div class="wrap bg-wrap"> -->
	<div>
		<div class="dimmed modal33" @click="excelPopClose();"></div>
		<div class="popup-wrap modal33">
      <div class="popup modal33 popup_form">
        <div class="pop-head">
          <h3 class="pop-tit">사용자 ID 대량 생성</h3>
        </div>
          <table>
            <tbody>
            <tr>
              <th>관리자 ID</th>
              <td>{{adminId}}</td>
            </tr>
            <tr>
              <th>사용자 ID 업로드</th>
              <td>
                <div class="popup-btn2 bulk">
                  <input type="file" ref="file" style="display: none" @change="readFile" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"/>
                  <button class="btn-default" @click="sampleDown">샘플 다운로드</button>
                  <button class="button btn-p2color" @click="$refs.file.click()">파일 업로드</button>
                </div>
                <p class="file" id="uploadFile"></p>
              </td>
            </tr>
            </tbody>
          </table>
        <div class="popup-btn2">
          <button class="btn-pcolor" @click="saveExcel">저장</button>
          <button class="btn-default" @click="excelPopClose">취소</button>
        </div>
      </div>
      <common-modal ref="commmonModal"></common-modal>
		</div>
	</div>
</template>

<script>
import api from '@/service/api';
import custMgtApi from "../service/custMgtApi.js";
import { utils_mixin, chkPattern2 } from '../service/mixins';
import xlsx from '@/common/excel';
import moment from 'moment';
import XLSX from 'xlsx';
import commonModal from "@/components/modal/commonModal";

export default {
	name: "memberBulkRegPop",
	mixins: [utils_mixin, chkPattern2],
	data(){
        return{
			row: {},
			excelHeader: [],
			pageType: 'SAMPLE',
			adminId:'',
			varList : ["이름","휴대폰번호","기타1","기타2","기타3","기타4"],
            varList2 : ["이름","기타1","기타2","기타3","기타4"],
            nData : [],
            oData : [],
			totalItems: 0,
        }
    },
  components: {
    commonModal,
  },
	created(){
		this.getExcelHeader();
    },
	methods :{
		// 모달 띄우기
		excelPopOpen(adminId, totalItems){
			this.adminId = adminId;
			this.totalItems = totalItems;
			console.log(totalItems)
			var excelPop = document.getElementsByClassName('modal33');
			for(var i = 0; i < excelPop.length; i++){
				excelPop[i].style.display = 'block';
			}
		},
		// 모달 끄기
		excelPopClose(){
			//this.formReset();
			var excelPop = document.getElementsByClassName('modal33');
			for(var i = 0; i < excelPop.length; i++){
				excelPop[i].style.display = 'none';
			}

		},
		// 저장 후 부모창 호출.
		toComplete(){
			this.getParent('custList').$refs.table.reloadData();
			this.excelPopClose();
        },
		async doInsert(){
            if(this.doValidate() && window.confirm('등록 하시겠습니까?')){
                try {
					const response = await custMgtApi.insertTestId(this.row);
					const result = response.data;
					if (result != null && result.retCode == "0000") {
            this.row.title = '청약고객관리';
            this.row.msg1 = '저장 하였습니다.';
            this.$refs.commmonModal.alertModalOpen(this.row);
						this.toComplete();
					}
                } catch(err) {
                  this.row.title = '청약고객관리';
                  this.row.msg1 = '실패 하였습니다.';
                  this.$refs.commmonModal.alertModalOpen(this.row);
                }
            }
        },
		async sampleDown(){
			let today = moment().format('YYYYMMDDHHmmss');
			const saveFileName = `어드민_사용자ID 대량생성_${today}.xlsx`;

			let options = {
				header: this.excelHeader,
				dataOrder: 'header'
			};
			xlsx.export([], saveFileName, options).then(() => {});
		},
		getExcelHeader() {
			// 헤더를 mockup으로 관리한다.
			custMgtApi.getExcelHeader(this.pageType).then(res => {
				this.excelHeader = res;
			});
		},
		readFile(event) {

			this.nData = []
			this.oData = []

			const file = event.target.files[0];
			console.log(file.name);

			// inner Html.
			const button = document.createElement('button');
			const text = document.createElement('p');
			text.innerText = file.name;
			button.addEventListener('click', () => {
				this.delFile(event);
			})
			const root = document.getElementById('uploadFile');
			root.appendChild(text);
			root.appendChild(button);



			let reader = new FileReader();
			let tmpResult = {};
			const vm = this;
			reader.onerror = (e) => {
        this.row.title = '청약고객관리';
        this.row.msg1 = '파일을 읽는 동안 에러가 발생 했습니다.';
        this.$refs.commmonModal.alertModalOpen(this.row);
      }
      reader.onloadend = (e) => {
      }


			reader.onload = (e) => {
				let data = reader.result;
				let workbook = XLSX.read(data, {type: 'binary'});
				workbook.SheetNames.forEach(sheetName => {

					const rowObj = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName],{raw:true});
					tmpResult = rowObj;
					const limitCnt = 100;

					const totalCnt = Number(this.totalItems) + rowObj.length;

					if(totalCnt > limitCnt){
            this.row.title = '청약고객관리';
            this.row.msg1 = '100건이상은 등록되지 않습니다.';
            this.$refs.commmonModal.alertModalOpen(this.row);
						return false;
					}

					for (const [idx,r] of rowObj.entries()) {
                        if(idx > limitCnt-1 ) {
                            break;
                        }
                        let {ID,이름,휴대폰번호,이메일,ID잠금} = r;
                        ID = ''+(vm.isNull(ID)?'':ID);
                        이름 = ''+(vm.isNull(이름)?'':이름);
                        휴대폰번호 = ''+(vm.isNull(휴대폰번호)?'':휴대폰번호);
                        이메일 = ''+(vm.isNull(이메일)?'':이메일);
                        ID잠금 = ''+(vm.isNull(ID잠금)?'':ID잠금);

                        // 휴대폰번호=''+휴대폰번호;
                        if(!vm.isMobile(휴대폰번호)){
                            if(vm.isMobile2(휴대폰번호)){
                                휴대폰번호='0'+휴대폰번호;
                            }
                        }

                        let {retVal,msg } = vm.validXlxs({ID,이름,휴대폰번호,이메일,ID잠금});
                        if(retVal){
                            const pVal = [{ name:'이름',val:이름, len:20,},
                            { name:'ID잠금',val:ID잠금, len:4,},];

                            const rVal = vm.isTitle(pVal);

                            if(rVal.retVal){
                                vm.nData.push({userId:ID,userNm:이름,mdn:휴대폰번호,email:이메일,stat:ID잠금,msg});
                            }else{
                                vm.oData.push({ID,이름,휴대폰번호,이메일,ID잠금,오류내용:rVal.msg});
                            }

                        }else{
                            vm.oData.push({ID,이름,휴대폰번호,이메일,ID잠금,오류내용:msg});
                        }
                    }
				});
				console.log(vm.nData);
				console.log(vm.nData.length);
				console.log(vm.oData);
				console.log(vm.oData.length);
			};
			reader.readAsBinaryString(file);
		},
		validXlxs({이름,휴대폰번호,이메일}){
            if(this.isNull(이름)){
                return {retVal:false,msg:'이름 누락'};
            }
            if(this.isNull(휴대폰번호)){
                return {retVal:false,msg:'휴대폰번호 누락'};
            }
            if(!this.isMobile(휴대폰번호)){
                if(!this.isMobile2(휴대폰번호)){
                    return {retVal:false,msg:'휴대폰번호 형식 오류'};
                }
            }
			if(!this.emailCheck(이메일)){
				return {retVal:false,msg:'이메일 형식 오류'};
            }
            return {retVal:true,msg:'정상'};
        },
        isTitle(pVal) {
            for (const o of pVal) {
                if (this.bytes(o.val) > o.len) {
                    return {retVal:false,msg:`${o.name} 컬럼: 문자열 길이 오류(${o.len}자)`};
                }
                const strRegExp = '^[ㄱ-ㅎㅏ-ㅣ가-힣a-zA-Z0-9]*$';
                const regExp_g = new RegExp(strRegExp,'g');
                if(!(regExp_g.test(o.val))){
                    return {retVal:false,msg:`${o.name} 컬럼: 특수 문자 오류`};
                }
            }
            return {retVal:true,msg:'정상'};
        },
		delFile(event){
			console.log("del~~~~");
			const file = event.target.files[0];
			console.log(file.name);
			//this.$refs.file.reset();
			this.$refs.file.value=null;
			let element = document.getElementById("uploadFile");
				while (element.firstChild) {
				element.removeChild(element.firstChild);
			}
			// uploadFile
		},
		async saveExcel(){
			//
			this.row.adminId = this.adminId;
			this.row.list = this.nData;

			try {
				const response = await custMgtApi.insertMassUser(this.row);
				const result = response.data;
				console.log(result);
				if (result != null && result.retCode == "0000") {

					// this.totalCnt = result.data.totalCnt;
					// this.successCnt = result.data.successCnt;
					// this.failCnt = result.data.failCnt;
					// this.toComplete();/
				}
			} catch (error) {
				console.log(error);
        this.row.title = '청약고객관리';
        this.row.msg1 = '실패 하였습니다.';
        this.$refs.commmonModal.alertModalOpen(this.row);
			}

			// 오류건수.
			console.log(this.oData.length);
		},

	}
}
</script>

<style>
	.popup-btn-wrap {width: 500px; margin: auto; padding: 100px 0;}
	.popup-btn-wrap button {width: 100%; margin-bottom: 10px; height: 50px; border-radius: 5px; box-shadow: none; border: 1px solid #000; }
	.popup-btn-wrap button:hover {background: #000; color: #fff;}
</style>