<template>
  <div>
    <div class="dimmed memberInsert" @click="memberInsertModalClose();"></div>
    <div class="popup-wrap memberInsert">
      <div class="popup modal31 popup_form memberInsert">
        <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><input type="text" v-model.trim="userId" ref="_userId" @keypress="onlyId" @input="onlyId" minlength="6"
                       maxlength="16"></td>
          </tr>
          <tr>
            <th>이름</th>
            <td><input type="text" v-model.trim="userNm" ref="_userNm" @keypress="onlyRoleNm_Space"
                       @input="onlyRoleNm_Space" maxlength="100"></td>
          </tr>
          <tr>
            <th>휴대폰번호</th>
            <td><input type="text" placeholder="- 자 제외 숫자만 입력" v-model.trim="mdn" ref="_phone" @keypress="onlyNum"
                       @input="onlyNum" minlength="10" maxlength="11"></td>
          </tr>
          <tr>
            <th>이메일</th>
            <td><input type="email" v-model.trim="email" ref="_email" @keypress="onlyEmail" @input="onlyEmail"
                       maxlength="100"></td>
          </tr>
          <tr>
            <th class="center">ID 잠금</th>
            <td>
              <input type="radio" name="userStateInsert" value="01" id="user_popup_insert_radio1" v-model="stat">
              <label for="user_popup_insert_radio1">사용</label>
              <input type="radio" name="userStateInsert" value="02" id="user_popup_insert_radio2" v-model="stat">
              <label for="user_popup_insert_radio2">정지</label>
            </td>
          </tr>
          </tbody>
        </table>
        <div class="popup-btn2">
          <button class="btn-pcolor" @click="memberInsertConfirm();">저장</button>
          <button class="btn-default" @click="memberInsertModalClose();">취소</button>
        </div>
      </div>
    </div>
    <validation-confirm-modalPop ref="validationConfirmModalPop"></validation-confirm-modalPop>
<!--    <common-modal ref="commmonModal"></common-modal>-->
  </div>
</template>

<script>
import api from '@/service/api';
import custMgtApi from "../service/custMgtApi.js";
import {utils_mixin, chkPattern2} from '../service/mixins';
import lodash from "lodash";
import validationConfirmModalPop from "@/modules/custMgt/components/ValidationConfirmModalPop";
// import commonModal from "../components/commonModal";

