<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { useForm, useFormRules } from '@/hooks/common/form';
import BusinessFormDialog from '@/components/custom/business-form-dialog.vue';
import {
  type RequirementStatusActionCode,
  isRequirementActionNeedProject,
  isRequirementActionNeedReviewChoice
} from '../shared/requirement-master-data';

defineOptions({ name: 'RequirementActionDialog' });

interface Props {
  action: Api.Product.RequirementLifecycleAction | null;
  requirementTitle: string;
  projectOptions: Api.Project.Project[];
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted', payload: { actionCode: string; reason?: string; implementProjectId?: string }): void;
}

const emit = defineEmits<Emits>();

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

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

interface Model {
  reviewChoice: string;
  implementProjectId: string;
  reason: string;
}

const model = ref<Model>({ reviewChoice: '', implementProjectId: '', reason: '' });
const submitting = ref(false);

const actionCode = computed(() => props.action?.actionCode as RequirementStatusActionCode | undefined);

const isClaimAction = computed(() =>
  actionCode.value ? isRequirementActionNeedReviewChoice(actionCode.value) : false
);
const isDispatchAction = computed(() => (actionCode.value ? isRequirementActionNeedProject(actionCode.value) : false));
const needReason = computed(() => Boolean(props.action?.needReason));

const dialogTitle = computed(() => {
  if (!props.action) return '';
  if (isClaimAction.value) return '认领需求';
  return props.action.actionName;
});

const reviewChoiceOptions = [
  { label: '需要评审', value: 'claim_to_review', description: '认领后进入评审流程' },
  { label: '不需要评审', value: 'claim_to_dispatch', description: '认领后直接进入指派' }
];

const rules = computed(() => {
  const baseRules: Record<string, App.Global.FormRule[]> = {};

  if (isClaimAction.value) {
    baseRules.reviewChoice = [createRequiredRule('请选择是否需要评审')];
  }

  if (isDispatchAction.value) {
    baseRules.implementProjectId = [createRequiredRule('请选择关联项目')];
  }

  if (needReason.value) {
    baseRules.reason = [createRequiredRule('请输入状态变更原因')];
  }

  return baseRules;
});

watch(
  () => visible.value,
  val => {
    if (val) {
      model.value = { reviewChoice: '', implementProjectId: '', reason: '' };
    }
  }
);

async function handleSubmit() {
  await validate();

  submitting.value = true;

  const payload: { actionCode: string; reason?: string; implementProjectId?: string } = {
    actionCode: isClaimAction.value ? model.value.reviewChoice : props.action!.actionCode
  };

  if (isDispatchAction.value) {
    payload.implementProjectId = model.value.implementProjectId;
  }

  if (needReason.value) {
    payload.reason = model.value.reason.trim();
  }

  emit('submitted', payload);
  submitting.value = false;
  visible.value = false;
}
</script>

<template>
  <BusinessFormDialog
    v-model="visible"
    :title="dialogTitle"
    preset="sm"
    :confirm-loading="submitting"
    @confirm="handleSubmit"
  >
    <ElAlert
      v-if="requirementTitle"
      :title="`需求名称：${requirementTitle}`"
      type="info"
      :closable="false"
      class="mb-16px"
    />

    <ElForm ref="formRef" :model="model" :rules="rules" label-position="top">
      <ElFormItem v-if="isClaimAction" label="是否需要评审" prop="reviewChoice">
        <ElRadioGroup v-model="model.reviewChoice" class="business-form-radio-group">
          <ElRadio v-for="option in reviewChoiceOptions" :key="option.value" :value="option.value">
            <div class="flex flex-col gap-2px">
              <span>{{ option.label }}</span>
              <span class="text-12px text-gray-400">{{ option.description }}</span>
            </div>
          </ElRadio>
        </ElRadioGroup>
      </ElFormItem>

      <ElFormItem v-if="isDispatchAction" label="关联项目" prop="implementProjectId">
        <ElSelect v-model="model.implementProjectId" class="w-full" filterable placeholder="请选择关联项目（必选）">
          <ElOption v-for="item in projectOptions" :key="item.id" :label="item.projectName" :value="item.id" />
        </ElSelect>
      </ElFormItem>

      <ElFormItem v-if="needReason" label="变更原因" prop="reason">
        <ElInput
          v-model="model.reason"
          type="textarea"
          :rows="4"
          maxlength="500"
          show-word-limit
          placeholder="请输入状态变更原因（必填）"
        />
      </ElFormItem>
    </ElForm>
  </BusinessFormDialog>
</template>
