<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { useResizeObserver } from '@vueuse/core';
import dayjs from 'dayjs';
import { fetchGetProjectRequirementReview } from '@/service/api';
import BusinessAttachmentUploader from '@/components/custom/business-attachment-uploader.vue';
import BusinessFormDialog from '@/components/custom/business-form-dialog.vue';
import BusinessFormSection from '@/components/custom/business-form-section.vue';
import BusinessRichTextEditor from '@/components/custom/business-rich-text-editor.vue';
import ReadonlyField from '@/components/custom/readonly-field.vue';

defineOptions({ name: 'ProjectRequirementReviewRecordDialog' });

interface Props {
  projectId: string;
  requirement: Api.Project.ProjectRequirement | null;
  memberOptions: Api.Project.ProjectMember[];
}

const props = defineProps<Props>();

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

const loading = ref(false);
const reviewRecord = ref<Api.Project.ProjectRequirementReview | null>(null);
const leftColRef = ref<HTMLElement>();
const editorHeight = ref<string>('47vh');

const ATTACHMENT_SECTION_RESERVE_PX = 140;
const ATTENDEE_VISIBLE_COUNT = 5;

useResizeObserver(leftColRef, entries => {
  const height = entries[0]?.contentRect.height;

  if (height && height > 120) {
    editorHeight.value = `${Math.max(height - 60 - ATTACHMENT_SECTION_RESERVE_PX, 200)}px`;
  }
});

const operatorLabelMap = computed(() => {
  return new Map(props.memberOptions.map(item => [item.userId, item.userNickname]));
});

const conclusionText = computed(() => {
  if (!reviewRecord.value) {
    return '--';
  }

  return reviewRecord.value.conclusion === 0 ? '通过评审' : '不通过评审';
});

const operatorText = computed(() => {
  if (!reviewRecord.value?.operatorId) {
    return '--';
  }

  return operatorLabelMap.value.get(reviewRecord.value.operatorId) || reviewRecord.value.operatorId;
});

const visibleAttendees = computed(() => reviewRecord.value?.attendees?.slice(0, ATTENDEE_VISIBLE_COUNT) ?? []);
const overflowAttendees = computed(() => reviewRecord.value?.attendees?.slice(ATTENDEE_VISIBLE_COUNT) ?? []);

