<template>
  <div class="page">
    <div class="page-header">
      <div>
        <h1 class="page-title">{{ isEdit ? TEXT.modules.financeSpecials.editTitle : TEXT.modules.financeSpecials.newTitle }}</h1>
        <p class="page-subtitle">{{ TEXT.modules.financeSpecials.subtitle }}</p>
      </div>
      <el-button @click="goBack">{{ TEXT.common.actions.back }}</el-button>
    </div>

    <el-card>
      <el-form :model="form" label-width="110px">
        <el-form-item :label="TEXT.common.fields.site" required>
          <el-input v-model="form.site_name" :disabled="isReadOnly" :placeholder="TEXT.common.placeholders.input + TEXT.common.fields.site" />
        </el-form-item>
        <el-form-item :label="TEXT.common.fields.type" required>
          <el-select v-model="form.fee_type" :disabled="isReadOnly" :placeholder="TEXT.common.placeholders.select">
            <el-option :label="TEXT.enums.financeSpecialType.TRAVEL" value="TRAVEL" />
            <el-option :label="TEXT.enums.financeSpecialType.HOTEL" value="HOTEL" />
            <el-option :label="TEXT.enums.financeSpecialType.TRANSPORT" value="TRANSPORT" />
            <el-option :label="TEXT.enums.financeSpecialType.OTHER" value="OTHER" />
          </el-select>
        </el-form-item>
        <el-form-item :label="TEXT.common.fields.amount" required>
          <el-input-number v-model="form.amount" :disabled="isReadOnly" :min="0" :precision="2" :step="100" />
        </el-form-item>
        <el-form-item :label="TEXT.common.fields.occurDate">
          <el-date-picker v-model="form.occur_date" :disabled="isReadOnly" type="date" value-format="YYYY-MM-DD" :placeholder="TEXT.common.placeholders.select" />
        </el-form-item>
        <el-form-item :label="TEXT.common.fields.staff">
          <el-input v-model="form.staff_name" :disabled="isReadOnly" :placeholder="TEXT.common.placeholders.input + TEXT.common.fields.staff" />
        </el-form-item>
        <el-form-item :label="TEXT.common.fields.remark">
          <el-input v-model="form.remark" :disabled="isReadOnly" type="textarea" :rows="3" :placeholder="TEXT.common.placeholders.input" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="saving" :disabled="isReadOnly" @click="submit">{{ TEXT.common.actions.save }}</el-button>
          <el-button @click="goBack">{{ TEXT.common.actions.cancel }}</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <AttachmentList
      v-if="isEdit && specialId"
      :study-id="studyId"
      entity-type="finance_special"
      :entity-id="specialId"
      :readonly="isReadOnly"
    />
    <el-card v-else class="hint-card">
      <StateEmpty :description="TEXT.modules.financeSpecials.uploadHint" />
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { useStudyStore } from "../../store/study";
import { createFinanceSpecial, getFinanceSpecial, updateFinanceSpecial } from "../../api/financeSpecials";
import { fetchSites } from "../../api/sites";
import AttachmentList from "../../components/attachments/AttachmentList.vue";
import StateEmpty from "../../components/StateEmpty.vue";
import { TEXT } from "../../locales";

const route = useRoute();
const router = useRouter();
const study = useStudyStore();
const saving = ref(false);
const sites = ref<any[]>([]);

const specialId = computed(() => route.params.specialId as string | undefined);
const isEdit = computed(() => !!specialId.value);
const studyId = computed(() => study.currentStudy?.id || "");

const form = reactive({
  site_name: "",
  fee_type: "TRAVEL",
  amount: 0,
  occur_date: "",
  staff_name: "",
  remark: "",
});

const siteActiveMap = computed(() => {
  const map: Record<string, boolean> = {};
  sites.value.forEach((site) => {
    if (site?.name) map[site.name] = !!site.is_active;
  });
  return map;
});
const isReadOnly = computed(() => isEdit.value && !!form.site_name && siteActiveMap.value[form.site_name] === false);

const loadSites = async () => {
  if (!studyId.value) return;
  try {
    const { data } = await fetchSites(studyId.value, { limit: 500 });
    sites.value = Array.isArray(data) ? data : data.items || [];
  } catch {
    sites.value = [];
  }
};

const load = async () => {
  if (!isEdit.value || !studyId.value || !specialId.value) return;
  try {
    const { data } = await getFinanceSpecial(studyId.value, specialId.value);
    Object.assign(form, {
      site_name: data.site_name || "",
      fee_type: data.fee_type || "TRAVEL",
      amount: Number(data.amount || 0),
      occur_date: data.occur_date || "",
      staff_name: data.staff_name || "",
      remark: data.remark || "",
    });
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || TEXT.common.messages.loadFailed);
  }
};

const submit = async () => {
  if (!studyId.value) return;
  if (isReadOnly.value) {
    ElMessage.warning("中心已停用");
    return;
  }
  if (!form.site_name) {
    ElMessage.warning(TEXT.common.messages.required);
    return;
  }
  if (siteActiveMap.value[form.site_name] === false) {
    ElMessage.warning("中心已停用");
    return;
  }
  saving.value = true;
  try {
    const payload = {
      site_name: form.site_name,
      fee_type: form.fee_type,
      amount: form.amount,
      occur_date: form.occur_date || null,
      staff_name: form.staff_name || null,
      remark: form.remark || null,
    };
    if (isEdit.value && specialId.value) {
      await updateFinanceSpecial(studyId.value, specialId.value, payload);
      ElMessage.success(TEXT.common.messages.saveSuccess);
      router.push(`/finance/special/${specialId.value}`);
    } else {
      const { data } = await createFinanceSpecial(studyId.value, payload);
      ElMessage.success(TEXT.common.messages.createSuccess);
      router.push(`/finance/special/${data.id}`);
    }
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || TEXT.common.messages.saveFailed);
  } finally {
    saving.value = false;
  }
};

const goBack = () => router.push("/finance/special");

onMounted(async () => {
  await loadSites();
  load();
});
</script>

<style scoped>
.page {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
}

.page-title {
  margin: 0;
  font-size: 22px;
  font-weight: 600;
}

.page-subtitle {
  margin: 6px 0 0;
  font-size: 13px;
  color: var(--ctms-text-secondary);
}

.hint-card {
  padding: 12px;
}
</style>
