<template>
  <!-- 表单 -->
  <FlexCol gap="gap.xl" padding="space.lg">
    <Alert
      v-if="(formModel as any).progress === -1 && !isReviewer && !isAdmin" 
      message="提示：您的信息已被审核退回，请根据审核建议修改后重新提交。"
      :description="(formModel as any).comment"
      type="warning"
      showIcon
    />
    <Result 
      v-if="loadError"
      :title="loadError"
      type="error"
    />
    <template v-else>
      <DynamicForm
        ref="formBase"
        :model="(formModel as any)" 
        :options="finalFormOptions"
      />
      <FlexCol gap="gap.md">
        <Alert type="info" message="提示：上传文件时请勿离开页面防止上传失败，离开之前请保存您的修改以防丢失。
        如果未完成编辑，可以先点击“保存”按钮保存修改，完成后再点击“提交”审核。您可以在历史版本中查看之前的修改。" />
        
        <Button type="primary" block :loading="loading" @click="handleSubmitBase(true)">
          提交
        </Button>
        <Button block @click="handleSubmitBase(false)">
          保存
        </Button>
        <Button block @click="handleShowHistory">
          历史版本
        </Button>
      </FlexCol>
    </template>

    <Popup
      v-model:show="showHistory"
      position="bottom"
      size="80vh"
      title="历史版本"
      closeable
    >
      <FlexCol v-if="showHistoryModel">
        <NavBar 
          leftButton="arrow-left-bold" 
          :title="`您正在查看 ${showHistoryModel.desc} 保存的版本`"
          @leftButtonPressed="showHistory = false" 
        />
        <ActivityIndicator v-if="showHistoryLoading" />
        <DynamicForm
          v-else
          :model="(showHistoryModel as any)" 
          :options="{
            ...formOptions,
            disabled: true,
          }"
        />
      </FlexCol>
      <CommonListBlock
        v-else
        :load="(page: number, pageSize: number) => loadHistoryData(page, pageSize)"
        :pageSize="10"
        titleKey="_title"
      >
        <template #itemRight="{ item }">
          <Button type="text" @click.stop="handleShowHistory(item)">查看</Button>
        </template>
      </CommonListBlock>
    </Popup>
  </FlexCol>
</template>

<script setup lang="ts" generic="T extends DataModel, U extends DataModel">
import { onMounted, ref, toRefs, type PropType, computed } from 'vue';
import { useAuthStore } from '@/store/auth';
import { useImageSimpleUploadCo } from '@/common/components/upload/ImageUploadCo';
import { alert, confirm, toast } from '@/components/utils/DialogAction';
import { ArrowLeftOutlined, ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { formatError, waitTimeOut } from '@imengyu/imengyu-utils';
import type { DataModel } from '@imengyu/js-request-transform';
import InheritorContent, { InheritorWorkInfo } from '@/api/collect/InheritorContent';
import FlexCol from '@/components/layout/FlexCol.vue';
import Alert from '@/components/feedback/Alert.vue';
import Popup from '@/components/dialog/Popup.vue';
import Button from '@/components/basic/Button.vue';
import DynamicForm from '@/components/dynamic/DynamicForm.vue';
import type { IDynamicFormOptions, IDynamicFormRef } from '@/components/dynamic';
import type { FormInstance } from '@/components/form/Form.vue';
import { useLoadQuerys } from '@/components/composeabe/LoadQuerys';
import { back } from '@/components/utils/PageAction';
import ActivityIndicator from '@/components/basic/ActivityIndicator.vue';
import NavBar from '@/components/nav/NavBar.vue';
import CommonListBlock from '@/pages/article/common/CommonListBlock.vue';
import type { CommonListItem } from '@/pages/article/common/CommonListPage.vue';
import Result from '@/components/feedback/Result.vue';

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
  },
  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, load } = toRefs(props);
const formBase = ref<IDynamicFormRef>();

const { querys } = useLoadQuerys({
  id: 0,
  readonly: false,
});

