<template>
  <!-- 管理员管理首页 -->
  <div class="about main-background main-background-type0">
    <div v-if="!isInMiniProgram" class="nav-placeholder">
    </div>
    <!-- 表单 -->
    <section class="main-section large">
      <div class="content">
        <div v-if="!isInMiniProgram" class="title">
          <h2>管理员管理</h2>
        </div>
       
        <a-tabs v-model:activeKey="activeKey" centered>
          <template #renderTabBar="{ DefaultTabBar, ...props }">
            <component v-if="!isInMiniProgram" :is="DefaultTabBar" v-bind="props" />
          </template>
          <a-tab-pane key="1" tab="传承人列表">
            <CommonListBlock 
              ref="listRef"
              :showTotal="true"
              :rowCount="1"
              :rowType="5"
              :dropDownNames="[
                {
                  options: categoryData.content.value ?? [],
                  label: '分类',
                  defaultSelectedValue: lastValueCategory,
                },
                {
                  options: computedCategoryOptions,
                  label: '状态',
                  defaultSelectedValue: lastValueStatus,
                },
                {
                  options: typesettingData,
                  label: '排版',
                  defaultSelectedValue: 0,  
                },
                {
                  options: selfAssessmentLevelOptions,
                  label: '等级',
                  defaultSelectedValue: lastAgreementLevel,
                },
              ]"
              :load="(page: number, pageSize: number, _, searchText: string, dropDownValues: number[]) => loadInheritorData(page, pageSize, dropDownValues, searchText)"  
              :showDetail="(item) => router.push({ name: 'FormInheritor', query: { id: item.id } })"
            >
              <template #itemRight="{ item }">
                <AdminItemState :item="item" />
                <a-button type="link">编辑/审核</a-button>
                <a-button v-if="!authStore.isReviewer" type="link" @click.stop="handleCopyAccount(item)">传承人账号</a-button>
              </template>
            </CommonListBlock>
          </a-tab-pane>
          <a-tab-pane key="2" tab="非遗项目列表">
            <CommonListBlock 
              ref="listRef"
              :showTotal="true"
              :rowCount="1"
              :rowType="5"
              :dropDownNames="[
                {
                  options: categoryData.content.value ?? [],
                  label: '分类',
                  defaultSelectedValue: lastValueCategory,
                },
                {
                  options: computedCategoryOptions,
                  label: '状态',
                  defaultSelectedValue: lastValueStatus,  
                },
                {
                  options: typesettingData,
                  label: '排版',
                  defaultSelectedValue: 0,  
                },
                {
                  options: selfAssessmentLevelOptions,
                  label: '等级',
                  defaultSelectedValue: lastAgreementLevel,
                },
              ]"
              :load="(page: number, pageSize: number, _, searchText: string, dropDownValues: number[]) => loadIchData(page, pageSize, dropDownValues, searchText)"
              :showDetail="(item) => router.push({ name: 'FormIch', query: { id: item.id } })"
              >
              <template #itemRight="{ item }">
                <AdminItemState :item="item" />
                <a-button type="link" @click.stop="router.push({ name: 'FormIch', query: { id: item.id } })">编辑/审核</a-button>
                <a-button type="link" @click.stop="handleGoWorks(item)">非遗项目作品</a-button>
                <a-button type="link" @click.stop="handleGoSeminar(item)">添加/修改传习所</a-button>
              </template>
            </CommonListBlock>
          </a-tab-pane>
          <a-tab-pane key="3" tab="传习所列表">
            <div v-if="false" class="flex justify-end">
              <a-button type="primary" @click="router.push({ name: 'FormSeminar' })">+ 新增</a-button>
            </div>

            <CommonListBlock 
              ref="listRef"
              :showTotal="true"
              :rowCount="1"
              :rowType="5"
              :load="(page: number, pageSize: number, _, searchText: string, dropDownValues: number[]) => loadSeminarData(page, pageSize, dropDownValues, searchText)"
              :showDetail="(item) => router.push({ name: 'FormSeminar', query: { id: item.id } })"
            >
              <template #itemRight="{ item }">
                <a-button type="link" @click.stop="router.push({ name: 'FormSeminar', query: { id: item.id } })">编辑</a-button>
              </template>
              <template #headLeft>
                <InfoCircleOutlined />
                请在非遗项目列表中添加传习所
              </template>
            </CommonListBlock>
          </a-tab-pane>
          <!-- <a-tab-pane key="5" tab="老字号">
            <a-empty description="暂无数据" />
          </a-tab-pane>
          <a-tab-pane key="6" tab="传统村落">
            <a-empty description="暂无数据" />
          </a-tab-pane>
          <a-tab-pane key="7" tab="区级非遗传承人">
            <a-empty description="暂无数据" />
          </a-tab-pane> -->
          <a-tab-pane key="9" tab="传承协议签署">
            <CommonListBlock
              ref="listRef"
              :show-total="true"
              :row-count="1"
              :row-type="5"
              :page-size="10"
              :drop-down-names="[
                {
                  options: agreementProgressOptions,
                  label: '状态',
                  defaultSelectedValue: lastAgreementProgress,
                },
                {
                  options: selfAssessmentLevelOptions,
                  label: '等级',
                  defaultSelectedValue: lastAgreementLevel,
                },
              ]"
              :load="(page: number, pageSize: number, _tag: number, searchText: string, drop: number[]) => loadAgreementSignAdminList(page, pageSize, searchText, drop)"
              :show-detail="(item) => router.push({ name: 'CollectAgreementSign', query: { id: item.agreementId && item.agreementId > 0 ? item.agreementId : 0, userId: item.userId ?? 0 } })"
            >
              <template #itemRight="{ item }">
                <span class="mr-3 text-sm text-gray-600">{{ agreementProgressLabel(item.progress) }}</span>
                <a-button type="link" @click.stop="router.push({ name: 'CollectAgreementSign', query: { id: item.agreementId && item.agreementId > 0 ? item.agreementId : 0, userId: item.userId ?? 0 } })">编辑</a-button>
              </template>
            </CommonListBlock>
          </a-tab-pane>
          <a-tab-pane key="8" tab="自查评估表">
            <EvaluationFormList ref="listRef" />
          </a-tab-pane>
          <a-tab-pane v-if="false" key="4" tab="重点区域">
            <div class="flex justify-end">
              <a-button type="primary" :disabled="true" @click="router.push({ name: 'FormWork' })">+ 新增</a-button>
            </div>
            <CommonListBlock 
              ref="listRef"
              :showTotal="true"
              :rowCount="1"
              :rowType="5"
              :dropDownNames="[{
                options: categoryData.content.value ?? [],
                label: '分类',
                defaultSelectedValue: 0,
              }]"
              :load="(page: number, pageSize: number, _, searchText: string, dropDownValues: number[]) => loadAreaData(page, pageSize, dropDownValues, searchText)"
              :showDetail="(item) => router.push({ name: 'FormIch', query: { id: item.id } })"
              >
              <template #itemRight="{ item }">
                <AdminItemState :item="item" />
                <a-button type="link" @click.stop="router.push({ name: 'FormIch', query: { id: item.id } })">编辑</a-button>
                <a-button type="link" @click.stop="handleGoWorks(item)">非遗项目作品</a-button>
              </template>
            </CommonListBlock>
          </a-tab-pane>
        </a-tabs>
      </div>
    </section>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useAuthStore } from '@/stores/auth';
