<script setup lang="ts">
import { ref, watch } from 'vue';
import { fetchGetPersonalItemDetail } from '@/service/api';
import BusinessFormDialog from '@/components/custom/business-form-dialog.vue';
import PersonalItemWorklogPanel from './personal-item-worklog-panel.vue';

defineOptions({ name: 'PersonalItemDetailDialog' });

type TabName = 'worklog';

interface Props {
  rowData?: Api.PersonalItem.PersonalItem | null;
  defaultTab?: TabName;
}

const props = withDefaults(defineProps<Props>(), {
  defaultTab: 'worklog'
});

const emit = defineEmits<{
  changed: [item: Api.PersonalItem.PersonalItem];
}>();

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

const activeTab = ref<TabName>('worklog');
const detailData = ref<Api.PersonalItem.PersonalItem | null>(null);

function syncDetailFromPageRow() {
  detailData.value = props.rowData ?? null;
}

async function refreshDetail() {
  if (!detailData.value?.id) {
    return;
  }

  const { error, data } = await fetchGetPersonalItemDetail(detailData.value.id);

  if (!error && data) {
    detailData.value = data;
  }
}

async function handleWorklogChanged() {
  await refreshDetail();

  if (detailData.value) {
    emit('changed', detailData.value);
  }
}

watch(
  () => visible.value,
  value => {
    if (value) {
      activeTab.value = props.defaultTab;
      syncDetailFromPageRow();
    }
  }
);

watch(
  () => props.rowData,
  () => {
    if (visible.value) {
      syncDetailFromPageRow();
    }
  }
);

watch(
  () => props.defaultTab,
  value => {
    if (visible.value) {
      activeTab.value = value;
    }
  }
);
</script>

<template>
  <BusinessFormDialog
    v-model="visible"
    title="工作日志"
    width="1100px"
    max-body-height="78vh"
    :show-footer="false"
    :scrollbar="false"
  >
    <ElTabs v-model="activeTab" class="personal-item-detail-dialog__tabs">
      <ElTabPane label="工作日志" name="worklog" lazy>
        <PersonalItemWorklogPanel
          v-if="detailData"
          :item="detailData"
          :active="activeTab === 'worklog' && visible"
          @changed="handleWorklogChanged"
        />
      </ElTabPane>
    </ElTabs>
  </BusinessFormDialog>
</template>

<style scoped lang="scss">
.personal-item-detail-dialog__tabs {
  --el-tabs-header-height: 40px;
}

.personal-item-detail-dialog__tabs :deep(.el-tabs__content),
.personal-item-detail-dialog__tabs :deep(.el-tab-pane) {
  min-height: 640px;
}
</style>
