<template>
  <CommonRoot>
    <FlexCol padding="space.lg">
      <SimplePageContentLoader :loader="loader">
        <template v-if="loader.isFinished.value">
          <Result
            v-if="!currentForm"
            status="warning"
            title="无法加载评估表"
            description="请从自查评估表列表进入，并确认参数正确。"
          />
          <FlexCol v-else gap="gap.lg">
            <Alert type="info" :message="progressHint" />
            <SelfAssessmentFormDisplay
              :current-form="(currentForm as SelfAssessmentDetail)"
              :form-options="formOptions"
              :form-options-end="formOptionsEnd"
              :check-item-list="(checkItemList as CheckItemInfo[])"
              :current-form-check-items="(currentFormCheckItems as SelfAssessmentCheckItemAnswer[])"
              :readonly="true"
            />
            <Divider />
            <H3>审核提交</H3>
            <Alert
              v-if="!canSubmitReview"
              type="warning"
              message="当前账号用户组无权在此环节审核"
              description="仅项目保护单位(9)、县（区）文旅部门(5)、设区市文旅部门/省非遗中心(10)、省文化和旅游厅(11) 可提交。"
            />
            <FlexCol gap="gap.md">
              <Text bold :text="`审核环节：${reviewLevelLabel}`" />
              <Text fontConfig="subText" text="审核意见（必选）" />
              <FlexRow wrap gap="gap.sm">
                <Button
                  v-for="o in opinionSelectOptions"
                  :key="o.value"
                  :type="reviewOpinion === o.value ? 'primary' : 'default'"
                  size="small"
                  @click="reviewOpinion = o.value"
                >
                  {{ o.label }}
                </Button>
              </FlexRow>
              <Text fontConfig="subText" text="评分（可选，0–100）" />
              <Stepper
                :min="0"
                :max="100"
                :step="1"
                :model-value="reviewPoints ?? 0"
                @update:model-value="reviewPoints = $event"
              />
              <Text fontConfig="subText" text="提交后进度" />
              <Text :text="progressSubmitLabel" />
              <Button
                type="primary"
                block
                :loading="submitLoading"
                :touchable="canSubmitReview"
                @click="submitReview"
              >
                提交审核
              </Button>
              <Button
                type="danger"
                block
                :loading="rejectLoading"
                :touchable="canSubmitReview"
                @click="submitReject"
              >
                回退
              </Button>
            </FlexCol>
          </FlexCol>
        </template>
      </SimplePageContentLoader>
      <XBarSpace />
    </FlexCol>
  </CommonRoot>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { useSimpleDataLoader } from '@/components/composeabe/loader/SimpleDataLoader';
import { formatError, waitTimeOut } from '@imengyu/imengyu-utils';
import { toast, alert } from '@/components/dialog/CommonRoot';
import AssessmentContentApi, {
  type CheckItemInfo,
  type SelfAssessmentCheckItemAnswer,
  SelfAssessmentDetail,
} from '@/api/collect/AssessmentContent';
import CommonRoot from '@/components/dialog/CommonRoot.vue';
import FlexCol from '@/components/layout/FlexCol.vue';
import SimplePageContentLoader from '@/components/loader/SimplePageContentLoader.vue';
import Result from '@/components/feedback/Result.vue';
import SelfAssessmentFormDisplay from './components/SelfAssessmentFormDisplay.vue';
import { buildSelfAssessmentFormOptions } from './evaluationFormOptions';
import { useImageSimpleUploadCo } from '@/common/components/upload/ImageUploadCo';
import Divider from '@/components/display/Divider.vue';
import H3 from '@/components/typography/H3.vue';
import Text from '@/components/basic/Text.vue';
import Button from '@/components/basic/Button.vue';
import FlexRow from '@/components/layout/FlexRow.vue';
import Stepper from '@/components/form/Stepper.vue';
import Alert from '@/components/feedback/Alert.vue';
import XBarSpace from '@/components/layout/space/XBarSpace.vue';
import { useLoadQuerys } from '@/components/composeabe/LoadQuerys';
import { useAuthStore } from '@/store/auth';

const signUploadCo = useImageSimpleUploadCo();
const formOptions = buildSelfAssessmentFormOptions(signUploadCo, 'start');
const formOptionsEnd = buildSelfAssessmentFormOptions(signUploadCo, 'end');