import { message, Modal } from 'ant-design-vue';
import type { GetContentListItem } from '@/api/CommonContent';
import useClipboard from 'vue-clipboard3';
import CommonContent, { GetContentListParams } from '@/api/CommonContent';
import CommonListBlock, { type DropdownCommonItem } from '@/components/content/CommonListBlock.vue';
import InheritorContent from '@/api/inheritor/InheritorContent';
import AssessmentContentApi from '@/api/collect/AssessmentContent';
import AdminItemState from './components/AdminItemState.vue';
import EvaluationFormList from './collect/assessment/evaluation-form-list.vue';
import { InfoCircleOutlined } from '@ant-design/icons-vue';
import { useSimpleDataLoader } from '@/composeables/useSimpleDataLoader';
import { useMemorizeVar } from '@/composeables/useMemorizeVar';
import { isInMiniProgram } from '@/composeables/MiniProgramIng.ts';

const { toClipboard } = useClipboard();
const router = useRouter();
const route = useRoute();
const authStore = useAuthStore();
const activeKey = ref(route.query.tab as string || '1');
const inheritorData = ref<GetContentListItem[]>([]);
const listRef = ref<any>(null);

onMounted(() => {
  switch (activeKey.value) {
    case '1': document.title = '传承人管理'; break;
    case '3': document.title = '传习所管理'; break;
    case '5': document.title = '老字号管理'; break;
    case '9': document.title = '传承协议签署'; break;
    case '8': document.title = '自查评估表'; break;
  }
});

