<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>
      <a-button type="link" @click="completeApproval">全部完成审阅</a-button>
      <a-select
        v-model:value="searchParams.processStatusQuery"
        allow-clear
        placeholder="请选择审批状态"
        style="width: 200px"
        @change="statusChange"
      >
        <a-select-option value="ALL">全部</a-select-option>
        <a-select-option value="FINISH">审批完成</a-select-option>
        <a-select-option value="RUNNING">审批中</a-select-option>
      </a-select>
    </a-col>
  </a-row>
  <a-table
    sticky
    bordered
    :pagination="false"
    :columns="approveColumns"
    :data-source="copyDatas"
  >
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'title'">
        <span v-if="record.category != 'CurdWindow'">
          {{ record.name }}
        </span>
        <span v-else>
          {{ record.title }}
        </span>
      </template>
      <template v-if="column.key === 'description'">
        <span
          v-if="record.category != 'CurdWindow'"
          style="white-space: pre-line"
        >{{ record.description }}</span>
        <span v-else style="white-space: pre-line">{{ 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="copyDatas.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 { ajaxApi } from '../api/workflow/workflow.js';
import { message } from 'ant-design-vue';
import { approvedColumns } from './configData.js';
import TaskOpenUtil from './TaskOpenUtil.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';


const emit = defineEmits(['refreshStasticCount']);
const customerTask = ref(null);
const selectedTaskId = ref(null);
const isLoading = ref(false);
const isShowMore = ref(true);
const copyDatas = ref([]);
const approveColumns = ref(approvedColumns);
const searchParams = ref({
  condition: '',
  processStatusQuery: 'ALL',
});
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, ...pager };
  searchApprove(params, isSearch);
};

// 状态改变事件
const statusChange = value => {
  if (!value) searchParams.value.processStatusQuery = 'ALL';
  pager.start = 0;
  isShowMore.value = true;
  searchDatas(true);
};
// 全部完成审阅
const completeApproval = () => {
  const _self = this;
  isLoading.value = true;
  $.ajax({
    url: Common.getApiURL('WorkflowResource/completeCopyTasks'),
    type: 'post',
    dataType: 'json',
    contentType: 'application/json',
    beforeSend: function (request) {
      Common.addTokenToRequest(request);
    },
    success: function (data) {
      isLoading.value = false;
      if (data.errorCode === 0) {
        _self.$emit('refreshStasticCount');
        _self.searchCopyTask();
      } else {
        Notify.error('错误', data.errorMessage, false);
      }
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
      isLoading.value = false;
      Common.processException(XMLHttpRequest, textStatus, errorThrown);
    },
  });
};
// 查询数据API
const searchApprove = (params, isSearch) => {
  isLoading.value = true;
  const url = 'api/WorkflowResource/copyTask';
  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) {
              copyDatas.value.push(item);
            }
          });
          if (isSearch) {
            copyDatas.value = success.datas;
          }
        } else {
          if (!isSearch) {
            message.info('没有更多数据了。');
            isShowMore.value = false;
            isLoading.value = false;
            return;
          }
          copyDatas.value = [];
        }
      } else {
        message.warning(success.errorMessage);
      }
      isLoading.value = false;
    },
    error => {
      isLoading.value = false;
      Common.processException(error);
    },
  );
};

// 调整审批页
const goWindow = taskInfo => {
  
  if (taskInfo.systemProcess == undefined || taskInfo.systemProcess == false) {
    isLoading.value = true;
    $.ajax({
      url: Common.getApiURL('WorkflowResource/processTaskInfo'),
      type: 'get',
      dataType: 'json',
      contentType: 'application/json',
      beforeSend: function (request) {
        Common.addTokenToRequest(request);
      },
      data: {
        taskInfoId: taskInfo.id,
      },
      success: function (data) {
        isLoading.value = false;

      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        isLoading.value = false;
        Common.processException(XMLHttpRequest, textStatus, errorThrown);
      },
    });
  }

  TaskOpenUtil.openCopyTask(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);
    },
  );
};

// 处理content json
const parseContent = content => {
  const x = content;
  try {
    let content = JSON.parse(x);
    let parentForm = '';
    if (content != null && content.parentForm != null) {
      content.parentForm.forEach(item => {
        parentForm = parentForm + item.title + ':' + item.content + '，\n';
      });
      return parentForm;
    } else {
      return null;
    }
    // eslint-disable-next-line no-empty
  } catch (e) {}
};
</script>

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