<template>
  <div>
    <div
      v-if="processInstanceDescription != undefined"
      class="panel panel-default"
    >
      <div class="panel-heading">
        {{ $t("lang.approveComment.approveStatus") }}
        <span class="label label-primary m-label">
          {{
            processInstanceDescription.isActive
              ? $t("lang.approveComment.running")
              : $t("lang.approveComment.finished")
          }}
        </span>

        <span class="label label-info m-label">
          {{ $t("lang.approveComment.needApprove") }}:
          {{
            processInstanceDescription.activeTaskDescriptions == undefined
              ? "0"
              : processInstanceDescription.activeTaskDescriptions.length
          }}
        </span>

        <span class="label label-success m-label">
          {{ $t("lang.approveComment.approved") }}:
          {{
            processInstanceDescription.taskComments == undefined
              ? "0"
              : processInstanceDescription.taskComments.length
          }}
        </span>

        <span class="label label-warning m-label">
          {{ $t("lang.approveComment.abandon") }}:
          {{
            processInstanceDescription.abandonCount == undefined
              ? "0"
              : processInstanceDescription.abandonCount
          }}
        </span>
        
        <span v-if="windowNo == '20220707_162600'" class="label label-primary m-label" @click="viewApprovalProcess()">
          {{ $t("lang.approveComment.viewApprovalProcess") }}
        </span>
        <span v-if="windowNo == '20220703_174047'" class="label label-primary m-label" @click="viewApprovalProcess()">
          {{ $t("lang.approveComment.viewApprovalProcess") }}
        </span>
      </div>
      <div class="panel-body">
        <div class="progress">
          <div
            class="progress-bar progress-bar-success progress-bar-striped"
            role="progressbar"
            aria-valuenow="40"
            aria-valuemin="0"
            aria-valuemax="100"
            :style="{
              width: processInstanceDescription.isActive ? '50%' : '100%',
            }"
          >
            <span class="sr-only">{{
              processInstanceDescription.isActive
                ? $t("lang.approveComment.running")
                : $t("lang.approveComment.finished")
            }}</span>
            <!-- <span>查看审批流程</span> -->
          </div>
        </div>

        <div v-if="showChoiceButton && isActiveTask" class="form">
          <PreviousNodeSelectUser
            ref="previousNodeSelectUser"
            :process-instance-id="processInstanceId"
            :model-data="modelData"
            :work-flow="workFlow"
            :task-id="taskInfoId"
            :approve-form-value="approveFormValue"
          />

          <div class="form-group" style="margin-top: 10px">
            <div
              class="btn-group btn-group-justified"
              role="group"
              aria-label="..."
            >
              <div class="btn-group" role="group">
                <button
                  type="button"
                  class="btn btn-primary"
                  @click="modal3 = true"
                >
                  {{ $t("lang.approveComment.approve") }}<br />
                  <font v-if="$i18n.locale == 'zh-CN'">Approve</font>
                </button>
              </div>
              <div class="btn-group" role="group">
                <button type="button" class="btn btn-secondary" @click="transfer">
                  {{ $t("lang.approveComment.transfer") }}
                  <br />
                  <font v-if="$i18n.locale == 'zh-CN'">Forward</font>
                </button>
              </div>
              <div class="btn-group" role="group">
                <button type="button" class="btn btn-danger" @click="reject">
                  {{ $t("lang.approveComment.reject") }}
                  <br />
                  <font v-if="$i18n.locale == 'zh-CN'">Reject</font>
                </button>
              </div>
              <div class="btn-group" role="group">
                <button type="button" class="btn btn-warning" @click="withdraw">
                  {{ $t("lang.approveComment.return") }}
                  <br />
                  <font v-if="$i18n.locale == 'zh-CN'">Return</font>
                </button>
              </div>
              <div class="btn-group" role="group">
                <button
                  type="button"
                  class="btn btn-info"
                  @click="addComment"
                >
                  {{ $t("lang.approveComment.comment") }}
                  <br />
                  <font v-if="$i18n.locale == 'zh-CN'">Comments</font>
                </button>
              </div>
            </div>
          </div>

          <!-- 表单属性 -->

          <ApproveForm
            ref="approveForm"
            :process-instance-id="processInstanceId"
            :workflow="workFlow"
            :task-id="taskInfoId"
            @value-changed="approveFormValueChanged"
          />

          <div class="form-group">
            <label class="control-label">{{ $t("lang.approveComment.opinion") }}</label>
            <textarea v-model="comment" class="form-control" rows="3" />
          </div>

          <div class="form-group" :class="{ 'image-height': hasImage() }">
            <label class="control-label">{{ $t("lang.approveComment.picture") }}</label>
            <div class="input-group">
              <ImageListWidget ref="imageListWidget" :class-name="className" />
            </div>
          </div>

          <div class="form-group">
            <div id="uploadAttachmentForm">
              <label class="control-label" for="uploadAttachmentForm">{{
                $t("lang.approveComment.attachment")
              }}</label>
              <div class="input-group">
                <div
                  v-for="(item, index) in attachments"
                  :key="item.id"
                  class="file-box"
                >
                  <FileImage
                    :file-property="generateFileProperty(item)"
                    :show-image="true"
                  />
                  <span
                    class="glyphicon glyphicon-trash file-remove"
                    @click="removeFile(index)"
                  />
                </div>
                <div>
                  <label for="exampleInputFile" class="label-btn">
                    {{ $t("lang.approveComment.chooseFile") }}
                  </label>
                  <input
                    id="exampleInputFile"
                    autocomplete="off"
                    type="file"
                    class="inputfile"
                    @change="uploadFile"
                  />
                </div>
              </div>
            </div>
          </div>
        </div>

        <ul
          v-for="item in processInstanceDescription.historyProcessInstanceDescriptions"
          :key="item.id"
          class="media-list"
        >
          <li class="media">
            <div class="media-left">
              <a>
                <AuthImage
                  :auth-src="
                    Common.getThumbnailImageSrc(
                      'com.leanwo.prodog.base.model.User',
                      item.startUserImage
                    )
                  "
                  class="media-object thumbnail m-image"
                />
              </a>
            </div>
            <div class="media-body">
              <h4 class="media-heading">
                {{ item.startUserName }}
                <small class="badge alert-error">
                  {{ $t("lang.approveComment.submitUser") }}
                  ({{ $t("lang.approveComment.abandon") }})
                </small>
              </h4>
              <h5 class="m-h5">{{ item.startTime }}</h5>
              <p>{{ $t("lang.approveComment.submitApprove") }}</p>
            </div>
          </li>

          <template v-if="item.taskComments != undefined">
            <li
              v-for="taskComment in item.taskComments"
              :key="taskComment.id"
              class="media"
            >
              <div class="media-left">
                <a>
                  <AuthImage
                    :auth-src="
                      Common.getThumbnailImageSrc(
                        'com.leanwo.prodog.base.model.User',
                        taskComment.userImageUrl
                      )
                    "
                    class="media-object thumbnail m-image"
                  />
                </a>
              </div>
              <div class="media-body">
                <h4 class="media-heading">
                  {{ taskComment.userName }}
                  <small class="badge alert-error">{{ taskComment.taskName }}({{
                    $t("lang.approveComment.abandon")
                  }})</small>
                </h4>

                <div v-if="taskComment.comments != undefined">
                  <div
                    v-for="commentItem in taskComment.comments"
                    :key="commentItem.id"
                  >
                    <h5 class="m-h5">{{ commentItem.commentDate }}</h5>
                    <p>{{ commentItem.comment }}</p>
                  </div>
                </div>

                <div v-if="taskComment.imageNames != undefined">
                  <AuthImage
                    v-for="(imageName, index) in taskComment.imageNames"
                    :key="index"
                    :auth-src="getCommentImageSrc(imageName)"
                    class="thumbnail m-image1"
                    @click="openImageAttachment(imageName)"
                  />
                </div>

                <div v-if="taskComment.attachmentNames != undefined">
                  <a
                    v-for="(
                      attachmentName, index
                    ) in taskComment.attachmentNames"
                    :key="index"
                    :href="getAttachmentsUrl(attachmentName)"
                    target="view_window"
                    class="btn btn-primary btn-sm btn-block"
                  >{{ attachmentName }}</a>
                </div>
              </div>
            </li>
          </template>

          <template v-for="activeTask in processInstanceDescription.activeTaskDescriptions" :key="activeTask.id">
            <li
            
              v-if="processInstanceDescription.activeTaskDescriptions != undefined"
            
              class="media"
            >
              <div class="media-left">
                <a>
                  <AuthImage
                    :auth-src="
                      Common.getThumbnailImageSrc(
                        'com.leanwo.prodog.base.model.User',
                        activeTask.assigneeImageUrl
                      )
                    "
                    class="media-object thumbnail m-image"
                  />
                </a>
              </div>
              <div class="media-body">
                <h4 class="media-heading">
                  {{ activeTask.assignee }}
                  <small class="badge alert-error">{{ activeTask.name }}({{
                    $t("lang.approveComment.abandon")
                  }})</small>
                </h4>
                <h5 class="m-h5">{{ activeTask.startTime }}</h5>
                <p>{{ $t("lang.approveComment.processing") }}</p>
              </div>
            </li>
          </template>
        </ul>

        <ul class="media-list">
          <li class="media">
            <div class="media-left">
              <a>
                <AuthImage
                  id="image202002281140001"
                  :auth-src="
                    Common.getThumbnailImageSrc(
                      'com.leanwo.prodog.base.model.User',
                      processInstanceDescription.startUserImage
                    )
                  "
                  class="media-object thumbnail m-image"
                />
              </a>
            </div>
            <div class="media-body">
              <h4 class="media-heading">
                {{ processInstanceDescription.startUserName }}
                <small class="badge alert-success">{{
                  $t("lang.approveComment.submitUser")
                }}</small>
              </h4>
              <h5 class="m-h5">{{ processInstanceDescription.startTime }}</h5>
              <p>{{ $t("lang.approveComment.submitApprove") }}</p>
            </div>
          </li>

          <template v-if="processInstanceDescription.taskComments != undefined">
            <li
              v-for="taskComment in processInstanceDescription.taskComments"
              :key="taskComment.id"
              class="media"
            >
              <div class="media-left">
                <a>
                  <AuthImage
                    :auth-src="
                      Common.getThumbnailImageSrc(
                        'com.leanwo.prodog.base.model.User',
                        taskComment.userImageUrl
                      )
                    "
                    class="media-object thumbnail m-image"
                  />
                </a>
              </div>
              <div class="media-body">
                <h4 class="media-heading">
                  {{ taskComment.userName }}
                  <small class="badge alert-success">{{
                    taskComment.taskName
                  }}</small>
                </h4>

                <div v-if="taskComment.comments != undefined">
                  <div
                    v-for="commentItem in taskComment.comments"
                    :key="commentItem.id"
                  >
                    <h5 class="m-h5">{{ commentItem.commentDate }}</h5>
                    <p>{{ commentItem.comment }}</p>
                  </div>
                </div>

                <div v-if="taskComment.imageNames != undefined">
                  <AuthImage
                    v-for="(imageName, index) in taskComment.imageNames"
                    :key="index"
                    :auth-src="getCommentImageSrc(imageName)"
                    class="thumbnail m-image1"
                    @click="openImageAttachment(imageName)"
                  />
                </div>

                <div v-if="taskComment.attachmentNames != undefined">
                  <a
                    v-for="(
                      attachmentName, index
                    ) in taskComment.attachmentNames"
                    :key="index"
                    :href="getAttachmentsUrl(attachmentName)"
                    target="view_window"
                    class="btn btn-primary btn-sm btn-block"
                  >{{ attachmentName }}</a>
                </div>
              </div>
            </li>
          </template>

          <template v-for="activeTask in processInstanceDescription.activeTaskDescriptions" :key="activeTask.id">
            <li
            
              v-if="
                processInstanceDescription.activeTaskDescriptions != undefined
              "
            
              class="media"
            >
              <div class="media-left">
                <a>
                  <AuthImage
                    :auth-src="
                      Common.getThumbnailImageSrc(
                        'com.leanwo.prodog.base.model.User',
                        activeTask.assigneeImageUrl
                      )
                    "
                    class="media-object thumbnail m-image"
                  />
                </a>
              </div>
              <div class="media-body">
                <h4 class="media-heading">
                  {{ activeTask.assignee }}
                  <small class="badge alert-info">{{ activeTask.name }}</small>
                </h4>
                <h5 class="m-h5">{{ activeTask.startTime }}</h5>
                <p>{{ $t("lang.approveComment.processing") }}</p>
              </div>
            </li>
          </template>
        </ul>
      </div>
    </div>

    <Modal
      v-model:show="modal3"
      :small="true"
      :show-ok-button="false"
      :show-canel-button="false"
    >
      <template #header>
        <h3>{{ $t("lang.approveComment.notice") }}</h3>
      </template>
      <div class="row">
        <div class="col-md-12">
          <h3>{{ $t("lang.approveComment.confirmSubmit") }}</h3>
        </div>
        <div class="col-md-6">
          <button
            type="button"
            class="btn btn-success btn-lg"
            style="margin-top: 20px; width: 100%"
            @click="confirmApprove"
          >
            {{ $t("lang.approveComment.confirm") }}
          </button>
        </div>
        <div class="col-md-6">
          <button
            type="button"
            class="btn btn-default btn-lg"
            style="margin-top: 20px; width: 100%"
            @click="modal3 = false"
          >
            {{ $t("lang.approveComment.cancel") }}
          </button>
        </div>
      </div>
    </Modal>

    <Modal
      v-model:show="modal4"
      :small="true"
      :show-ok-button="false"
      :show-canel-button="false"
    >
      <template #header>
        <h3>{{ $t("lang.approveComment.notice") }}</h3>
      </template>
      <div class="row">
        <div class="col-md-12">
          <h3>{{ $t("lang.approveComment.rejectConfirm") }}</h3>
        </div>
        <div class="col-md-6">
          <button
            type="button"
            class="btn btn-success btn-lg"
            style="margin-top: 20px; width: 100%"
            @click="confirmReject"
          >
            {{ $t("lang.approveComment.confirm") }}
          </button>
        </div>

        <div class="col-md-6">
          <button
            type="button"
            class="btn btn-default btn-lg"
            style="margin-top: 20px; width: 100%"
            @click="modal4 = false"
          >
            {{ $t("lang.approveComment.cancel") }}
          </button>
        </div>
      </div>
    </Modal>

    <Modal v-model:show="modal5" :full="true">
      <InfoWindow
        ref="info"
        :info-window-no="infoWindowNo"
        :where-clause-source="whereClauseSource"
        @data-selected="transferSelectedUser"
      />
      <template #header>
        {{ $t("lang.approveComment.chooseTransferUser") }}
      </template>
    </Modal>

    <Modal v-model:show="modal6" :full="true" @ok="transferSave">
      <textarea
        v-model="transferText"
        width="100%"
        class="form-control"
        :placeholder="$t('lang.approveComment.inputComment')"
      />
      <template #header>
        {{ $t("lang.approveComment.transferTo") }}{{ transferUserName }}
      </template>
    </Modal>

    <Modal
      v-model:show="modal7"
      :small="true"
      :show-ok-button="false"
      :show-canel-button="false"
    >
      <template #header>
        <h3>{{ $t("lang.approveComment.notice") }}</h3>
      </template>
      <div class="row">
        <div class="col-md-12">
          <h3>{{ $t("lang.approveComment.returnConfirm") }}</h3>
        </div>
        <div class="col-md-6">
          <button
            type="button"
            class="btn btn-success btn-lg"
            style="margin-top: 20px; width: 100%"
            @click="confirmReturn"
          >
            {{ $t("lang.approveComment.confirm") }}
          </button>
        </div>

        <div class="col-md-6">
          <button
            type="button"
            class="btn btn-default btn-lg"
            style="margin-top: 20px; width: 100%"
            @click="modal7 = false"
          >
            {{ $t("lang.approveComment.cancel") }}
          </button>
        </div>
      </div>
    </Modal>

    <Loading v-if="loading" />
  </div>
