<template>
  <div class="contents">
    <div class="contents_wrap">
      <div class="top_wrap">
        <h3 class="title">권한 관리</h3>
        <p class="breadcrumb">시스템관리 &gt; 권한 관리 &gt; 권한 추가</p>
      </div>
      <div class="info">
        <div class="title">권한 추가</div>
      </div>
      <div class="table table_form">
        <table>
          <tbody>
          <tr class="tr_input w30">
            <th>권한명</th>
            <td colspan="5"><input type="text" v-model.trim="authNm" ref="_authNm" maxlength="100"></td>
          </tr>
          <tr class="tr_input w75">
            <th>권한 코드</th>
            <td colspan="2"><input type="text" v-model.trim="authCd" ref="_authCd" maxlength="4"></td>
            <th>상태</th>
            <td class="td_radio" colspan="2">
              <input type="radio" name="state" value="01" id="right_radio1" v-model="stat" checked>
              <label for="right_radio1">사용</label>
              <input type="radio" name="state" value="02" id="right_radio2" v-model="stat">
              <label for="right_radio2">정지</label>
            </td>
          </tr>
          <tr class="tr_input w100">
            <th>권한 설명</th>
            <td colspan="5"><input type="text" v-model.trim="authDesc" maxlength="100"></td>
          </tr>
          <tr class="tr_checkbox">
            <td class="check">
              <p>메뉴 권한 체크</p>
              <input type="checkbox" id="right_check0" ref="checkedAuthMenuAll_" v-model="checkedAuthMenuAll">
              <!--<div class="label_group">
                <label for="right_check0"></label>
                <label for="right_check0">전체 체크</label>
              </div>-->
            </td>
            <td colspan="6">
              
              <div class="div_authcheck" v-for="(upper, i) in list" v-bind:key="i">
                <p>{{ upper.name }}</p>
                <div v-for="(auth, x) in upper.list" v-bind:key="x" >
                  <div v-if="!(auth.autchkGrpno !== '' && auth.autchkGrpno !== null)">
                    <input type="checkbox" :id="'right_check'+auth.menuNo" :value="auth.menuNo" v-model="checkedAuthMenu"/>
                    <div class="label_group">
                      <label :for="'right_check'+auth.menuNo"></label>
                      <label :for="'right_check'+auth.menuNo">{{auth.name}}</label>
                    </div>
                  </div>
                  <div v-if="auth.autchkGrpno !== '' && auth.autchkGrpno !== null">
                    <input type="checkbox" :name="'oneCheck'+upper.menuNo+auth.autchkGrpno" :id="'right_check'+auth.menuNo" :value="auth.menuNo" @change="channelCheck" v-model="checkedAuthMenu"/>
                    <div class="label_group">
                      <label :for="'right_check'+auth.menuNo"></label>
                      <label :for="'right_check'+auth.menuNo">{{auth.name}}</label>
                    </div>
                  </div>
                </div>
              </div>

            </td>
          </tr>
          </tbody>
        </table>
    </div>
    <div class="pop-btn2">
      <button class="btn-default" type="button" @click="authAddCancel()">취소</button>
      <button class="btn-pcolor" type="button" @click="authAddSave()">저장</button>
    </div>
  </div>
  <common-modal ref="commmonModal"></common-modal>
  </div>
</template>

<script>

import sysMgtApi from "../service/sysMgtApi.js";
import {utils_mixin, chkPattern2} from '../service/mixins';
import commonModal from "../components/commonModal";