export default {
  name: "memberRegPop",
  mixins: [utils_mixin, chkPattern2],
  watch: {
    stat() {
    }
  },
  components: {
    validationConfirmModalPop,
  },
  model: {
  },
  created() {
    this.formReset();
  },
  data() {
    return {
      row: {},
      madangId: '',
      adminId: '',
      name: '',
      mdn: '',
      email: '',
      auth: '',
      stat: "01",
      userId: "",
      userNm: "",
      code: "",
      userTotalCnt: 0,
    }
  },
  methods: {
    //사용자ID 생성 모달 Open
    memberInsertModalOpen(props) {
      this.adminId = props.adminId;
      this.userTotalCnt = props.userTotalCnt;

      // 모달 오픈
      var dimmed = document.getElementsByClassName('memberInsert');
      for (var i = 0; i < dimmed.length; i++) {
        dimmed[i].style.display = 'block';
      }
    },
    //사용자ID 생성 Confirm
    async memberInsertConfirm() {
      // confirm 팝업 노출
      if (this.doValidate()) {
        // ID 중복체크 
        try{
          this.row.adminId = this.adminId;
          this.row.userId = this.userId;
          this.row.userNm = this.userNm;
          this.row.userEmail = this.email;
          this.row.mdn = this.mdn;
          this.row.userStat = this.stat;
          const response = await custMgtApi.duplicateCheckUserId(this.row);
          const result = response.data;
          if (result != null && result.retCode == "0000") {
            this.$refs.validationConfirmModalPop.confirmInsertOpen();
          } else if (result != null && result.retCode == "4018") {
            // 이미 사용중인 ID
            this.row.title = '청약고객관리';
            this.row.msg1 = '중복된 아이디가 있습니다.';
            this.row.msg2 = '아이디를 다시 확인하여 등록 부탁드립니다.';
            this.$parent.$refs.commmonModal.alertModalOpen(this.row);
          }
        }catch(err){

        }
        
      }
    },
    //사용자ID 수정 처리
    async memberInsert() {
      this.row.adminId = this.adminId;
      this.row.userId = this.userId;
      this.row.userNm = this.userNm;
      this.row.userEmail = this.email;
      this.row.mdn = this.mdn;
      this.row.userStat = this.stat;
      try {
        const response = await custMgtApi.insertUser(this.row);
        const result = response.data;
        if (result != null && result.retCode == "0000") {
          this.row.title = '청약고객관리';
          this.row.msg1 = '사용자 생성 완료하였습니다.';
          this.$parent.$refs.commmonModal.alertModalOpen(this.row);
          this.toComplete();
        } else if (result != null && result.retCode == "4018") {
          // 이미 사용중인 ID
          this.row.title = '청약고객관리';
          this.row.msg1 = '중복된 아이디가 있습니다.';
          this.row.msg2 = '아이디를 다시 확인하여 등록 부탁드립니다.';
          this.$parent.$refs.commmonModal.alertModalOpen(this.row);
        } else {
          this.row.title = '청약고객관리';
          this.row.msg1 = '실패 하였습니다.';
          this.$parent.$refs.commmonModal.alertModalOpen(this.row);
        }
      } catch (err) {
        this.row.title = '청약고객관리';
        this.row.msg1 = '실패 하였습니다.';
        this.$parent.$refs.commmonModal.alertModalOpen(this.row);
      }
    },
    //사용자ID 생성 모달 Close
    memberInsertModalClose() {
      var dimmed = document.getElementsByClassName('memberInsert');
      for (var i = 0; i < dimmed.length; i++) {
        dimmed[i].style.display = 'none';
      }
      this.formReset();
    },
    toComplete() {
      this.row.serviceId = this.adminId;
      this.memberInsertModalClose();
      this.$parent.memberDetail(this.adminId);
    },
    async setAuthData() {
      // 권한 옵션.
      // api.commAuth().then(response => {
      //   this.authType = response.data.data.list;
      // });
      try {
				const response = await api.commAuth();
				if(response.data.retCode == '0000'){
					this.authType = response.data.data.list;
				}				
			}catch(err){
				
			}
    },
    formReset() {
      var targetAdminId = this.adminId;
      Object.assign(this.$data, this.$options.data());
      this.adminId = targetAdminId;
    },
    doValidate() {
      if (this.userTotalCnt >= 100) {
        // 사용자등록제한_최대100개까지
        this.$parent.$refs.validationConfirmPopModal.validationMaxlimitOpen();
        return false;
      }

      if (this.isNull(this.userId)) {
        this.$refs._userId.focus();
        this.row.title = '청약고객관리';
        this.row.msg1 = 'ID를 입력해 주세요.';
        this.row.focusTaget = '1';
        this.$parent.$refs.commmonModal.alertModalOpen(this.row);
        return false;
      }
      // 청약 ID  길이 체크 6~16
      var userIdlength = this.userId.length;
      if (userIdlength < 6 || userIdlength > 16) {
        this.row.title = '청약고객관리';
        this.row.msg1 = 'ID 형식에 맞지 않습니다.';
        this.row.msg2 = '확인하여 다시 등록 부탁 드립니다.';
        this.row.focusTaget = '1';
        this.$parent.$refs.commmonModal.alertModalOpen(this.row);
        return false;
      }

      if (this.isNull(this.userNm)) {
        this.row.title = '청약고객관리';
        this.row.msg1 = '이름을 입력해 주세요.';
        this.row.focusTaget = '2';
        this.$parent.$refs.commmonModal.alertModalOpen(this.row);
        return false;
      }

      if (this.isNull(this.mdn)) {
        this.row.title = '청약고객관리';
        this.row.msg1 = '휴대폰번호를 입력해주세요.';
        this.row.focusTaget = '3';
        this.$parent.$refs.commmonModal.alertModalOpen(this.row);
        return false;
      }
      const hp = this.mdn;
      if (!this.isNull(hp) && !this.isMobile(hp)) {
        this.row.focusTaget = '3';
        //this.$refs.validationConfirmPopModal.validationPhonenumberOpen();
        this.row.title = '청약고객관리';
        this.row.msg1 = '휴대폰번호 형식에 맞지 않습니다.';
        this.row.msg2 = '확인하여 다시 등록 부탁 드립니다.';
        this.row.focusTaget = '3';
        this.$parent.$refs.commmonModal.alertModalOpen(this.row);
        return false;
      }

      if (this.isNull(this.email)) {
        this.row.title = '청약고객관리';
        this.row.msg1 = '이메일을 입력해주세요.';
        this.row.focusTaget = '4';
        this.$parent.$refs.commmonModal.alertModalOpen(this.row);
        return false;
      }
      const email = this.email;
      if (!this.isNull(email) && !lodash.isEqual(email, '@') && !this.emailCheck(email)) {
        // this.$refs.validationConfirmPopModal.validationEmailOpen();
        this.row.title = '청약고객관리';
        this.row.msg1 = 'E-mail 형식에 맞지 않습니다.';
        this.row.msg2 = '확인하여 다시 등록 부탁 드립니다.';
        this.row.focusTaget = '4';
        this.$parent.$refs.commmonModal.alertModalOpen(this.row);
        return false;
      }

      if (this.isNull(this.stat)) {
        this.row.title = '청약고객관리';
        this.row.msg1 = '상태를 선택 해주세요.';
        this.$parent.$refs.commmonModal.alertModalOpen(this.row);
        return false;
      }

      return true;
    },
    checkFocus() {
      if (this.row.focusTaget === '1') {
        this.$refs._userId.focus();
      } else if (this.row.focusTaget === '2') {
        this.$refs._userNm.focus();
      } else if (this.row.focusTaget === '3') {
        this.$refs._phone.focus();
      } else if (this.row.focusTaget === '4') {
        this.$refs._email.focus();
      }
    },
    checkPhoneFocus() {
      this.$refs._phone.focus();
    },
    checkEmailFocus() {
      this.$refs._email.focus();
    },
    checkIdDupFocus() {
      this.$refs._userId.focus();
    },
  }
}
</script>