<template>
  <!-- 表单 -->
  <div class="about main-background main-background-type0">
    <div class="nav-placeholder"></div>
    <!-- 表单 -->
    <section class="main-section small-h">
      <div class="content">
        <div class="title left-right small">
          <a-button :icon="h(ArrowLeftOutlined)" @click="handleBack">返回主页</a-button>
          <h2>{{ title }}</h2>
          <div class="button-placeholder"></div>
        </div>
        <a-spin v-if="loadingData" class="w-100 h-100" />
        <template v-else>   
          <a-tabs centered>
            <a-tab-pane key="1" :tab="basicTabText">
              <ScrollRect scroll="vertical" style="height: 70vh">
                <DynamicForm
                  ref="formBase"
                  :model="(formModel as any)" 
                  :options="formOptions"
                />
              </ScrollRect>
              <div class="d-flex flex-column mt-3">
                <div class="d-flex flex-row w-100 align-items-center justify-content-between">
                  <span>
                    <ExclamationCircleOutlined class="me-3" />
                    提示：上传文件时请勿离开页面防止上传失败，在关闭页面之前请提交您的修改以防丢失。
                  </span>
                  <a-button size="small" type="primary" @click="showHistory = true">历史版本</a-button>
                </div>
                <a-button 
                  type="primary"
                  block 
                  :loading="loading" class="mt-3" 
                  @click="handleSubmitBase"
                >
                  提交
                </a-button>
              </div>
            </a-tab-pane>
            <a-tab-pane v-if="extendFormOptions" key="2" tab="扩展信息">
              <DynamicForm
                ref="formExtend"
                :model="(extendFormModel as any)" 
                :options="extendFormOptions"
              />
              <a-button 
                type="primary"
                block 
                :loading="loading" class="mt-3" 
                @click="handleSubmitExtend"
              >
                提交
              </a-button>
            </a-tab-pane>
          </a-tabs>
        </template>
      </div>
    </section>

    <a-drawer
      v-model:open="showHistory"
      title="历史版本"
      placement="right"
      :width="showHistoryModel ? '90%' : '50%'"
    >
      <div v-if="showHistoryModel">
        <div class="d-flex flex-row justify-content-between">
          <a-button :icon="h(ArrowLeftOutlined)" @click="showHistoryModel = null">返回</a-button>
          <span>您正在查看 {{ showHistoryModel.desc }} 保存的版本</span>
        </div>
        <a-spin v-if="showHistoryLoading" class="w-100 h-100" />
        <DynamicForm
          v-else
          :model="(showHistoryModel as any)" 
          :options="{
            ...formOptions,
            disabled: true,
          }"
        />
      </div>
      <CommonListBlock 
        v-else
        :showTotal="true"
        :showSearch="false"
        :rowCount="1"
        :rowType="6"
        :load="(page: number, pageSize: number, _, searchText: string, dropDownValues: number[]) => loadHistoryData(page, pageSize, dropDownValues, searchText)"
        detailsPage="none"
      >
        <template #itemRight="{ item }">
          <a-button type="link" @click.stop="handleShowHistory(item)">查看</a-button>
        </template>
      </CommonListBlock>
    </a-drawer>
  </div>
</template>

