<template>
  <div class="ne--topology--pop">
    <div class="v-common-dialog-wrapper custom-dialog">
      <div class="modal-tit">NE Topology</div>
      <div class="v-common-dialog-content">
        <div class="dialog-tree">
          <div class="tree-area">
            <div class="tree-depth1">
              <ul>
                <li class="depth1-item" v-for="(tenant, index) in myTreeView" :key="index">
                  <div class="depth-item-tit depth1-item-tit" :class="[tenant.fold ? '' : 'down']">
                    <button class="arr" :class="[tenant.neGroupList.length == 0 ? 'nor' : '']" @click="tenant.neGroupList.length > 0 && (tenant.fold = !tenant.fold)"></button>
                    <i class="ico"></i>
                    <strong>{{ tenant.tenantName }}{{tenant.neGroupList.length > 0 ? '('+tenant.neGroupList.length+')': ''}}</strong>
                    <!-- <button class="btn-tree btn-add" @click="addTree2(item1, index)"></button> -->
                  </div>
                  <div class="tree-depth2" v-if="tenant.fold">
                    <ul>
                      <li class="depth2-item" v-if="tenant.add">
                        <div class="depth-item-tit depth2-item-tit depth-item-reg">
                          <button class="arr"></button>
                          <i class="ico"></i>
                          <v-text-field 
                            class="custom-input mini" 
                            placeholder=""
                            v-model="addGroupTitle"
                          ></v-text-field>
                          <button class="btn-tree btn-save" @click="saveTree2(tenant)"></button>
                        </div>
                      </li>
                      <li class="depth2-item" v-for="(neGroup, index2) in tenant.neGroupList" :key="index2">
                        <div class="depth-item-tit depth2-item-tit" :class="[neGroup.fold ? '' : 'down']">
                          <button class="arr"  @click="neGroup.fold = !neGroup.fold"></button>
                          <i class="ico"></i>
                          <v-checkbox
                            class="custom-check type2"
                            hide-details
                            v-model="neGroup.isAllCheck"
                            @update:modelValue="fnAllCheck($event, neGroup)">
                            <template v-slot:label>{{neGroup.neGroup}}{{neGroup.neList.length > 0 ? '('+neGroup.neList.length+')': ''}}</template>
                          </v-checkbox>
                          <!-- <button class="btn-ne-add" @click="neRegPop = true"><i class="plus"></i>NE</button>
                          <button class="btn-tree btn-pos"></button> -->
                        </div>
                        <div class="tree-depth3" v-if="neGroup.fold">
                          <ul>
                            <li class="depth3-item" v-for="(ne, index3) in neGroup.neList" :key="index3">
                              <div class="depth-item-tit depth3-item-tit">
                                <i class="ico" :class="getNeType(ne.neType)"></i>
                                <v-checkbox
                                  class="custom-check type2"
                                  hide-details
                                  v-model="neGroup.selectNeList"
                                  :value="ne.neId"
                                  :id="neGroup.neGroup+ne.neId"
                                  @update:modelValue="fnCheckNeBox($event, neGroup)">
                                  <template v-slot:label v-if="ne.modify == false">{{ ne.neName }}</template>
                                </v-checkbox>
                                <!-- <v-text-field 
                                  v-if="ne.modify"
                                  class="custom-input mini" 
                                  v-model="treeName3"
                                ></v-text-field> -->
                                <!-- <button class="btn-tree btn-mod" v-if="ne.modify == false" @click="txtModify(ne)" ></button>
                                <button class="btn-tree btn-save" v-if="ne.modify" @click="txtSave(ne)"></button> -->
                              </div>
                            </li>
                          </ul>
                        </div>
                      </li>
                    </ul>
                  </div>
                </li>
              </ul>
            </div>
          </div>
        </div>
      </div>
      <div class="btn-wrap">
        <v-btn
          class="custom-btn btn-white mini"
          @click="$emit('closePop')"
        >
          취소
        </v-btn>
        <v-btn
          class="custom-btn btn-blue mini"
          @click="fnSave"
        >
          선택
        </v-btn>
      </div>
    </div>
  </div>

</template>