const authStore = useAuthStore();
const currentUserGroups = computed(() => authStore.userInfo?.adminGroup || []);

const currentForm = ref<SelfAssessmentDetail | null>(null);
const currentFormCheckItems = ref<SelfAssessmentCheckItemAnswer[]>([]);
const checkItemList = ref<CheckItemInfo[]>([]);

const submitLoading = ref(false);
const rejectLoading = ref(false);
const reviewOpinion = ref<number | null>(null);
const reviewPoints = ref<number | null>(null);

/** 用户组 → 本环节提交后的 progress */
const GROUP_TO_REVIEW_PROGRESS: Record<number, number> = {
  9: 2, // 项目保护单位
  5: 3, // 县（区）文旅部门
  10: 4, // 设区市文旅部门、省非遗中心
  11: 5, // 省文化和旅游厅
};

const PROGRESS_SUBMIT_LABELS: Record<number, string> = {
  2: '2 — 项目保护单位审核完成',
  3: '3 — 县（区）文旅部门审核完成',
  4: '4 — 设区市文旅部门、省非遗中心审核完成',
  5: '5 — 省文化和旅游厅审核完成',
};

const opinionSelectOptions = [
  { label: '优秀', value: 1 },
  { label: '合格', value: 2 },
  { label: '不合格', value: 3 },
  { label: '丧失传承能力', value: 4 },
  { label: '取消资格', value: 5 },
];

const reviewProgress = computed(() => {
  const currentUserGroup = currentUserGroups.value.find(
    (group) => GROUP_TO_REVIEW_PROGRESS[group.id],
  );
  return GROUP_TO_REVIEW_PROGRESS[currentUserGroup?.id ?? 0] ?? 0;
});

const canSubmitReview = computed(
  () => reviewProgress.value >= 2 && reviewProgress.value <= 5,
);

const progressSubmitLabel = computed(
  () => PROGRESS_SUBMIT_LABELS[reviewProgress.value] ?? '—',
);

const { querys } = useLoadQuerys({
  id: 0,
  userId: 0,
  progress: Number.NaN,
}, () => {
  loader.load();
});

const listProgress = computed(() => {
  const p = querys.value.progress;
  return Number.isFinite(p) ? p : Number.NaN;
});

const reviewLevelLabel = computed(() => {
  switch (reviewProgress.value) {
    case 2:
      return '项目保护单位';
    case 3:
      return '县（区）文旅部门';
    case 4:
      return '设区市文旅部门、省非遗中心';
    case 5:
      return '省文化和旅游厅';
    default:
      return '';
  }
});

const progressHint = computed(() => {
  const roleText = canSubmitReview.value
    ? `当前账号审核环节：${reviewLevelLabel.value}`
    : `当前用户组 ${currentUserGroups.value.map((group) => group.name).join('、') || '—'} 无对应审核环节`;
  return `${roleText}。`;
});

const currentYear = new Date().getFullYear();

function levelTitleFromForm(f: SelfAssessmentDetail) {
  if (f.level === 23) return '国家级';
  if (f.level === 24) return '省级';
  if (f.level === 25) return '市级';
  return '国家级';
}

function loadEditorContent(f: SelfAssessmentDetail) {
  if (typeof f.content !== 'object' || f.content === null)
    f.content = {};
  f.content.title = `传承人填写${currentYear}年1月1日至${currentYear}年12月31日${levelTitleFromForm(f)}非遗传承人义务履行和传承补助经费使用情况等，不超过1000字，如未履行职责请进行说明。参考提纲如下:`;
  for (let i = 0; i < 8; i++) {
    if (typeof f.content[`item${i}`] !== 'string')
      f.content[`item${i}`] = '';
  }
}

async function loadCheckItems(f: SelfAssessmentDetail) {
  const { top } = await AssessmentContentApi.getCheckItems(Number(f.level));
  checkItemList.value = top;
  currentFormCheckItems.value = [...f.checkItems] as SelfAssessmentCheckItemAnswer[];
}