<script setup lang="ts" generic="T extends DataModel, U extends DataModel">
import { onMounted, ref, toRefs, type PropType, h, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useWindowOnUnLoadConfirm } from '@/composeable/WindowOnUnLoad';
import { DynamicForm, type IDynamicFormOptions, type IDynamicFormRef } from '@imengyu/vue-dynamic-form';
import { message, Modal, type FormInstance } from 'ant-design-vue';
import { ArrowLeftOutlined, ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { ScrollRect } from '@imengyu/vue-scroll-rect';
import { useAuthStore } from '@/stores/auth';
import type { DataModel } from '@imengyu/js-request-transform';
import InheritorContent from '@/api/inheritor/InheritorContent';
import CommonListBlock from '@/components/content/CommonListBlock.vue';
import { DateUtils, waitTimeOut } from '@imengyu/imengyu-utils';

const props = defineProps({
  title: {
    type: String,
    default: '非遗数字化资源信息校对'
  },
  basicTabText: {
    type: String,
    default: '基础信息'
  },
  formModel: {
    type: Object as PropType<T>,
    required: true
  },
  formOptions: {
    type: Object as PropType<IDynamicFormOptions>,
    required: true
  },
  extendFormModel: {
    type: Object as PropType<U>,
    default: null
  },
  extendFormOptions: {
    type: Object as PropType<IDynamicFormOptions>,
    default: null
  },
  model: {
    type: Object as PropType<new () => DataModel>,
    required: true
  },
  load: {
    type: Function as PropType<(id: number|undefined) => Promise<void>>,
    default: () => Promise.resolve()
  },
  save: {
    type: Function as PropType<(model: T) => Promise<void>>,
    default: () => Promise.resolve()
  },
  saveExtend: {
    type: Function as PropType<(model: U) => Promise<void>>,
    default: () => Promise.resolve()
  },
})

const { formModel, formOptions, extendFormOptions, load } = toRefs(props);
const formBase = ref<IDynamicFormRef>();
const formExtend = ref<IDynamicFormRef>();

const authStore = useAuthStore();
const router = useRouter();
const route = useRoute();
const loading = ref(false);
const loadingData = ref(false);
const readonly = ref(false);
const showHistory = ref(false);
const showHistoryLoading = ref(false);
const showHistoryModel = ref<any>(null);

watch(readonly, (newValue) => {
  formOptions.value.disabled = newValue;
  extendFormOptions.value.disabled = newValue;
})

useWindowOnUnLoadConfirm();

async function handleSubmitBase() {
  loading.value = true;

  const ref = (formBase.value?.getFormRef() as FormInstance);
  try {
    await ref.validate();
  } catch (e) {
    message.warn('请填写完整信息');
    loading.value = false;
    if ((e as any).errorFields)
      ref.scrollToField((e as any).errorFields[0].name, { block: 'center' })
    return;
  }
  try {
    const result = await InheritorContent.saveBaseInfo(formModel.value);
    await props.save(formModel.value);
    Modal.success({
      title: '提交成功',
      content: result.message,
      onOk() {
        router.back();
      },
    });
  } catch (error) {
    Modal.error({
      title: '提交失败',
      content: '' + error,
    });
  } finally {
    loading.value = false;
  }
}
async function handleSubmitExtend() {
  loading.value = true;

  const ref = (formExtend.value?.getFormRef() as FormInstance);
  try {
    await ref.validate();
  } catch (e) {
    message.warn('请填写完整信息');
    loading.value = false;
    if ((e as any).errorFields)
      ref.scrollToField((e as any).errorFields[0].name, { block: 'center' })
    return;
  }
  try {
    const result = await InheritorContent.saveExpandInfo(formModel.value);
    await props.save(formModel.value);
    Modal.success({
      title: '提交成功',
      content: result.message,
      onOk() {
        router.back();
      },
    });
  } catch (error) {
    Modal.error({
      title: '提交失败',
      content: '' + error,
    });
  } finally {
    loading.value = false;
  }
}

async function loadData() {
  loadingData.value = true;
  readonly.value = Boolean(route.query.readonly);
  try {
    await load.value(route.query.id ? Number(route.query.id) : undefined);
  } catch (error) {
    console.log(error);
    message.error('加载失败 ' + error);
  } finally {
    loadingData.value = false;
  }
}
async function loadHistoryData(page: number, pageSize: number, dropDownValues: number[], searchText: string) {
  const res = (await InheritorContent.getCollectList(props.model, {
    contentId: Number(route.query.id || formModel.value.contentId),
    collectType: 'content',
    modelId: 2,
    userId: authStore.userInfo?.id,
    page,
    pageSize
  }))
  return {
    page,
    total: res.total,
    data: res.data.map((p) => {
      p.title = `提交人：${p.nickname}`;
      p.desc = `提交时间：${p.updatedAt}`;
      return p;
    }),
  };
}

async function handleShowHistory(item: any) {
  showHistoryLoading.value = true;
  showHistory.value = true;
  await waitTimeOut(100);
   // showHistoryModel.value = await InheritorContent.getCollectListInfo(props.model, item.id);
  showHistoryModel.value = item;
  showHistoryLoading.value = false;
}

function handleBack() {
  Modal.confirm({
    title: '确定返回吗？',
    content: '返回后将丢失当未提交的信息，若有修改请先提交哦！',
    okText: '确定',
    okType: 'danger',
    onOk() {
      router.back();
    },
  });
}

onMounted(async () => {
  await loadData();
})

defineExpose({
  getFormRef() {
    return formBase.value;
  },
  getExtraFormRef() {
    return formExtend.value;
  },
})
</script>