export default {
  name: 'authAdd',
  mixins: [utils_mixin, chkPattern2],
  data() {
    return {
      row: {},
      authType: [],
      authNm: "",
      authCd: "",
      authDesc: "",
      stat: "01", // 등록화면 상태 Default 값 지정(사용:01)
      defaultAuthMenu: ["2001", "2004", "2005", "2006", "2007", "2008", "2009", "2010", "2011", "2012", "2013", "2015", "2016", "2017", "2018", "2019", "2020", "2021", "2022", "2023", "2024", "2025"],
      checkedAuthMenu: [],
      channelAuth: "",
      list: []
    };
  },
  components: {
    commonModal,
  },
  created() {
    //this.setCodeData();
  },
  destroyed() {

  },
  mounted() {
    this.athMenuList();
  },
  methods: {
    async athMenuList() {
      this.params = {}
      try {
        const response = await sysMgtApi.athMenuList(this.params);

        const result = response.data;
        
        if (result != null && result.retCode == '0000') {
          this.list = result.data.list;
        }

      } catch(err){
        this.row.title = '권한 목록 조회 실패';
        this.row.msg1 = err;
        this.$parent.$refs.commmonModal.alertModalOpen(this.row);
        return false;
      }
    },
    doValidate() {

      // 필수 등록정보 체크
      if (this.isNull(this.authNm)) {
        this.row.title = '시스템관리';
        this.row.msg1 = '권한명을 입력해 주세요.';
        this.row.focusTaget = '1';
        this.$refs.commmonModal.alertSysModalOpen(this.row);
        return false;
      }

      if (this.isNull(this.authCd)) {
        this.row.title = '시스템관리';
        this.row.msg1 = '권한 코드를 입력해 주세요.';
        this.row.focusTaget = '2';
        this.$refs.commmonModal.alertSysModalOpen(this.row);
        return false;
      }

      if (this.authCd.length > 5) {
        this.row.title = '시스템관리';
        this.row.msg1 = '권한코드는 영문과 숫자포함 최대4자리까지 입력해주세요.';
        this.row.focusTaget = '2';
        this.$refs.commmonModal.alertModalOpen(this.row);
        return false;
      }

      if (this.isNull(this.stat)) {
        this.row.title = '시스템관리';
        this.row.msg1 = '상태를 체크해 주세요.';
        this.$refs.commmonModal.alertSysModalOpen(this.row);
        return false;
      }

      if (this.checkedAuthMenu.length == 0) {
        this.row.title = '시스템관리';
        this.row.msg1 = '메뉴 권한 체크를 해주세요.';
        this.$refs.commmonModal.alertSysModalOpen(this.row);
        return false;
      }

      return true;

    },
    authAddCancel() {
      // 권한리스트 페이지로 이동
      this.$router.push({name: 'authList'});

    },
    authAddSave() {
      if (this.doValidate()) {
        this.row.title = '시스템관리';
        this.row.msg1 = '권한 등록 저장하시겠습니까?';
        this.row.focusTaget = '0';
        this.$refs.commmonModal.confirmModalOpen(this.row);
        return false;
      }
    },
    async authInsert() {

      var reqAuthMenuArr = this.checkedAuthMenu;
      var listArr = [];
      var dataMap = {};
      if (this.channelAuth !== '') {
        dataMap.menuNo = this.channelAuth;
        listArr.push(dataMap);
      }
      for (var i = 0; i < reqAuthMenuArr.length; i++) {
        dataMap = {};
        dataMap.menuNo = reqAuthMenuArr[i];
        listArr.push(dataMap);
      }


      this.row.authCd = this.authCd;
      this.row.authNm = this.authNm;
      this.row.authDesc = this.authDesc;
      this.row.stat = this.stat;
      this.row.list = listArr;


      try {
        let response = await sysMgtApi.insertAuth(this.row);
        const result = response.data;
        if (result != null && result.retCode == "0000") {
          //alert('저장 하였습니다.');
          // 권한리스트 페이지 이동
          this.$router.push({name: 'authList'});

        } else if (result.retCode == "4017") {
          //alert("권한코드가 이미 존재합니다.");
          //this.$refs._authCd.focus();
          this.row.title = '시스템관리';
          this.row.msg1 = '권한코드가 이미 존재합니다.';
          this.row.focusTaget = '2';
          this.$refs.commmonModal.alertSysModalOpen(this.row);
          return false;

        } else {
          //alert("실패 하였습니다.");
          this.row.title = '시스템관리';
          this.row.msg1 = '실패 하였습니다.';
          this.row.focusTaget = '0';
          this.$refs.commmonModal.alertSysModalOpen(this.row);
          return false;
        }

      } catch (err) {
        //alert("실패 하였습니다.");
        this.row.title = '시스템관리';
        this.row.msg1 = '실패 하였습니다.';
        this.row.focusTaget = '0';
        this.$refs.commmonModal.alertSysModalOpen(this.row);
        return false;
      }

    },
    checkFocus() {
      if (this.row.focusTaget === '1') {
        this.$refs._authNm.focus();
      } else if (this.row.focusTaget === '2') {
        this.$refs._authCd.focus();
      }
    },
    confirmCalbackFnc(props) {
      if (props.result) {
        this.authInsert();
      }
    },
    channelCheck(e, len, isEventCall){
      if(e.target.checked){
        for(const target of document.getElementsByName(e.target.name)){
          if(target != e.target){
            target.checked = false;
            this.checkedAuthMenu = this.checkedAuthMenu.filter((data) => {
              if(data != target.value){
                return data;
              }
            });

          }
        }
      }
    }
  },
  computed: {
    // 체크박스 전체선택 기능
    checkedAuthMenuAll: {
      get: function () {
        if (this.defaultAuthMenu.length === this.checkedAuthMenu.length) {
          if (this.channelAuth === '') {
            return false;
          }
          return true;
        } else {
          return false;
        }
      },
      set: function (e) {
        if (e) {
          this.checkedAuthMenu = this.defaultAuthMenu;
          if (this.channelAuth === '') {
            this.channelAuth = '2002';
          }
        } else {
          this.checkedAuthMenu = [];
          this.channelAuth = '';
        }
      }
    }
  }
};
</script>