<script setup>
  /***********************
   *     import
   ************************/
  import { useI18n } from "vue-i18n"
  import useUtil from "@/composables/useUtil"
  import useValid from "@/composables/useValid"
  /***********************
   *     plugins inject
   ************************/
  const { $toast, $log, $dayjs, $eventBus } = useNuxtApp();

  // props
    const props = defineProps({
      isTopologyPop: Boolean,
    })
    // 참조가능 데이터 설정
  defineExpose({
    fnInit,
  })
  // 발신 이벤트 선언
  const emit = defineEmits(["closePop", "selectTarget"])
  /***********************
   *     data & created
   ************************/
  const coreList = ['AMF', 'SMF', 'UDC', 'MEC', 'UPF']
  const ranList = ['CU', 'DU', 'RU', 'AU']
  const myTreeView = ref([])
  const userLevel = ref('')
  const userTenant = ref('')
  /***********************
   *     Watch & computed
   ************************/
  const getNeType = computed(() => {
    return (val) => {
      if(!useUtil.isNull(val)) {
        if(coreList.includes(val)) return 'core'
        else if(ranList.includes(val)) return 'ran'
      }else return ''
    }
  })
  /***********************
   *     Methods
   ************************/
  onMounted(() =>{
    userTenant.value = useAuthStore().getTenantName
    userLevel.value = useAuthStore().getAccountLevel
    /*
      userlevel구분
      {title: 'superAdmin', value: -1},
      {title: 'adminSds', value: 0},
      {title: 'managerBusiness', value: 1},
      {title: 'operatorBusiness', value: 2}
    */
    fnInit()
  })
  function fnInit(){
    fnGetNeTopology()
  }
  /**
   * NE Topology 트리뷰 데이터 조회
   */
  function fnGetNeTopology(){
    useAxios().post(useApi.getTopology).then((res) => {
      $log.debug("[neMgmt][fnGetNeTopology][success]")
      let list = res.data.data
      let temp = []
      list.forEach((item, idx) => {
        let depth1 = {}
        depth1.tenantName = item.tenantName
        depth1.fold = true
        depth1.neGroupList = []
        if(item.neGroupList){
          item.neGroupList.forEach((neGroup, idx2) => {
            let depth2 = {}
            depth2.neGroup = neGroup.neGroup
            depth2.fold = true
            depth2.add = false
            depth2.neList = []
            depth2.isAllCheck = false
            depth2.selectNeList = []
            if(neGroup.neList && neGroup.neList.length > 0){
              neGroup.neList.forEach((ne, idx3)=> {
                let depth3 = {}
                depth3.neName = ne.neName
                depth3.neId = ne.neId
                depth3.neType = ne.neType
                depth3.upfNum = ne.upfNum
                depth3.customerType = ne.customerType
                depth3.modify = false
                depth2.neList.push(depth3)
              })
              if(depth2.neList.length > 0){
                depth1.neGroupList.push(depth2)
              }
            }
          })
        }
        if(userLevel.value == 0 || userLevel.value == -1){
          if(depth1.neGroupList.length > 0){
            temp.push(depth1)
          }
        } else{
          if(depth1.neGroupList.length > 0 && userTenant.value == depth1.tenantName){
            temp.push(depth1)
          }
        }
      })
      myTreeView.value = _cloneDeep(temp)
    }).catch((error)=>{
      $log.debug("[neMgmt][fnGetNeTopology][error]")
      useErrorHandler().fnSetCommErrorHandle(error, fnGetNeTopology)
    }).finally(()=>{
      $log.debug("[neMgmt][fnGetNeTopology][finished]")
    })
  }
  const checkList = ref([])
  function fnAllCheck(event, obj) {
    if(event) {
      obj.neList.forEach((item) => {
        obj.selectNeList.push(item.neId)
      })
    }else{
      obj.selectNeList = []
    }
  }
  function fnCheckNeBox(event, group){
    group.isAllCheck = group.selectNeList.length === group.neList.length
  }
  function fnSave(){
    let selectItems = { 
      tenantName: [],
      groupName: [],
      neName: [],
      singleData: []
    }
    myTreeView.value.forEach((tenant)=>{
      let successfulNeGroups = []
      let failedNeGroups = []
      tenant.neGroupList.forEach((neGroup)=>{
        let neGroupChk = neGroup.neList.every((ne,idx)=>{
          let neChk = neGroup.selectNeList.includes(ne.neId)
          return neChk
        })
        if(neGroupChk){
          successfulNeGroups.push(neGroup)
        } else{
          failedNeGroups.push(neGroup)
        }
      })
      //전부선택시 테넌트명 전달
      if(failedNeGroups.length == 0){
        if(tenant.neGroupList.length > 0){
          if(tenant.neGroupList[0].neList.length > 0){
            selectItems.tenantName.push(tenant.tenantName)
          }
        }
      } else if(successfulNeGroups.length > 0){ //전부 선택하지 않았을시 그룹명 전달
        successfulNeGroups.forEach(item=>{
          selectItems.groupName.push(item.neGroup)
        })
      }
      //전부선택이 아닌값중 선택한값
      failedNeGroups.forEach(group=>{
        group.neList.forEach((ne) => {
          if(group.selectNeList.includes(ne.neId)) {
            let obj = {}
            obj.tenantName = tenant.tenantName
            obj.neGroup = group.neGroup
            obj.neName = ne.neName
            obj.neId = ne.neId
            selectItems.neName.push(obj)
          }
        })
      })
      //이벤트 이력 개별 neName값
      tenant.neGroupList.forEach((neGroup)=>{
        neGroup.neList.forEach((ne) => {
          if(neGroup.selectNeList.includes(ne.neId)) {
            let obj = {}
            obj.tenantName = tenant.tenantName
            obj.neGroup = neGroup.neGroup
            obj.neName = ne.neName
            obj.neId = ne.neId
            selectItems.singleData.push(obj)
          }
        })
      })
    })
    emit('selectTarget', selectItems)
  }
</script>
<style lang="scss" scoped>
  .checked-text{
    color:#7ba1c5;
  }
  .label-text{
    font-size: 0.75rem;
    margin-left: 0.63rem;
    line-height: 1.06rem;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
    display: block;
  }
</style>
