<template>
  <Modal
    v-model:show="showModal"
    :show-ok-button="false"
    :show-canel-button="false"
    :large="true"
  >
    <template #header>
      {{ selectedTask != null ? selectedTask.title : "" }}
    </template>
    <div>
      <component :is="currentComponent" @finish-task="finishTask" />
    </div>
    <template #footer />
  </Modal>
</template>


<script setup>
import Common from '../common/Common.js';
import PrivacyStatement from '../confirm/privacy-statement.vue';
import StudyVideo from '../confirm/StudyVideo.vue';
import ResetPassword from '../confirm/ResetPassword.vue';
import KnowledgeTrain from '../confirm/KnowledgeTrain1.vue';
import WorkflowResource from '../api/workflow/WorkflowResource.js';
import { Notify, Uuid } from 'pc-component-v3';

import { ref, defineEmits, defineProps, defineExpose, watch } from 'vue';

const props = defineProps({
  taskId: {
    type: String,
    default: null,
  },
});
const emit = defineEmits(['closed']);

const selectedTask = ref('');
const currentComponent = ref('');
const showModal = ref(false);

/**
 * 获取任务
 */
const fetchTask = () => {
  if (props.taskId == null) {
    selectedTask.value = null;
    currentComponent.value = null;
    showModal.value = false;
    emit('closed');
    return;
  }
  WorkflowResource.uniqueTaskInfoByTaskIdUserId(this.taskId).then(
    successData => {
      if(successData.errorCode == 0 && successData.data != null){
        selectedTask.value = successData.data;
        if (selectedTask.value.formKey == 'ConfirmPrivacy') {
          currentComponent.value = 'PrivacyStatement';
        } else if (selectedTask.value.formKey == 'TrainApprove') {
          currentComponent.value = 'StudyVideo';
        } else if (selectedTask.value.formKey == 'ResetPassword') {
          currentComponent.value = 'ResetPassword';
        } else if (selectedTask.value.formKey == 'KnowledgeTrain') {
          currentComponent.value = 'KnowledgeTrain';
        }
        showModal.value = true;
      } else {
        selectedTask.value = null;
        currentComponent.value = null;
        showModal.value = false;
        emit('closed');
      }
    },
    errorData => {
      console.error(errorData);
    },
  );
};
/**
 * 完成任务
 */
const finishTask = () => {
  if (selectedTask.value == null) {
    Notify.error('错误', '请先选择任务。', true);
    return;
  }

  WorkflowResource.finishTask(selectedTask.value.id).then(
    successData => {
      if (successData.errorCode == 0) {
        showModal.value = false;
        emit('closed');
      } else {
        Notify.error('错误', successData.errorMessage, true);
      }
    },
    errorData => {
      Common.processException(errorData);
    },
  );
};

watch(
  props.taskId,
  newData => {
    if (newData) {
      fetchTask();
    }
  },
  { immediate: true },
);
const show = () => {
  fetchTask();
  showModal.value = true;
};
defineExpose({ show });
</script>