<template>
  <div>
    <Navbar title="工作流管理" :is-go-back="false" />

    <a-form :colon="false" style="margin: 10px 0">
      <a-row :gutter="[8, 14]" justify="space-start">
        <a-col style="display: flex; align-items: center">
          <a-form-item
            label="文件编码"
            :label-col="{ style: 'width: 68px' }"
            class="horizontal-form-item"
          >
            <a-input v-model:value="documentNo" class="w-full" />
          </a-form-item>
        </a-col>
        <a-col>
          <a-form-item
            label="单据主题"
            :label-col="{ style: 'width: 68px' }"
            class="horizontal-form-item"
          >
            <a-input v-model:value="title" class="w-full" />
          </a-form-item>
        </a-col>
        <a-col>
          <a-form-item
            label="审批摘要"
            :label-col="{ style: 'width: 68px' }"
            class="horizontal-form-item"
          >
            <a-input v-model:value="content" class="w-full" />
          </a-form-item>
        </a-col>
        <a-col>
          <a-form-item
            label="单据状态"
            :label-col="{ style: 'width: 68px' }"
            class="horizontal-form-item"
          >
            <a-select
              v-model:value="status"
              class="w-full"
              @change="changeFilterData"
            >
              <a-select-option value="Running">运行中</a-select-option>
              <a-select-option value="Suspended">已暂停</a-select-option>
              <a-select-option value="Finished">已完成</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col>
          <a-form-item
            label="开始时间"
            :label-col="{ style: 'width: 68px' }"
            class="horizontal-form-item"
          >
            <DateTime v-model="startAfter" class="w-full" />
          </a-form-item>
        </a-col>
        <a-col>
          <a-form-item
            label="结束时间"
            :label-col="{ style: 'width: 68px' }"
            class="horizontal-form-item"
          >
            <DateTime v-model="startBefore" class="w-full" />
          </a-form-item>
        </a-col>
        <a-col>
          <a-form-item
            label=""
            :label-col="{ style: 'width: 68px' }"
            class="horizontal-form-item"
          >
            <a-button type="primary" @click="requery">查询</a-button>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </div>
  <div style="margin-top: 16px">
    <table class="table table-bordered table-hover table-condensed">
      <thead>
        <tr>
          <th style="width: 60px">序号</th>
          <th style="width: 100px">文件编码</th>
          <th style="width: 100px">单据主题</th>
          <th>审批摘要</th>
          <th style="width: 60px">状态</th>
          <th style="width: 100px">开始时间</th>
          <th style="width: 100px">结束时间</th>
          <th style="width: 100px">流程实例Id</th>
          <th style="width: 100px">操作</th>
        </tr>
      </thead>
      <tbody>
        <template v-for="(data, index) in datas" :key="data.processInstanceId">
          <tr>
            <td>
              {{
                index + (pagination.current_page - 1) * pagination.per_page + 1
              }}
            </td>
            <td>
              {{ data.documentNo }}
            </td>
            <td>
              {{ data.title }}
            </td>
            <td>
              <span
                v-if="data.content != null && data.content != 'null'"
                style="white-space: pre-line"
              >{{ data.content }}</span>
            </td>
            <td>
              {{
                data.status === "Running"
                  ? "运行中"
                  : data.status === "Suspended"
                    ? "暂停"
                    : data.status === "Finished"
                      ? "已完成"
                      : ""
              }}
            </td>
            <td>
              {{ data.startTime }}
            </td>
            <td>
              {{ data.endTime }}
            </td>
            <td>
              {{ data.processInstanceId }}
            </td>
            <td>
              <a-button
                v-if="data.status === 'Running'"
                @click="changeProcessInstance(data, 'suspend', null)"
              >
                暂停
              </a-button>
              <a-button
                v-if="data.status === 'Suspended'"
                type="dashed"
                @click="changeProcessInstance(data, 'activate', null)"
              >
                激活
              </a-button>
              <a-button
                v-if="data.status === 'Running'"
                danger
                @click="deleteProcessInstance(data, 'delete', null)"
              >
                删除
              </a-button>
              <a-button type="primary" @click="listTaskInfo(data)">
                查看
              </a-button>
            </td>
          </tr>
          <template
            v-if="data.taskDocInfos != null && data.taskDocInfos.length > 0"
          >
            <tr :key="'tasks-title' + data.processInstanceId" class="info">
              <td colspan="9">进行中的任务</td>
            </tr>
            <tr :key="'tasks' + data.processInstanceId" class="info">
              <td colspan="9" style="padding: 0px">
                <table
                  class="table table-bordered table-hover table-condensed inner-table"
                >
                  <thead>
                    <tr class="warning">
                      <th style="width: 60px">序号</th>
                      <th style="width: 200px">任务名称</th>
                      <th style="width: 100px">审批人</th>
                      <th style="width: 100px">发起日期</th>
                      <th>评论信息</th>
                    </tr>
                  </thead>
                  <tbody>
                    <template
                      v-for="(taskDocInfo, index1) in data.taskDocInfos"
                      :key="taskDocInfo.id"
                    >
                      <tr class="warning">
                        <td>
                          {{ index1 }}
                        </td>
                        <td>
                          {{ taskDocInfo.name }}
                        </td>
                        <td>
                          {{ taskDocInfo.assigneeName }}
                        </td>
                        <td>
                          {{ taskDocInfo.createTime }}
                        </td>
                        <td>
                          {{ taskDocInfo.comments }}
                        </td>
                      </tr>
                    </template>
                  </tbody>
                </table>
              </td>
            </tr>
          </template>

          <template
            v-if="
              data.historicTaskDocInfos != null &&
                data.historicTaskDocInfos.length > 0
            "
          >
            <tr
              :key="'historicTasks-title' + data.processInstanceId"
              class="success"
            >
              <td colspan="9">已完成的任务</td>
            </tr>
            <tr :key="'historicTasks' + data.processInstanceId" class="success">
              <td colspan="9" style="padding: 0px">
                <table
                  class="table table-bordered table-hover table-condensed inner-table"
                >
                  <thead>
                    <tr class="warning">
                      <th style="width: 60px">序号</th>
                      <th style="width: 200px">任务名称</th>
                      <th style="width: 100px">审批人</th>
                      <th style="width: 100px">发起日期</th>
                      <th style="width: 100px">完成日期</th>
                      <th>评论信息</th>
                    </tr>
                  </thead>
                  <tbody>
                    <template
                      v-for="(
                        historicTaskDocInfo, index2
                      ) in data.historicTaskDocInfos"
                      :key="historicTaskDocInfo.id"
                    >
                      <tr class="warning">
                        <td>
                          {{ index2 }}
                        </td>
                        <td>
                          {{ historicTaskDocInfo.name }}
                        </td>
                        <td>
                          {{ historicTaskDocInfo.assigneeName }}
                        </td>
                        <td>
                          {{ historicTaskDocInfo.createTime }}
                        </td>
                        <td>
                          {{ historicTaskDocInfo.endTime }}
                        </td>
                        <td>
                          {{ historicTaskDocInfo.comments }}
                        </td>
                      </tr>
                    </template>
                  </tbody>
                </table>
              </td>
            </tr>
          </template>
        </template>
      </tbody>
    </table>
    <div style="float: right;">
      <AntdPagination
        ref="paginationRef"
        style="margin-bottom: 10px;"
        :pagination="pagination"
        @get-page-params="getPageParams"
      />
    </div>
  </div>
