<script setup lang="ts">
import { computed, nextTick, ref, watch } from 'vue';
import {
  fetchGetProjectListByProductId,
  fetchGetRequirement,
  fetchGetRequirementModuleTree,
  fetchUpdateRequirement
} from '@/service/api';
import { useForm, useFormRules } from '@/hooks/common/form';
import { useDict } from '@/hooks/business/dict';
import BusinessFormDialog from '@/components/custom/business-form-dialog.vue';
import BusinessRichTextEditor from '@/components/custom/business-rich-text-editor.vue';
import ReadonlyField from '@/components/custom/readonly-field.vue';
import MemberSelectOption from './member-select-option.vue';

defineOptions({ name: 'RequirementDetailDialog' });

type DialogMode = 'view' | 'edit';

interface Props {
  mode: DialogMode;
  requirement: Api.Product.Requirement | null;
  productId: string;
  memberOptions: Api.Product.ProductMember[];
  categoryDictCode: string;
  priorityDictCode: string;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted', requirementId?: string): void;
}

const emit = defineEmits<Emits>();

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

const { formRef, validate } = useForm();
const { createRequiredRule } = useFormRules();

const { getLabel: getCategoryLabel } = useDict(() => props.categoryDictCode);
const { getLabel: getPriorityLabel, enabledDictData: priorityDictData } = useDict(() => props.priorityDictCode);

const priorityOptions = computed(() => {
  return priorityDictData.value.map(item => ({
    label: item.label,
    value: Number(item.value)
  }));
});

interface Model {
  title: string;
  description: string;
  reviewRequired: number;
  moduleId: string;
  category: string;
  priority: number | null;
  proposerId: string;
  proposerNickname: string;
  currentHandlerUserId: string;
  currentHandlerUserNickname: string;
  implementProjectId: string | null;
  workHours: number | null;
  sort: number;
  lastStatusReason: string;
}

const loading = ref(false);
const submitting = ref(false);
const moduleTree = ref<Api.Product.RequirementModule[]>([]);
const projectOptions = ref<Api.Project.Project[]>([]);

const model = ref<Model>(createDefaultModel());

const isViewMode = computed(() => props.mode === 'view');
const isEditMode = computed(() => props.mode === 'edit');
const dialogTitle = computed(() => {
  if (isViewMode.value) {
    return '查看需求';
  }
  return '编辑需求';
});

const memberUserOptions = computed(() => {
  return props.memberOptions.filter(m => m.status === 0);
});

const memberLabelMap = computed(() => {
  return new Map(memberUserOptions.value.map(item => [String(item.userId), item.userNickname]));
});

const moduleLabelMap = computed(() => {
  const map = new Map<string | undefined, string>();

  function traverse(modules: Api.Product.RequirementModule[]) {
    for (const module of modules) {
      map.set(module.id, module.moduleName);
      if (module.children?.length) {
        traverse(module.children);
      }
    }
  }

  traverse(moduleTree.value);
  return map;
});

const projectOptionsMap = computed(() => {
  return new Map(projectOptions.value.map(item => [String(item.id), item.projectName]));
});

const flatModuleOptions = computed<Array<{ label: string; value: string }>>(() => {
  const options: Array<{ label: string; value: string }> = [];

  function walk(modules: Api.Product.RequirementModule[], parentPath: string) {
    for (const module of modules) {
      const currentPath = `${parentPath}/${module.moduleName}`;
      options.push({
        label: currentPath,
        value: module.id || ''
      });
      if (module.children?.length) {
        walk(module.children, currentPath);
      }
    }
  }

  if (moduleTree.value.length > 0) {
    walk(moduleTree.value, '');
  }

  return options;
});

const reviewRequiredOptions = [
  { label: '不需要', value: 0 },
  { label: '需要', value: 1 }
];

const rules = computed(() => {
  const baseRules: Record<string, App.Global.FormRule[]> = {
    title: isEditMode.value ? [createRequiredRule('请输入需求名称')] : [],
    category: isEditMode.value ? [createRequiredRule('请选择需求类型')] : [],
    priority: isEditMode.value ? [createRequiredRule('请选择优先级')] : [],
    proposerId: isEditMode.value ? [createRequiredRule('请选择提出人')] : [],
    currentHandlerUserId: isEditMode.value ? [createRequiredRule('请选择负责人')] : []
  };

  return baseRules;
});

