<template>
  <!-- <div class="wrap bg-wrap"> -->
  <div>
    <div class="dimmed modal52" @click="ModalClose();"></div>
    <div class="popup-wrap modal52">

      <!-- 발신번호 차단 신규 등록 -->
      <div class="popup modal52 popup_form">
        <div class="pop-head">
          <h3 class="pop-tit">발신번호 차단 신규 등록</h3>
        </div>
        <form autocomplete="off">
          <table>
            <tbody>
            <tr>
              <th>발신번호</th>
              <td><input type="text" placeholder="- 자 제외 숫자만 입력" v-model.trim="blckSndrno"
                         @keypress="onlyNum" @input="onlyNum" minlength="10" maxlength="11" ref="_blckSndrno"></td>
            </tr>
            <tr>
              <th>발송타입</th>
              <td v-if="code === null || code === ''">
                <div v:class="select_box">
                  <select name="" id="right" v-model.trim="sndblckTpCd" ref="sndblckTpCd">
                    <option v-for="(option, i) in tpType" :value="option.code" v-bind:key="i">
                      {{ option.codeNm }}
                    </option>

                  </select>
                </div>
              </td>
            </tr>
            <tr>
              <th>차단사유</th>
              <td>
                <div>
                  <select name="" id="" v-model.trim="blckRsnCd" ref="blckRsnCd">
                    <option v-for="(option, i) in rsnType" :value="option.code" v-bind:key="i">
                      {{ option.codeNm }}
                    </option>
                  </select>
                </div>
              </td>
            </tr>
            <tr>
              <th>메모</th>
              <td class="sender"><textarea class="memo_text" v-model.trim="meno" ref="meno" maxlength="1000"
                                           @input="memoLimitByte()"></textarea></td>
            </tr>
            </tbody>
          </table>
        </form>
        <div class="popup-btn2">
          <button class="btn-pcolor" @click="regisConfirm()">등록</button>
          <button class="btn-default" @click="ModalClose();">취소</button>
        </div>
      </div>
      <common-modal ref="commonModal"></common-modal>
      <validation-confirm-popup ref="ValidationConfirmPopup"></validation-confirm-popup>

    </div>
  </div>

</template>
<script>
import api from '@/service/api';
import riskMgtApi from '../service/riskMgtApi'
import {utils_mixin, chkPattern2} from '../service/mixins';
import lodash from "lodash";
// import commonModal from "@/components/modal/commonModal";
import ValidationConfirmPopup from './ValidationConfirmPopup.vue';