watch(() => authStore.userId, (newV) => {
  if (newV) {
    setTimeout(() => {
      listRef.value?.reload();
    }, 1000);
  }
});

const { variable: lastValueCategory } = useMemorizeVar('categoryLastSelectValue', 0);
const { variable: lastValueStatus } = useMemorizeVar('statusLastSelectValue', -10);
const { variable: lastAgreementProgress } = useMemorizeVar('adminUserAgreementProgress', -100);
const { variable: lastAgreementLevel } = useMemorizeVar('adminUserAgreementLevel', 0);

const selfAssessmentLevelOptions: DropdownCommonItem[] = [
  { id: 0, name: '全部等级' },
  { id: 23, name: '国家级' },
  { id: 24, name: '省级' },
  { id: 25, name: '市级' },
];

/** 传承人传承协议列表：进度筛选（与 ich/check/getUserAgreement 一致） */
const agreementProgressOptions: DropdownCommonItem[] = [
  { id: -100, name: '全部状态' },
  { id: -1, name: '未提交' },
  { id: 0, name: '草稿' },
  { id: 1, name: '已提交审核' },
  { id: 2, name: '审核完成' },
];

function agreementProgressLabel(progress: number | null | undefined) {
  if (progress === null || progress === undefined)
    return '未填写';
  const hit = agreementProgressOptions.find((o) => o.id === progress);
  return hit?.name ?? `进度 ${progress}`;
}

const computedCategoryOptions = computed<DropdownCommonItem[]>(() => {
  if (authStore.isReviewer) {
    return [
      { name: '全部状态', id: -10 },
      { name: '待审核', id: 1 },
      { name: '已通过', id: 2 },
    ]
  }
  if (authStore.isAdmin) {
    return [
      { name: '全部状态', id: -10 },
      { name: '保存未审核', id: -2 },
      { name: '审核退回', id: -1 },
      { name: '待初审', id: 0 },
      { name: '初审通过待专家审核', id: 1 },
      { name: '专家审核通过', id: 2 },
    ]
  }
  return [];
})
const typesettingData = [
  {
    id: -1,
    name: '全部',
  },
  {
    id: 0,
    name: '未排版',
  },
  {
    id: 1,
    name: '已排版',
  },
];

watch(activeKey, (newValue) => {
  router.replace({ query: { tab: newValue } });
})

const categoryData = useSimpleDataLoader(async () => {
  const arr = (await CommonContent.getCategoryList(4)).map((item) => ({
    id: item.id,
    name: item.title,
  }));
  arr.unshift({
    id: 0,
    name: '全部',
  });
  return arr;
})

