<template>
  <div>
    <div v-if="processInstanceDescription != undefined">
      <div class="page-header-box">
        <a-space align="center" :size="16">
          <h4 style="margin: 0">{{ $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?.length || 0 }}
          </a-tag>

          <a-tag color="success">
            <template #icon><check-circle-outlined /></template>
            {{ $t("lang.approveComment.approved") }}: {{
              processInstanceDescription.historicTaskInstanceDescriptions?.length || 0
            }}
          </a-tag>
        </a-space>
      </div>

      <div class="approve-content">
        <a-typography-title v-if="currentTaskInfo?.description" :level="3" class="task-title">
          {{ currentTaskInfo?.description }}
        </a-typography-title>

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

          <a-flex class="action-buttons" justify="space-between" align="flex-start" gap="middle">
            <a-button style="width: 100%;" type="primary" size="large" @click="modal3 = true">
              {{ (currentTaskInfo?.category === 'MandatoryTask') ? $t("lang.approveComment.complete") :
                $t("lang.approveComment.approve") }}
            </a-button>
            <a-button style="width: 100%;" size="large" @click="transfer">
              {{ $t("lang.approveComment.transfer")
              }}
            </a-button>
            <a-button style="width: 100%;" size="large" danger @click="reject">
              {{ $t("lang.approveComment.reject")
              }}
            </a-button>
            <a-button style="width: 100%;" size="large" @click="withdraw">
              {{ $t("lang.approveComment.return")
              }}
            </a-button>
            <a-button style="width: 100%;" size="large" @click="addComment">
              {{ $t("lang.approveComment.comment")
              }}
            </a-button>
          </a-flex>

          <ApproveForm
            v-if="currentTaskInfo?.category !== 'MandatoryTask'" ref="approveForm"
            :process-instance-id="processInstanceId" :workflow="workFlow" :task-id="taskInfoId"
            @value-changed="approveFormValueChanged"
          />

          <div v-if="currentTaskInfo?.category !== 'MandatoryTask'" class="comment-section">
            <a-typography-text strong>{{ $t("lang.approveComment.opinion") }}</a-typography-text>
            <a-textarea v-model:value="comment" :auto-size="{ minRows: 3, maxRows: 5 }" />
          </div>

          <ApproveTaskAttachmentEdit v-if="currentTaskInfo?.category !== 'MandatoryTask'" :task-id="taskInfoId" />
        </div>

        <a-list size="small" :split="false" class="approve-list">
          <!-- 提交人信息 -->
          <a-list-item>
            <a-list-item-meta>
              <template #avatar>
                <AntdAuthImage
                  :is-preview="false" :width="64" :height="64"
                  :auth-src="Common.getThumbnailImageSrc('com.leanwo.prodog.base.model.User', processInstanceDescription.startUserImage)"
                />
              </template>
              <template #title>
                <a-space>
                  {{ processInstanceDescription.startUserName }}
                  <a-tag color="red">{{ $t("lang.approveComment.submitUser") }}</a-tag>
                </a-space>
              </template>
              <template #description>
                <div class="comment-group">
                  <div class="comment-item">
                    <div class="time-info">{{ processInstanceDescription.startTime }}</div>
                    <span class="comment-text">{{ $t("lang.approveComment.submitApprove") }}</span>
                  </div>
                </div>
              </template>
            </a-list-item-meta>
          </a-list-item>

          <!-- 历史审批记录 -->
          <template v-if="processInstanceDescription.historicTaskInstanceDescriptions">
            <a-list-item
              v-for="historicTaskInstanceDescription in processInstanceDescription.historicTaskInstanceDescriptions"
              :key="historicTaskInstanceDescription.id"
            >
              <a-list-item-meta>
                <template #avatar>
                  <AntdAuthImage
                    :is-preview="false" :width="64" :height="64"
                    :auth-src="Common.getThumbnailImageSrc('com.leanwo.prodog.base.model.User', historicTaskInstanceDescription.assigneeImageUrl)"
                  />
                </template>
                <template #title>
                  <a-space>
                    {{ historicTaskInstanceDescription.assigneeName }}
                    <a-tag color="blue">
                      {{ historicTaskInstanceDescription.name }}({{
                        getTaskCompleteType(historicTaskInstanceDescription.completeReason) }})
                    </a-tag>
                  </a-space>
                </template>
                <template #description>
                  <div v-if="historicTaskInstanceDescription.comments" class="comment-group">
                    <div
                      v-for="commentItem in historicTaskInstanceDescription.comments" :key="commentItem.id"
                      class="comment-item"
                    >
                      <div class="time-info">{{ commentItem.time }}</div>
                      <span class="comment-text">{{ commentItem.message }}</span>
                    </div>
                  </div>
                  <ApproveTaskAttachmentView
                    :enable-delete="false"
                    :attachments="historicTaskInstanceDescription.attachments"
                  />
                </template>
              </a-list-item-meta>
            </a-list-item>
          </template>

          <!-- 当前任务 -->
          <template v-for="activeTask in processInstanceDescription.taskDescriptions" :key="activeTask.id">
            <a-list-item>
              <a-list-item-meta>
                <template #avatar>
                  <AntdAuthImage
                    :is-preview="false" :width="64" :height="64"
                    :auth-src="Common.getThumbnailImageSrc('com.leanwo.prodog.base.model.User', activeTask.assigneeImageUrl)"
                  />
                </template>
                <template #title>
                  <a-space>
                    {{ activeTask.assigneeName }}
                    <a-tag color="cyan">{{ activeTask.name }}</a-tag>
                  </a-space>
                </template>
                <template #description>
                  <div class="time-info">{{ activeTask.startTime }}</div>
                  <span class="comment-text">{{ $t("lang.approveComment.processing") }}</span>

                  <div v-if="activeTask.comments" class="comment-group">
                    <div v-for="commentItem in activeTask.comments" :key="commentItem.id" class="comment-item">
                      <div class="time-info">{{ commentItem.time }}</div>
                      <span class="comment-text">{{ commentItem.message }}</span>
                    </div>
                  </div>

                  <ApproveTaskAttachmentView
                    :enable-delete="activeTask.id === taskInfoId"
                    :attachments="activeTask.attachments"
                  />
                </template>
              </a-list-item-meta>
            </a-list-item>
          </template>
        </a-list>
      </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 AntdAuthImage from '../widget/AntdAuthImage.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: {
    AntdAuthImage,
    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, // 自定义表单的数据
      currentTaskInfo: 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 {
          if (this.$refs.approveForm != null) {
            chooseTask.keyValueObjects = this.$refs.approveForm.getData();
          }
        } catch (exception) {
          console.log(exception);
          return;
        }

        try {
          if (this.$refs.previousNodeSelectUser != null) {
            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.errorCode != 0) {

            notification.error({
              message: '操作失败',
              description: successData.errorMessage,
            });

            return;
          }
          var routeDate = {
            path: successData.data.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 () {
      let _self = this;
      if (this.taskInfoId == null) {
        this.isActiveTask = false;
        this.currentTaskInfo = null;
        return;
      }

      WorkflowResource.uniqueTaskInfoByTaskIdUserId(this.taskInfoId).then(
        successData => {
          if (successData.errorCode != 0 || successData.data == null || successData.data.id == null) {
            this.isActiveTask = false;
            this.currentTaskInfo = null;
          } else {
            this.isActiveTask = true;
            this.currentTaskInfo = successData.data;
          }
        },
        errorData => {
          Common.processException(errorData);
        },
      );
    },
    /**
     * 自定义表单的数据发生变化
     */
    approveFormValueChanged: function (newApproveFormValue) {
      this.approveFormValue = newApproveFormValue;
    },
  },
};
</script>
<style scoped>
.page-header-box {
  padding: 16px 0 !important;
  background: #fff;
}

.approve-content {
  background: #fff;
  /* padding: 24px; */
}

.task-title {
  margin-bottom: 24px;
}

.action-section {
  margin-bottom: 24px;
}

.action-buttons {
  margin: 16px 0;
}

.comment-section {
  margin-top: 16px;
}

.approve-list {
  background: #fff;
}

.time-info {
  color: rgba(0, 0, 0, 0.45);
  font-size: 14px;
}

.comment-text {
  color: rgba(0, 0, 0, 0.85);
  margin: 8px 0;
}

.comment-group {
  margin: 4px 0;
}

.comment-item {
  border-bottom: none;
}

.comment-item:last-child {
  border-bottom: none;
}

.ant-list-item-meta-avatar {
  margin-right: 16px;
}

:deep(.ant-list .ant-list-item) {
  padding: 2px 0 !important;
}
</style>