function formatExpectedTime(value?: string | number[] | null): string {
  if (!value) {
    return '--';
  }

  if (Array.isArray(value)) {
    const [year, month, day] = value;
    return `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
  }

  return dayjs(value).format('YYYY-MM-DD');
}

function formatDateTime(value?: string | null): string {
  if (!value) {
    return '--';
  }

  return dayjs(value).format('YYYY-MM-DD HH:mm:ss');
}

async function loadReviewRecord() {
  if (!props.projectId || !props.requirement?.id) {
    reviewRecord.value = null;
    return;
  }

  loading.value = true;

  const { error, data } = await fetchGetProjectRequirementReview(props.projectId, props.requirement.id);

  loading.value = false;

  if (error || !data) {
    reviewRecord.value = null;
    return;
  }

  reviewRecord.value = data;
}

watch(
  () => visible.value,
  value => {
    if (value) {
      loadReviewRecord();
    } else {
      reviewRecord.value = null;
    }
  }
);
</script>

<template>
  <BusinessFormDialog
    v-model="visible"
    title="查看评审记录"
    width="1100px"
    max-body-height="78vh"
    :loading="loading"
    :show-footer="true"
  >
    <template #footer="{ close }">
      <ElButton type="primary" @click="close">关闭</ElButton>
    </template>

    <ElEmpty v-if="!loading && !reviewRecord" description="暂无评审记录" />

    <div v-else class="requirement-review-record-dialog__grid">
      <div ref="leftColRef" class="requirement-review-record-dialog__col-left">
        <BusinessFormSection title="评审信息">
          <ElForm label-position="top">
            <ElFormItem label="需求名称">
              <ReadonlyField :value="requirement?.title || '--'" />
            </ElFormItem>

            <ElFormItem label="评审结论">
              <ReadonlyField :value="conclusionText" />
            </ElFormItem>

            <ElFormItem label="评审提交人">
              <ReadonlyField :value="operatorText" />
            </ElFormItem>

            <ElFormItem label="参会人">
              <div v-if="reviewRecord?.attendees?.length" class="requirement-review-record-dialog__tags">
                <ElTag v-for="item in visibleAttendees" :key="item.userId" effect="light">
                  {{ item.nickname }}
                </ElTag>
                <ElPopover
                  v-if="overflowAttendees.length"
                  trigger="click"
                  placement="bottom-start"
                  :width="280"
                  popper-class="requirement-review-record-dialog__attendee-popper"
                >
                  <template #reference>
                    <button type="button" class="requirement-review-record-dialog__tag-more">
                      +{{ overflowAttendees.length }} 更多
                    </button>
                  </template>
                  <div class="requirement-review-record-dialog__attendee-overflow">
                    <div class="requirement-review-record-dialog__attendee-overflow-head">
                      另外
                      <strong>{{ overflowAttendees.length }}</strong>
                      人
                    </div>
                    <div class="requirement-review-record-dialog__attendee-overflow-tags">
                      <ElTag v-for="item in overflowAttendees" :key="item.userId" effect="light">
                        {{ item.nickname }}
                      </ElTag>
                    </div>
                  </div>
                </ElPopover>
              </div>
              <ReadonlyField v-else value="--" />
            </ElFormItem>

            <ElFormItem label="需求预估工时">
              <ReadonlyField
                :value="
                  reviewRecord?.requirementEstimatedHours !== null &&
                  reviewRecord?.requirementEstimatedHours !== undefined &&
                  reviewRecord?.requirementEstimatedHours !== ''
                    ? String(reviewRecord.requirementEstimatedHours)
                    : '--'
                "
              />
            </ElFormItem>

            <ElFormItem label="实际评审日期">
              <ReadonlyField :value="formatExpectedTime(reviewRecord?.reviewTime)" />
            </ElFormItem>

            <ElFormItem label="提交时间">
              <ReadonlyField :value="formatDateTime(reviewRecord?.createTime)" />
            </ElFormItem>
          </ElForm>
        </BusinessFormSection>
      </div>

      <div class="requirement-review-record-dialog__col-right">
        <BusinessFormSection title="评审内容">
          <ElFormItem class="requirement-review-record-dialog__desc-item">
            <BusinessRichTextEditor
              :model-value="reviewRecord?.reviewContent || ''"
              disabled
              :height="editorHeight"
              upload-directory="requirement-review"
              placeholder="--"
            />
          </ElFormItem>
        </BusinessFormSection>

        <BusinessFormSection title="会议资料">
          <ElFormItem class="requirement-review-record-dialog__attachment-item">
            <BusinessAttachmentUploader
              :model-value="reviewRecord?.attachments || []"
              disabled
              directory="requirement-review"
            />
          </ElFormItem>
        </BusinessFormSection>
      </div>
    </div>
  </BusinessFormDialog>
</template>

<style scoped>
.requirement-review-record-dialog__grid {
  display: grid;
  grid-template-columns: 360px 1fr;
  gap: 24px;
  align-items: start;
}

.requirement-review-record-dialog__col-left,
.requirement-review-record-dialog__col-right {
  min-width: 0;
}

.requirement-review-record-dialog__col-right {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.requirement-review-record-dialog__desc-item,
.requirement-review-record-dialog__attachment-item {
  margin-bottom: 0;
}

.requirement-review-record-dialog__tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.requirement-review-record-dialog__tag-more {
  display: inline-flex;
  align-items: center;
  height: 24px;
  padding: 0 10px;
  border: 1px dashed var(--el-border-color-darker);
  border-radius: 999px;
  background: transparent;
  color: var(--el-color-primary);
  cursor: pointer;
  font-size: 11.5px;
  transition:
    border-color 0.15s ease,
    background-color 0.15s ease;
}

.requirement-review-record-dialog__tag-more:hover {
  border-color: var(--el-color-primary);
  background: var(--el-color-primary-light-9);
}

.requirement-review-record-dialog__attendee-overflow {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.requirement-review-record-dialog__attendee-overflow-head {
  color: var(--el-text-color-regular);
  font-size: 12px;
}

.requirement-review-record-dialog__attendee-overflow-head strong {
  color: var(--el-color-primary);
}

.requirement-review-record-dialog__attendee-overflow-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  max-height: 180px;
  overflow-y: auto;
}

@media (width <= 1024px) {
  .requirement-review-record-dialog__grid {
    grid-template-columns: 1fr;
  }
}
</style>