</template>

<script>
import Common from '../common/Common.js';
import WindowService from '../common/WindowService.js';

import CustomerWindowResource from '../resource/dictionary/CustomerWindowResource.js';
import UserStorageResource from '../api/base/UserStorageResource.js';
import UserResource from '../api/base/UserResource.js';
import WorkflowResource from '../api/workflow/WorkflowResource.js';

import ImageListWidget from './ImageListWidget.vue';
import PreviousNodeSelectUser from './PreviousNodeSelectUser.vue';


import FileImage from '../widget/FileImage.vue';

import AuthImage from '../widget/AuthImage.vue';
import ApproveForm from './ApproveForm.vue';

import vSelect from 'vue-select';
import 'vue-select/dist/vue-select.css';
import { Notify, Uuid } from 'pc-component-v3';
export default {

  components: {
    ImageListWidget,
    FileImage,
    AuthImage,
    vSelect,
    PreviousNodeSelectUser,
    ApproveForm,
  },

  props: {
    windowNo: {
      type: String,
      default: null,
    },
    processInstanceId: {
      type: String,
      default: null,
    },
    taskInfoId: {
      type: String,
      default: null,
    },
    showChoiceButton: {
      type: Boolean,
      default: null,
    },
    recordId: {
      type: Number,
      default: null,
    },
    workFlow: {
      type: Object,
      default : function(){
        return null;
      },
    },
    workflowType: {
      type: String,
      default: null,
    },
    modelData: {
      type: Object,
      default : function(){
        return null;
      },
    },
    uuid: {
      type: String,
      default: null,
    },
    parentWidget: {
      type: String,
      default: null,
    },
    workflowClassName: {
      type: String,
      default: null,
    },
  },
  emits: ['saveData'],

  data: function () {
    this.Common = Common;
    return {
      processInstanceDescription: {},
      attachments: [],
      comment: '',
      className: 'WorkFlow',
      infoWindowNo: '050408',
      className1: 'com.leanwo.prodog.base.model.User',
      copyUsers: [],
      currentUser: '',
      whereClauseSource: {
        customWhere: null,
      },
      selectedUserTaskDto: '',
      currentUsers: [],
      transferUserId: undefined,
      transferUserName: undefined,
      transferText: undefined,
      userName: undefined,
      organizationName: undefined,
      userItem: undefined,
      isActiveTask: false, // 是否是有效的任务(任务未结束，任务属于登录人员)
      approveFormValue: null, // 自定义表单的数据
      loading: false,
      modal3: false,
      modal4: false,
      modal5: false,
      modal6: false,
      modal7: false,
    };
  },

  watch: {
    processInstanceId: function (currentValue, oldValue) {
      this.refresh();
    },

    taskInfoId: function (currentValue, oldValue) {
      this.checkIsActiveTask();
    },
  },

  mounted: function () {
    var _self = this;
    this.refresh();
    this.checkIsActiveTask();
  },

  methods: {
    /**
     * 获取图片路径
     * @param  {String} imageName 图片名称
     * @return {void}
     */
    getImgSrc: function (imageName) {
      var _self = this;
      if (imageName == undefined || imageName == '') {
        return '/static/assets/client-base-v4/image/noImage.jpg';
      }
      return Common.getImageSrc(_self.className, imageName);
    },

    /**
     * 转交保存
     */
    transferSave: function () {
      var _self = this;
      _self.loading=true;
      var transferTask = new Object();
      transferTask.workflowType = _self.workFlow.workflowType;
      transferTask.taskId = _self.taskInfoId;
      transferTask.comment = _self.transferText;
      transferTask.transferUserName = _self.transferUserName;
      transferTask.transferUserId = _self.transferUserId;
      transferTask.className = _self.workflowClassName;
      transferTask.recordId = _self.recordId;
      console.log(_self.workflowClassName);
      $.ajax({
        url: Common.getApiURL('WorkflowResource/transfer'),
        type: 'post',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        contentType: 'application/json',
        data: JSON.stringify(transferTask),
        success: function (data) {
          _self.loading=false;
          Notify.success('通知', '数据提交成功', true);
          setTimeout(function () {
            window.close();
          }, 1000);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          _self.loading=false;
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    /**
     * 选择用户后
     * @param  {Object} modelData 用户信息
     * @return {void}
     */
    transferSelectedUser: function (modelData) {
      var _self = this;
      this.modal5 = false;
      var userId = modelData.id;
      _self.loading=true;
      $.ajax({
        url: Common.getApiURL('userResource/getUser'),
        type: 'get',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        data: {
          userId: userId,
        },
        success: function (data) {
          _self.loading=false;
          _self.transferUserId = data.id;
          _self.transferUserName = data.name;
          _self.modal6 = true;
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          _self.loading=false;
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    /**
     * 查看审批流程
     * @author XiongLiuJie 20221952
     */
    viewApprovalProcess: function(){
      let _self = this;
      if(_self.windowNo == '20220707_162600'){
        let isAutoFlow = _self.modelData.data.isAutoFlow.displayValue[0];
        if(isAutoFlow == 'false'){
          let totalAmountUSD = _self.modelData.data.totalAmountUSD.displayValue[0];
          if(totalAmountUSD < 5000){
            let url = '/static/x-spreadsheet/index.html?processReportNo=20221110_200758&recordId=' + _self.recordId;
            window.open(url);
            // window.layer.open({
            //   title: '查看ADA审批人报告',
            //   type: 2,
            //   area: ['1280px', '720px'],
            //   fixed: false, //不固定
            //   maxmin: true,
            //   content: url,
            // });
          }
          if(totalAmountUSD > 5000){
            let url = '/static/x-spreadsheet/index.html?processReportNo=20221117_022208&recordId=' + _self.recordId;
            window.open(url);
            // window.layer.open({
            //   title: '查看ADA审批人报告',
            //   type: 2,
            //   area: ['1280px', '720px'],
            //   fixed: false, //不固定
            //   maxmin: true,
            //   content: url,
            // });
          }
          
        }else{
          let url = '/static/x-spreadsheet/index.html?processReportNo=20221117_013808&recordId=' + _self.recordId;
          window.open(url);
          // window.layer.open({
          //   title: '查看Auto_ADA审批人报告',
          //   type: 2,
          //   area: ['1280px', '720px'],
          //   fixed: false, //不固定
          //   maxmin: true,
          //   content: url,
          // });
        }
      }
      if(_self.windowNo == '20220703_174047'){
        let totalAmountUSD = _self.modelData.data.totalAmountUSD.displayValue[0];
        if(totalAmountUSD < 5000){
          let url = '/static/x-spreadsheet/index.html?processReportNo=20221110_204424&recordId=' + _self.recordId;
          window.open(url);
          // window.layer.open({
          //   title: '查看ATA审批人报告',
          //   type: 2,
          //   area: ['1280px', '720px'],
          //   fixed: false, //不固定
          //   maxmin: true,
          //   content: url,
          // });
        }
        if(totalAmountUSD > 5000){
          let url = '/static/x-spreadsheet/index.html?processReportNo=20221117_025516&recordId=' + _self.recordId;
          window.open(url);
          // window.layer.open({
          //   title: '查看ATA审批人报告',
          //   type: 2,
          //   area: ['1280px', '720px'],
          //   fixed: false, //不固定
          //   maxmin: true,
          //   content: url,
          // });
        }
      }
    },

    /**
     * 转批
     * @author GuoZhiBo 20200611
     */
    transfer: function () {
      var _self = this;
      _self.initData();
      if(_self.windowNo != null && (_self.windowNo == '20220707_162600' || _self.windowNo == '20220703_174047')){
        _self.infoWindowNo = '20220928_175733';
        let areaId = _self.modelData.data.area.id;
        _self.whereClauseSource.customWhere = ' fm.areaId = ' + areaId;
      }else{
        _self.infoWindowNo = '050408';
        let customerDataDimensions = [{
          fieldName: 'client.id',
          dataDimensionTypeNo: '202201191757',
          defaultDataDimensionTypeValueNo: '4',
        }];
        _self.whereClauseSource.customerDataDimensions = customerDataDimensions;
      }
      _self.modal5 = true;
    },

    /**
     * 确认审批通过
     */
    confirmApprove: function () {
      var _self = this;
      _self.modal3 = false;
      if (_self.parentWidget == 'TabFormEdit') {
        this.$emit('saveData', 'APPROVE');
      } else {
        this.saveData('APPROVE');
      }
    },

    /**
     * 确认审批不通过
     */
    confirmReject: function () {
      var _self = this;
      _self.modal4 = false;
      this.saveData('REJECT');
    },

    /**
     * 初始化数据
     * @return {void}
     */
    initData: function () {
      var _self = this;
    },

    /**
     * 删除文件
     */
    removeFile: function (index) {
      this.attachments.splice(index, 1);
    },

    /**
     * 生成文件属性
     */
    generateFileProperty: function (item) {
      return {
        fileName: item,
      };
    },

    /**
     * 表单搜索框数据发生改变
     */
    valueChanged: function (newFieldValue, item) {
      item.value = newFieldValue.id;
    },

    /**
     * 刷新流程信息
     */
    refresh: function () {
      var _self = this;
      _self.loading=true;

      if (
        _self.processInstanceId == undefined ||
        _self.processInstanceId.length == 0
      ) {
        _self.processInstanceDescription = {};
        return;
      }

      $.ajax({
        url: Common.getApiURL('WorkflowResource/ProcessInstanceDescription'),
        type: 'GET',
        dataType: 'json',
        data: {
          processInstanceId: _self.processInstanceId,
          recordId: _self.recordId,
        },
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          _self.loading=false;
          _self.processInstanceDescription = data;
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          _self.loading=false;
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    /**
     * 上传文件
     */
    uploadFile: function (event) {
      var _self = this;

      let fileList = event.target.files;
      var selectedFile = null;
      if (fileList.length > 0) {
        selectedFile = fileList[0];
      }
      if (selectedFile == null) {
        return;
      }
      var formData = new FormData();
      formData.append('file', selectedFile);
      formData.append('className', _self.className);
      _self.loading=true;

      $.ajax({
        url: Common.getApiURL('file/multipleAttachmentUpload'),
        type: 'post',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        data: formData,
        contentType: false,
        processData: false,
        success: function (data) {
          _self.loading=false;
          if (data.success) {
            var fileNames = data.fileNames;
            if (fileNames != undefined && fileNames.length > 0) {
              fileNames.forEach(function (item) {
                //   _self.attachments = [item.nameAfterSave];
                _self.attachments.push(item.nameAfterSave);
              });
            }
          }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          _self.loading=false;
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    /**
     * 拒绝
     */
    reject: function () {
      var _self = this;
      if (_self.comment == undefined || _self.comment.length == 0) {
        Notify.error('没有理由', '请填写拒绝的理由。', false);
        return;
      }
      _self.modal4 = true;
    },

    /**
     * 退回审批
     */
    withdraw: function () {
      var _self = this;
      if (_self.comment == undefined || _self.comment.length == 0) {
        Notify.error('没有理由', '请填写退回的理由。', false);
        return;
      }
      _self.modal7 = true;
      
    },

    /**
     * 确认退回
     */
    confirmReturn: function () {
      var _self = this;
      _self.modal7 = false;
      this.saveData('WITHDRAW');
    },

    /**
     * 添加评论
     */
    addComment: function () {
      var _self = this;

      if (_self.comment == undefined || _self.comment.length == 0) {
        Notify.error('无评论', '请填写评论。', false);
        return;
      }

      var chooseTask = {
        taskId: _self.taskInfoId,
        comment: _self.comment,
        imageNames: _self.$refs.imageListWidget.getImages(),
        attachmentNames: _self.attachments,
      };

      _self.loading=true;

      $.ajax({
        url: Common.getApiURL('WorkflowResource/AddComment'),
        type: 'post',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        contentType: 'application/json',
        data: JSON.stringify(chooseTask),
        success: function (data) {
          _self.loading=false;
          _self.comment = '';
          _self.refresh();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          _self.loading=false;
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    /**
     * 提交审批结果
     */
    saveData: function (command, modelData) {
      var _self = this;
      var chooseTask = new Object();

      chooseTask.workflowType = _self.workFlow.workflowType;
      chooseTask.taskId = _self.taskInfoId;
      chooseTask.command = command;
      chooseTask.comment = _self.comment;
      chooseTask.processInstanceId = _self.processInstanceId;
      chooseTask.windowNo = _self.windowNo;
      chooseTask.tabIndex = 0;
      chooseTask.recordId = _self.recordId;
      chooseTask.modelData = modelData;
      chooseTask.className = _self.workflowClassName;

      //var images = _self.$refs.imageListWidget.getImages();
      //console.log(images);
      //chooseTask.imageNames = images;
      //chooseTask.attachmentNames = _self.attachments;

      // 添加工作流表单数据

      if (command === 'APPROVE') {
        try {
          chooseTask.keyValueObjects = this.$refs.approveForm.getData();
        } catch (exception) {
          console.log(exception);
          return;
        }

        try {
          const param = this.$refs.previousNodeSelectUser.getData();
          chooseTask.copyUserIds = param.copyUsers;
          chooseTask.userSelectDtos = param.userSelectDtos;
        } catch (exception) {
          Notify.error('存在未设置的审批人', exception.message, false);
          return;
        }
      }

      _self.loading=true;
      $.ajax({
        url: Common.getApiURL('WorkflowResource/SetChoice'),
        type: 'post',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        contentType: 'application/json',
        data: JSON.stringify(chooseTask),
        success: function (data) {
          _self.loading=false;

          Notify.success('通知', '数据提交成功', true);

          setTimeout(function () {
            window.location.reload();
            WindowService.close();
          }, 1000);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          _self.loading=false;
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    hasImage: function () {
      var _self = this;
      if (_self.$refs.imageListWidget) {
        var images = _self.$refs.imageListWidget.getImages();
        if (images != undefined && images.length > 0) {
          return true;
        }
      }
      return false;
    },

    /**
     * 获取评论的图片
     * @param  {[type]} imageUrl [description]
     * @return {[type]}          [description]
     */
    getCommentImageSrc: function (imageUrl) {
      console.log(imageUrl);
      var realImageUrl = Common.getImageSrc(
        this.className,
        'thumbnail/' + imageUrl,
      );
      return realImageUrl;
    },

    /**
     * 打开图片附件的功能
     * @param  {[type]} imageName [description]
     * @return {[type]}           [description]
     */
    openImageAttachment: function (imageName) {
      if (imageName == undefined) {
        return;
      }
      var fullPath = Common.getImageSrc(this.className, imageName);
      window.open(fullPath);
    },

    /**
     * 获取附件的URL
     * @param  {[type]} url [description]
     * @return {[type]}     [description]
     */
    getAttachmentsUrl: function (url) {
      console.log(url);
      return Common.getAttachmentsSrc(this.className, url);
    },

    /**
     * 打开自定义窗口
     */
    openCustomerWindow: function (customerWindowId) {
      var _self = this;

      CustomerWindowResource.getById(customerWindowId).then(
        successData => {
          if (successData == null) {
            Notify.error(
              '自定义窗口',
              'id=' + customerWindowId + '的自定义窗口已经被删除。',
              true,
            );
            return;
          }
          var routeDate = {
            path: successData.routeUrl,
            params: {
              modelData: _self.modelData,
            },
          };
          // 请勿修改，会影响生单的功能
          let key = _self.uuid + '_modelData';
          let userStorageDtos = [
            {
              key: key,
              value: JSON.stringify(_self.modelData),
            },
          ];
          // 组装查询条件，然后放到后台数据库当中
          _self.saveToUserStorage(userStorageDtos);

          // localStorage.setItem(uuid + "_modelDatas", JSON.stringify(this.modelDatas));
          routeDate.path = routeDate.path + '/' + _self.uuid;

          _self.$emit('saveView');

          _self.$router.push(routeDate);
        },
        errorData => {
          Common.processException(errorData);
        },
      );
    },

    /**
     * 保存到userStorage中
     * @author LeiGuoXian
     * @date 2020-09-17
     */
    saveToUserStorage: function (userStorageDtos) {
      var _self = this;
      // 组装查询条件，然后放到后台数据库当中
      UserStorageResource.uploadUserStorage(userStorageDtos).then(
        successData => {},
        errorData => {
          Common.processException(errorData);
        },
      );
    },

    /**
     * 检查是否是有效的任务
     * 1. 任务仍然存在
     * 2. 任务属于登录人
     */
    checkIsActiveTask: function () {
      if (this.taskInfoId == null) {
        this.isActiveTask = false;
        return;
      }

      WorkflowResource.uniqueTaskInfoByTaskIdUserId(this.taskInfoId).then(
        successData => {
          if (successData == null) {
            this.isActiveTask = false;
          } else {
            this.isActiveTask = true;
          }
        },
        errorData => {
          Common.processException(errorData);
        },
      );
    },
    /**
     * 自定义表单的数据发生变化
     */
    approveFormValueChanged: function (newApproveFormValue) {
      this.approveFormValue = newApproveFormValue;
    },
  },
};
</script>
<style scoped>
.m-label {
  margin-left: 10px;
}

.m-h5 {
  display: inline;
}

.m-image {
  width: 64px;
  height: 64px;
}

.m-image1 {
  display: inline !important;
  width: 64px;
  height: 64px;
  cursor: pointer;
  margin-right: 5px;
}
.inputfile {
  width: 0.1px;
  height: 0.1px;
  opacity: 0;
  overflow: hidden;
  position: absolute;
  z-index: -1;
}
.label-btn {
  color: white;
  background-color: #006699;
  display: inline-block;
  padding: 5px 15px;
  border-radius: 5px;
}
.label-btn:hover {
  color: white;
  background-color: #003399;
  display: inline-block;
  padding: 5px 15px;
  border-radius: 5px;
  cursor: pointer;
}
.file-box {
  width: 150px;
  position: relative;
  display: table-cell;
}
.file-remove {
  position: absolute;
  right: 0px;
  color: #43a51e;
  cursor: pointer;
}

.img-label {
  height: 80px;
  line-height: 80px;
  padding-top: 0px !important;
}

.img-box {
  width: 60px;
  height: 80px;
  float: left;
  text-align: center;
  margin-right: 20px;
}

.img-box div img {
  width: 60px;
  height: 60px;
}

.add-box {
  width: 60px;
  height: 60px;
  float: left;
  border-radius: 30px;
  border: 1px #999 dashed;
  text-align: center;
  margin-top: 20px;
}

.add-box:hover {
  cursor: pointer;
  background-color: #ccc;
}

.add-icon {
  width: 60px;
  height: 60px;
  color: #aaa;
  font-size: 40px;
  line-height: 60px;
  position: relative;
  top: -1px;
}

.remove-icon {
  color: red;
  position: relative;
  top: 10px;
  right: -30px;
  cursor: pointer;
}

.table-box td,
th {
  text-align: center;
}

@keyframes go {
  0 {
    transform: scale(1);
  }
  /* 25% {
		transform: scale(1.2);
	} */
  50% {
    transform: scale(1.2);
  }
  /* 75% {
		transform: scale(1.2);
	} */
  100% {
    transform: scale(1);
  }
}
button.forSaleOrder {
  animation: go 3s infinite;
  text-shadow: 1px 1px 1px black;
}
</style>