function createDefaultModel(): Model {
  return {
    title: '',
    description: '',
    reviewRequired: 0,
    moduleId: '0',
    category: '',
    priority: 1,
    proposerId: '',
    proposerNickname: '',
    currentHandlerUserId: '',
    currentHandlerUserNickname: '',
    implementProjectId: null,
    workHours: null,
    sort: 0,
    lastStatusReason: ''
  };
}

function getNullableText(value?: string | null) {
  return value?.trim() || null;
}

function closeDialog() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();

  if (!props.productId || !props.requirement?.id) {
    return;
  }

  submitting.value = true;

  const updatePayload: Api.Product.UpdateRequirementParams = {
    id: props.requirement.id,
    productId: props.productId,
    moduleId: model.value.moduleId || '0',
    reviewRequired: model.value.reviewRequired as Api.Product.RequirementReviewRequired,
    title: model.value.title.trim(),
    description: getNullableText(model.value.description),
    category: model.value.category,
    priority: Number(model.value.priority) as Api.Product.RequirementPriority,
    proposerId: model.value.proposerId,
    proposerNickname: model.value.proposerNickname,
    currentHandlerUserId: model.value.currentHandlerUserId,
    currentHandlerUserNickname: model.value.currentHandlerUserNickname,
    implementProjectId: model.value.implementProjectId,
    workHours: model.value.workHours || 0,
    sort: model.value.sort
  };

  const { error } = await fetchUpdateRequirement(updatePayload);

  submitting.value = false;

  if (error) {
    return;
  }

  window.$message?.success('需求更新成功');
  closeDialog();
  emit('submitted', props.requirement.id);
}

async function loadModuleTree() {
  if (!props.productId) {
    moduleTree.value = [];
    return;
  }

  const { error, data } = await fetchGetRequirementModuleTree(props.productId);

  if (error || !data) {
    moduleTree.value = [];
    return;
  }

  moduleTree.value = data;
}

async function loadProjectOptions() {
  if (!props.productId) {
    projectOptions.value = [];
    return;
  }

  const { error, data } = await fetchGetProjectListByProductId(props.productId);

  if (error || !data) {
    projectOptions.value = [];
    return;
  }

  projectOptions.value = data;
}

async function loadRequirementDetail() {
  if (!props.productId || !props.requirement?.id) {
    return;
  }

  loading.value = true;

  const { error, data } = await fetchGetRequirement(props.requirement.id, props.productId);

  loading.value = false;

  if (error || !data) {
    return;
  }

  model.value = {
    title: data.title || '',
    description: data.description || '',
    reviewRequired: data.reviewRequired ?? 0,
    moduleId: data.moduleId || '0',
    category: data.category || '',
    priority: data.priority ?? null,
    proposerId: data.proposerId || '',
    proposerNickname: data.proposerNickname || '',
    currentHandlerUserId: data.currentHandlerUserId || '',
    currentHandlerUserNickname: data.currentHandlerUserNickname || '',
    implementProjectId: data.implementProjectId || null,
    workHours: data.workHours ?? null,
    sort: data.sort ?? 0,
    lastStatusReason: data.lastStatusReason || ''
  };
}

watch(
  () => visible.value,
  async value => {
    if (!value) {
      return;
    }

    await Promise.all([loadModuleTree(), loadProjectOptions()]);

    if (props.requirement?.id) {
      await loadRequirementDetail();
    }

    await nextTick();
    formRef.value?.clearValidate();
  }
);
</script>

