<!--
  Program: SoldToCode.vue  
  Description: Page to view, add and delete mail group mapping list
-->

<template>
  <div class="ui--content-wrapper">
    <sdl-breadcrumb></sdl-breadcrumb>
    <!-- Detail Info Area -->
    <div class="ui--view-container">
      <h4 class="mb-3">Select</h4>
    </div>
    <table class="table table-bordered ui--table-form mb-5">
      <colgroup>
        <col style="width:13%" />
        <col style="width:35%" />
        <col style="width:13%" />
        <col style="width:35%" />
      </colgroup>
      <tbody>
        <tr>
          <th class="text-nowrap" scope="row">{{ $t('sdl.mailGroup.label.mailGroupName') }}</th>
          <td>{{ mailGroupItem.label }}</td>
          <th class="text-nowrap" scope="row">{{ $t('sdl.common.label.used') }}</th>
          <td>{{ mailGroupItem.used }}</td>
        </tr>

        <tr>
          <th class="text-nowrap" scope="row">{{ $t('sdl.common.label.description') }}</th>
          <td colspan="3">{{ mailGroupItem.description }}</td>
        </tr>
        <tr>
          <th class="text-nowrap" scope="row">{{ $t('sdl.common.label.createdBy') }}</th>
          <td>{{ mailGroupItem.firstRegrName }}</td>
          <th class="text-nowrap" scope="row">{{ $t('sdl.common.label.createdDate') }}</th>
          <td>{{ $filters.dateFormat(mailGroupItem.firstRegDatetime, $t('data-format.date.ymd')) }}</td>
        </tr>
        <tr>
          <th class="text-nowrap" scope="row">{{ $t('sdl.mailGroup.label.mailGroupNameLang', ['언어별']) }}</th>
          <td colspan="3">
            <span v-for="(locale, index) in $i18n.availableLocales" :key="locale+index">
              <span v-if="index !== 0">&nbsp;/&nbsp;</span>
              <strong>{{ locale }}</strong> : {{ mailGroupItem.labelJson[locale] }}
            </span>
          </td>
        </tr>
      </tbody>
    </table>
    <!-- Detail Info Area -->
    <div class="ui--view-container">
      <h4 class="mb-3">{{ $t('sdl.mailGroup.label.mailGroupMappList') }}</h4>
    </div>
    <!-- Button Area -->
    <div class="ui--list-heading clearfix">
      <span class="ui--text-total"><strong>Total</strong> {{ $filters.numberFormat(total) }}</span>
      <div class="float-end">
        <button
          type="button"
          class="btn btn-secondary btn-sm"
          @click="deleteMailGroupMappBtn"
          v-authorization="'update'"
        >
          {{ $t('sdl.common.label.delete') }}
        </button>
        <button type="button" class="btn btn-secondary btn-sm" @click="addMailGroupUserBtn" v-authorization="'execute'">
          {{ $t('sdl.user.label.active') }} {{ $t('sdl.common.label.add') }}
        </button>
        <button type="button" class="btn btn-secondary btn-sm" @click="addMailGroupRoleBtn" v-authorization="'execute'">
          {{ $t('sdl.role.label.heading') }} {{ $t('sdl.common.label.add') }}
        </button>
        <button
          type="button"
          class="btn btn-secondary btn-sm"
          @click="addMailGroupWorkgroupBtn"
          v-authorization="'execute'"
        >
          {{ $t('sdl.workGroup.label.heading') }} {{ $t('sdl.common.label.add') }}
        </button>
        <button type="button" class="btn btn-primary btn-sm" @click="saveMailGroupMappBtn" v-authorization="'execute'">
          {{ $t('sdl.common.label.save') }}
        </button>
      </div>
    </div>
    <!-- Button Area -->
    <!-- List Area -->
    <table class="table table-bordered ui--table">
      <colgroup>
        <col style="width:3%" />
        <col style="width:10%" />
        <col style="width:15%" />
        <col style="width:15%" />
        <col style="width:15%" />
        <col style="" />
      </colgroup>
      <thead>
        <tr>
          <th scope="col">
            <input type="checkbox" @click.stop v-model="selectAll" @change="toggleSelectAll()" />
          </th>
          <th scope="col">{{ $t('sdl.mailGroup.label.mailGroupMappType') }}</th>
          <th scope="col" class="text-center" colspan="3">
            {{ $t('sdl.user.label.heading') }} / {{ $t('sdl.role.label.roleName') }} /
            {{ $t('sdl.workGroup.label.workGroupName') }}
          </th>
          <th scope="col">{{ $t('sdl.mailGroup.label.mailGroupMappRemark') }}</th>
        </tr>
      </thead>
      <tr
        v-for="mailGroupMapp in mailGroupMappList"
        :key="mailGroupMapp.userId"
        :class="{ 'alert-warning': !mailGroupMapp.existed }"
      >
        <td class="text-center" @click.stop>
          <input type="checkbox" v-model="mailGroupMapp.selected" @change="checkBoxClick(mailGroupMapp)" />
        </td>
        <template v-if="mailGroupMapp.type === 0">
          <td class="text-center">{{ $t('sdl.mailGroup.label.mailGroupMappTypeUser') }}</td>
          <td class="text-left" colspan="3">
            {{ mailGroupMapp.user.userName }} ( {{ mailGroupMapp.user.knoxId }} / {{ mailGroupMapp.user.email }} )
          </td>
        </template>
        <template v-if="mailGroupMapp.type === 1">
          <td class="text-center">{{ $t('sdl.mailGroup.label.mailGroupMappTypeRole') }}</td>
          <td class="text-left" colspan="3">
            <div>
              <span>{{ mailGroupMapp.role.label }}</span>
              <span v-for="locale in $i18n.availableLocales" :key="locale">&nbsp;/&nbsp;{{ mailGroupMapp.role.labelJson[locale] }}</span>
            </div>
          </td>
        </template>
        <template v-if="mailGroupMapp.type === 2">
          <td class="text-center">{{ $t('sdl.mailGroup.label.mailGroupMappTypeWorkgroup') }}</td>
          <td class="text-left" colspan="3">
            <div>
              <span>{{ mailGroupMapp.workgroup.label }}</span>
              <span v-for="locale in $i18n.availableLocales" :key="locale">&nbsp;/&nbsp;{{ mailGroupMapp.workgroup.labelJson[locale] }}</span>
            </div>
          </td>
        </template>
        <td class="text-left">{{ mailGroupMapp.remark }}</td>
      </tr>
    </table>

    <!-- List Area -->
    <!-- Pagination Area-->
    <sdl-pagination
      :current-page="current_page"
      :total-rows="total"
      :per-page="per_page"
      @change="handleCurrentChange"
      align="center"
    />
    <!-- Pagination Area-->
    <div class="ui--list-heading clearfix">
      <div class="float-end">
        <button type="button" class="btn btn-secondary btn-lg" @click="goBackToList">
          {{ $t('sdl.common.label.list') }}
        </button>
        <button type="button" class="btn btn-secondary btn-lg" @click="deleteMailGroupBtn" v-authorization="'update'">
          {{ $t('sdl.common.label.delete') }}
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import { SDLUtil, StringUtil } from '@/utils';
import StoreParams from '@/mixin/StoreParams';
import UserPopup from '@/components/common/popup/UserListPopup.vue';
import RolePopup from '@/components/common/popup/RoleListPopup.vue';
import WorkgroupPopup from '@/components/common/popup/WorkgroupListPopup.vue';

