<template>
  <a-row type="flex" justify="space-between">
    <a-col>
      <a-input-search
        v-model:value="searchParams.condition"
        :placeholder="$t('lang.NeedApproveWorkflow.describe1')"
        enter-button="搜索"
        allow-clear
        style="width: 300px"
        @search="queryDatas"
      />
    </a-col>
    <a-col>
      <WorkflowType @get-type="getTypeNo" />
      <WorkflowSearch :function-type="4" @get-search-params="searchWorkflow" />
    </a-col>
  </a-row>
  <a-table
    sticky
    bordered
    :pagination="false"
    :columns="approveColumns"
    :data-source="applyDatas"
  >
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'description'">
        <span style="white-space: pre-line">{{ record.description }} <br />{{ record.content }}</span>
      </template>
      <template v-if="column.key === 'documentStatus'">
        <a-tag v-if="record.documentStatus === '已完成'" color="success">
          已完成
        </a-tag>
        <a-tag v-if="record.documentStatus === '进行中'" color="processing">
          进行中
        </a-tag>
      </template>
      <template v-if="column.key === 'operation'">
        <a-button type="link" @click="selectTaskInfo(record)">
          {{ $t("lang.NeedApproveWorkflow.viewTasks") }}
        </a-button>
      </template>
    </template>
    <template v-if="applyDatas.length > 0 && isShowMore" #footer>
      <div style="text-align: center">
        <a-button type="link" @click="loadMore">加载更多</a-button>
      </div>
    </template>
  </a-table>
  <Loading v-if="isLoading" />
  <CustomerTask
    ref="customerTask"
    :task-id="selectedTaskId"
    @closed="() => searchDatas"
  />
</template>

<script setup>
import { ref, reactive, defineEmits, onMounted } from 'vue';
import Common from '../common/Common';
import WorkflowType from './WorkflowType.vue';
import WorkflowSearch from './WorkflowSearch.vue';
import { ajaxApi } from '../api/workflow/workflow.js';
import { message } from 'ant-design-vue';
import { approvedColumns } from './configData.js';
import CustomerTask from './CustomerTask.vue';
import { Uuid } from 'pc-component-v3';
import { queryAuth, addAuth } from '../api/authorization/index.js';
import TaskOpenUtil from './TaskOpenUtil1.js';
import { parseContent } from './parseWorkflowContent.js';

const emit = defineEmits(['refreshStasticCount']);
const customerTask = ref(null);
const selectedTaskId = ref(null);
const isLoading = ref(false);
const isShowMore = ref(true);
const applyDatas = ref([]);
const approveColumns = ref(approvedColumns);
const searchParams = ref({});
const filterParams = ref({});
const pager = reactive({
  start: 0,
  length: 10,
});

onMounted(() => {
  searchDatas();
});

// 查询条件时从0开始
const queryDatas = () => {
  pager.start = 0;
  isShowMore.value = true;
  searchDatas(true);
};

// 加载更多时push
const loadMore = () => {
  pager.start += 10;
  searchDatas();
};

// 查询
const searchDatas = isSearch => {
  const params = { ...searchParams.value, ...filterParams.value, ...pager };
  searchApprove(params, isSearch);
};

// 获取类型no
const getTypeNo = windowNo => {
  pager.start = 0;
  isShowMore.value = true;
  searchParams.value.windowNo = windowNo;
  searchDatas(true);
};

// 通过高级查询搜索
const searchWorkflow = value => {
  pager.start = 0;
  isShowMore.value = true;
  filterParams.value = value;
  searchDatas(true);
};

// 查询数据API
const searchApprove = (params, isSearch) => {
  isLoading.value = true;
  const url = 'api/WorkflowResource/myApply';
  ajaxApi(url, params).then(
    success => {
      if (success.errorCode === 0) {
        if (success.datas && success.datas.length > 0) {
          success.datas.forEach(item => {
            item.content = parseContent(item.content);
            if (!isSearch) {
              applyDatas.value.push(item);
            }
          });
          if (isSearch) {
            applyDatas.value = success.datas;
          }
        } else {
          if (!isSearch) {
            message.info('没有更多数据了。');
            isShowMore.value = false;
            isLoading.value = false;
            return;
          }
          applyDatas.value = [];
        }
      } else {
        message.warning(success.errorMessage);
      }
      isLoading.value = false;
    },
    error => {
      isLoading.value = false;
      Common.processException(error);
    },
  );
};

// 跳到审批页
const goWindow = taskInfo => {
  if (taskInfo.category === 'DynamicForm') {
    window.open(TaskOpenUtil.buildDynamicFormUrl(taskInfo));
    return;
  }
  const type = 'view';
  const windowNo = taskInfo.windowNo;
  const tabIndex = taskInfo.tabIndex;
  const recordId = taskInfo.recordId;
  const url =
    '/desktop/window1/window-read/' +
    type +
    '/' +
    windowNo +
    '/' +
    tabIndex +
    '/' +
    recordId +
    '?workflowType=approve&taskInfoId=' +
    taskInfo.id +
    '&currIndex=1&totalCount=1&canGoBack=false&uuid=' +
    Uuid.createUUID();

  window.open(Common.getRedirectUrl('#' + url));
};

// 选择了taskInfo 先查询授权资源
const selectTaskInfo = taskInfo => {
  const params = {
    userId: JSON.parse(localStorage.getItem('#LoginInfo')).userId,
    recordId: taskInfo.recordId,
    windowNo: taskInfo.windowNo,
  };
  queryAuth(params).then(
    success => {
      if (success.errorCode === 0) {
        goWindow(taskInfo);
      } else {
        addAuthorization(params, taskInfo);
      }
    },
    err => {
      Common.processException(err);
    },
  );
};

// 增加授权资源
const addAuthorization = (params, taskInfo) => {
  addAuth(params).then(
    success => {
      if (success.errorCode === 0) {
        goWindow(taskInfo);
      } else {
        message.warning(success.errorMessage);
      }
    },
    err => {
      Common.processException(err);
    },
  );
};

</script>

<style scoped>
.ant-table-wrapper {
  margin-top: 8px;
}
</style>