<template>
  <div class="hospital-edit" v-loading="loading">
    <el-page-header
      :icon="ArrowLeft"
      :content="$t('common.back')"
      @back="goBack"
      class="page-header"
    >
      <template #content>
        <span class="page-title">{{
          isEdit ? $t("modal.editHospital") : $t("modal.addHospital")
        }}</span>
      </template>
    </el-page-header>

    <el-card shadow="never">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        style="max-width: 800px"
      >
        <el-form-item :label="$t('label.hospitalName')" prop="name">
          <el-input
            v-model="form.name"
            :placeholder="$t('placeholder.hospital')"
          />
        </el-form-item>
        <el-form-item :label="$t('label.category')" prop="customerCategory">
          <el-select
            v-model="form.customerCategory"
            :placeholder="$t('label.category')"
            style="width: 200px"
          >
            <el-option label="A类客户（活跃）" value="A" />
            <el-option label="B类客户（不活跃）" value="B" />
            <el-option label="C类客户（待挽回）" value="C" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('label.contactDept')">
          <el-input v-model="form.contactDept" />
        </el-form-item>
        <el-form-item :label="$t('label.contactPerson')">
          <el-input v-model="form.contactPerson" />
        </el-form-item>
        <el-form-item :label="$t('label.contactPosition')">
          <el-input v-model="form.contactPosition" />
        </el-form-item>
        <el-form-item :label="$t('label.contactPhone')">
          <el-input v-model="form.contactPhone" />
        </el-form-item>
        <el-form-item :label="$t('label.signDate')" prop="signDate">
          <el-date-picker
            v-model="form.signDate"
            type="date"
            value-format="YYYY-MM-DD"
            :placeholder="$t('common.pleaseSelect')"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item :label="$t('label.acceptDate')" prop="acceptDate">
          <el-date-picker
            v-model="form.acceptDate"
            type="date"
            value-format="YYYY-MM-DD"
            :placeholder="$t('common.pleaseSelect')"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item :label="$t('label.years')" prop="contractYears">
          <el-input-number v-model="form.contractYears" :min="1" :max="20" />
        </el-form-item>
        <el-form-item
          :label="$t('label.maintenanceEndDate')"
          prop="maintenanceEnd"
        >
          <el-date-picker
            v-model="form.maintenanceEnd"
            type="date"
            value-format="YYYY-MM-DD"
            :placeholder="$t('common.pleaseSelect')"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item :label="$t('label.manager')">
          <el-select
            v-model="form.managerId"
            :placeholder="$t('label.manager')"
            filterable
            clearable
            style="width: 240px"
          >
            <el-option
              v-for="item in managerOptions"
              :key="item.id"
              :label="`${item.name}`"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('label.acceptanceReport')">
          <el-upload
            v-model:file-list="reportFileList"
            :auto-upload="false"
            :limit="1"
            :on-exceed="handleReportExceed"
            accept=".pdf"
          >
            <el-button type="primary" plain>{{ $t("btn.upload") }}</el-button>
            <template #tip>
              <div class="el-upload__tip">
                {{ $t("label.acceptanceReportTip") }}
              </div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item :label="$t('common.remark')">
          <el-input v-model="form.remark" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="submitting" @click="submit">
            {{ isEdit ? $t("common.save") : $t("common.add") }}
          </el-button>
          <el-button @click="goBack">{{ $t("common.cancel") }}</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { computed, onMounted, reactive, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { ArrowLeft } from "@element-plus/icons-vue";
import { useI18n } from "vue-i18n";
import {
  getAdminHospitalDetail,
  createAdminHospital,
  updateAdminHospital,
  getAdminAccounts,
} from "@/service/modular/admin";

const { t: $t } = useI18n();
const route = useRoute();
const router = useRouter();
const loading = ref(false);
const submitting = ref(false);
const formRef = ref();

const isEdit = computed(() => !!route.params.id);

const form = reactive({
  name: "",
  customerCategory: "",
  contactDept: "",
  contactPerson: "",
  contactPosition: "",
  contactPhone: "",
  signDate: "",
  acceptDate: "",
  contractYears: 1,
  maintenanceEnd: "",
  managerId: undefined,
  remark: "",
});

const rules = {
  name: [
    {
      required: true,
      message: () => $t("placeholder.hospital"),
      trigger: "blur",
    },
  ],
  customerCategory: [
    { required: true, message: () => $t("label.category"), trigger: "change" },
  ],
  signDate: [
    { required: true, message: () => $t("label.signDate"), trigger: "change" },
  ],
  acceptDate: [
    {
      required: true,
      message: () => $t("label.acceptDate"),
      trigger: "change",
    },
  ],
  contractYears: [
    { required: true, message: () => $t("label.years"), trigger: "blur" },
  ],
  maintenanceEnd: [
    {
      required: true,
      message: () => $t("label.maintenanceEndDate"),
      trigger: "change",
    },
  ],
};

const managerOptions = ref([]);

const reportFileList = ref([]);

const handleReportExceed = (files) => {
  reportFileList.value = files.slice(-1);
};

const buildHospitalFormData = () => {
  const fd = new FormData();
  Object.entries(form).forEach(([key, value]) => {
    if (value === undefined || value === null || value === "") return;
    fd.append(key, value);
  });
  const file = (reportFileList.value || [])
    .map((f) => f.raw)
    .filter(Boolean)[0];
  if (file) fd.append("files", file);
  return fd;
};

const loadManagers = async () => {
  try {
    const res = await getAdminAccounts({ type: "Admin" });
    managerOptions.value = res?.list || [];
  } catch (e) {
    // request 层已统一提示错误
  }
};

const loadDetail = async () => {
  if (!isEdit.value) return;
  loading.value = true;
  try {
    const data = await getAdminHospitalDetail(route.params.id);
    Object.assign(form, data);
  } finally {
    loading.value = false;
  }
};

const submit = async () => {
  await formRef.value.validate(async (valid) => {
    if (!valid) return;
    if (!reportFileList.value?.length) {
      ElMessage.warning($t("label.acceptanceReport"));
      return;
    }
    submitting.value = true;
    try {
      const fd = buildHospitalFormData();
      if (isEdit.value) {
        await updateAdminHospital(route.params.id, fd);
        ElMessage.success($t("msg.hospitalEditSuccess"));
      } else {
        await createAdminHospital(fd);
        ElMessage.success($t("msg.hospitalAddSuccess"));
      }
      router.replace("/admin/hospitals");
    } finally {
      submitting.value = false;
    }
  });
};

const goBack = () => router.back();

onMounted(() => {
  loadManagers();
  loadDetail();
});
</script>

<style scoped lang="scss">
.page-header {
  margin-bottom: 12px;
  .page-title {
    font-size: 16px;
    font-weight: 600;
  }
}
</style>
