<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="3" @get-search-params="searchWorkflow" />
    </a-col>
  </a-row>
  <a-table
    sticky
    bordered
    :pagination="false"
    :columns="approveColumns"
    :data-source="approveDatas"
  >
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'title'">
        <span v-if="record.category != 'CurdWindow' && record.category != 'DynamicForm'">
          {{ record.name }}
        </span>
        <span v-else>
          {{ record.title }}
        </span>
      </template>
      <template v-if="column.key === 'description'">
        <span
          v-if="record.category != 'CurdWindow' && record.category != 'DynamicForm'"
          style="white-space: pre-line"
        >{{ record.description }}</span>
        <span v-else 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="approveDatas.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(true)"
  />
</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 TaskOpenUtil from './TaskOpenUtil1.js';
import WindowService from '../common/WindowService.js';
import CustomerTask from './CustomerTask.vue';
import { Notify } from 'pc-component-v3';
import { queryAuth, addAuth } from '../api/authorization/index.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 approveDatas = ref([]);
const approveColumns = ref(approvedColumns);
const searchParams = ref({});
const filterParams = ref({});
const pager = reactive({
  start: 0,
  length: 10,
});

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

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

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

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

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

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

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

// 跳转到审批页
const goWindow = taskInfo => {
  TaskOpenUtil.openHistoryTask(taskInfo).then(
    successData => {
      if (successData.type === 'newWindow') {
        WindowService.open(successData.url, '已处理的', function () {
          searchDatas(true);
          emit('refreshStasticCount');
        });
      } else if (successData.type === 'customerTask') {
        // 打开自定义的界面
        selectedTaskId.value = taskInfo.id;
        customerTask.value.show();
        searchDatas(true);
        emit('refreshStasticCount');
      }
    },
    errorData => {
      if (errorData != null) {
        Notify.error(errorData.title, errorData.message, false);
      }
    },
  );
};

// 选择了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>