<template>
  <div class="page">
    <div class="page-header">
      <div>
        <h1 class="page-title">{{ isEdit ? "编辑合同费用" : "新增合同费用" }}</h1>
        <p class="page-subtitle">填写分中心合同信息并保存</p>
      </div>
      <el-button @click="goBack">返回</el-button>
    </div>

    <el-card>
      <el-form ref="formRef" :model="form" label-width="110px">
        <el-form-item label="分中心" prop="site_name" required>
          <el-input v-model="form.site_name" placeholder="输入分中心/机构名称" />
        </el-form-item>
        <el-form-item label="合同编号" prop="contract_no" required>
          <el-input v-model="form.contract_no" placeholder="输入合同编号" />
        </el-form-item>
        <el-form-item label="签署日期">
          <el-date-picker v-model="form.signed_date" type="date" value-format="YYYY-MM-DD" placeholder="选择日期" />
        </el-form-item>
        <el-form-item label="合同金额" prop="amount" required>
          <el-input-number v-model="form.amount" :min="0" :precision="2" :step="1000" />
        </el-form-item>
        <el-form-item label="币种">
          <el-select v-model="form.currency" placeholder="选择币种">
            <el-option label="CNY" value="CNY" />
            <el-option label="USD" value="USD" />
            <el-option label="EUR" value="EUR" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="补充说明" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="saving" @click="submit">保存</el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <AttachmentList
      v-if="isEdit && contractId"
      :study-id="studyId"
      entity-type="finance_contract"
      :entity-id="contractId"
    />
    <el-card v-else class="hint-card">
      <StateEmpty description="保存后可上传合同附件" />
    </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 { createFinanceContract, getFinanceContract, updateFinanceContract } from "../../api/financeContracts";
import AttachmentList from "../../components/attachments/AttachmentList.vue";
import StateEmpty from "../../components/StateEmpty.vue";

const route = useRoute();
const router = useRouter();
const study = useStudyStore();
const saving = ref(false);

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

const form = reactive({
  site_name: "",
  contract_no: "",
  signed_date: "",
  amount: 0,
  currency: "CNY",
  remark: "",
});

const load = async () => {
  if (!isEdit.value || !studyId.value || !contractId.value) return;
  try {
    const { data } = await getFinanceContract(studyId.value, contractId.value);
    Object.assign(form, {
      site_name: data.site_name || "",
      contract_no: data.contract_no || "",
      signed_date: data.signed_date || "",
      amount: Number(data.amount || 0),
      currency: data.currency || "CNY",
      remark: data.remark || "",
    });
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || "加载失败");
  }
};

const submit = async () => {
  if (!studyId.value) return;
  saving.value = true;
  try {
    const payload = {
      site_name: form.site_name,
      contract_no: form.contract_no,
      signed_date: form.signed_date || null,
      amount: form.amount,
      currency: form.currency,
      remark: form.remark || null,
    };
    if (isEdit.value && contractId.value) {
      await updateFinanceContract(studyId.value, contractId.value, payload);
      ElMessage.success("已保存");
      router.push(`/finance/contracts/${contractId.value}`);
    } else {
      const { data } = await createFinanceContract(studyId.value, payload);
      ElMessage.success("已创建");
      router.push(`/finance/contracts/${data.id}`);
    }
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || "保存失败");
  } finally {
    saving.value = false;
  }
};

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

onMounted(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>
