<template>
  <div>
    <div v-if="processInstanceDescription != undefined">
      <div class="page-header">
        <h4 style="display: inline-block; margin-right: 2rem;">
          {{ $t("lang.approveComment.approveStatus") }}
        </h4>
        <a-tag color="processing">
          <template #icon>
            <sync-outlined :spin="true" />
          </template>
          {{
            !processInstanceDescription.suspended
              ? $t("lang.approveComment.running")
              : $t("lang.approveComment.finished")
          }}
        </a-tag>

        <a-tag color="warning">
          <template #icon>
            <clock-circle-outlined />
          </template>
          {{ $t("lang.approveComment.needApprove") }}:
          {{
            processInstanceDescription.taskDescriptions == undefined
              ? "0"
              : processInstanceDescription.taskDescriptions.length
          }}
        </a-tag>


        <a-tag color="success">
          <template #icon>
            <check-circle-outlined />
          </template>
          {{ $t("lang.approveComment.approved") }}:
          {{
            processInstanceDescription.historicTaskInstanceDescriptions == undefined
              ? "0"
              : processInstanceDescription.historicTaskInstanceDescriptions.length
          }}
        </a-tag>
      </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">
            <a-flex justify="space-between" align="flex-start" gap="middle">
              <a-button type="primary" size="large" class="approve-button" @click="modal3 = true">
                {{ $t("lang.approveComment.approve") }}<br />
              </a-button>
              <a-button size="large" class="approve-button" @click="transfer">
                {{ $t("lang.approveComment.transfer") }}
              </a-button>
              <a-button size="large" class="approve-button" danger @click="reject">
                {{ $t("lang.approveComment.reject") }}
              </a-button>
              <a-button size="large" class="approve-button" @click="withdraw">
                {{ $t("lang.approveComment.return") }}
              </a-button>
              <a-button size="large" class="approve-button" @click="addComment">
                {{ $t("lang.approveComment.comment") }}
              </a-button>
            </a-flex>
          </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>

          <ApproveTaskAttachmentEdit :task-id="taskInfoId" />
        </div>



        <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 class="comment-text">{{ $t("lang.approveComment.submitApprove") }}</p>
            </div>
          </li>

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

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

                <ApproveTaskAttachmentView
                  :enable-delete="false"
                  :attachments="historicTaskInstanceDescription.attachments"
                />
              </div>
            </li>
          </template>

          <template v-for="activeTask in processInstanceDescription.taskDescriptions" :key="activeTask.id">
            <li
              v-if="
                processInstanceDescription.taskDescriptions != 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.assigneeName }}
                  <small class="badge alert-info">{{ activeTask.name }}</small>
                </h4>
                <h5 class="m-h5">{{ activeTask.startTime }}</h5>
                <p class="comment-text">{{ $t("lang.approveComment.processing") }}</p>


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

                <ApproveTaskAttachmentView
                  :enable-delete="activeTask.id == taskInfoId"
                  :attachments="activeTask.attachments"
                />
              </div>
            </li>
          </template>
        </ul>
      </div>
    </div>

    <a-modal
      v-model:open="modal3"
      :title="$t('lang.approveComment.notice')"
      :cancel-text="$t('lang.approveComment.cancel')"
      :ok-text="$t('lang.approveComment.confirm')"
      @ok="confirmApprove"
    >
      {{ $t("lang.approveComment.confirmSubmit") }}
    </a-modal>

    <a-modal
      v-model:open="modal4" 
      :title="$t('lang.approveComment.notice')"
      :cancel-text="$t('lang.approveComment.cancel')"
      :ok-text="$t('lang.approveComment.confirm')"
      @ok="confirmReject"
    >
      {{ $t("lang.approveComment.rejectConfirm") }}
    </a-modal>

    <a-modal v-model:open="modal5" width="80%" :title="$t('lang.approveComment.chooseTransferUser')">
      <InfoWindow
        ref="info" :info-window-no="infoWindowNo" :where-clause-source="whereClauseSource"
        @data-selected="transferSelectedUser"
      />
    </a-modal>

    <a-modal v-model:open="modal6" :title="$t('lang.approveComment.transfer')" @ok="transferSave">
      <a-flex gap="small" vertical>
        <div>{{ $t("lang.approveComment.transferTo") }}: {{ transferUserName }}</div>
        <div>
          {{ $t('lang.approveComment.transferReason') }}
        </div>
        <a-textarea
          v-model:value="transferText" :placeholder="$t('lang.approveComment.inputTransferReason')"
          :auto-size="{ minRows: 3, maxRows: 10 }"
        />
      </a-flex>
    </a-modal>

    <a-modal
      v-model:open="modal7" :small="true" 
      :title="$t('lang.approveComment.notice')" :cancel-text="$t('lang.approveComment.cancel')"
      :ok-text="$t('lang.approveComment.confirm')" @ok="confirmReturn"
    >
      {{ $t("lang.approveComment.returnConfirm") }}
    </a-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 PreviousNodeSelectUser from './PreviousNodeSelectUser.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 ApproveTaskAttachmentEdit from './ApproveTaskAttachmentEdit.vue';
import ApproveTaskAttachmentView from './ApproveTaskAttachmentView.vue';
import { CheckCircleOutlined, SyncOutlined, ClockCircleOutlined } from '@ant-design/icons-vue';
import { notification } from 'ant-design-vue';


export default {

  components: {
    AuthImage,
    vSelect,
    PreviousNodeSelectUser,
    ApproveForm,
    ApproveTaskAttachmentEdit,
    ApproveTaskAttachmentView,
    CheckCircleOutlined,
    SyncOutlined,
    ClockCircleOutlined,
  },

  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: {},
      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;
          notification.success({
            message: '操作成功',
            description: '单据转交成功',
          });
          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 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;
    },


    /**
     * 生成文件属性
     */
    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);
        },
      });
    },


    /**
     * 拒绝
     */
    reject: function () {
      var _self = this;
      if (_self.comment == undefined || _self.comment.length == 0) {
        notification.error({
          message: '操作失败',
          description: '请填写拒绝原因',
        });
        return;
      }
      _self.modal4 = true;
    },

    /**
     * 退回审批
     */
    withdraw: function () {
      var _self = this;
      if (_self.comment == undefined || _self.comment.length == 0) {
        notification.error({
          message: '操作失败',
          description: '请填写退回原因',
        });
        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) {
        notification.error({
          message: '操作失败',
          description: '未填写评论信息，请先填写评论信息。',
        });
        return;
      }

      var addCommentRequest = {
        taskId: _self.taskInfoId,
        comment: _self.comment,
      };

      _self.loading = true;

      $.ajax({
        url: Common.getApiURL('WorkflowResource/addComment'),
        type: 'post',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        contentType: 'application/json',
        data: JSON.stringify(addCommentRequest),
        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;


      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) {

          notification.error({
            message: '操作失败',
            description: '存在未设置的审批人。' + exception.message,
          });
        
          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;

          
          notification.success({
            message: '操作成功',
            description: '已经成功的完成了任务。',
          });


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


    /**
     * 获取评论的图片
     * @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);
    },


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

      CustomerWindowResource.getById(customerWindowId).then(
        successData => {
          if (successData == null) {
            
            notification.error({
              message: '操作失败',
              description: '自定义窗口已经被删除。',
            });
          
            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 || successData.id == 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;
  margin-bottom: 0px;
}

.m-image1 {
  display: inline !important;
  width: 64px;
  height: 64px;
  cursor: pointer;
  margin-right: 5px;
}

.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;
}

.comment-text {
  margin-bottom: 0px;
}

.approve-button {
  width: 100%;
}
</style>