<script setup lang="ts">
import { computed, nextTick, ref, watch } from 'vue';
import { fetchSplitRequirement } 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 DictSelect from '@/components/custom/dict-select.vue';
import MemberSelectOption from './member-select-option.vue';

defineOptions({ name: 'RequirementSplitDialog' });

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

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

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

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

const { 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;
  category: string;
  priority: number | null;
  currentHandlerUserId: string;
  completionDate: string;
  sort: number;
}

const submitting = ref(false);
const loading = ref(false);

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

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

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

const rules = {
  title: [createRequiredRule('请输入子需求标题')],
  category: [createRequiredRule('请选择分类')],
  priority: [createRequiredRule('请选择优先级')],
  currentHandlerUserId: [createRequiredRule('请选择负责人')],
  completionDate: [createRequiredRule('请选择预期完成时间')]
} satisfies Record<string, App.Global.FormRule[]>;

function createDefaultModel(): Model {
  return {
    title: '',
    description: '',
    reviewRequired: 0,
    category: '',
    priority: 1,
    currentHandlerUserId: '',
    completionDate: '',
    sort: 0
  };
}

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

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

async function handleSubmit() {
  await validate();

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

  const payload: Api.Product.SplitRequirementParams = {
    parentId: props.parentRequirement.id,
    productId: props.productId,
    moduleId: props.parentRequirement.moduleId,
    proposerId: props.parentRequirement.proposerId,
    title: model.value.title.trim(),
    description: getNullableText(model.value.description),
    reviewRequired: model.value.reviewRequired as Api.Product.RequirementReviewRequired,
    category: model.value.category,
    priority: Number(model.value.priority) as Api.Product.RequirementPriority,
    currentHandlerUserId: model.value.currentHandlerUserId,
    completionDate: model.value.completionDate,
    sort: model.value.sort
  };

  console.log('payload', payload);

  submitting.value = true;

  const result = await fetchSplitRequirement(payload);

  submitting.value = false;

  if (result.error) {
    return;
  }

  window.$message?.success('需求拆分成功');
  closeDialog();
  emit('submitted');
}

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

    model.value = createDefaultModel();

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

<template>
  <BusinessFormDialog
    v-model="visible"
    title="拆分需求"
    preset="lg"
    :loading="loading"
    :confirm-loading="submitting"
    @confirm="handleSubmit"
  >
    <ElAlert
      v-if="parentRequirement"
      :title="`正在拆分需求：${parentRequirement.title}`"
      type="info"
      :closable="false"
      class="mb-16px"
    />

    <ElForm ref="formRef" :model="model" :rules="rules" label-position="top">
      <ElRow :gutter="16">
        <ElCol :span="12">
          <ElFormItem label="子需求标题" prop="title">
            <ElInput v-model="model.title" clearable maxlength="256" placeholder="请输入子需求标题" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="预期完成时间" prop="completionDate" style="width: 100%">
            <ElDatePicker
              v-model="model.completionDate"
              type="datetime"
              class="w-full"
              placeholder="选择预期完成时间"
              value-format="x"
              style="width: 100%"
            />
          </ElFormItem>
        </ElCol>
        <ElCol :span="24">
          <ElFormItem label="描述">
            <ElInput
              v-model="model.description"
              type="textarea"
              :rows="6"
              maxlength="2000"
              show-word-limit
              placeholder="请输入需求描述"
            />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="是否需要评审">
            <ElSelect v-model="model.reviewRequired" class="w-full" placeholder="请选择">
              <ElOption
                v-for="item in reviewRequiredOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </ElSelect>
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="分类" prop="category">
            <DictSelect v-model="model.category" :dict-code="categoryDictCode" filterable placeholder="请选择分类" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="优先级" prop="priority">
            <ElSelect 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="负责人" prop="currentHandlerUserId">
            <ElSelect 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="排序值">
            <ElInputNumber v-model="model.sort" class="w-full" :min="0" :max="9999" placeholder="请输入排序值" />
          </ElFormItem>
        </ElCol>
      </ElRow>
    </ElForm>
  </BusinessFormDialog>
</template>

<style scoped></style>
