<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue';
import { fetchGetPersonalItemExecutionOptions } from '@/service/api';
import { useForm, useFormRules } from '@/hooks/common/form';
import BusinessFormDialog from '@/components/custom/business-form-dialog.vue';

defineOptions({ name: 'PersonalItemBindExecutionDialog' });

interface Props {
  selectedCount: number;
  submitLoading?: boolean;
}

interface Emits {
  (e: 'submit', payload: { executionId: string }): void;
}

const props = withDefaults(defineProps<Props>(), {
  submitLoading: false
});

const emit = defineEmits<Emits>();

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

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

const loading = ref(false);
const executionOptions = ref<Api.PersonalItem.PersonalItemExecutionOption[]>([]);

const model = reactive({
  executionId: ''
});

const rules = computed(
  () =>
    ({
      executionId: [createRequiredRule('请选择执行')]
    }) satisfies Record<string, App.Global.FormRule[]>
);

function getExecutionOptionLabel(option: Api.PersonalItem.PersonalItemExecutionOption) {
  if (option.projectName?.trim()) {
    return `${option.projectName} / ${option.executionName}`;
  }

  return option.executionName;
}

async function loadExecutionOptions() {
  loading.value = true;
  const { error, data } = await fetchGetPersonalItemExecutionOptions();
  loading.value = false;

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

  executionOptions.value = data.map(item => ({ ...item }));
}

async function initDialog() {
  model.executionId = '';
  await loadExecutionOptions();
  formRef.value?.clearValidate();
}

async function handleConfirm() {
  await validate();

  emit('submit', {
    executionId: model.executionId
  });
}

watch(
  () => visible.value,
  value => {
    if (value) {
      initDialog();
    }
  }
);
</script>

<template>
  <BusinessFormDialog
    v-model="visible"
    title="批量关联执行"
    preset="sm"
    :loading="loading"
    :confirm-loading="props.submitLoading"
    @confirm="handleConfirm"
  >
    <ElAlert
      :title="`已选中 ${props.selectedCount} 条个人事项，关联成功后这些事项会从当前列表移除。`"
      type="info"
      :closable="false"
      class="mb-16px"
    />

    <ElForm ref="formRef" :model="model" :rules="rules" label-position="top" :validate-on-rule-change="false">
      <ElFormItem label="执行" prop="executionId">
        <ElSelect
          v-model="model.executionId"
          clearable
          filterable
          placeholder="请选择执行"
          class="w-full"
          :loading="loading"
        >
          <ElOption
            v-for="option in executionOptions"
            :key="option.executionId"
            :label="getExecutionOptionLabel(option)"
            :value="option.executionId"
          />
        </ElSelect>
      </ElFormItem>
    </ElForm>
  </BusinessFormDialog>
</template>

<style scoped></style>