export default {
  mixins: [utils_mixin, chkPattern2],
  data() {
    return {
      props: {},
      row: {},
      rsnType: [],
      tpType: [],
      blckSndrno: '',
      sndblckTpCd: '01',
      blckRsnCd: '01',
      meno: '',
      code: "",
      LINE_FEED: 10, // '\n',
      maxByte: 2000,
      // params: {
      //     'blckSndrno' : ''
      //     ,'sndblckTpCd' : '01'
      //     ,'blckRsnCd' : '02'
      //     ,'meno' : ''
      // }
    }
  },
  create() {
    this.setCodeDate();
    this.formReset();
  },
  mounted() {
    //this.sndblckTpCd = '01'
  },
  components: {
    // commonModal,
    ValidationConfirmPopup
  },
  methods: {
    //모달 띄우기
    ModalOpen() {

      var dimmed = document.getElementsByClassName('modal52');
      for (var i = 0; i < dimmed.length; i++) {
        dimmed[i].style.display = 'block';
      }
      this.setCodeDate();
    },
    // 모달 끄기
    ModalClose() {
      this.formReset();

      var dimmed = document.getElementsByClassName('modal52');
      for (var i = 0; i < dimmed.length; i++) {
        dimmed[i].style.display = 'none';
      }

    },
    // 저장 후 부모창 호출
    toComplete() {
      this.$parent.$refs.table.reloadData();
      this.ModalClose();
    },
    async doInsert() {
      // if(this.doValidate() && this.regisConfirm()){
      this.row.blckSndrno = this.blckSndrno;
      this.row.sndblckTpCd = this.sndblckTpCd;
      this.row.blckRsnCd = this.blckRsnCd;
      this.row.meno = this.meno;
      this.regId = 'admin';
      console.log(this.row);

      try {
        const response = await riskMgtApi.insertIntrcp(this.row);
        const result = response.data;
        if (result != null && result.retCode == "0000") {
          this.row.title = '발신번호 차단';
          this.row.msg1 = '성공 하였습니다.';
          this.$parent.alertInsert(this.row);
        }else if (result != null && result.retCode == "4018") {
          this.row.title = '발신번호 차단';
          this.row.msg1 = '이미등록된 발신번호입니다.';
          this.$parent.alertInsert(this.row);
          return false;
        }
        this.toComplete();
      } catch (err) {
        console.log(err);
        this.row.title = '발신번호 차단';
        this.row.msg1 = '실패 하였습니다.';
        this.$parent.alertInsert(this.row);
      }
      // }
    },
    setCodeDate() {
      // 발송타입
      api.commCode({'grpCd': 'SNDBLCK_TP_CD'}).then(response => {
        this.tpType = response.data.data.list;
      });
      api.commCode({'grpCd': 'SNDBLCK_RSN_CD'}).then(response => {
        this.rsnType = response.data.data.list;
      });
    },

    doValidate() {
      if (this.isNull(this.blckSndrno)) {
        this.row.title = '발신번호 차단';
        this.row.msg1 = '발신번호를 입력해주세요.';
        this.$parent.alertInsert(this.row);
        this.$refs._blckSndrno.focus();
        return false;
      }
      const hp = this.blckSndrno;
      if (!this.isNull(hp) && !this.isMobile(hp)) {
        this.row.title = '발신번호 차단';
        this.row.msg1 = '발신번호 형식이 잘못되었습니다. 확인 해주세요.';
        this.$parent.alertInsert(this.row)
        this.$refs._blckSndrno.focus();
        return false;
      }
      this.row.blckSndrno = this.blckSndrno;
      this.row.sndblckTpCd = this.sndblckTpCd;
      this.row.blckRsnCd = this.blckRsnCd;
      this.row.meno = this.meno;
      return true;
    },
    formReset() {
      var type = this.insertType;
      Object.assign(this.$data, this.$options.data());
      this.insertType = type;
    },
    regisConfirm() {
      if (this.doValidate()) {
        this.$refs.ValidationConfirmPopup.confirmInsertOpen();
      }
    },
    // 바이트길이 구하기
    getByteLength: function (decimal) {
      return (decimal >> 7) || (this.LINE_FEED === decimal) ? 2 : 1
    },

    getByte: function (str) {
      return str
          .split('')
          .map((s) => s.charCodeAt(0))
          .reduce((prev, unicodeDecimalValue) => prev + this.getByteLength(unicodeDecimalValue), 0)
    },
    getLimitedByteText: function (inputText, maxByte) {
      const characters = inputText.split('')
      let validText = ''
      let totalByte = 0

      for (let i = 0; i < characters.length; i += 1) {
        const character = characters[i]
        const decimal = character.charCodeAt(0)
        const byte = this.getByteLength(decimal) // 글자 한 개가 몇 바이트 길이인지 구해주기
        // console.log(byte)
        // 현재까지의 바이트 길이와 더해 최대 바이트 길이를 넘지 않으면
        if (totalByte + byte <= maxByte) {
          totalByte += byte      // 바이트 길이 값을 더해 현재까지의 총 바이트 길이 값을 구함
          validText += character // 글자를 더해 현재까지의 총 문자열 값을 구함
        } else {                 // 최대 바이트 길이를 넘으면
          break                  // for 루프 종료
        }
      }
      return validText
    },

    memoLimitByte() {
      this.meno = this.getLimitedByteText(this.meno, this.maxByte);

    },	//END 바이트길이 구하기

  },

}
</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>