<template>
  <full-page v-if="!visible">
    <view v-if="formItems.length === 0" class="flex items-center justify-center h-full">
      <empty-data />
    </view>
    <view v-else class="p-15" :class="canEdit ? '' : 'disabled'">
      <view class="bg-white rounded shadow-lg">
        <form-template ref="tempRef" :items="displayFormItems" :form="formData" @change="change($event)" />
      </view>
    </view>

    <template #footer>
      <button-footer v-if="canEdit" :confirmText="nextTypes.length ? '下一步' : '保存'" :showCancel="false"
        @confirm="confirm()" />
    </template>
  </full-page>
</template>
<script setup>
import { computed, ref } from 'vue';
import { storeToRefs } from 'pinia';
import { onLoad } from "@dcloudio/uni-app";
import dayjs from 'dayjs';
import useGuard from '@/hooks/useGuard';
import useAccount from '@/store/account';
import api from '@/utils/api';
import { toast } from '@/utils/widget';

import ButtonFooter from '@/components/button-footer.vue';
import EmptyData from '@/components/empty-data.vue';
import FullPage from '@/components/full-page.vue';
import formTemplate from '@/components/form-template/index.vue';

const { useLoad } = useGuard();
const { account } = storeToRefs(useAccount());
const corpId = ref('');
const customerId = ref('');
const id = ref('');
const form = ref({});
const record = ref({});
const formItems = ref([]);
const teamId = ref('');
const tempRef = ref(null);
const type = ref('');
const visible = ref(false);
const timeTitle = ref('');
const canEdit = ref(false)
const nextTypes = ref([]);
const source = ref('');
const templateName = ref('');

const formData = computed(() => ({ ...record.value, ...form.value }));
const displayFormItems = computed(() => {
  const list = formItems.value.map(i => {
    const item = { ...i };
    if (i.referenceField && i.referenceValue) {
      item.displayRow = formData.value[i.referenceField] === i.referenceValue;
    } else {
      item.displayRow = true
    }
    return item
  })
  return list.filter(i => i.displayRow);
})


function change({ title, value }) {
  if (title) {
    form.value[title] = value;
  }
}

function confirm() {
  if (!tempRef.value.verify() || Object.keys(form.value).length === 0) return;
  if (id.value) {
    updateHealthRecord();
  } else {
    addHealthRecord()
  }
}

async function addHealthRecord() {
  const data = {
    ...form.value,
    corpId: corpId.value,
    memberId: customerId.value,
    // teamId: teamId.value,
    dataSource: 'customerReport',
    miniAppId: account.value.openid,
    medicalType: type.value,
    medicalTypeName: templateName.value
  }
  if (timeTitle.value) {
    data.sortTime = data[timeTitle.value] && dayjs(data[timeTitle.value]).isValid() ? dayjs(data[timeTitle.value]).valueOf() : dayjs().valueOf();
  }
  const res = await api('addMedicalRecord', data);
  if (res && res.success) {
    await toast('保存成功');
    const isFill = await fillNext();
    if (isFill) return;
    if (source.value === 'afterArchive') {
      uni.redirectTo({
        url: `/pages/archive/archive-result?corpId=${corpId.value}&teamId=${teamId.value}&customerId=${customerId.value}`
      })
    } else {
      uni.navigateBack();
    }
  } else {
    toast(res?.message || '保存失败');
  }
}

async function fillNext() {
  const nextType = nextTypes.value[0];
  const types = nextTypes.value.slice(1);
  if (nextType) {
    const url = `/pages/health/record?type=${nextType}&teamId=${teamId.value}&corpId=${corpId.value}&customerId=${customerId.value}&nextTypes=${types.join(',')}&source=${source.value}`
    uni.redirectTo({ url });
    return true
  }
  return false
}

async function updateHealthRecord() {
  if (Object.keys(form.value).length === 0) {
    uni.navigateBack();
    return;
  };
  const data = {
    ...form.value,
    _id: id.value,
    corpId: corpId.value,
    memberId: customerId.value,
    miniAppId: account.value.openid,
    medicalType: type.value,
    medicalTypeName: templateName.value
  }
  if (timeTitle.value) {
    data.sortTime = formData.value[timeTitle.value] && dayjs(formData.value[timeTitle.value]).isValid() ? dayjs(formData.value[timeTitle.value]).valueOf() : dayjs().valueOf();
  }
  const res = await api('updateMedicalRecord', data);
  if (res && res.success) {
    await toast('保存成功');
    uni.navigateBack();
  } else {
    toast(res?.message || '保存失败');
  }
}

async function init() {
  await getBaseForm();
  if (id.value) {
    getRecord()
  } else {
    canEdit.value = true
  }
}

async function getBaseForm() {
  const res = await api('getTeamHealthTemplate', { corpId: corpId.value, teamId: teamId.value, templateType: type.value });
  if (res && res.success) {
    formItems.value = Array.isArray(res.data) ? res.data : [];
    timeTitle.value = typeof res.timeTitle === 'string' ? res.timeTitle : '';
    templateName.value = typeof res.templateName === 'string' ? res.templateName : '';
    setPageTitle();
  } else {
    toast(res?.message || '查询失败');
    return Promise.reject()
  }
}

function setPageTitle() {
  const action = id.value ? '编辑' : '新增';
  uni.setNavigationBarTitle({ title: `${action}${templateName.value || '健康档案'}` })
}

async function getRecord() {
  const res = await api('getMedicalRecordById', {
    corpId: corpId.value,
    memberId: customerId.value,
    _id: id.value,
    medicalType: type.value
  });
  if (res && res.success) {
    record.value = res.record
    canEdit.value = record.value.dataSource === 'customerReport'
  } else {
    await toast(res?.message || '查询失败');
    uni.navigateBack();
  }
}
onLoad(options => {
  type.value = options.type;
  id.value = options.id || '';
  customerId.value = options.customerId || '';
  corpId.value = options.corpId;
  teamId.value = options.teamId;
  source.value = options.source || '';
  const nextTypeStr = typeof options.nextTypes === 'string' ? options.nextTypes : '';
  nextTypes.value = nextTypeStr.split(',');
  setPageTitle();
})
useLoad(options => {
  init();
})

</script>
<style scoped>
.disabled {
  pointer-events: none;
}
</style>
