<template>
  <v-dialog
    v-model="props.isSettingModal"
    persistent
    width="91.875rem"
  >
    <div class="v-common-dialog-wrapper custom-dialog alert">
      <div class="modal-tit">
        <strong>Dashborad</strong>
        <button
          class="btn-close"
          @click="fnClose()"
        />
      </div>
      
      <div class="v-common-dialog-content type--z">
        <div class="dash--set--contents">
          <div class="set--list">
            <!-- 왼쪽 배열 리스트 : S -->
            <div class="left--cell">
              <v-radio-group
                v-model="layoutType"                
                class="custom-radio"
                @change="fnLayoutChange"
              >
                <v-radio
                  v-for="(item, index) in layoutTypeList"
                  :key="index"
                  :label="item.value"
                  :value="item.value"
                  class="radio_n"
                >
                  <template #label>
                    <div class="db--list--set--wrap">
                      <h2>{{ item.name }}</h2>
                      <div :class="item.class" />
                    </div>                    
                  </template>
                </v-radio>
              </v-radio-group>
            </div>
            <!-- 왼쪽 배열 리스트 : E -->

            <!-- 오른쪽 디테일 리스트 : S -->
            <div class="right--cell">
              <div>
                <h2>{{ fnGetLayoutTypeInfo('name') }}</h2>
                <div class="dashboard--detail--contents">
                  <div class="detail--list">
                    <div
                      v-for="(type, index) in fnGetLayoutTypeInfo('sort')"
                      :key="`${type}-${index}`"
                    >
                      <h2>{{ fnGetLayoutTypeInfo(type) }}</h2>
                      <div class="group--wrapper">
                        <v-radio-group
                          v-model="widgetType[type]"                
                          class="custom-radio"
                        >
                          <v-radio
                            v-for="(widgets, idx) in widgetDetails[type]"
                            :key="`${type}-widget-${idx}`"
                            :label="widgets.widgetId"
                            :value="widgets.widgetId"
                            class="radio_n"
                          >
                            <template #label>
                              <div class="db--detail--list--set--wrap size--14">
                                <h2>{{ widgets.widgetName }}</h2>
                                <div class="db--set--01 size--v--box">
                                  {{ widgets.widgetName }} Image
                                </div>
                              </div>                    
                            </template>
                          </v-radio>
                        </v-radio-group>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <!-- 오른쪽 디테일 리스트 : E -->
          </div>
        </div>
      </div>
      <div class="btn-wrap nw--btn--wrap">
        <div />
        <div class="inner--btn--wrap">
          <v-btn
            class="custom-btn btn-white mini"
            @click="fnClose()"
          >
            <i class="ico" />
            취소
          </v-btn>
          <v-btn
            class="custom-btn btn-blue mini"
            @click="fnSaveDashboardSetting()"
          >
            <i class="ico" />
            확인
          </v-btn>
        </div>
      </div>
    </div>
  </v-dialog>  