const authStore = useAuthStore();
const loading = ref(false);
const loadingData = ref(false);
const loadError = ref('');
const readonly = ref(false);
const showHistory = ref(false);
const showHistoryLoading = ref(false);
const showHistoryModel = ref<any>(null);
const isAdmin = computed(() => Boolean(authStore.isCollectAdmin));
const isReviewer = computed(() => Boolean(authStore.isCollectReviewer));
const finalFormOptions = computed(() => {
  
  const options: IDynamicFormOptions = {
    ...formOptions.value,
    formAdditionaProps: {
      labelFlex: 4,
      inputFlex: 8,
    },
    formItems: [
      ...formOptions.value.formItems,
      ...(props.pushExamine ? [
        {
          type: 'flat-group', label: '审核', name: 'ichInfo',
          childrenColProps: { span: 24 },
          children: [
            { 
              label: '已排版完成', name: 'typesetting', type: 'check-box-int', 
              show: { callback: (_: any, model: any) => (isAdmin.value) },
              additionalProps: {
                text: '确认',
              },
              formProps: {
                extraMessage: '编辑员专用，如果已经排版，请打勾'
              }
            },
            { 
              label: '审核人员', name: 'text1', type: 'static-text', 
              show: { callback: (_: any, model: any) => !(isAdmin.value || isReviewer.value) },
              additionalProps: {
                text: '黄念旭，李向群，卢志明',
                style: { color: '#999', }
              }
            },
            { 
              label: '填报人', name: 'text3', type: 'static-text', 
              show: { callback: (_: any, model: any) => (!isAdmin.value && !isReviewer.value) },
              additionalProps: {
                text: authStore.userInfo?.nickname,
              }
            },
            /* { 
              label: '填报人', name: 'text3', type: 'static-text', 
              show: { callback: (_: any, model: any) => (isAdmin.value || isReviewer.value) },
              additionalProps: {
                text: authStore.userInfo?.nickname,
              }
            }, */
            { 
              label: '初审状态', name: 'progress', type: 'select', 
              show: { callback: (_: any, model: any) => (isAdmin.value && !isReviewer.value) },
              additionalProps: {
                columns: [[
                  { text: '保存未审核', value: -2, disabled: true },
                  { text: '审核退回', value: -1 },
                  { text: '暂未审核', value: 0 },
                  { text: '初审通过', value: 1 },
                  { text: '专家审核通过', value: 2, disabled: true },
                ]]
              }
            },
            { 
              label: '审核状态', name: 'progress', type: 'select', 
              show: { callback: (_: any, model: any) => (isReviewer.value) },
              additionalProps: {
                columns: [[
                  { 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', 
              show: { callback: (_: any, model: any) => !(isAdmin.value || isReviewer.value) },
              disabled: true,
              additionalProps: {
                columns: [[
                  { 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',
              show: { callback: (_: any, model: any) => (isReviewer.value) },
              additionalProps: {
                upload: useImageSimpleUploadCo({}),
              }
            },
          ]
        }
      ] : [])
    ],
    formRules: {
      ...formOptions.value.formRules,
      sign: [{ required: true, message: '请审核签名' }],
    },
    disabled: readonly.value,
  }
  return options;
});

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

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

  const ref = (formBase.value?.getFormRef() as FormInstance);
  if (valid) {
    try {
      await ref.validate();
    } catch (e) {
      toast('请填写完整信息');
      loading.value = false;
      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);
    alert({
      title: '提交成功',
      content: result.message,
    });
  } catch (error) {
    alert({
      title: '提交失败',
      content: '' + error,
    });
  } finally {
    loading.value = false;
  }
}
async function loadData() {
  loadingData.value = true;
  readonly.value = querys.value.readonly;
  try {
    loadError.value = '';
    await load.value(querys.value.id ? Number(querys.value.id) : undefined);
  } catch (error) {
    console.log(error);
    loadError.value = formatError(error);
    toast('加载失败 ' + error);
  } finally {
    loadingData.value = false;
  }
}
async function loadHistoryData(page: number, pageSize: number) {
  const contentId = Number(querys.value.id || formModel.value.contentId)
  if (isNaN(contentId))
    return {
      page,
      total: 0,
      list: []
    };
  const res = (await InheritorContent.getCollectList(props.model, {
    contentId,
    collectType: 'content',
    userId: authStore.userInfo?.id,
    page,
    pageSize
  }))
  return {
    page,
    total: res.total,
    list: res.data.map((p) => {
      p._title = p.nickname ? `提交人：${p.nickname}` : p.title;
      p.desc = `提交时间：${p.updatedAt}`;
      return p as unknown as CommonListItem;
    }),
  };
}

async function handleShowHistory(item: any) {
  showHistoryLoading.value = true;
  showHistory.value = true;
  await waitTimeOut(100);
  showHistoryModel.value = item;
  showHistoryLoading.value = false;
}

function handleBack() {
  confirm({
    title: '确定返回吗？',
    content: '返回后将丢失当未提交的信息，若有修改请先提交哦！',
  }).then((res) => {
    if (res) {
      back();
    }
  });
}

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

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

