<!--
  Program: WorkgroupRoleInfo.vue
  Author: SDL
  Description: Page that retrieves the detailed workgroup information and retrieves, registers, modifies, and deletes the role / user for the workgroup.
-->
<template>
  <!-- SUB Contents -->
  <div class="ui--content-wrapper">
    <sdl-breadcrumb></sdl-breadcrumb>
    <!--Contents Area -->
    <div class="ui--view-container">
      <h4 class="mb-3">{{ $t('sdl.workGroup.label.heading') }} - {{ $t('sdl.role.label.heading') }}</h4>
      <table class="table table-bordered ui--table-form mb-5">
        <colgroup>
          <col style="width:12.5%" />
          <col style="width:35.5%" />
          <col style="width:12.5%" />
          <col style="width:35.5%" />
        </colgroup>
        <tbody>
          <tr>
            <th class="text-nowrap" scope="row">{{ $t('sdl.workGroup.label.heading') }}</th>
            <td>{{ workgroupItem.workgroupName }}</td>
            <th class="text-nowrap" scope="row">{{ $t('sdl.workGroup.label.workGroupNameOt') }}</th>
            <td>{{ workgroupItem.label }}</td>
          </tr>
          <tr v-for="(locale, index) in $i18n.availableLocales" :key="'tr' + index">
            <th class="text-nowrap" scope="row">{{ $t('sdl.workGroup.label.workGroupName') }}({{ locale }})</th>
            <td colspan="3">{{ workgroupItem.labelJson? workgroupItem.labelJson[locale]: '' }}</td>
          </tr>
          <tr>
            <th class="text-nowrap" scope="row">{{ $t('sdl.common.label.description') }}</th>
            <td colspan="3">{{ workgroupItem.description }}</td>
          </tr>
        </tbody>
      </table>

      <!-- buttons -->
      <div class="ui--list-heading clearfix">
        <div class="float-end">
          <button type="button" class="btn btn-secondary btn-sm" @click="deleteWorkgroupRoleUserBtn">
            {{ $t('sdl.common.label.delete') }}
          </button>
          <button type="button" class="btn btn-secondary btn-sm" @click="addWorkgroupUserBtn">
            {{ $t('sdl.user.label.active') }} {{ $t('sdl.common.label.add') }}
          </button>
          <button type="button" class="btn btn-secondary btn-sm" @click="addWorkgroupRoleBtn">
            {{ $t('sdl.role.label.heading') }} {{ $t('sdl.common.label.add') }}
          </button>
          <button type="button" class="btn btn-primary btn-sm" @click="saveWorkgroupRoleUserBtn">
            {{ $t('sdl.common.label.save') }}
          </button>
        </div>
      </div>
      <!-- buttons -->
      <!-- workgroup-role/user TABLE Area-->
      <table class="table table-bordered ui--table mb-4">
        <colgroup>
          <col style="width:3%" />
          <col style="width:15%" />
          <col style="width:17%" />
          <col style="width:25%" />
          <col style="width:15%" />
          <col style="width:15%" />
        </colgroup>
        <thead>
          <tr>
            <th scope="col">
              <input type="checkbox" @click.stop v-model="selectAll" @change="toggleSelectAll" />
            </th>
            <th scope="col">{{ $t('sdl.distribution.type') }}</th>
            <th scope="col">
              {{ $t('sdl.role.label.heading') }} / {{ $t('sdl.user.label.knoxId') }}
            </th>
            <th scope="col">
              {{ $t('sdl.role.label.roleName') }} / {{ $t('sdl.user.label.userName') }}
            </th>
            <th scope="col">{{ $t('sdl.common.label.fromDate') }}</th>
            <th scope="col">{{ $t('sdl.common.label.thruDate') }}</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="workgroupRoleUser in workgroupRoleUserList" :key="workgroupRoleUser.roleId">
            <td class="text-center">
              <input type="checkbox" v-model="workgroupRoleUser.selected" @change="checkBoxClick(workgroupRoleUser)" />
            </td>
            <td class="text-center">{{ workgroupRoleUser.type }}</td>
            <template v-if="workgroupRoleUser.type === 'USER'">
              <td class="text-left">{{ workgroupRoleUser.knoxId }}</td>
              <td class="text-left">{{ workgroupRoleUser.userName }}</td>
              <td class="text-left">
                <sdl-datepicker v-model="workgroupRoleUser.fromDate" wrap-class="" :disabled-date="workgroupRoleUser.disabledDate" @input="dateInput($event, workgroupRoleUser)"></sdl-datepicker>
              </td>
              <td class="text-left">
                <sdl-datepicker
                  v-model="workgroupRoleUser.thruDate"
                  wrap-class=""
                  :disabled-date="workgroupRoleUser.disabledDate"
                  @input="dateInput($event, workgroupRoleUser)"
                ></sdl-datepicker>
              </td>
            </template>
            <template v-else>
              <td class="text-left">{{ workgroupRoleUser.roleName }}</td>
              <td class="text-left">{{ getRoleLabel(workgroupRoleUser) }}</td>
              <td class="text-left"></td>
              <td class="text-left"></td>
            </template>
          </tr>
        </tbody>
      </table>
      <!--/ workgroup-role/user TABLE Area-->
      <hr class="mb-4">
      <div class="ui--button-container">
        <button type="button" class="btn btn-secondary btn-lg" @click="returnWorkgroupListBtn">
          {{ $t('sdl.common.label.list') }}
        </button>
      </div>
    </div>
    <!--/Contents Area -->
  </div>
  <!--/SUB Contents -->