</template>

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

  // props
  const props = defineProps({
    isSettingModal: Boolean,
  })

  // 참조가능 데이터 설정
  defineExpose({
    fnInit,
  })


  // 발신 이벤트 선언
  const emit = defineEmits(["closeModal"]);
  const i18n = useI18n();

  /***********************
   *     data & created
   ************************/
  // Layout 목록
  const layoutTypeList = ref([
    {name: 'Dashboard #1', value: 'LAYOUT01', class: 'db--set--01', sort: ['CORE', 'USER', 'RANE'],  CORE: 'CORE (12 X 14)', USER: '가입자 (12 X 10)', RANE: 'RAN (12 X 24)'},
    {name: 'Dashboard #2', value: 'LAYOUT02', class: 'db--set--02', sort: ['CORE', 'USER', 'RANE'], CORE: 'CORE (12 X 12)', USER: '가입자 (12 X 12)', RANE: 'RAN (24 X 12)'},
    {name: '현황판', value: 'LAYOUT03', class: 'db--set--03', sort: ['CORE', 'RANE', 'USER'], CORE: 'CORE (6 X 24)', USER: '가입자 (6 X 24)', RANE: 'RAN (12 X 24)'},
  ]);

  // 사용자 위젯 정보
  const userDashType = computed(() => useAuthStore().getDashType || layoutGroupList[0].value);
  // 사용자 위젯 정보
  const userWidget = computed(() => useAuthStore().getWidgets || [])

  // 레이아웃별 위젯 목록 (전체 목록)
  const widgetDetails = ref({
    CORE: [],
    USER: [], 
    RANE: [],
  });
  // 레이아웃 타입
  const layoutType = ref();
  // 위젯 타입 
  const widgetType = ref({
    CORE: '',
    USER: '', 
    RANE: '',
  });



  /***********************
   *     Methods
   ************************/
  /** 모달 시작 */ 
  function fnInit() {
    //레이아웃 기본값 셋팅
    layoutType.value = useAuthStore().getDashType || layoutGroupList[0].value;

    fnGetDashboardWidgetList(layoutType.value);
  }

  /** 모달 닫기 */ 
  function fnClose(isReload = false) {
    fnReset()
    emit('closeModal', {isReload: isReload})
  }

  /** 데이터 초기화 */ 
  function fnReset() {
    widgetDetails.value = {
      CORE: [],
      USER: [], 
      RANE: [],
    }
    widgetType.value = {
      CORE: '',
      USER: '', 
      RANE: '',
    }
  }

    /** 레이아웃 선택 */
  function fnLayoutChange() {
    fnGetDashboardWidgetList(layoutType.value)
  }

  /** 레이아웃 정보 가져오기 from layoutTypeList */
  function fnGetLayoutTypeInfo(key, type) {
    if(!type) type = layoutType.value;
    const layout = layoutTypeList.value.find((item) => item.value == type);

    return layout ? (layout[key] || '') : '';
  }

  /** 사용자 지정 위젯 정보 가져오기 from userWidget */
  function fnGetUserWidgetInfo(key, type) {
    const widget = userWidget.value.find((item) => item.widgetGrp == type);

    return widget ? (widget[key] || '') : ''; 
  }

  /** 위젯 리스트 조회 (전체 리스트) */
  function fnGetDashboardWidgetList(type) {

    fnReset();
    const params = {layoutType: type}
    useAxios().get(apiUrl.getDashboardWidgetList, {params: params}).then((res) => {
      if(res.data.resCode === '200') {
        const widgets = res?.data?.data || [];

        // 타입별 Object 생성
        if(widgets && widgets.length > 0) {
          widgetDetails.value = widgets.reduce((acc, cur, idx) => {
            const { widgetGrp } = cur;

            if(acc[widgetGrp]) acc[widgetGrp].push(cur);
            else acc[widgetGrp] = [cur];

            // 기본값 셋팅
            if(cur.defaultYN == 'Y') {
              widgetType.value[cur.widgetGrp] = cur.widgetId;
            }

            return acc;
          }, {})
        }

        // 선택한 레이아웃이 사용자지정 레이아웃인 경우 사용자가 선택한 값으로 기본값 셋팅
        if(type == userDashType.value) {
          widgetType.value.CORE =  fnGetUserWidgetInfo('widgetId', 'CORE');
          widgetType.value.USER =  fnGetUserWidgetInfo('widgetId', 'USER');
          widgetType.value.RANE =  fnGetUserWidgetInfo('widgetId', 'RANE');
        } 
      }
      $log.debug("[settingModal][fnGetTenantList][success]")
    }).catch((error)=>{
      $log.debug("[settingModal][fnGetDashboardWidgetList][error]")
      useErrorHandler().fnSetCommErrorHandle(error, fnGetDashboardWidgetList)
    }).finally(()=>{
      $log.debug("[settingModal][fnGetDashboardWidgetList][finished]")
    })
  }


  function fnSaveDashboardSetting() {
    const params = {
      dashType: layoutType.value, 
      widgets: [
        {
          areaType: 'AREA01', widgetId: widgetType.value.CORE
        },
        {
          areaType: layoutType.value == 'LAYOUT03' ? 'AREA03' : 'AREA02', widgetId: widgetType.value.USER
        },
        {
          areaType: layoutType.value == 'LAYOUT03' ? 'AREA02' : 'AREA03', widgetId: widgetType.value.RANE
        },
      ]
    }

    useAxios().post(apiUrl.myInfoUpdate, params).then((res) => {
      $toast.success(i18n.t('common.updateSuccessMsg'))

      useAuthStore().setDashType(layoutType.value);

      const authWidget = Object.keys(widgetType.value).map((type) => {
        const widgetId = widgetType.value[type];
        const widgetDetail = widgetDetails.value[type].find((w) => w.widgetId == widgetId);
        const param = params.widgets.find((w) => w.widgetId == widgetId);

        return {
          accountId: useAuthStore().getAccountId,
          areaType: param.areaType, 
          widgetGrp: type, 
          widgetId: widgetId,
          widgetName: widgetDetail.widgetName,
          widgetSize: widgetDetail.widgetSize,
          widgetWh: widgetDetail.widgetWh
        }
      })

      useAuthStore().setWidgetsUpdate(authWidget);

      fnClose(true);

      $log.debug("[settingModal][fnSaveDashboardSetting][success]")
    }).catch((error)=>{
      $log.debug("[settingModal][fnSaveDashboardSetting][error]", error)
      useErrorHandler().fnSetCommErrorHandle(error, fnSaveDashboardSetting)
    }).finally(()=>{
      $log.debug("[settingModal][fnSaveDashboardSetting][finished]")
    })
  }
</script>