function applyPrefillFromDetail(f: SelfAssessmentDetail) {
  const t = reviewProgress.value;
  if (!canSubmitReview.value)
    return;
  if (t === 2) {
    reviewOpinion.value = f.ichUnit ?? null;
    reviewPoints.value = f.unitPoints || null;
  } else if (t === 3) {
    reviewOpinion.value = f.county ?? null;
    reviewPoints.value = f.countyPoints || null;
  } else if (t === 4) {
    reviewOpinion.value = f.district ?? null;
    reviewPoints.value = f.districtPoints || null;
  } else if (t === 5) {
    reviewOpinion.value = f.province ?? null;
    reviewPoints.value = f.provincePoints || null;
  }
}

const loader = useSimpleDataLoader(async () => {
  const id = querys.value.id;
  const uid = querys.value.userId;
  if (!id || !uid) {
    currentForm.value = null;
    return null;
  }
  const detail = await AssessmentContentApi.getSelfAssessmentDetail(id, uid);
  await waitTimeOut(200);
  currentForm.value = detail;
  loadEditorContent(detail);
  await waitTimeOut(200);
  await loadCheckItems(detail);
  await waitTimeOut(200);
  applyPrefillFromDetail(detail);
  await waitTimeOut(200);
  return detail;
}, false);

watch(reviewProgress, () => {
  const f = currentForm.value;
  if (f)
    applyPrefillFromDetail(f as SelfAssessmentDetail);
});

/** 回退后 progress：退回至上一环节 */
const rejectTargetProgress = computed(() => Math.max(1, reviewProgress.value - 1));

function promptRejectReason() {
  return new Promise<string | null>((resolve) => {
    uni.showModal({
      title: '回退自查评估表',
      editable: true,
      placeholderText: '请输入回退原因（必填）',
      content: '',
      confirmText: '确认回退',
      cancelText: '取消',
      success: (res) => {
        if (!res.confirm) {
          resolve(null);
          return;
        }
        const reason = (res.content ?? '').trim();
        if (!reason) {
          toast('请输入回退原因');
          resolve(null);
          return;
        }
        resolve(reason);
      },
      fail: () => resolve(null),
    });
  });
}

async function submitReject() {
  const f = currentForm.value;
  if (!f?.id) {
    toast('缺少自查表 ID');
    return;
  }
  if (!canSubmitReview.value) {
    toast('当前账号用户组无权回退');
    return;
  }
  const rejectReason = await promptRejectReason();
  if (rejectReason === null)
    return;
  const t = reviewProgress.value;
  rejectLoading.value = true;
  try {
    await AssessmentContentApi.reviewSelfAssessment({
      id: f.id,
      progress: rejectTargetProgress.value,
      rejectType: t,
      rejectReason,
    });
    toast('已回退');
    await waitTimeOut(400);
    uni.navigateBack();
  } catch (e) {
    alert({ title: '回退失败', content: formatError(e) });
  } finally {
    rejectLoading.value = false;
  }
}

async function submitReview() {
  const f = currentForm.value;
  if (!f?.id) {
    toast('缺少自查表 ID');
    return;
  }
  if (!canSubmitReview.value) {
    toast('当前账号用户组无权提交审核');
    return;
  }
  if (reviewOpinion.value == null) {
    toast('请选择审核意见');
    return;
  }
  const t = reviewProgress.value;
  const base = { id: f.id, progress: t };
  const points = reviewPoints.value != null && reviewPoints.value >= 0 ? reviewPoints.value : undefined;
  const op = reviewOpinion.value;
  submitLoading.value = true;
  try {
    if (t === 2)
      await AssessmentContentApi.reviewSelfAssessment({ ...base, ichUnit: op, unitPoints: points });
    else if (t === 3)
      await AssessmentContentApi.reviewSelfAssessment({ ...base, county: op, countyPoints: points });
    else if (t === 4)
      await AssessmentContentApi.reviewSelfAssessment({ ...base, district: op, districtPoints: points });
    else
      await AssessmentContentApi.reviewSelfAssessment({ ...base, province: op, provincePoints: points });
    toast('审核提交成功');
    await waitTimeOut(400);
    uni.navigateBack();
  } catch (e) {
    alert({ title: '审核提交失败', content: formatError(e) });
  } finally {
    submitLoading.value = false;
  }
}
</script>