</template>
<script>
import axios from 'axios';
import _ from 'lodash';
import SDLUtil from '@/utils/SDLUtil';
import RolePopup from '@/components/common/popup/RoleListPopup.vue';
import UserPopup from '@/components/common/popup/UserListPopup.vue';
import StoreParams from '@/mixin/StoreParams';
import SDLLocale from '@/mixin/SDLLocale';

export default {
  data() {
    return {
      workgroupId: null,
      workgroupItem: {},
      selectAll: false,
      workgroupRoleUserList: [],
      tempWorkgroupRoleUserList: [],
      beforeWorkgroupRoleUserList: [],
      updateWorkgroupRoleUserList: [],
    };
  },
  mixins: [StoreParams, SDLLocale],
  methods: {
    getRoleLabel(workgroupRoleUser) {
      const role = {
        labelJson: workgroupRoleUser.roleLabelJson,
        label: workgroupRoleUser.roleLabel,
      };
      return this.getLabel(role);
    },
    /**
     * param: nothing
     * return: nothing
     * exception: Call error alert
     * description: Retrieve workgroup details
     */
    getWorkgroupInfo() {
      // Launch Loading bar
      SDLUtil.showLoadingBar(true);
      axios
        .get(`${SDLUtil.API_URL}/auth/workgroups/${this.workgroupId}`)
        .then(({ data }) => {
          this.workgroupItem = data;

          // Remove Loading bar
          SDLUtil.showLoadingBar(false);
        })
        .catch(err => {
          // Remove Loading bar
          SDLUtil.showLoadingBar(false);
          // Call error alert
          SDLUtil.errorAlert(err);
        });
    },
    /**
     * param: nothing
     * return: nothing
     * exception: Call error alert
     * description: Workgroup-Role/User Lookup
     */
    getWorkgroupRoleUserList() {
      axios
        .get(`${SDLUtil.API_URL}/auth/workgroups/${this.workgroupId}/roles`)
        .then(({ data }) => {
          this.workgroupRoleUserList = data;

          const tempRoleUserList = [];

          this.workgroupRoleUserList.forEach(workgroupRoleUser => {
            tempRoleUserList.push({
              selected: false,
              type: workgroupRoleUser.type,
              userRoleId: workgroupRoleUser.userRoleId,
              knoxId: workgroupRoleUser.user.knoxId,
              userName: workgroupRoleUser.user.userName,
              roleName: workgroupRoleUser.role.roleName,
              roleLabel: workgroupRoleUser.role.label,
              roleLabelJson: workgroupRoleUser.role.labelJson,
              fromDate: this.$filters.dateFormat(workgroupRoleUser.fromDate, 'YYYY-MM-DD'),
              thruDate: this.$filters.dateFormat(workgroupRoleUser.thruDate, 'YYYY-MM-DD'),
              disabledDate: { to: this.$moment().subtract(1, 'd').toDate() },
            });
          });

          this.workgroupRoleUserList = tempRoleUserList;
          this.selectAll = false;
        })
        .catch(err => {
          // Call error alert
          SDLUtil.errorAlert(err);
        });
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Go to workgroup Management Page
     */
    returnWorkgroupListBtn() {
      this.goBackToList();
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Call workgroup-role/user deletion API after verifying that the selected workgroup-role/user exists
     */
    deleteWorkgroupRoleUserBtn() {
      const selectWorkgroupRoleUser = this.workgroupRoleUserList.filter(workgroupRoleUser => workgroupRoleUser.selected);

      if (selectWorkgroupRoleUser.length === 0) {
        SDLUtil.alert('sdl.common.message.checkRowsToDelete');
        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.deleteWorkgroupRoleUser(selectWorkgroupRoleUser),
        onCancelEvt: () => console.log('cancel'),
      });
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Call the user query popup function
     */
    addWorkgroupUserBtn() {
      this.openUserPopup();
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Call the role query popup function
     */
    addWorkgroupRoleBtn() {
      this.openRolePopup();
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: After checking if there is a temporary workgroup-role/user list, call the workgroup-role/user registration function
     */
    saveWorkgroupRoleUserBtn() {
      if (this.tempWorkgroupRoleUserList.length === 0 && this.updateWorkgroupRoleUserList.length === 0) {
        return;
      }

      SDLUtil.confirm({
        title: 'sdl.common.label.save',
        msg: 'sdl.common.message.doSave',
        okLabel: 'sdl.common.label.confirm',
        cancelLabel: 'sdl.common.label.cancel',
        onOkEvt: () => this.saveWorkgroupRoleUser(),
        onCancelEvt: () => console.log('cancel'),
      });
    },
    /**
     * param: array
     * return: nothing
     * exception: Call error alert
     * description: Locate the ID of the selected role/user and delete the appropriate user from the workgroup-role/user list
     */
    deleteWorkgroupRoleUser(selectWorkgroupRoleUser) {
      const selectDbWorkgroupRoleUserIds = [];

      selectWorkgroupRoleUser.forEach(selectWorkgroupRoleUserItem => {
        // Check if it is a menu registered in DB
        const tempIdx = this.tempWorkgroupRoleUserList.findIndex(
          tempWorkgroupRoleUserItem => tempWorkgroupRoleUserItem.userRoleId === selectWorkgroupRoleUserItem.userRoleId,
        );

        if (tempIdx === -1) {
          selectDbWorkgroupRoleUserIds.push(selectWorkgroupRoleUserItem.userRoleId);
        } else {
          this.tempWorkgroupRoleUserList.splice(tempIdx, 1);
        }

        this.workgroupRoleUserList.splice(
          this.workgroupRoleUserList.findIndex(
            workgroupRoleUserItem => workgroupRoleUserItem.userRoleId === selectWorkgroupRoleUserItem.userRoleId,
          ),
          1,
        );
        this.beforeWorkgroupRoleUserList.splice(
          this.beforeWorkgroupRoleUserList.findIndex(
            beforeItem => beforeItem.userRoleId === selectWorkgroupRoleUserItem.userRoleId,
          ),
          1,
        );
        this.updateWorkgroupRoleUserList.splice(
          this.updateWorkgroupRoleUserList.findIndex(
            updateItem => updateItem.userRoleId === selectWorkgroupRoleUserItem.userRoleId,
          ),
          1,
        );
      });

      // If it exists in the workgroup-role/user registered in DB, it is deleted from the workgroup-role/user.
      if (selectDbWorkgroupRoleUserIds.length > 0) {
        axios
          .delete(`${SDLUtil.API_URL}/auth/workgroups/${this.workgroupId}/roles`, { data: selectDbWorkgroupRoleUserIds })
          .then(response => {
            if (response.status === 200) {
              // console.log('sdl.common.message.deleted');
            }
          })
          .catch(err => {
            SDLUtil.errorAlert(err);
          });
      }
      this.selectAll = false;
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Call the role Popup
     */
    openRolePopup() {
      SDLUtil.show(
        RolePopup,
        {
          rtnFunc: args => {
            this.checkWorkgroupRoleUserList(args, 'ROLE');
          },
        },
        { width: '850px', height: 'auto' },
      );
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Call the user Popup
     */
    openUserPopup() {
      SDLUtil.show(
        UserPopup,
        {
          rtnFunc: args => {
            this.checkWorkgroupRoleUserList(args, 'USER');
          },
        },
        { width: '850px', height: 'auto' },
      );
    },
    /**
     * param: array
     * return: nothing
     * exception: nothing
     * description: Compare with saved workgroup-role/user lists, and save to workgroup-role/user lists
     */
    checkWorkgroupRoleUserList(popupList, type) {
      popupList.forEach(popupItem => {
        if (type.indexOf('USER') > -1) {
          popupItem.userRoleId = popupItem.userId;
          popupItem.knoxId = popupItem.knoxId;
          popupItem.userName = popupItem.userName;
          popupItem.fromDate = this.$filters.dateFormat(this.$moment(), 'YYYY-MM-DD');
          popupItem.thruDate = this.$filters.dateFormat(this.$moment().add('2', 'Y'), 'YYYY-MM-DD');
          popupItem.disabledDate = { to: this.$moment().subtract(1, 'd').toDate() };
        } else {
          popupItem.userRoleId = popupItem.roleId;
          popupItem.roleName = popupItem.roleName;
          popupItem.roleLabel = popupItem.label;
          popupItem.roleLabelJson = popupItem.labelJson;
          popupItem.fromDate = '';
          popupItem.thruDate = '';
          popupItem.disabledDate = '';
        }

        if (
          !this.workgroupRoleUserList.find(workgroupRoleUserItem => workgroupRoleUserItem.userRoleId === popupItem.userRoleId)
        ) {
          // Add only if there is no comparison between added user information and temporary workgroup-role/user list
          if (
            !this.tempWorkgroupRoleUserList.find(
              tempWorkgroupRoleUserItem => tempWorkgroupRoleUserItem.userRoleId === popupItem.userRoleId,
            )
          ) {
            this.tempWorkgroupRoleUserList.push({
              selected: false,
              type,
              userRoleId: popupItem.userRoleId,
              knoxId: popupItem.knoxId,
              userName: popupItem.userName,
              roleName: popupItem.roleName,
              roleLabel: popupItem.label,
              roleLabelJson: popupItem.labelJson,
              fromDate: popupItem.fromDate,
              thruDate: popupItem.thruDate,
              disabledDate: popupItem.disabledDate,
            });
            this.workgroupRoleUserList.push({
              selected: false,
              type,
              userRoleId: popupItem.userRoleId,
              knoxId: popupItem.knoxId,
              userName: popupItem.userName,
              roleName: popupItem.roleName,
              roleLabel: popupItem.label,
              roleLabelJson: popupItem.labelJson,
              fromDate: popupItem.fromDate,
              thruDate: popupItem.thruDate,
              disabledDate: popupItem.disabledDate,
            });

            this.setValue();
          }
        }
      });
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Register and modify workgroup-role/user
     */
    async saveWorkgroupRoleUser() {
      const saveInsertRoleUserList = [];
      const saveUpdateRoleUserList = [];
      let check = false;

      if (this.tempWorkgroupRoleUserList.length > 0) {
        this.workgroupRoleUserList.forEach(workgroupRoleUserListItem => {
          const isInsertRoleUser = this.tempWorkgroupRoleUserList.find(
            insert => insert.userRoleId === workgroupRoleUserListItem.userRoleId,
          );

          if (isInsertRoleUser) {
            const isUpdateRoleUser = this.updateWorkgroupRoleUserList.find(
              updateRoleUserItem => updateRoleUserItem.userRoleId === isInsertRoleUser.userRoleId,
            );

            if (isUpdateRoleUser) {
              saveInsertRoleUserList.push(this.setParam(isUpdateRoleUser));
            } else {
              saveInsertRoleUserList.push(this.setParam(isInsertRoleUser));
            }
          } else {
            const isUpdateRoleUser = this.updateWorkgroupRoleUserList.find(
              updateRoleUserItem => updateRoleUserItem.userRoleId === workgroupRoleUserListItem.userRoleId,
            );

            if (isUpdateRoleUser) {
              if (isUpdateRoleUser.type === 'USER') {
                saveUpdateRoleUserList.push(this.setParam(isUpdateRoleUser));
              }
            }
          }
        });

        if (saveInsertRoleUserList.length > 0) {
          /**
           * Call the Workgroup-Role/User Registration API
           */
          await axios
            .post(`${SDLUtil.API_URL}/auth/workgroups/${this.workgroupId}/roles`, saveInsertRoleUserList, {
              headers: { 'Content-Type': 'application/json' },
            })
            .then(response => {
              if (response.status === 200) {
                check = true;
              }
            })
            .catch(err => {
              SDLUtil.errorAlert(err);
              check = false;
            });
        }
      } else {
        this.updateWorkgroupRoleUserList.filter(updateRoleUserItem => updateRoleUserItem.type === 'USER').forEach(updateRoleUserItem => {
          saveUpdateRoleUserList.push(this.setParam(updateRoleUserItem));
        });
      }

      if (saveUpdateRoleUserList.length > 0) {
        /**
         * Call the Workgroup-Role/User Modification API
         */
        await axios
          .put(`${SDLUtil.API_URL}/auth/workgroups/${this.workgroupId}/roles`, saveUpdateRoleUserList, {
            headers: { 'Content-Type': 'application/json' },
          })
          .then(response => {
            if (response.status === 200) {
              check = true;
            }
          })
          .catch(err => {
            SDLUtil.errorAlert(err);
            check = false;
          });
      }

      if (check) {
        // SDLUtil.alert('sdl.common.message.saved');
        this.getWorkgroupRoleUserList();

        this.tempWorkgroupRoleUserList.splice(0);
      }
    },
    /**
     * param: object
     * return: nothing
     * exception: nothing
     * description: Select check box in the list of workgroup
     */
    checkBoxClick(item) {
      if (!item.selected) {
        if (this.selectAll) {
          this.selectAll = false;
        }
      }
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Select All
     */
    toggleSelectAll() {
      this.workgroupRoleUserList.forEach(item => {
        item.selected = this.selectAll;
      });
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Save to the pre-change data list to synchronize the pre-change data
     */
    setValue() {
      this.beforeWorkgroupRoleUserList = _.cloneDeep(this.workgroupRoleUserList);
    },
    /**
     * param: array
     * return: object
     * exception: nothing
     * description: Setting parameters for registration and modification
     */
    setParam(roleUserList) {
      const roleUserItem = {};

      roleUserItem.type = roleUserList.type;

      if (roleUserItem.type === 'USER') {
        roleUserItem.userId = roleUserList.userRoleId;
        roleUserItem.fromDate = this.$filters.dateFormat(roleUserList.fromDate, 'YYYYMMDD');
        roleUserItem.thruDate = this.$filters.dateFormat(roleUserList.thruDate, 'YYYYMMDD');
      } else {
        roleUserItem.roleId = roleUserList.userRoleId;
      }

      return roleUserItem;
    },

    dateInput(value, item) {
      if (item.fromDate > item.thruDate) {
        item.thruDate = item.fromDate;
      }
    },
  },
  created() {
    this.workgroupItem = {};
    this.workgroupId = this.$route.params.workgroupId;
    this.getWorkgroupInfo();
    this.getWorkgroupRoleUserList();
  },
  mounted() {
    this.$nextTick(() => {
      // console.info('loaded UserInfo.vue');
    });

    this.setValue();
  },
  watch: {
    workgroupRoleUserList: {
      handler(after, before) {
        if (before.length > 0) {
          const changedWorkgroupRoleUserList = after.filter((p, idx) => Object.keys(p).some(prop => p[prop] !== this.beforeWorkgroupRoleUserList[idx][prop]));

          for (let i = 0; i < changedWorkgroupRoleUserList.length; i += 1) {
            const changedWorkgroupRoleUserItem = changedWorkgroupRoleUserList[i];
            const isExistIndex = this.updateWorkgroupRoleUserList.findIndex(
              workgroupRoleUser => workgroupRoleUser.userRoleId === changedWorkgroupRoleUserItem.userRoleId,
            );

            if (isExistIndex > -1) {
              this.updateWorkgroupRoleUserList.splice(isExistIndex, 1);
            }
            this.updateWorkgroupRoleUserList.push(changedWorkgroupRoleUserItem);
          }
        }
        this.setValue();
      },
      deep: true,
    },
  },
};
</script>