async function loadInheritorData(page: number, pageSize: number, dropDownValues: number[], searchText: string) {
  lastValueCategory.value = dropDownValues[0];
  lastValueStatus.value = dropDownValues[1];
  const submitList = await InheritorContent.getInheritorSubmtList(7);
  const res = await CommonContent.getContentList(
    new GetContentListParams()
      .setModelId(7)
      .setMainBodyColumnId(38)
      .setKeywords(searchText)
      .setSelfValues({
        ichType: dropDownValues[0] == 0 ? undefined: dropDownValues[0],
        progress: dropDownValues[1] <= -5 ? undefined: dropDownValues[1],
        typesetting: dropDownValues[2] < 0 ? undefined: dropDownValues[2],
        level: dropDownValues[3] <= 0 ? undefined: dropDownValues[3],
        region: authStore.userInfo?.regionId,
      }), 
    page,
    pageSize
  );
  return {
    page,
    total: res.total,
    data: res.list.map((item) => {
      const submitInfo = submitList.find((item2) => item2.id == item.id);
      return {
        ...item,
        desc: `${item.ichName} ${item.levelText} ${item.batchText}`,
        hasSubmit: Boolean(submitInfo),
        ...submitInfo,
      }
    }),
  }
}
async function loadIchData(page: number, pageSize: number, dropDownValues: number[], searchText: string) {
  lastValueCategory.value = dropDownValues[0];
  lastValueStatus.value = dropDownValues[1];
  const submitList = await InheritorContent.getInheritorSubmtList(2);
  const res = await CommonContent.getContentList(
    new GetContentListParams()
      .setModelId(2)
      .setKeywords(searchText)
      .setSelfValues({
        ichType: dropDownValues[0] == 0 ? undefined: dropDownValues[0],
        progress: dropDownValues[1] <= -5 ? undefined: dropDownValues[1],
        typesetting: dropDownValues[2] < 0 ? undefined: dropDownValues[2],
        level: dropDownValues[3] <= 0 ? undefined: dropDownValues[3],
        region: authStore.userInfo?.regionId,
      }), 
    page,
    pageSize
  );
  return {
    page,
    total: res.total,
    data: res.list.map((item) => {
      const submitInfo = submitList.find((item2) => item2.id == item.id);
      return {
        ...item,
        desc: `${item.ichTypeText} - ${item.levelText} ${item.batchText}`,
        hasSubmit: Boolean(submitInfo),
        ...submitInfo,
      }
    }),
  }
}
async function loadSeminarData(page: number, pageSize: number, dropDownValues: number[], searchText: string) {
  if (page === 1) {
    const res = await InheritorContent.getIchSeminarInfo({
      ichId: undefined,
      keywords: searchText,
    });
    return {
      page,
      total: pageSize,
      data: res.map((item) => ({
        ...item,
        desc: item.address,
      })),
    }
  }
  return {
    page,
    total: 0,
    data: [],
  }
}
async function loadAreaData(page: number, pageSize: number, dropDownValues: number[], searchText: string) {
  return {
    page,
    total: 0,
    data: [],
  }
}

/** 管理员：传承人传承协议分页（ich/check/getUserAgreement） */
async function loadAgreementSignAdminList(page: number, pageSize: number, searchText: string, dropDownValues: number[]) {
  const pv = dropDownValues?.[0];
  const lv = dropDownValues?.[1];
  lastAgreementProgress.value = pv ?? -100;
  lastAgreementLevel.value = lv ?? 0;
  const progress = pv != null && pv > -50 ? pv : undefined;
  const level = lv != null && lv > 0 ? lv : undefined;
  const list = await AssessmentContentApi.getUserAgreementList({
    year: new Date().getFullYear(),
    page,
    pageSize,
    keywords: searchText?.trim() || undefined,
    progress,
    level,
  });
  console.log(list);
  
  return {
    page,
    total: list.total,
    data: list.data.map((row) => ({
      ...row,
      id: row.id,
      agreementId: row.agreementId,
      userId: row.userId,
      title: row.title,
      desc: [row.mobile, row.unit, row.ichTitle].filter(Boolean).join(' · ') || '—',
    })),
  };
}

async function handleCopyAccount(item: GetContentListItem) {
  let result;
  try {
    result = await InheritorContent.getInheritorAccountInfo(item.id);
    if (!result)
      throw '该传承人没有账号';
  } catch (e) {
    Modal.error({
      title: '获取账号失败',
      content: '' + e,
    });
    return;
  }

  const resultString = `传承人${item.title}的账号：\n用户名：${result.username}\n密码：${result.password}\n登录网址：https://zycj.wenlvti.net/#login`;

  try {
    await toClipboard(resultString);
    message.success('复制到剪贴板成功');
  } catch (e) {
    Modal.error({
      title: '复制失败',
      content: '复制到剪贴板失败，可能是浏览器不支持或未授权，可手动复制：' + resultString,
    });
  }

}

function handleGoSeminar(item: GetContentListItem) {
  router.push({ name: 'AdminSeminar', query: { 
    ichId: item.id,
  } })
}
function handleGoWorks(item: GetContentListItem) {
  router.push({ name: 'AdminWorks', query: { 
    ichId: item.id,
  } })
}
</script>