</template>

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

export default {
  components: {},
  data: function () {
    return {
      documentNo: null,
      title: null,
      content: null,
      status: 'Running',
      startAfter: null,
      startBefore: null,
      datas: [],
      pagination: {
        total: 0,
        per_page: 20, // required
        current_page: 1, // required
        last_page: 0, // required
      },
    };
  },

  mounted: function () {
    this.listProcessInstanceDoc();
  },

  methods: {
    /**
     * 重新查询
     */
    requery: function () {
      this.pagination.total = 0;
      this.pagination.current_page = 1;
      this.listProcessInstanceDoc();
    },

    // 页数改变
    getPageParams: function (page, pageSize) {
      this.pagination.current_page = page;
      this.pagination.per_page = pageSize;
      this.listProcessInstanceDoc();
    },

    /**
     * 查询所有的单据流程实例
     */
    listProcessInstanceDoc: function () {
      let _self = this;

      let processInstanceDocRequest = {
        documentNo: this.documentNo,
        title: this.title,
        content: this.content,
        status: this.status,
        startAfter: this.startAfter,
        startBefore: this.startBefore,
        start: (this.pagination.current_page - 1) * this.pagination.per_page,
        length: this.pagination.per_page,
      };

      $.ajax({
        url: Common.getApiURL('DocManagmentResource/query'),
        type: 'POST',
        contentType: 'application/json',
        dataType: 'json',
        data: JSON.stringify(processInstanceDocRequest),
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (data) {
          data.datas.forEach(item => {
            try {
              var content = JSON.parse(item.content);
              var parentForm = '';
              if (content != null && content.parentForm != null) {
                content.parentForm.forEach(item => {
                  parentForm =
                    parentForm + item.title + ':' + item.content + '\n';
                });
                item.content = parentForm;
              }
            } catch (error) {
              console.error(error);
            } finally {
              item.taskDocInfos = [];
              item.historicTaskDocInfos = [];
            }
          });
          _self.datas = data.datas;
          _self.pagination.total = data.total;
          _self.pagination.last_page = Math.ceil(
            data.total / _self.pagination.per_page,
          );
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    /**
     * 查询流程实例的任务信息
     */
    listTaskInfo(processInstanceInfo) {
      $.ajax({
        url: Common.getApiURL('DocManagmentResource/listTasks'),
        type: 'GET',
        dataType: 'json',
        data: {
          processInstanceId: processInstanceInfo.processInstanceId,
        },
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (datas) {
          processInstanceInfo.taskDocInfos = datas;
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
      $.ajax({
        url: Common.getApiURL('DocManagmentResource/listHistoricTasks'),
        type: 'GET',
        dataType: 'json',
        data: {
          processInstanceId: processInstanceInfo.processInstanceId,
        },
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (datas) {
          processInstanceInfo.historicTaskDocInfos = datas;
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },

    /**
     * 删除流程实例
     */
    deleteProcessInstance(processInstanceInfo, changeType, reason) {
      let _self = this;
      Notify.show({
        title: '确认',
        message: '删除流程实例是不可恢复的操作，您确认要删除流程实例吗？',
        buttons: [
          {
            label: '确认',
            action: function (dialogItself) {
              _self.changeProcessInstance(
                processInstanceInfo,
                changeType,
                reason,
              );
              dialogItself.close();
            },
          },
          {
            label: '取消',
            action: function (dialogItself) {
              dialogItself.close();
            },
          },
        ],
      });
    },

    /**
     * 修改流程实例的状态
     */
    changeProcessInstance(processInstanceInfo, changeType, reason) {
      let _self = this;
      $.ajax({
        url: Common.getApiURL('DocManagmentResource/changeProcessInstance'),
        type: 'GET',
        dataType: 'json',
        data: {
          processInstanceId: processInstanceInfo.processInstanceId,
          changeType: changeType,
          reason: reason,
        },
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        success: function (datas) {
          _self.listProcessInstanceDoc();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },
  },
};
</script>

<style scoped>
.horizontal-form-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

:deep(.ant-form-item) {
  margin-bottom: -5px !important;
}

/* 调整标签样式 */
:deep(.ant-form-item-label) {
  flex: 0 0 auto;
  white-space: nowrap;
  overflow: visible;
  text-overflow: unset;
}

/* 确保控件容器填充剩余空间 */
:deep(.ant-form-item-control) {
  flex: 1;
  min-width: 0;
}

/* 设置组件宽度 */
.w-full {
  width: 230px;
}

.form-group {
  margin-bottom: 10px;
}

:deep(.ant-form-item-label > label) {
  font-size: 14px !important;
  font-weight: 600 !important;
}
</style>