export default {
  data() {
    return {
      mailGroupId: null,
      mailGroupItem: {
        labelJson: {},
      },
      selectAll: false,
      per_page: 10,
      current_page: null,
      total: null,
      mailGroupMappList: [],
    };
  },
  mixins: [StoreParams],
  methods: {
    getMailGroupInfo() {
      // Launch Loading bar
      SDLUtil.showLoadingBar(true);
      // Call Mail Group Mapping list lookup API
      axios
        .get(`${SDLUtil.API_URL}/mail-group/${this.mailGroupId}`)
        .then(({ data }) => {
          this.mailGroupItem = data;
          // Remove Loading bar
          SDLUtil.showLoadingBar(false);
        })
        .catch(err => {
          // Remove Loading bar
          SDLUtil.showLoadingBar(false);
          // Call error alert
          SDLUtil.errorAlert(err);
        });
    },
    /**
     * param: number
     * return: nothing
     * exception: Call error alert
     * description: Mail Group Mapping lookup
     */
    getMailGroupMappList(pageIndex = 1) {
      // Set the page number sent to the current page number
      this.current_page = pageIndex;

      // Launch Loading bar
      SDLUtil.showLoadingBar(true);

      // Set Mail Group Mapping lookup API enforcement parameter
      const params = {
        mailGroupId: this.mailGroupId,
        pageIndex: this.current_page,
        pageSize: this.per_page,
      };

      // Save parameter to store
      this.setStoreParameter(params);

      // Call Mail Group Mapping lookup API
      axios
        .get(`${SDLUtil.API_URL}/mail-group-mapp-with-paging?${StringUtil.queryStringfy(params)}`)
        .then(({ data }) => {
          this.mailGroupMappList = data.rows;
          // Apply the page number that was retrieved to the current_page
          this.current_page = data.currentPage;
          // Full Row Count
          this.total = data.records;
          // Remove Loading bar
          SDLUtil.showLoadingBar(false);
        })
        .catch(err => {
          // Remove Loading bar
          SDLUtil.showLoadingBar(false);
          // Call error alert
          SDLUtil.errorAlert(err);
        });

      // Unselect All
      this.selectAll = false;
    },
    addMailGroupUserBtn() {
      this.openUserPopUp();
    },
    addMailGroupRoleBtn() {
      this.openRolePopup();
    },
    addMailGroupWorkgroupBtn() {
      this.openWorkgroupPopup();
    },
    deleteMailGroupMappBtn() {
      const selectedMailGroupMappList = this.mailGroupMappList.filter(mailGroupMapp => mailGroupMapp.selected);
      if (selectedMailGroupMappList.length === 0) {
        SDLUtil.alert('sdl.common.message.selectRow');
        return;
      }
      SDLUtil.confirm({
        title: 'sdl.common.label.delete',
        msg: 'sdl.common.message.doDelete',
        okLabel: 'sdl.common.label.confirm',
        cancelLabel: 'sdl.common.label.cancel',
        onOkEvt: () => this.deleteMailGroupMapp(selectedMailGroupMappList),
        onCancelEvt: () => console.log('cancel'),
      });
    },
    deleteMailGroupMapp(selectedMailGroupMappList) {
      selectedMailGroupMappList = this.mailGroupMappList.filter(mailGroupMapp => mailGroupMapp.selected);
      selectedMailGroupMappList.forEach(mgm => {
        if (Object.prototype.hasOwnProperty.call(mgm, 'role')) {
          mgm.role.labelJson = JSON.stringify(mgm.role.labelJson);
        }
        if (Object.prototype.hasOwnProperty.call(mgm, 'workgroup')) {
          mgm.workgroup.labelJson = JSON.stringify(mgm.workgroup.labelJson);
        }
      });

      axios
        .delete(`${SDLUtil.API_URL}/mail-group-mapp`, { data: selectedMailGroupMappList })
        .then(() => {
          this.getMailGroupMappList();
        }).catch(err => {
          SDLUtil.errorAlert(err);
        });
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Call user lookup popup
     */
    openUserPopUp() {
      SDLUtil.show(
        UserPopup,
        {
          userStatus: true,
          knoxSearch: true,
          rtnFunc: args => {
            this.checkMailGroupUserList(args);
          },
        },
        { width: '850px', height: 'auto' },
      );
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Compare with saved Mail Group user lists, and add to user lists
     */
    checkMailGroupUserList(userPopupList) {
      userPopupList.forEach(userPopupItem => {
        if (this.checkBeforePush(userPopupItem)) {
          this.mailGroupMappList.push({
            type: 0,
            mappId: userPopupItem.userId,
            userId: userPopupItem.userId,
            user: {
              userName: userPopupItem.userName,
              knoxId: userPopupItem.knoxId,
              email: userPopupItem.email,
            },
            remark: null,
            existed: false,
          });
        }
      });
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Call the role Popup
     */
    openRolePopup() {
      SDLUtil.show(
        RolePopup,
        {
          rtnFunc: args => {
            this.checkMailGroupRoleList(args);
          },
        },
        { width: '850px', height: 'auto' },
      );
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Compare with saved Mail Group role lists, and add to role lists
     */
    checkMailGroupRoleList(rolePopupList) {
      rolePopupList.forEach(rolePopupItem => {
        if (this.checkBeforePush(rolePopupList)) {
          this.mailGroupMappList.push({
            type: 1,
            mappId: rolePopupItem.roleId,
            roleId: rolePopupItem.roleId,
            role: {
              label: rolePopupItem.label,
              labelJson: rolePopupItem.labelJson,
            },
            remark: rolePopupItem.description,
            existed: false,
          });
        }
      });
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Call the workgroup Popup
     */
    openWorkgroupPopup() {
      SDLUtil.show(
        WorkgroupPopup,
        {
          rtnFunc: args => {
            this.checkMailGroupWorkgroupList(args);
          },
        },
        { width: '850px', height: 'auto' },
      );
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Compare with saved Mail Group workgroup lists, and add to workgroup lists
     */
    checkMailGroupWorkgroupList(workgroupPopupList) {
      workgroupPopupList.forEach(workgroupPopupItem => {
        if (this.checkBeforePush(workgroupPopupList)) {
          this.mailGroupMappList.push({
            type: 2,
            mappId: workgroupPopupItem.workgroupId,
            workgroupId: workgroupPopupItem.workgroupId,
            workgroup: {
              label: workgroupPopupItem.label,
              labelJson: workgroupPopupItem.labelJson,
            },
            remark: workgroupPopupItem.description,
            existed: false,
          });
        }
      });
    },
    checkBeforePush(item) {
      if (undefined === this.mailGroupMappList.find(mailGroupMapp => (
        mailGroupMapp.mappId === item.userId
          || mailGroupMapp.mappId === item.roleId
          || mailGroupMapp.mappId === item.workgroupId))) return true;
      SDLUtil.alert('sdl.common.message.retry');
      return false;
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Call the Mail Group Mapp registration function
     */
    saveMailGroupMappBtn() {
      SDLUtil.confirm({
        title: 'sdl.common.label.save',
        msg: 'sdl.common.message.doSave',
        okLabel: 'sdl.common.label.confirm',
        cancelLabel: 'sdl.common.label.cancel',
        onOkEvt: () => this.saveMailGroupMapp(),
        onCancelEvt: () => console.log('cancel'),
      });
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Insert and modify Mail Group Mapping info
     */
    saveMailGroupMapp() {
      SDLUtil.showLoadingBar(true);
      const notExistedMailGroupMappList = this.mailGroupMappList.filter(mailGroupMapp => !mailGroupMapp.existed);
      notExistedMailGroupMappList.forEach(mgm => {
        if (Object.prototype.hasOwnProperty.call(mgm, 'role')) {
          mgm.role.labelJson = JSON.stringify(mgm.role.labelJson);
        }
        if (Object.prototype.hasOwnProperty.call(mgm, 'workgroup')) {
          mgm.workgroup.labelJson = JSON.stringify(mgm.workgroup.labelJson);
        }
      });
      axios
        .post(`${SDLUtil.API_URL}/mail-group-mapp/${this.mailGroupId}`, notExistedMailGroupMappList, {
          headers: { 'Content-Type': 'application/json' },
        })
        .then(response => {
          if (response.status === 200) {
            SDLUtil.showLoadingBar(false);
            this.getMailGroupMappList();
          }
        })
        .catch(err => {
          SDLUtil.showLoadingBar(false);
          SDLUtil.errorAlert(err);
        });
    },
    /**
     * param: number
     * return: nothing
     * exception: Call error alert
     * description: paging
     */
    handleCurrentChange(currentPage) {
      // Invoke Mail Group list lookup method
      this.getMailGroupMappList(currentPage);
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Select All
     */
    toggleSelectAll() {
      this.mailGroupMappList.forEach(item => {
        item.selected = this.selectAll;
      });
    },
    /**
     * param: object
     * return: nothing
     * exception: nothing
     * description: Select check box in the list of Mail Group Mapping
     */
    checkBoxClick(item) {
      if (!item.selected) {
        if (this.selectAll) {
          this.selectAll = false;
        }
      }
    },
    deleteMailGroupBtn() {
      SDLUtil.confirm({
        title: 'sdl.common.label.delete',
        msg: 'sdl.common.message.doDelete',
        okLabel: 'sdl.common.label.confirm',
        cancelLabel: 'sdl.common.label.cancel',
        onOkEvt: () => this.deleteMailGroup(),
        onCancelEvt: () => console.log('cancel'),
      });
    },
    /**
     * param: array
     * return: nothing
     * exception: nothing
     * description: Delete Mail Group
     */
    deleteMailGroup() {
      const mailGroupIds = [this.mailGroupId];

      axios
        .delete(`${SDLUtil.API_URL}/mail-group`, { data: mailGroupIds })
        .then(response => {
          if (response.status === 200) {
            this.goBackToList();
          }
        })
        .catch(err => {
          // Call error alert
          SDLUtil.errorAlert(err);
        });
    },
  },
  created() {
    const storeParams = this.getStoreParameter();
    if (storeParams) {
      this.per_page = storeParams.pageSize;
      this.current_page = storeParams.pageIndex;
    }
    this.mailGroupId = this.$route.params.mailGroupId;
    this.getMailGroupInfo();
    this.getMailGroupMappList();
  },
};
</script>
