<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import BusinessFormDialog from '@/components/custom/business-form-dialog.vue';
import TaskAssigneeCurrentPanel from './task-assignee-current-panel.vue';
import TaskAssigneeLogPanel from './task-assignee-log-panel.vue';

defineOptions({ name: 'ProjectExecutionTaskAssigneeDialog' });

interface Props {
  task: Api.Project.ProjectTask | null;
  assignees: Api.Project.TaskAssigneeRef[];
  userOptions: Api.SystemManage.UserSimple[];
  loading: boolean;
  canManage: boolean;
}

interface Emits {
  (e: 'add', payload: Api.Project.CreateTaskAssigneeParams): void;
  (e: 'inactive', assignee: Api.Project.TaskAssigneeRef, payload: Api.Project.InactiveTaskAssigneeParams): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

type TabName = 'current' | 'log';

const activeTab = ref<TabName>('current');

const currentPanelRef = ref<InstanceType<typeof TaskAssigneeCurrentPanel> | null>(null);

const dialogTitle = computed(() => (props.task ? `协办人管理：${props.task.taskTitle}` : '协办人管理'));

const projectId = computed(() => props.task?.projectId || '');
const executionId = computed(() => props.task?.executionId || '');
const taskId = computed(() => props.task?.id || '');

function handleAdd(payload: Api.Project.CreateTaskAssigneeParams) {
  emit('add', payload);
}

function handleInactive(assignee: Api.Project.TaskAssigneeRef, payload: Api.Project.InactiveTaskAssigneeParams) {
  emit('inactive', assignee, payload);
}

watch(
  () => visible.value,
  value => {
    if (value) {
      activeTab.value = 'current';
      return;
    }

    currentPanelRef.value?.reset();
  }
);
</script>

<template>
  <BusinessFormDialog v-model="visible" :title="dialogTitle" preset="lg" :show-footer="false" :scrollbar="false">
    <ElTabs v-model="activeTab" class="task-assignee-dialog__tabs">
      <ElTabPane label="当前协办人" name="current">
        <TaskAssigneeCurrentPanel
          ref="currentPanelRef"
          :task="task"
          :assignees="assignees"
          :user-options="userOptions"
          :loading="loading"
          :can-manage="canManage"
          @add="handleAdd"
          @inactive="handleInactive"
        />
      </ElTabPane>
      <ElTabPane label="变更历史" name="log" lazy>
        <TaskAssigneeLogPanel
          v-if="projectId && executionId && taskId"
          :project-id="projectId"
          :execution-id="executionId"
          :task-id="taskId"
          :user-options="userOptions"
          :active="activeTab === 'log'"
        />
      </ElTabPane>
    </ElTabs>
  </BusinessFormDialog>
</template>

<style scoped lang="scss">
.task-assignee-dialog__tabs {
  --el-tabs-header-height: 40px;
}
</style>