<template>
  <BusinessFormDialog
    v-model="visible"
    :title="dialogTitle"
    preset="lg"
    :loading="loading"
    :confirm-loading="submitting"
    :show-footer="isEditMode"
    @confirm="handleSubmit"
  >
    <ElForm ref="formRef" :model="model" :rules="rules" label-position="top">
      <ElRow :gutter="16">
        <ElCol :span="12">
          <ElFormItem label="需求名称" prop="title">
            <ReadonlyField :value="model.title" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="模块">
            <template v-if="isViewMode">
              <ReadonlyField :value="moduleLabelMap.get(model.moduleId) || '--'" />
            </template>
            <ElSelect v-else v-model="model.moduleId" class="w-full" filterable placeholder="请选择所属模块">
              <ElOption v-for="item in flatModuleOptions" :key="item.value" :label="item.label" :value="item.value" />
            </ElSelect>
          </ElFormItem>
        </ElCol>
        <ElCol :span="24">
          <ElFormItem label="内容">
            <template v-if="isViewMode">
              <div class="readonly-textarea" v-html="model.description || '--'"></div>
            </template>
            <BusinessRichTextEditor
              v-else
              v-model="model.description"
              height="240px"
              upload-directory="requirement"
              placeholder="请输入需求内容"
            />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="是否需要评审">
            <ReadonlyField :value="reviewRequiredOptions.find(opt => opt.value === model.reviewRequired)?.label" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="优先级" prop="priority">
            <template v-if="isViewMode">
              <ReadonlyField
                :value="model.priority !== null ? getPriorityLabel(String(model.priority)) || '--' : '--'"
              />
            </template>
            <ElSelect v-else v-model="model.priority" class="w-full" filterable placeholder="请选择优先级">
              <ElOption v-for="item in priorityOptions" :key="item.value" :label="item.label" :value="item.value" />
            </ElSelect>
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="所需工时">
            <template v-if="isViewMode">
              <ReadonlyField :value="model.workHours != null ? `${model.workHours}小时` : '--'" />
            </template>
            <ElInputNumber
              v-else
              v-model="model.workHours"
              class="w-full"
              :min="0"
              :max="9999"
              :precision="1"
              placeholder="请输入所需工时"
            />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="需求类型" prop="category">
            <ReadonlyField :value="getCategoryLabel(model.category) || '--'" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="提出人" prop="proposerId">
            <ReadonlyField :value="memberLabelMap.get(model.proposerId) || '--'" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="负责人" prop="currentHandlerUserId">
            <template v-if="isViewMode">
              <ReadonlyField :value="memberLabelMap.get(model.currentHandlerUserId) || '--'" />
            </template>
            <ElSelect v-else v-model="model.currentHandlerUserId" class="w-full" filterable placeholder="请选择负责人">
              <ElOption
                v-for="item in memberUserOptions"
                :key="item.userId"
                :label="item.userNickname"
                :value="item.userId"
              >
                <MemberSelectOption :nickname="item.userNickname" :role-name="item.roleName" />
              </ElOption>
            </ElSelect>
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="实现项目">
            <template v-if="isViewMode">
              <ReadonlyField :value="projectOptionsMap.get(model.implementProjectId || '') || '--'" />
            </template>
            <ElSelect
              v-else
              v-model="model.implementProjectId"
              class="w-full"
              filterable
              clearable
              placeholder="请选择实现项目"
            >
              <ElOption v-for="item in projectOptions" :key="item.id" :label="item.projectName" :value="item.id" />
            </ElSelect>
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="排序值">
            <template v-if="isViewMode">
              <ReadonlyField :value="model.sort" />
            </template>
            <ElInputNumber v-else v-model="model.sort" class="w-full" :min="0" :max="9999" placeholder="请输入排序值" />
          </ElFormItem>
        </ElCol>
        <ElCol v-if="isViewMode && model.lastStatusReason" :span="24">
          <ElFormItem label="状态变更原因">
            <div class="readonly-textarea">
              {{ model.lastStatusReason }}
            </div>
          </ElFormItem>
        </ElCol>
      </ElRow>
    </ElForm>
  </BusinessFormDialog>
</template>

<style scoped>
.readonly-textarea {
  box-sizing: border-box;
  width: 100%;
  min-height: 100px;
  padding: 8px 12px;
  border-radius: 4px;
  background: linear-gradient(180deg, rgb(241 245 249 / 98%), rgb(226 232 240 / 94%)), rgb(241 245 249);
  box-shadow: 0 0 0 1px rgb(203 213 225 / 96%) inset;
  color: rgb(51 65 85 / 96%);
  font-size: 14px;
  line-height: 1.5;
  white-space: pre-wrap;
  word-break: break-all;
}
</style>
