<template>
  <view class="page">
    <CustomerProfileTab :data="archive" :floatingBottom="16" @save="savePatch" />
  </view>
</template>

<script setup>
import { ref } from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app';
import CustomerProfileTab from '@/components/archive-detail/customer-profile-tab.vue';
import { ensureSeed } from '@/components/archive-detail/mock';

const STORAGE_KEY = 'ykt_case_archive_detail';

const archiveId = ref('');
const archive = ref({
  name: '',
  sex: '',
  age: '',
  avatar: '',
  mobile: '',
  outpatientNo: '',
  inpatientNo: '',
  medicalRecordNo: '',
  createTime: '',
  creator: '',
  createdByDoctor: true,
  hasBindWechat: false,
  notes: '',
  groups: [],
  groupOptions: [],
});

function loadFromStorage() {
  const cached = uni.getStorageSync(STORAGE_KEY);
  if (cached && typeof cached === 'object') {
    archive.value = {
      ...archive.value,
      ...cached,
      groups: Array.isArray(cached.groups) ? cached.groups : archive.value.groups,
      groupOptions: Array.isArray(cached.groupOptions) ? cached.groupOptions : archive.value.groupOptions,
    };
  }
  if (!archiveId.value) {
    archiveId.value = String(archive.value.medicalRecordNo || archive.value.outpatientNo || archive.value.inpatientNo || `mock_${Date.now()}`);
  }
  ensureSeed(archiveId.value, archive.value);
}

function savePatch(patch) {
  archive.value = { ...archive.value, ...(patch && typeof patch === 'object' ? patch : {}) };
  uni.setStorageSync(STORAGE_KEY, { ...archive.value });
}

onLoad((options) => {
  archiveId.value = options?.archiveId ? String(options.archiveId) : '';
  loadFromStorage();
});

onShow(() => loadFromStorage());
</script>

<style scoped>
.page {
  min-height: 100vh;
  background: #f5f6f8;
}
</style>
