<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="searchDatas"
      />
    </a-col>
    <a-col>
      <WorkflowType @get-type="getTypeNo" />
      <WorkflowSearch :function-type="2" @get-search-params="searchWorkflow" />
    </a-col>
  </a-row>
  <CommonTable
    ref="table"
    :total="total"
    :columns="approveColumns"
    :data-source="needApproveDatas"
    @get-pager="getPageParams"
  >
    <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 === 'operation'">
        <a-button type="link" @click="selectTaskInfo(record)">
          {{ $t("lang.NeedApproveWorkflow.viewTasks") }}
        </a-button>
      </template>
    </template>
  </CommonTable>
  <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 CommonTable from '../common/CommonTable.vue';
import { ajaxApi } from '../api/workflow/workflow.js';
import { message } from 'ant-design-vue';
import { needApproveColumns } 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 total = ref(0);
const table = ref(null);
const customerTask = ref(null);
const selectedTaskId = ref(null);
const isLoading = ref(false);
const needApproveDatas = ref([]);
const approveColumns = ref(needApproveColumns);
const searchParams = ref({});
const filterParams = ref({});
const pager = reactive({
  start: 1,
  length: 20,
});

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

// 查询,回到第一页
const searchDatas = () => {
  table.value.backFirstPage();
};

// 获取分页
const getPageParams = (start, length) => {
  pager.start = (start - 1) * length;
  pager.length = length;
  const params = { ...searchParams.value, ...filterParams.value, ...pager };
  searchApprove(params);
};

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

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

// 查询数据API
const searchApprove = params => {
  isLoading.value = true;
  const url = 'api/WorkflowResource/needApprove';
  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);
          });
          total.value = success.total;
          needApproveDatas.value = success.datas;
        } else {
          total.value = 0;
          needApproveDatas.value = [];
        }
      } else {
        message.warning(success.errorMessage);
      }
      isLoading.value = false;
    },
    error => {
      isLoading.value = false;
      Common.processException(error);
    },
  );
};

// 跳转到审批页
const goWindow = taskInfo => {
  TaskOpenUtil.openTask(taskInfo).then(
    successData => {
      if (successData.type === 'newWindow') {
        WindowService.open(successData.url, '待处理', function () {
          searchDatas();
          emit('refreshStasticCount');
        });
      } else if (successData.type === 'customerTask') {
        // 打开自定义的界面
        selectedTaskId.value = taskInfo.id;
        customerTask.value.show();
        searchDatas();
        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>
</style>