<script setup lang="ts">
import { computed } from 'vue';
import { RDMS_REQ_PRIORITY_DICT_CODE, RDMS_TASK_ITEM_TYPE_DICT_CODE } from '@/constants/dict';
import BusinessAttachmentUploader from '@/components/custom/business-attachment-uploader.vue';
import BusinessFormSection from '@/components/custom/business-form-section.vue';
import BusinessRichTextEditor from '@/components/custom/business-rich-text-editor.vue';
import BusinessUserSelect from '@/components/custom/business-user-select.vue';
import DictSelect from '@/components/custom/dict-select.vue';
import { SHOW_TASK_PARENT_FIELD } from '../shared';

defineOptions({ name: 'ProjectExecutionTaskInfoReadonly' });

interface Props {
  task: Api.Project.ProjectTask | null;
  userOptions?: Api.SystemManage.UserSimple[];
  taskOptions?: Api.Project.ProjectTask[];
}

const props = withDefaults(defineProps<Props>(), {
  userOptions: () => [],
  taskOptions: () => []
});

const taskTitle = computed(() => props.task?.taskTitle ?? '');
const taskType = computed(() => props.task?.type ?? '');
const taskDesc = computed(() => props.task?.taskDesc ?? '');
const ownerId = computed(() => props.task?.ownerId ?? null);
const parentTaskId = computed(() => props.task?.parentTaskId ?? null);
const plannedStartDate = computed(() => props.task?.plannedStartDate ?? null);
const plannedEndDate = computed(() => props.task?.plannedEndDate ?? null);
const priority = computed(() => props.task?.priority ?? null);
const attachments = computed(() => props.task?.attachments ?? []);

const ownerOptions = computed(() => {
  const currentOwnerId = ownerId.value;

  if (!currentOwnerId) {
    return props.userOptions;
  }

  const hasOwner = props.userOptions.some(item => item.id === currentOwnerId);
  if (hasOwner) {
    return props.userOptions;
  }

  return [
    ...props.userOptions,
    {
      id: currentOwnerId,
      nickname: props.task?.ownerNickname?.trim() || currentOwnerId
    }
  ];
});

const assigneeIds = computed(() => props.task?.assignees?.map(a => a.userId) ?? []);
const assigneeOptions = computed(() => props.task?.assignees ?? []);

// 父任务在当前页 taskOptions 中找；找不到（跨页）回退用 ID 当 label，避免显示空
const parentTaskOptions = computed(() => {
  if (!parentTaskId.value) return [];
  const found = props.taskOptions.find(t => t.id === parentTaskId.value);
  if (found) return [{ id: found.id, taskTitle: found.taskTitle }];
  return [{ id: parentTaskId.value, taskTitle: parentTaskId.value }];
});
</script>

<template>
  <ElForm label-position="top" class="task-info-readonly">
    <div class="task-info-readonly__grid">
      <div class="task-info-readonly__col-left">
        <BusinessFormSection title="任务信息">
          <ElFormItem label="任务名称">
            <ElInput :model-value="taskTitle" readonly placeholder="--" />
          </ElFormItem>
          <ElFormItem label="任务类型">
            <DictSelect :model-value="taskType" :dict-code="RDMS_TASK_ITEM_TYPE_DICT_CODE" disabled placeholder="--" />
          </ElFormItem>
          <ElFormItem v-if="SHOW_TASK_PARENT_FIELD" label="父任务">
            <ElSelect :model-value="parentTaskId" disabled clearable filterable class="w-full" placeholder="无">
              <ElOption v-for="item in parentTaskOptions" :key="item.id" :label="item.taskTitle" :value="item.id" />
            </ElSelect>
          </ElFormItem>
          <ElFormItem label="优先级">
            <DictSelect
              :model-value="priority"
              :dict-code="RDMS_REQ_PRIORITY_DICT_CODE"
              disabled
              placeholder="--"
              show-remark
            />
          </ElFormItem>
          <ElFormItem label="负责人">
            <BusinessUserSelect :model-value="ownerId" :options="ownerOptions" disabled placeholder="--" />
          </ElFormItem>
          <ElFormItem label="协办人">
            <ElSelect
              :model-value="assigneeIds"
              multiple
              disabled
              collapse-tags
              collapse-tags-tooltip
              :max-collapse-tags="2"
              class="w-full"
              placeholder="暂无协办人"
            >
              <ElOption
                v-for="item in assigneeOptions"
                :key="item.userId"
                :label="item.nickname"
                :value="item.userId"
              />
            </ElSelect>
          </ElFormItem>
          <ElFormItem label="计划开始日期">
            <ElDatePicker
              :model-value="plannedStartDate"
              type="date"
              value-format="YYYY-MM-DD"
              disabled
              placeholder="--"
              class="task-info-readonly__date-picker"
            />
          </ElFormItem>
          <ElFormItem label="计划结束日期">
            <ElDatePicker
              :model-value="plannedEndDate"
              type="date"
              value-format="YYYY-MM-DD"
              disabled
              placeholder="--"
              class="task-info-readonly__date-picker"
            />
          </ElFormItem>
        </BusinessFormSection>
      </div>

      <div class="task-info-readonly__col-right">
        <BusinessFormSection title="任务说明">
          <ElFormItem class="task-info-readonly__desc-item">
            <BusinessRichTextEditor
              :model-value="taskDesc"
              disabled
              :height="320"
              upload-directory="task"
              placeholder="--"
            />
          </ElFormItem>
        </BusinessFormSection>

        <BusinessFormSection title="附件">
          <ElFormItem class="task-info-readonly__attachment-item">
            <BusinessAttachmentUploader :model-value="attachments" disabled directory="task" />
          </ElFormItem>
        </BusinessFormSection>
      </div>
    </div>
  </ElForm>
</template>

<style scoped>
.task-info-readonly__grid {
  display: grid;
  grid-template-columns: 360px 1fr;
  gap: 24px;
  align-items: start;
}

.task-info-readonly__col-left,
.task-info-readonly__col-right {
  min-width: 0;
}

.task-info-readonly__col-right {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.task-info-readonly__desc-item,
.task-info-readonly__attachment-item {
  margin-bottom: 0;
}

:deep(.task-info-readonly__date-picker.el-date-editor.el-input) {
  width: 100%;
}
</style>
