<template>
  <el-dialog
    :model-value="modelValue"
    class="report-generate-dialog"
    top="15vh"
    :close-on-click-modal="false"
    @update:model-value="(v) => $emit('update:modelValue', v)"
    @open="onOpen"
  >
    <div class="body-wrap">
      <div class="body-header">
        <div class="body-title">生成报告</div>
        <img src="@/assets/image/close-btn.svg" alt="" class="close-btn" @click="closeDialog" />
      </div>

      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="医院名称" prop="hospitalId">
              <el-select
                v-model="form.hospitalId"
                placeholder="全部医院"
                clearable
                filterable
                style="width: 100%"
              >
                <el-option
                  v-for="h in hospitals"
                  :key="h.id"
                  :label="h.name"
                  :value="h.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报告类型" prop="type">
              <el-select v-model="form.type" placeholder="季度报告" style="width: 100%">
                <el-option label="季度报告" value="quarterly" />
                <el-option label="年度报告" value="annual" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="年份" prop="year">
              <el-date-picker
                v-model="form.year"
                type="year"
                format="YYYY年"
                value-format="YYYY"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col v-if="form.type !== 'annual'" :span="12">
            <el-form-item label="报告周期" prop="quarter">
              <el-select
                v-model="form.quarter"
                placeholder="Q1（第一季度）"
                style="width: 100%"
              >
                <el-option label="Q1（第一季度）" :value="1" />
                <el-option label="Q2（第二季度）" :value="2" />
                <el-option label="Q3（第三季度）" :value="3" />
                <el-option label="Q4（第四季度）" :value="4" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <div class="body-footer">
      <el-button @click="closeDialog">取消</el-button>
      <el-button type="primary" :loading="submitting" @click="onSubmit">确定</el-button>
    </div>
  </el-dialog>
</template>

<script setup>
import { onMounted, reactive, ref, watch } from "vue";
import { ElMessage } from "element-plus";
import dayjs from "dayjs";
import { useI18n } from "vue-i18n";
import { generateAdminReport, getAdminHospitals } from "@/service/modular/admin";

const { t: $t } = useI18n();

const props = defineProps({
  modelValue: { type: Boolean, default: false },
});
const emit = defineEmits(["update:modelValue", "generated"]);

const formRef = ref();
const submitting = ref(false);
const hospitals = ref([]);

const currentYear = new Date().getFullYear();
const yearOptions = Array.from({ length: 5 }, (_, i) => currentYear - i);

const form = reactive({
  hospitalId: undefined,
  type: "quarterly",
  year: dayjs().format('YYYY'),
  quarter: 1,
});

const rules = {
  hospitalId: [{ required: true, message: "请选择医院名称", trigger: "change" }],
  type: [{ required: true, message: "请选择报告类型", trigger: "change" }],
  year: [{ required: true, message: "请选择年份", trigger: "change" }],
  quarter: [
    {
      validator: (_, value, cb) => {
        if (form.type === "quarterly" && (value === undefined || value === null || value === ""))
          return cb(new Error("季度报告必须选择季度"));
        cb();
      },
      trigger: "change",
    },
  ],
};

watch(
  () => form.type,
  (v) => {
    if (v === "annual") form.quarter = 0;
    else if (form.quarter === 0 || form.quarter === undefined) form.quarter = 1;
  },
);

const loadHospitals = async () => {
  try {
    const res = await getAdminHospitals({ page: 1, pageSize: 1000 });
    hospitals.value = res?.list || [];
  } catch (_) {
    hospitals.value = [];
  }
};

const reset = () => {
  form.hospitalId = undefined;
  form.type = "quarterly";
  form.year = dayjs().format("YYYY");
  form.quarter = 1;
};

const onOpen = () => {
  reset();
  if (hospitals.value.length === 0) loadHospitals();
};

watch(
  () => props.modelValue,
  (v) => {
    if (v) onOpen();
  },
);

onMounted(() => {
  if (hospitals.value.length === 0) loadHospitals();
});

const closeDialog = () => emit("update:modelValue", false);

const onSubmit = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid) => {
    if (!valid) return;
    submitting.value = true;
    try {
      const payload = {
        hospitalId: form.hospitalId,
        type: form.type,
        year: Number(form.year),
        quarter: form.type === "annual" ? 0 : form.quarter,
      };
      await generateAdminReport(payload);
      emit("generated");
      closeDialog();
    } finally {
      submitting.value = false;
    }
  });
};
</script>

<style lang="scss">
.report-generate-dialog {
  width: 800px;
  .body-wrap {
    padding: 24px;
  }
}
</style>