<!--
Program: ApprovalPath.vue
Author: SDL
Description: Approval path common component
-->
<template>
  <div class="ui--approval-container">
    <div class="input-group">
      <input type="text" class="form-control" :placeholder="$t('sdl.common.label.payer')" aria-label="add User" v-model="searchUserNm" @keyup.esc="searchUserNm = ''" @keyup.enter.stop="openSearchUser()" />
      <button class="btn btn-outline-secondary" type="button" @click="openSearchUser">
        <i class="bi bi-search"></i>
      </button>
    </div>

    <div class="ui--approval-list">
      <!-- file-button -->
      <div class="ui--approval-button">
        <div class="ui--apv-flex">
          <button class="btn ui--btn-apv-outline" type="button" :class="{ on: approvalType === 'APPROVAL' }" @click="changeApprovalType('APPROVAL')">
            {{ $t('sdl.approval.label.APPROVE') }}
          </button>
          <button class="btn ui--btn-apv-outline" type="button" :class="{ on: approvalType === 'AGREEMENT' }" @click="changeApprovalType('AGREEMENT')">
            {{ $t('sdl.approval.label.AGREEMENT') }}
          </button>
          <button class="btn ui--btn-apv-outline" type="button" :class="{ on: approvalType === 'NOTIFICATION' }" @click="changeApprovalType('NOTIFICATION')">
            {{ $t('sdl.approval.label.NOTIFY') }}
          </button>
        </div>
        <span class="ui--slide ms-2 me-2">|</span>
        <button class="btn ui--btn-xs" type="button" @click="changeApprovalType('EX_POST_APPROVAL')">
          {{ $t('sdl.approval.label.SKIP') }}
        </button>
        <span class="ui--slide ms-2 me-2">|</span>
        <button class="btn ui--btn-xs me-1" type="button" @click="setApprovalParallel(true)"><i class="bi bi-view-stacked"></i>{{ $t('sdl.common.label.parallel') }}</button>
        <button class="btn ui--btn-xs" type="button" @click="setApprovalParallel(false)"><i class="bi bi-grid"></i>{{ $t('sdl.approval.label.PARALLEL_CANCEL') }}</button>
        <span v-if="showRequired" class="ui--slide ms-2 me-2">|</span>
        <button v-if="showRequired" class="btn btn-outline-info btn-xs" @click="onRequiredApprListPopup" type="button" style="position: relative">
          {{ $t('sdl.approval.label.addRequiredApprovalUser') }}
          <div v-if="showRequiredTooltip" class="ui--app-required"><i class="bi bi-info-circle"></i> {{ $t('sdl.approval.message.selectRequiredApprovalUser') }}</div>
        </button>
        <span v-if="showRequired" class="ui--slide ms-2 me-2">|</span>
        <button class="btn ui--btn-icon-sm" :title="$t('sdl.common.label.Top')" type="button" @click="stepTopUp()">
          <i class="bi bi-skip-end-fill ui--trans-rotate-270"></i>
        </button>
        <button class="btn ui--btn-icon-sm" :title="$t('sdl.common.label.moveup')" type="button" @click="stepUp()">
          <i class="bi bi-play-fill ui--trans-rotate-270"></i>
        </button>
        <button class="btn ui--btn-icon-sm" :title="$t('sdl.common.label.movedown')" type="button" @click="stepDown()">
          <i class="bi bi-play-fill ui--trans-rotate-90"></i>
        </button>
        <button class="btn ui--btn-icon-sm" :title="$t('sdl.common.label.bottom')" type="button" @click="stepBottomDown()">
          <i class="bi bi-skip-end-fill ui--trans-rotate-90"></i>
        </button>
        <button class="btn ui--btn-icon-sm" :title="$t('sdl.common.label.delete')" type="button" @click="deleteUserTopBtn">
          <i class="bi bi-x"></i>
        </button>
        <span class="ui--slide ms-2 me-2">|</span>
        <span
          >{{ $t('sdl.common.label.total') }}<strong class="ms-1 me-2">{{ apprPathList.length }}</strong></span
        >
      </div>
      <!-- // file-button -->
      <!-- file-list -->
      <ul>
        <li v-for="user in apprPathList" :key="`${user.userId}_${user.stepIdx}`" :class="{ selected: user.selected, draft: user.approvalType === 'DRAFTING' }" @click="selectedPath(user)">
          <span class="count">{{ user.stepIdx }}</span>
          <div class="ui--apv-flex" v-if="user.approvalType === 'DRAFTING'">
            <button class="btn ui--btn-apv btn-apv-request" type="button">{{ $t('sdl.approval.label.REQUEST') }}</button>
          </div>
          <div class="ui--apv-flex" v-else-if="user.approvalType === 'EX_POST_APPROVAL'">
            <button class="btn ui--btn-apv btn-apv-after on" type="button">{{ $t('sdl.approval.label.SKIP') }}</button>
          </div>
          <div class="ui--apv-flex" v-else-if="user.approvalType === 'PARALLEL_APPROVAL'">
            <button class="btn ui--btn-apv ui--btn-apv-approve on" type="button">
              {{ $t('sdl.approval.label.PARALLEL_APPROVE') }}
            </button>
          </div>
          <div class="ui--apv-flex" v-else-if="user.approvalType === 'PARALLEL_AGREEMENT'">
            <button class="btn ui--btn-apv ui--btn-apv-approve on" type="button">
              {{ $t('sdl.approval.label.PARALLEL_AGREEMENT') }}
            </button>
          </div>
          <div class="ui--apv-flex" v-else>
            <button class="btn ui--btn-apv ui--btn-apv-approve" :class="{ on: user.approvalType === 'APPROVAL' }" @click.stop="changeUserApprovalType(user, 'APPROVAL')" type="button">
              {{ $t('sdl.approval.label.APPROVE') }}
            </button>
            <button class="btn ui--btn-apv ui--btn-apv-agreement" :class="{ on: user.approvalType === 'AGREEMENT' }" @click.stop="changeUserApprovalType(user, 'AGREEMENT')" type="button">
              {{ $t('sdl.approval.label.AGREEMENT') }}
            </button>
            <button class="btn ui--btn-apv ui--btn-apv-notice" :class="{ on: user.approvalType === 'NOTIFICATION' }" @click.stop="changeUserApprovalType(user, 'NOTIFICATION')" type="button">
              {{ $t('sdl.approval.label.NOTIFY') }}
            </button>
          </div>
          <span class="name" v-if="!user.required"> {{ user.userName }}/{{ user.deptName }}/{{ user.compName }}</span>
          <span class="name" v-if="user.required"
            ><span class="text-info">{{ user.userName }}/{{ user.deptName }}/{{ user.compName }} ({{ $t('sdl.approval.label.requiredApprovalUser') }})</span></span
          >
          <div v-if="user.approvalType === 'DRAFTING'" class="ui--apv-right text-black-50">
            {{ $t('sdl.common.label.requester') }}
          </div>
          <div class="ui--apv-right" v-else>
            <button class="btn ui--btn-icon-xs" :class="{ on: user.routeModify }" :title="$t('sdl.common.label.pathchange')" @click.stop="approvalRouteModify(user)" type="button">
              <i class="bi bi-arrow-down-up"></i>
            </button>
            <button class="btn ui--btn-icon-xs" :class="{ on: user.bodyModify }" :title="$t('sdl.approval.label.BODYMODIFY')" @click.stop="approvalBodyModify(user)" type="button">
              <i class="bi bi-fonts"></i>
            </button>
            <button class="btn ui--btn-icon-xs" :class="{ on: user.arbitrary }" :title="$t('sdl.approval.label.ARBITRARY')" @click.stop="approvalArbitrary(user)" type="button">
              <i class="bi bi-pencil-square"></i>
            </button>
            <button class="btn ui--btn-icon-sm float-end" :title="$t('sdl.common.label.delete')" @click.stop="deleteUserRightBtn(user)" type="button">
              <i class="bi bi-x"></i>
            </button>
          </div>
        </li>
      </ul>
      <!-- // file-list -->
    </div>
  </div>
