<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-full h-full" />
        <template v-else>   
          <a-tabs centered>
            <a-tab-pane key="1" :tab="basicTabText">
              <a-alert 
                v-if="(formModel as any).progress === -1 && !isReviewer && !isAdmin" 
                message="提示：您的信息已被审核退回，请根据审核建议修改后重新提交。"
                :description="(formModel as any).comment"
                showIcon
              ></a-alert>
              <DynamicForm
                ref="formBase"
                :model="(formModel as any)" 
                :options="finalFormOptions"
              />
              <div class="flex flex-col mt-4">
                <div class="flex flex-row w-full items-center justify-between">
                  <span>
                    <ExclamationCircleOutlined class="me-2" />
                    提示：上传文件时请勿离开页面防止上传失败，离开之前请保存您的修改以防丢失。
                  </span>
                  <a-button size="small" type="primary" @click="showHistory = true">历史版本</a-button>
                </div>
                <div class="flex flex-row w-full items-center justify-end mt-4">
                  <a-popover
                    v-if="!isReviewer && !isAdmin"
                    title="保存提示"
                    content="如果未完成编辑，可以先点击保存按钮保存修改，完成后再点击提交审核。您可以在历史版本中查看之前的修改。"
                  >
                    <a-button
                      block 
                      :loading="loading"
                      class="me-4" 
                      @click="handleSubmitBase(false)"
                    >
                      保存
                    </a-button>
                  </a-popover>
                  <a-button 
                    type="primary"
                    block 
                    :loading="loading"
                    @click="handleSubmitBase(true)"
                  >
                    提交
                </a-button>
              </div>
            </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-4" 
                @click="handleSubmitExtend"
              >
                提交
              </a-button>
            </a-tab-pane>
          </a-tabs>
        </template>
      </div>
    </section>

    <a-drawer
      v-model:open="showHistory"
      title="历史版本"
      placement="right"
      :width="showHistoryModel ? (isMobile ? '100%' : '60%') : (isMobile ? '80%' : '50%')"
    >
      <div v-if="showHistoryModel">
        <div class="flex flex-row justify-between">
          <a-button :icon="h(ArrowLeftOutlined)" @click="showHistoryModel = null">返回</a-button>
          <span>您正在查看 {{ showHistoryModel.desc }} 保存的版本</span>
        </div>
        
        <div class="main-section small-h">
          <div class="content">
              <a-spin v-if="showHistoryLoading" class="w-full h-full" />
              <DynamicForm
                v-else
                :model="(showHistoryModel as any)" 
                :options="{
                  ...formOptions,
                  disabled: true,
                }"
              />
          </div>
        </div>
      </div>
      <CommonListBlock 
        v-else
        :showTotal="true"
        :showSearch="false"
        :rowCount="1"
        :rowType="6"
        titleKey="_title"
        :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, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
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 { useAuthStore } from '@/stores/auth';
import type { DataModel } from '@imengyu/js-request-transform';
import InheritorContent, { InheritorWorkInfo } from '@/api/inheritor/InheritorContent';
import CommonListBlock from '@/components/content/CommonListBlock.vue';
import { waitTimeOut } from '@imengyu/imengyu-utils';
import { useImageSimpleUploadCo } from '@/common/upload/ImageUploadCo';
import { useWindowOnUnLoadConfirm } from '@/composeables/useWindowOnUnLoadConfirm';
import { getFormErrorFieldsMessage } from '@/common/Form';

