<template>
  <view>
    <CommonRoot>
      <LoadingPage v-if="loading" /> 
      <FlexCol :padding="30">
        <Alert
          v-if="localSavedState"
          type="info"
          message="您的修改已经暂存，可以放心离开，下次接着编辑"
        />
        <Height :height="20" />
        <DynamicForm
          ref="formRef"
          :options="formDefine"
          :model="formModel"
          :globalParams="querys"
        />
        <Height :height="20" />
        <Button type="primary" :loading="loading" @click="submit">提交</Button>
      </FlexCol>
      <XBarSpace />
    </CommonRoot>
  </view>
</template>

<script setup lang="ts">
import { nextTick, ref, watch, type Ref } from 'vue';
import { useCollectStore } from '@/store/collect';
import { useLoadQuerys } from '@/common/composeabe/LoadQuerys';
import { getVillageInfoForm, getVillageInfoFormIds, type SingleForm } from './forms';
import { showError } from '@/common/composeabe/ErrorDisplay';
import { backAndCallOnPageBack } from '@/components/utils/PageAction';
import { toast } from '@/components/utils/DialogAction';
import { confirm } from '@/components/dialog/CommonRoot';
import { Debounce, ObjectUtils, RequestApiError, waitTimeOut } from '@imengyu/imengyu-utils';
import VillageInfoApi, { CommonInfoModel } from '@/api/inhert/VillageInfoApi';
import DynamicForm from '@/components/dynamic/DynamicForm.vue';
import LoadingPage from '@/components/display/loading/LoadingPage.vue';
import Button from '@/components/basic/Button.vue';
import CommonRoot from '@/components/dialog/CommonRoot.vue';
import FlexCol from '@/components/layout/FlexCol.vue';
import Height from '@/components/layout/space/Height.vue';
import XBarSpace from '@/components/layout/space/XBarSpace.vue';
import type { IDynamicFormOptions, IDynamicFormRef } from '@/components/dynamic';
import Alert from '@/components/feedback/Alert.vue';

const loading = ref(false);
const subTitle = ref('');
const collectStore = useCollectStore();

const formRef = ref<IDynamicFormRef>();
const formModel = ref(new CommonInfoModel()) as Ref<CommonInfoModel>;
const formDefine = ref<IDynamicFormOptions>({
  formItems: [],
  formAdditionaProps: {
    labelWidth: '220rpx',
    labelAlign: 'left',
    innerStyle: {
      borderRadius: '20rpx',
      overflow: 'hidden',
    },
  },
});
let currentFormInfo : SingleForm|null = null;

const { querys } = useLoadQuerys({ 
  villageId: 0,  
  villageVolunteerId: 0,
  subType: '',
  subId: 0,
  subKey: '',
  subTitle: '',
  id: 0,
}, async (querys) => {
  loading.value = true;
  if (querys.subTitle) {
    subTitle.value = querys.subTitle;
    uni.setNavigationBarTitle({  title: subTitle.value + '详情', })
  }
  if (!formRef.value)
    return;

  let formData = undefined;
  await waitTimeOut(800);

  try {
    currentFormInfo = getVillageInfoForm(querys.subType, querys.subId);
    const [model, forms] = currentFormInfo;
    formModel.value = new model() as any;
    formDefine.value = {
      ...formDefine.value,
      ...forms(formRef as any)
    };
    if (querys.id >= 0) {
      let findId = querys.id;
      if (querys.subType === 'overview') {
        const list = await VillageInfoApi.getList(
          collectStore.getCollectModuleId(querys.subType), 
          querys.subType, 
          undefined, 
          undefined, 
          querys.villageId, 
          querys.villageVolunteerId
        );
        findId = list[0].id;
      }
      formData = await VillageInfoApi.getInfo(
        collectStore.getCollectModuleId(querys.subType),
        querys.subType, 
        querys.subId,
        querys.subKey,
        querys.villageId, 
        querys.villageVolunteerId,
        findId,
        model,
      );
    }
  } catch (e) {
    console.log(e);
    if (!(e instanceof RequestApiError && e.errorMessage.startsWith('请完成')))
      showError(e, undefined, () => backPrev(false));
  } finally {
    loading.value = false;
  }
    
  try {
    formData = await loadLocalSave(formData as CommonInfoModel);
    if (formData)
      formModel.value = formData as any;
  } catch (e) {
    console.log(e);
    showError(e, '加载本地保存数据失败');
  }

  await nextTick();
  await waitTimeOut(400);
  formRef.value.initDefaultValuesToModel();

  console.log(formModel.value);
  await waitTimeOut(1000);
  canSaveNow = true;
});

async function submit() {
  if (!formRef.value)
    return;
  try {
    await formRef.value.validate();
  } catch {
    toast('有必填项未填写，请检查');
    return;
  }
  try {
    loading.value = true;
    await waitTimeOut(800);
    await VillageInfoApi.updateInfo(
      collectStore.getCollectModuleId(querys.value.subType),
      querys.value.subType,
      querys.value.subKey,
      querys.value.subId,
      querys.value.villageId,
      querys.value.villageVolunteerId,
      formModel.value as CommonInfoModel,
    );
    deleteLocalSave();
    confirm({
      content: '您的提交已成功，感谢您的参与！',
      cancelText: '继续编辑',
      confirmText: '返回列表',
      icon: 'success',
      onConfirm: () => backPrev(true),
    })
  } catch (e) {
    showError(e);
  } finally {
    loading.value = false;
  }
}
function backPrev(needRefresh: boolean) {
  backAndCallOnPageBack('list', {
    needRefresh,
  });
}

const localSavedState = ref(false);
const saveLocalSaveDebounce = new Debounce(1000, saveLocalSave);
let canSaveNow = false;

function getSaveName() {
  return `FormLocalSave-${querys.value.id}-${querys.value.subType}-${querys.value.subId}-${querys.value.villageId}-${querys.value.villageVolunteerId}`;
}
async function loadLocalSave(formData: CommonInfoModel|undefined) {
  if (!currentFormInfo)
    return formData;
  console.log('加载暂存数据');
  const saveName = getSaveName();
  const saveData = uni.getStorageSync(saveName);
  if (saveData) {
    const res = await confirm({
      content: '您有上次编辑未完成的内容，是否要从上次的编辑数据继续？',
      cancelText: '取消',
      confirmText: '继续',
      icon: 'prompt',
    })
    if (res) {
      const d = JSON.parse(saveData);
      d.id = 0;
      formData = new currentFormInfo[0]().fromServerSide(d) as CommonInfoModel;  
      console.log('有暂存数据', formData);
    } else
      deleteLocalSave();
  }
  return formData;
}
function deleteLocalSave() {
  const saveName = getSaveName();
  uni.removeStorageSync(saveName);
  localSavedState.value = false;
}
function saveLocalSave() {
  const saveName = getSaveName();
  uni.setStorageSync(saveName, JSON.stringify(formModel.value.toServerSide()));
  localSavedState.value = true;
  console.log('保存暂存数据');
}

watch(formModel, () => {
  if (!canSaveNow)
    return;
  saveLocalSaveDebounce.executeWithDelay();
}, { deep: true })
</script>