</template>
<script>
import { SDLUtil } from '@/utils';
import RequiredApprListPopup from '@/components/view/admin/approval/popup/RequiredApprListPopup.vue';

export default {
  props: {
    approvalStepList: {
      type: Array,
    },
    showRequired: {
      type: Boolean,
      default: false,
    },
    requiredApprovalUserList: {
      type: Array,
      default: () => [],
    },
    internalFlag: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      searchUserNm: '',
      apprPathList: [],
      approvalType: 'APPROVAL',
      selectedDocTypeCode: '',
      checkParallesGroup: {},
      showRequiredTooltip: true,
      approvalPathStatus: [
        { code: 'DRAFTING', label: 'sdl.approval.label.REQUEST' },
        { code: 'APPROVAL', label: 'sdl.approval.label.APPROVE' },
        { code: 'CANCEL', label: 'sdl.approval.label.CANCELLED' },
        { code: 'AGREEMENT', label: 'sdl.approval.label.AGREEMENT' },
        { code: 'NOTIFICATION', label: 'sdl.approval.label.NOTIFY' },
        { code: 'EX_POST_APPROVAL', label: 'sdl.approval.label.SKIP' },
        { code: 'PARALLEL_AGREEMENT', label: 'sdl.approval.label.PARALLEL_AGREEMENT' },
        { code: 'PARALLEL_APPROVAL', label: 'sdl.approval.label.PARALLEL_APPROVE' },
        { code: 'REJECT', label: 'sdl.approval.label.REJECTED' },
      ],
    };
  },
  methods: {
    /**
     * param:
     * return:
     * exception:
     * Description : Page Initialization
     */
    init() {
      // this.apprPathList.splice(0);
      this.searchUserNm = '';
      if (this.approvalStepList) {
        this.setApprovalList();
      }
    },
    /**
     * param:
     * return:
     * exception:
     * Description : When receiving approval list as props from outside
     */
    setApprovalList() {
      this.apprPathList.splice(0);
      Object.keys(this.approvalStepList).forEach(idx => {
        const apprLine = this.approvalStepList[idx];
        this.apprPathList.push({
          stepIdx: apprLine.approvalStepSequence,
          parallel: apprLine.parallelProcess,
          approvalType: apprLine.approvalStepType,
          required: false,
          hasError: false,
          approverChangeAllowed: apprLine.approverChangeAllowed,
          bodyModify: apprLine.bodyModify,
          routeModify: apprLine.routeModify,
          arbitrary: apprLine.arbitrary,
          userId: apprLine.approvalPersonId,
          userName: apprLine.approvalPersonName,
          grdName: apprLine.approvalPersonPositionName,
          deptName: apprLine.approvalPersonDeptName,
          compName: apprLine.approvalPersonCompanyName,
          apprPathFlag: apprLine.apprPathFlag,
          docType: apprLine.docType,
        });
      });

      this.resetApprovalSeq();
    },
    /**
     * param:
     * return:
     * exception:
     * Description : When you take the approval list from the inside,
     */
    getApprovalList() {
      const rtnList = [];
      Object.keys(this.apprPathList).forEach(idx => {
        const apprLine = this.apprPathList[idx];
        rtnList.push({
          approvalStepSequence: apprLine.stepIdx,
          parallelProcess: apprLine.parallel,
          approvalStepType: apprLine.approvalType,
          required: false,
          hasError: false,
          approverChangeAllowed: true,
          bodyModify: apprLine.bodyModify,
          routeModify: apprLine.routeModify,
          arbitrary: apprLine.arbitrary,
          approvalPersonId: apprLine.userId,
          approvalPersonName: apprLine.userName,
          approvalPersonPositionName: apprLine.grdName,
          approvalPersonDeptName: apprLine.deptName,
          approvalPersonCompanyName: apprLine.compName,
        });
      });
      return rtnList;
    },
    /**
     * param: user -> json
     * return:
     * exception:
     * Description : Body can be modified
     */
    approvalBodyModify(user) {
      if (user.approvalStatusTypeCode === 'DRAFTING') return; // No change of DRAFTING

      user.bodyModify = !user.bodyModify;
      this.apprPathList.splice(this.apprPathList.indexOf(user), 1, user);
    },
    /**
     * param: user -> json
     * return:
     * exception:
     * Description : Is the approval path changed
     */
    approvalRouteModify(user) {
      if (user.approvalStatusTypeCode === 'DRAFTING') return; // No change of DRAFTING

      user.routeModify = !user.routeModify;
      this.apprPathList.splice(this.apprPathList.indexOf(user), 1, user);
    },
    /**
     * param: user -> json
     * return:
     * exception:
     * Description : Is the final decision for approval
     */
    approvalArbitrary(user) {
      if (user.approvalStatusTypeCode === 'DRAFTING') return; // No change of DRAFTING

      user.arbitrary = !user.arbitrary;
      this.apprPathList.splice(this.apprPathList.indexOf(user), 1, user);
    },
    /**
     * param: parallel -> Boolean
     * return:
     * exception:
     * Description : parallel approval setting
     */
    setApprovalParallel(parallel) {
      if (this.apprPathList[0].selected) return; // No change of DRAFTING

      if (this.checkRequired()) {
        // Required Approval Check
        SDLUtil.alert('sdl.approval.message.cannotChangeRequiredSteps');
        return;
      }
      const selectedRows = [];
      for (let i = 1; i < this.apprPathList.length; i += 1) {
        if (this.apprPathList[i].selected) {
          if (this.apprPathList[i].approvalType === 'NOTIFICATION') {
            // Notification does not pay in parallel
            SDLUtil.alert('sdl.approval.message.notifyCannotBeParallel');
            return;
          }
          if (this.apprPathList[i].approvalType === 'EX_POST_APPROVAL') {
            // No parallel payment for the latter decision
            SDLUtil.alert('sdl.approval.message.skipCannotBeParallel');
            return;
          }
          selectedRows.push(this.apprPathList[i]);
        }
      }

      if (selectedRows.length < 2) {
        // Select more than one parallel approval
        SDLUtil.alert('sdl.approval.message.parallelRequiresTwoOrMore');
        return;
      }

      if (this.checkApprovalStepsParallelPosition(selectedRows, parallel, false)) {
        return;
      }

      Object.keys(selectedRows).forEach(idx => {
        const user = selectedRows[idx];
        if (user.selected && user.approvalType !== 'NOTIFICATION' && user.approvalType !== 'EX_POST_APPROVAL') {
          user.parallel = parallel;
          if (parallel) {
            if (user.approvalType === 'PARALLEL_APPROVAL' || user.approvalType === 'PARALLEL_AGREEMENT') return;
            if (user.approvalType === 'APPROVAL') {
              user.approvalType = 'PARALLEL_APPROVAL';
            } else {
              user.approvalType = 'PARALLEL_AGREEMENT';
            }
          } else if (user.approvalType === 'PARALLEL_APPROVAL') {
            user.approvalType = 'APPROVAL';
          } else if (user.approvalType === 'PARALLEL_AGREEMENT') {
            user.approvalType = 'AGREEMENT';
          }
        }
        this.apprPathList.splice(this.apprPathList.indexOf(user), 1, user);
      });

      this.resetApprovalSeq();
    },
    /**
     * param: selectOptions -> array
     * param: parallel -> true/false(Boolean)
     * param: submit -> true/false(Boolean)
     * return:
     * exception:
     * Description : Check if parallel approval is possible
     */
    checkApprovalStepsParallelPosition(selectOptions, parallel, submit) {
      const paralles = [];
      let retStatus = true;

      selectOptions
        .filter(opt => opt.parallel)
        .forEach(opt => {
          if (typeof this.checkParallesGroup[opt.stepIdx] === 'undefined') {
            const checkParalles = [];
            checkParalles.push(opt);
            this.checkParallesGroup[opt.stepIdx] = checkParalles;
          } else {
            this.checkParallesGroup[opt.stepIdx].push(opt);
          }
        });

      if (submit) {
        // Select more than one parallel approval
        Object.keys(this.checkParallesGroup).some(index => {
          if (this.checkParallesGroup[index].length === 1) {
            SDLUtil.alert('sdl.approval.message.parallelRemainTwoOrMore');
            return true;
          }
          return false;
        });
        retStatus = false;
      } else {
        selectOptions
          .filter(opt => opt.selected && opt.approvalType !== 'NOTIFICATION')
          .forEach(opt => {
            paralles.push(opt);
          });

        for (let i = 1; i < paralles.length; i += 1) {
          const diff = paralles[i - 1].stepIdx - paralles[i].stepIdx;
          if (diff === 1 || diff === -1 || diff === 0) {
            if (!parallel && paralles[i - 1].parallel !== paralles[i].parallel) {
              SDLUtil.alert('sdl.approval.message.notMattchParallele');
              return true;
            }
            retStatus = false;
          } else {
            SDLUtil.alert('sdl.approval.message.linked');
            return true;
          }
        }
        // When releasing parallel payment, only one parallel approval step must be left.
        // If you select 3 parallel payments and replace the two parallel ones with the approval.
        if (!parallel && paralles.length > 0) {
          const opt = paralles[0];
          const opts = this.checkParallesGroup[opt.stepIdx];
          if (opts != null && opts.length - paralles.length === 1) {
            SDLUtil.alert('sdl.approval.message.parallelRemainTwoOrMore');
            return true;
          }
        }
      }
      return retStatus;
    },
    /**
     * param:
     * return:
     * exception:
     * Description : Required Approval Check
     */
    checkRequired() {
      for (let i = 0; i < this.apprPathList.length; i += 1) {
        if (this.apprPathList[i].selected) {
          if (this.apprPathList[i].required) return true;
        }
      }
      return false;
    },
    /**
     * param:
     * return:
     * exception:
     * Description : open user search popup
     */
    openSearchUser() {
      if (this.searchUserNm) {
        if (this.searchUserNm.length < 2) {
          SDLUtil.alert('sdl.common.message.enterMoreThan2CharForSearchTerms');
          return;
        }
      }
      SDLUtil.openUserPopup({
        searchColumn: 'userName',
        searchTxt: this.searchUserNm,
        rtnFunc: this.getUserList,
        knoxSearch: !this.internalFlag,
      });
    },
    /**
     * param: list -> array
     * return:
     * exception:
     * Description : return user search result
     */
    getUserList(list) {
      const n = this.apprPathList.length;
      let dupFlag = false;

      // Double-payer check
      Object.keys(list).forEach(i => {
        const userInfo = list[i];
        for (let j = 0; j < this.apprPathList.length; j += 1) {
          if (userInfo.userId === this.apprPathList[j].userId) {
            dupFlag = true;
            return;
          }
        }
      });
      if (dupFlag) {
        SDLUtil.alert('sdl.approval.message.duplicateApprover');
        return;
      }
      Object.keys(list).forEach(i => {
        const userInfo = list[i];

        this.apprPathList.push({
          stepIdx: parseInt(n, 10) + parseInt(i, 10),
          parallel: false,
          approvalType: this.approvalType,
          required: this.requiredApprovalUserList.some(requiredUser => requiredUser.userId === userInfo.userId),
          hasError: false,
          approverChangeAllowed: true,
          bodyModify: false,
          routeModify: false,
          arbitrary: false,
          departmentName: userInfo.deptName,
          positionName: userInfo.grdName,
          companyName: userInfo.compName,
          positionCode: userInfo.grdCode,
          departmentCode: userInfo.deptCode,
          companyCode: userInfo.compCode,
          requiredUser: userInfo.requiredUser,
          userId: userInfo.userId,
          userName: userInfo.userName,
          grdName: userInfo.grdName,
          deptName: userInfo.deptName,
          compName: userInfo.compName,
        });
      });

      this.resetApprovalSeq();
      this.searchUserNm = '';
    },
    /**
     * param: user -> Object
     * return:
     * exception:
     * Description : select approval path
     */
    selectedPath(user) {
      user.selected = !user.selected;

      this.apprPathList.splice(this.apprPathList.indexOf(user), 1, user);
    },
    /**
     * param:
     * return:
     * exception:
     * Description : search popup RequiredApprListPopup
     */
    onRequiredApprListPopup() {
      const { docType } = this.requiredApprovalUserList[0];
      SDLUtil.show(
        RequiredApprListPopup,
        {
          docType,
          rtnFunc: list => {
            this.showRequiredTooltip = false;

            let dupFlag = false;
            // Double-payer check
            Object.keys(list).forEach(i => {
              const userInfo = list[i];
              for (let j = 0; j < this.apprPathList.length; j += 1) {
                if (userInfo.userId === this.apprPathList[j].userId) {
                  dupFlag = true;
                  return;
                }
              }
            });
            if (dupFlag) {
              SDLUtil.alert('sdl.approval.message.duplicateApprover');
              return;
            }
            Object.keys(list).forEach(idx => {
              const apprLine = list[idx];
              this.apprPathList.push({
                stepIdx: apprLine.approvalStepSequence,
                parallel: false,
                approvalType: 'APPROVAL',
                required: true,
                hasError: false,
                approverChangeAllowed: true,
                bodyModify: apprLine.bodyModify,
                routeModify: apprLine.routeModify,
                arbitrary: apprLine.arbitrary,
                userId: apprLine.userId,
                userName: apprLine.userName,
                grdName: apprLine.grdName,
                deptName: apprLine.deptName,
                compName: apprLine.compName,
                apprPathFlag: false,
                docType,
              });
            });
            this.resetApprovalSeq();
          },
        },
        {
          width: '900px',
          height: 'auto',
        },
      );
    },
    /**
     * param: approvalType -> String
     * return:
     * exception:
     * Description : click top button(APPROVAL, AGREEMENT, NOTIFICATION)
     */
    changeApprovalType(approvalType) {
      if (this.apprPathList[0].selected) return; // The drafter cannot be changed

      // Approval person cannot be modified
      for (let i = 1; i < this.apprPathList.length; i += 1) {
        if (this.apprPathList[i].selected && !this.apprPathList[i].approverChangeAllowed) {
          SDLUtil.alert('sdl.approval.message.approverNotAllowedToChange');
          return;
        }
      }

      this.approvalType = approvalType;
      // if (!this.chkSelectDocType()) return;

      for (let i = 1; i < this.apprPathList.length; i += 1) {
        // Except the drafter
        if (this.apprPathList[i].selected) {
          this.apprPathList[i].approvalType = approvalType;
          this.apprPathList.splice(i, 1, this.apprPathList[i]);
        }
      }
    },
    /**
     * param: user -> Object
     * param: approvalType -> String
     * return:
     * exception:
     * Description : click left button(APPROVAL, AGREEMENT, NOTIFICATION)
     */
    changeUserApprovalType(user, approvalType) {
      if (this.apprPathList[0].selected) return; // The drafter cannot be changed

      // The authorized person cannot be modified
      if (!user.approverChangeAllowed) {
        SDLUtil.alert('sdl.approval.message.approverNotAllowedToChange');
        return;
      }

      user.approvalType = approvalType;
      this.apprPathList.splice(this.apprPathList.indexOf(user), 1, user);
    },
    /**
     * param:
     * return:
     * exception:
     * Description : click top delete button
     */
    deleteUserTopBtn() {
      if (this.apprPathList[0].selected) return; // The drafter cannot be changed

      let apprPathFlag = false;
      let parallelChkFlag = false;
      for (let i = 0; i < this.apprPathList.length; i += 1) {
        const opt = this.apprPathList[i];

        if (opt.selected && opt.parallel) {
          parallelChkFlag = true;
        }
        if (opt.selected && opt.apprPathFlag) {
          apprPathFlag = true;
        }
      }

      if (parallelChkFlag) {
        SDLUtil.alert('sdl.common.message.possibleToDeleteAfterParallelPayment');
        return;
      }

      if (apprPathFlag) {
        SDLUtil.alert('sdl.approval.message.delApprovalPathMgmt');
        return;
      }

      const selectedPathList = [];
      this.apprPathList.forEach(path => {
        if (path.selected) selectedPathList.push(path);
      });
      selectedPathList.forEach(selectedPath => {
        this.apprPathList.forEach((apprPath, idx) => {
          if (selectedPath === apprPath) this.apprPathList.splice(idx, 1);
        });
      });
      this.resetApprovalSeq();
    },
    /**
     * param: user -> Object
     * return:
     * exception:
     * Description : click right delete button
     */
    deleteUserRightBtn(user) {
      if (this.apprPathList[0].selected) return; // The drafter cannot be changed

      if (user.apprPathFlag) {
        SDLUtil.alert('sdl.approval.message.delApprovalPathMgmt');
        return;
      }

      if (user.parallel) {
        SDLUtil.alert('sdl.common.message.possibleToDeleteAfterParallelPayment');
        return;
      }

      this.apprPathList.splice(this.apprPathList.indexOf(user), 1);

      this.resetApprovalSeq();
    },
    /**
     * param:
     * return:
     * exception:
     * Description : reset approval sequence numbering
     */
    resetApprovalSeq() {
      let stepIdx = -1;
      let prevIsParallel = false;
      // let preIndex = -1;
      let preSelected = false;
      this.showRequiredTooltip = !this.apprPathList.some(appr => appr.required);
      for (let i = 0; i < this.apprPathList.length; i += 1) {
        const opt = this.apprPathList[i];
        if (!prevIsParallel || !opt.parallel) {
          stepIdx += 1;
        } else if (preSelected !== opt.selected) {
          stepIdx += 1;
        }
        // preIndex = opt.stepIdx;
        prevIsParallel = opt.parallel;
        opt.stepIdx = stepIdx;
        preSelected = opt.selected;

        this.apprPathList.splice(i, 1, opt);
      }
    },
    chkSelectDocType() {
      if (this.selectedDocTypeCode === '') {
        SDLUtil.alert('sdl.approval.message.selectApprovalDocType');
        return false;
      }
      return true;
    },
    /**
     * param:
     * return:
     * exception:
     * Description : Move to Top
     */
    stepTopUp() {
      while (this.stepUp());
    },
    /**
     * param:
     * return:
     * exception:
     * Description : Move up
     */
    stepUp() {
      if (this.apprPathList[0].selected) return false; // The drafter cannot be changed

      const checkParallesGroup = {};
      for (let i = 0; i < this.apprPathList.length; i += 1) {
        const opt = this.apprPathList[i];
        if (opt.parallel) {
          if (typeof checkParallesGroup[opt.stepIdx] === 'undefined') {
            const checkParalles = [];
            checkParalles.push(opt);
            checkParallesGroup[opt.stepIdx] = checkParalles;
          } else {
            checkParallesGroup[opt.stepIdx].push(opt);
          }
        }
      }
      // Check if it is parallel
      let paralleChkFlag = false;
      Object.keys(checkParallesGroup).forEach(i => {
        let n = 0;
        const opt = checkParallesGroup[i];
        Object.keys(opt).forEach(j => {
          if (opt[j].selected) {
            n += 1;
          }
        });
        if (n > 0 && n !== opt.length) {
          paralleChkFlag = true;
        }
      });

      if (paralleChkFlag) {
        SDLUtil.alert('sdl.common.message.parallelPaymentCanOnlyBeTransferred');
        return false;
      }

      let flag = false;
      for (let i = 1; i < this.apprPathList.length; i += 1) {
        if (this.apprPathList[i].selected) {
          if (i === 1) {
            return false;
          }
          const tmpItem = this.apprPathList[i];
          const parallelFlag = this.apprPathList[i - 1].parallel;
          this.apprPathList.splice(i, 1, this.apprPathList[i - 1]);
          this.apprPathList.splice(i - 1, 1, tmpItem);
          if (i - 2 >= 1 && this.apprPathList[i - 2].parallel && parallelFlag) {
            this.stepUp();
          }
          flag = true;
        }
      }
      this.resetApprovalSeq();
      return flag;
    },
    /**
     * param:
     * return:
     * exception:
     * Description : Move down
     */
    stepDown() {
      if (this.apprPathList[0].selected) return false; // The drafter cannot be changed

      const checkParallesGroup = {};
      for (let i = 0; i < this.apprPathList.length; i += 1) {
        const opt = this.apprPathList[i];
        if (opt.parallel) {
          if (typeof checkParallesGroup[opt.stepIdx] === 'undefined') {
            const checkParalles = [];
            checkParalles.push(opt);
            checkParallesGroup[opt.stepIdx] = checkParalles;
          } else {
            checkParallesGroup[opt.stepIdx].push(opt);
          }
        }
      }

      // Check if it is parallel
      let paralleChkFlag = false;
      Object.keys(checkParallesGroup).forEach(i => {
        let n = 0;
        const opt = checkParallesGroup[i];
        Object.keys(opt).forEach(j => {
          if (opt[j].selected) {
            n += 1;
          }
        });
        if (n > 0 && n !== opt.length) {
          paralleChkFlag = true;
        }
      });

      if (paralleChkFlag) {
        SDLUtil.alert('sdl.common.message.parallelPaymentCanOnlyBeTransferred');
        return false;
      }

      let flag = false;
      for (let i = this.apprPathList.length - 1; i >= 0; i -= 1) {
        if (this.apprPathList[i].selected) {
          if (i === this.apprPathList.length - 1) {
            return false;
          }
          const tmpItem = this.apprPathList[i];
          const parallelFlag = this.apprPathList[i + 1].parallel;
          this.apprPathList.splice(i, 1, this.apprPathList[i + 1]);
          this.apprPathList.splice(i + 1, 1, tmpItem);
          if (i + 2 < this.apprPathList.length && this.apprPathList[i + 2].parallel && parallelFlag) {
            this.stepDown();
          }
          flag = true;
        }
      }
      this.resetApprovalSeq();
      return flag;
    },
    /**
     * param:
     * return:
     * exception:
     * Description : Move to the bottom
     */
    stepBottomDown() {
      while (this.stepDown());
    },
  },
  created() {
    this.init();
  },
};
</script>
<style></style>