const isMobile = computed(() => {
  return window.innerWidth < 768;
});
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: Function as unknown 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<DataModel>>,
    default: (a: any) => Promise.resolve(a)
  },
  saveExtend: {
    type: Function as PropType<(model: U) => Promise<DataModel>>,
    default: (a: any) => Promise.resolve(a)
  },
  pushExamine: {
    type: Boolean,
    default: false
  },
})

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);
const isAdmin = computed(() => authStore.isAdmin);
const isReviewer = computed(() => authStore.isReviewer);
const finalFormOptions = computed(() => {
  
  return {
    ...formOptions.value,
    formItems: [
      ...formOptions.value.formItems,
      ...(props.pushExamine ? [
        {
          type: 'flat-group', label: '审核', name: 'ichInfo',
          childrenColProps: { span: 24 },
          children: [
            { 
              label: '已排版完成', name: 'typesetting', type: 'check-box-int', 
              hidden: { callback: (_: any, model: any) => !(isAdmin.value) },
              additionalProps: {
                text: '确认',
              },
              formItemProps: {
                extra: h('div', {}, [
                  h(ExclamationCircleOutlined),
                  h('span', { class: 'ms-2' }, '编辑员专用，如果已经排版，请打勾'),
                ]),
              }
            },
            { 
              label: '审核人员', name: 'text1', type: 'static-text', 
              hidden: { callback: (_: any, model: any) => isAdmin.value || isReviewer.value },
              additionalProps: {
                text: '黄念旭，李向群，卢志明',
                style: { color: '#999', }
              }
            },
            { 
              label: '填报人', name: 'text3', type: 'static-text', 
              hidden: { callback: (_: any, model: any) => !(!isAdmin.value && !isReviewer.value) },
              additionalProps: {
                text: authStore.userInfo?.nickname,
              }
            },
            /* { 
              label: '填报人', name: 'text3', type: 'static-text', 
              hidden: { callback: (_: any, model: any) => !(isAdmin.value || isReviewer.value) },
              additionalProps: {
                text: authStore.userInfo?.nickname,
              }
            }, */
            { 
              label: '初审状态', name: 'progress', type: 'select', 
              hidden: { callback: (_: any, model: any) => !(isAdmin.value && !isReviewer.value) },
              additionalProps: {
                options: [
                  { text: '保存未审核', value: -2, disabled: true },
                  { text: '审核退回', value: -1 },
                  { text: '暂未审核', value: 0 },
                  { text: '初审通过', value: 1 },
                  { text: '专家审核通过', value: 2, disabled: true },
                ]
              }
            },
            { 
              label: '审核状态', name: 'progress', type: 'select', 
              hidden: { callback: (_: any, model: any) => !(isReviewer.value) },
              additionalProps: {
                options: [
                  { text: '未审核', value: -2, disabled: true },
                  { text: '审核退回', value: -1 },
                  { text: '未审核', value: 0, disabled: true },
                  { text: '未审核', value: 1, disabled: true },
                  { text: '通过审核', value: 2 },
                ],
              }
            },
            { 
              label: '审核状态', name: 'progress', type: 'select', 
              hidden: { callback: (_: any, model: any) => isAdmin.value || isReviewer.value },
              disabled: true,
              additionalProps: {
                options: [
                  { text: '保存未审核', value: -2 },
                  { text: '审核退回', value: -1 },
                  { text: '暂未审核', value: 0 },
                  { text: '初审通过', value: 1 },
                  { text: '专家审核通过', value: 2 },
                ]
              }
            },
            { 
              label: '审核意见', name: 'comment', type: 'textarea',
              disabled: { callback: (_: any, model: any) => !isAdmin.value },
              additionalProps: {
                placeholder: { callback: (_: any, model: any) => (isAdmin.value || isReviewer.value) ? '若审核不通过，请输入审核意见' : '暂无审核意见' },
              }
            },
            {
              label: '审核签名', name: 'sign', type: 'sign',
              hidden: { callback: (_: any, model: any) => !isReviewer.value },
              additionalProps: {
                upload: useImageSimpleUploadCo({}),
              }
            },
          ]
        }
      ] : [])
    ],
    formRules: {
      ...formOptions.value.formRules,
      sign: [{ required: true, message: '请审核签名', trigger: ['blur'] }],
    },
    disabled: readonly.value,
  } as IDynamicFormOptions;
});


useWindowOnUnLoadConfirm();

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

  if (valid) {
    if (!isAdmin.value && !await new Promise((resolve, reject) => {
      Modal.confirm({
        title: '提交提示',
        content: '是否提交信息审核？填写完整信息后才可提交审核。如果需要离开，可先保存修改下次接着编辑。',
        okText: '提交',
        cancelText: '取消',
        onOk: () => resolve(true),
        onCancel: () => resolve(false),
      })
    })) {
      loading.value = false;
      return;
    }
  }

  const ref = (formBase.value?.getFormRef() as FormInstance);
  if (valid) {
    try {
      await ref.validate();
    } catch (e) {
      message.warning('请填写完整信息: ' + getFormErrorFieldsMessage(e));
      loading.value = false;
      if ((e as any).errorFields)
        ref.scrollToField((e as any).errorFields[0].name, { block: 'center' })
      return;
    }
  }
  try {

    let result = null;
    const data = await props.save(formModel.value);
    data.progress = valid ? 0 : -2;
    if (formModel.value instanceof InheritorWorkInfo)
      result = await InheritorContent.saveWorkInfo(data as InheritorWorkInfo);
    else
      result = await InheritorContent.saveBaseInfo(data);
    Modal.success({
      title: '提交成功',
      content: result.message,
      onOk() {
        router.back();
      },
      onCancel() {}
    });
  } 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.warning('请填写完整信息: ' + getFormErrorFieldsMessage(e));
    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(await props.saveExtend(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 contentId = Number(route.query.id || formModel.value.contentId)
  if (isNaN(contentId))
    return {
      page,
      total: 0,
      data: []
    };
  const res = (await InheritorContent.getCollectList(props.model, {
    contentId,
    collectType: 'content',
    userId: authStore.userInfo?.id,
    page,
    pageSize
  }))
  return {
    page,
    total: res.total,
    data: res.data.map((p) => {
      p._title = p.nickname ? `提交人：${p.nickname}` : p.title;
      p.desc = `提交时间：${p.updatedAt}`;
      return p;
    }),
  };
}

async function handleShowHistory(item: any) {
  showHistoryLoading.value = true;
  showHistory.value = true;
  await waitTimeOut(100);
  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>

