<script setup lang="tsx">
import { computed, ref } from 'vue';
import { NDivider, NTag } from 'naive-ui';
import { fetchBatchDeleteSchoolDetail, fetchGetSchoolDetailList } from '@/service/api/art/school-detail';
import { useAppStore } from '@/store/modules/app';
import { useAuth } from '@/hooks/business/auth';
import { useDownload } from '@/hooks/business/download';
import { defaultTransform, useNaivePaginatedTable, useTableOperate } from '@/hooks/common/table';
import { $t } from '@/locales';
import ButtonIcon from '@/components/custom/button-icon.vue';
import SchoolDetailOperateDrawer from './modules/school-detail-operate-drawer.vue';
import SchoolDetailSearch from './modules/school-detail-search.vue';

defineOptions({
  name: 'SchoolDetailList'
});

interface Props {
  schoolId?: CommonType.IdType | null;
  inModal?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  schoolId: null,
  inModal: false
});

const appStore = useAppStore();
const { download } = useDownload();
const { hasAuth } = useAuth();

const searchParams = ref<Api.Art.SchoolDetailSearchParams>({
  pageNum: 1,
  pageSize: 10,
  detailId: null,
  schoolId: props.schoolId,
  introduction: null,
  schoolIcon: null,
  backGround: null,
  address: null,
  contact: null,
  email: null,
  website: null,
  postcode: null,
  establishYear: null,
  campusAreaMu: null,
  libraryCollection: null,
  maleRatio: null,
  femaleRatio: null,
  is985: null,
  is211: null,
  isDoubleFirstClass: null,
  isKeyUniversity: null,
  isPublic: null,
  tags: [],
  studentCount: null,
  teacherCount: null,
  masterPoint: null,
  doctorPoint: null,
  keyMajorCount: null,
  employmentRate: null,
  satisfactionRate: null,
  univId: null,
  masterProportionRate: null,
  abroadProportionRate: null,
  hasRegular: null,
  hasJunior: null,
  hasMaster: null,
  isDoubleHighPlan: null,
  isStrongPlan: null,
  twsdlRank: null,
  xyhRank: null,
  wslRank: null,
  usdaluRank: null,
  qsdaluRank: null,
  combinedScore: null,
  overallRank: null,
  envSatisfaction: null,
  envVote: null,
  liveSatisfaction: null,
  liveVote: null,
  combinedSatisfaction: null,
  combinedVote: null,
  teachers: null,
  scholarship: null,
  grantDesc: null,
  canteen: null,
  dormitory: null,
  masterExplain: null,
  doctorExplain: null,
  params: {}
});

const requestParams = computed<Api.Art.SchoolDetailSearchParams>(() => ({
  ...searchParams.value,
  schoolId: props.schoolId ?? searchParams.value.schoolId
}));

function renderBooleanTag(value?: number | null) {
  if (value === null || value === undefined) return '-';

  return <NTag type={value === 1 ? 'success' : 'default'}>{value === 1 ? '是' : '否'}</NTag>;
}

function renderStringArray(values?: string[] | null) {
  if (!values?.length) return '-';
  return values.join(' / ');
}

const { columns, columnChecks, data, getData, getDataByPage, loading, mobilePagination, scrollX } =
  useNaivePaginatedTable({
    api: () => fetchGetSchoolDetailList(requestParams.value),
    transform: response => defaultTransform(response),
    onPaginationParamsChange: params => {
      searchParams.value.pageNum = params.page;
      searchParams.value.pageSize = params.pageSize;
    },
    columns: () => [
      {
        type: 'selection',
        align: 'center',
        width: 48
      },
      {
        key: 'index',
        title: $t('common.index'),
        align: 'center',
        width: 64,
        render: (_, index) => index + 1
      },
      {
        key: 'detailId',
        title: '主键ID',
        align: 'center',
        minWidth: 120
      },
      {
        key: 'schoolId',
        title: '关联学校主表ID',
        align: 'center',
        minWidth: 120
      },
      {
        key: 'introduction',
        title: '学校详细介绍（大文本）',
        align: 'center',
        minWidth: 120
      },
      {
        key: 'schoolIcon',
        title: '院校图标',
        align: 'center',
        minWidth: 140
      },
      {
        key: 'backGround',
        title: '学校背景图',
        align: 'center',
        minWidth: 140
      },
      {
        key: 'address',
        title: '学校地址',
        align: 'center',
        minWidth: 120
      },
      {
        key: 'contact',
        title: '联系电话',
        align: 'center',
        minWidth: 120
      },
      {
        key: 'email',
        title: '邮箱',
        align: 'center',
        minWidth: 120
      },
      {
        key: 'website',
        title: '官网地址',
        align: 'center',
        minWidth: 120
      },
      {
        key: 'postcode',
        title: '邮编',
        align: 'center',
        minWidth: 100
      },
      {
        key: 'establishYear',
        title: '建校年份',
        align: 'center',
        minWidth: 100
      },
      {
        key: 'campusAreaMu',
        title: '占地面积(亩)',
        align: 'center',
        minWidth: 120
      },
      {
        key: 'libraryCollection',
        title: '图书馆藏书量',
        align: 'center',
        minWidth: 120
      },
      {
        key: 'studentCount',
        title: '学生人数',
        align: 'center',
        minWidth: 100
      },
      {
        key: 'teacherCount',
        title: '教师人数',
        align: 'center',
        minWidth: 100
      },
      {
        key: 'employmentRate',
        title: '就业率(%)',
        align: 'center',
        minWidth: 100
      },
      {
        key: 'satisfactionRate',
        title: '满意度(%)',
        align: 'center',
        minWidth: 100
      },
      {
        key: 'is985',
        title: '985',
        align: 'center',
        minWidth: 80,
        render: row => renderBooleanTag(row.is985)
      },
      {
        key: 'is211',
        title: '211',
        align: 'center',
        minWidth: 80,
        render: row => renderBooleanTag(row.is211)
      },
      {
        key: 'isDoubleFirstClass',
        title: '双一流',
        align: 'center',
        minWidth: 90,
        render: row => renderBooleanTag(row.isDoubleFirstClass)
      },
      {
        key: 'isKeyUniversity',
        title: '重点大学',
        align: 'center',
        minWidth: 100,
        render: row => renderBooleanTag(row.isKeyUniversity)
      },
      {
        key: 'isPublic',
        title: '是否公办',
        align: 'center',
        minWidth: 100,
        render: row => renderBooleanTag(row.isPublic)
      },
      {
        key: 'tags',
        title: '详情标签',
        align: 'center',
        minWidth: 160,
        render: row => renderStringArray(row.tags)
      },
      {
        key: 'masterProportionRate',
        title: '考研率(%)',
        align: 'center',
        minWidth: 110
      },
      {
        key: 'abroadProportionRate',
        title: '出国率(%)',
        align: 'center',
        minWidth: 110
      },
      {
        key: 'hasRegular',
        title: '普通本科',
        align: 'center',
        minWidth: 100,
        render: row => renderBooleanTag(row.hasRegular)
      },
      {
        key: 'hasJunior',
        title: '专科',
        align: 'center',
        minWidth: 90,
        render: row => renderBooleanTag(row.hasJunior)
      },
      {
        key: 'hasMaster',
        title: '硕士点',
        align: 'center',
        minWidth: 90,
        render: row => renderBooleanTag(row.hasMaster)
      },
      {
        key: 'isDoubleHighPlan',
        title: '双高计划',
        align: 'center',
        minWidth: 100,
        render: row => renderBooleanTag(row.isDoubleHighPlan)
      },
      {
        key: 'isStrongPlan',
        title: '强基计划',
        align: 'center',
        minWidth: 100,
        render: row => renderBooleanTag(row.isStrongPlan)
      },
      {
        key: 'twsdlRank',
        title: '泰晤士排名',
        align: 'center',
        minWidth: 110
      },
      {
        key: 'xyhRank',
        title: '校友会排名',
        align: 'center',
        minWidth: 110
      },
      {
        key: 'wslRank',
        title: '武书连排名',
        align: 'center',
        minWidth: 110
      },
      {
        key: 'usdaluRank',
        title: 'US排名',
        align: 'center',
        minWidth: 90
      },
      {
        key: 'qsdaluRank',
        title: 'QS排名',
        align: 'center',
        minWidth: 90
      },
      {
        key: 'combinedScore',
        title: '综合评分',
        align: 'center',
        minWidth: 100
      },
      {
        key: 'overallRank',
        title: '综合排名',
        align: 'center',
        minWidth: 100
      },
      {
        key: 'envSatisfaction',
        title: '环境满意度',
        align: 'center',
        minWidth: 110
      },
      {
        key: 'envVote',
        title: '环境投票数',
        align: 'center',
        minWidth: 110
      },
      {
        key: 'liveSatisfaction',
        title: '生活满意度',
        align: 'center',
        minWidth: 110
      },
      {
        key: 'liveVote',
        title: '生活投票数',
        align: 'center',
        minWidth: 110
      },
      {
        key: 'combinedSatisfaction',
        title: '综合满意度',
        align: 'center',
        minWidth: 110
      },
      {
        key: 'combinedVote',
        title: '综合投票数',
        align: 'center',
        minWidth: 110
      },
      {
        key: 'teachers',
        title: '师资力量',
        align: 'center',
        minWidth: 140
      },
      {
        key: 'scholarship',
        title: '奖学金',
        align: 'center',
        minWidth: 140
      },
      {
        key: 'grantDesc',
        title: '助学金',
        align: 'center',
        minWidth: 140
      },
      {
        key: 'canteen',
        title: '食堂',
        align: 'center',
        minWidth: 140
      },
      {
        key: 'dormitory',
        title: '宿舍',
        align: 'center',
        minWidth: 140
      },
      {
        key: 'masterExplain',
        title: '硕士点说明',
        align: 'center',
        minWidth: 140
      },
      {
        key: 'doctorExplain',
        title: '博士点说明',
        align: 'center',
        minWidth: 140
      },
      {
        key: 'remark',
        title: '备注',
        align: 'center',
        minWidth: 120
      },
      {
        key: 'operate',
        fixed: 'right',
        title: $t('common.operate'),
        align: 'center',
        width: 130,
        render: row => {
          const divider = () => {
            if (!hasAuth('art:schoolDetail:edit') || !hasAuth('art:schoolDetail:remove')) {
              return null;
            }
            return <NDivider vertical />;
          };

          const editBtn = () => {
            if (!hasAuth('art:schoolDetail:edit')) {
              return null;
            }
            return (
              <ButtonIcon
                text
                type="primary"
                icon="material-symbols:drive-file-rename-outline-outline"
                tooltipContent={$t('common.edit')}
                onClick={() => edit(row.detailId)}
              />
            );
          };

          const deleteBtn = () => {
            if (!hasAuth('art:schoolDetail:remove')) {
              return null;
            }
            return (
              <ButtonIcon
                text
                type="error"
                icon="material-symbols:delete-outline"
                tooltipContent={$t('common.delete')}
                popconfirmContent={$t('common.confirmDelete')}
                onPositiveClick={() => handleDelete(row.detailId)}
              />
            );
          };

          return (
            <div class="flex-center gap-8px">
              {editBtn()}
              {divider()}
              {deleteBtn()}
            </div>
          );
        }
      }
    ]
  });

const { drawerVisible, operateType, editingData, handleAdd, handleEdit, checkedRowKeys, onBatchDeleted, onDeleted } =
  useTableOperate(data, 'detailId', getData);

async function handleBatchDelete() {
  // request
  const { error } = await fetchBatchDeleteSchoolDetail(checkedRowKeys.value);
  if (error) return;
  onBatchDeleted();
}

async function handleDelete(detailId: CommonType.IdType) {
  // request
  const { error } = await fetchBatchDeleteSchoolDetail([detailId]);
  if (error) return;
  onDeleted();
}

function edit(detailId: CommonType.IdType) {
  handleEdit(detailId);
}

function handleExport() {
  download('/art/schoolDetail/export', requestParams.value, `学校详细信息_${new Date().getTime()}.xlsx`);
}
</script>

<template>
  <div
    :class="
      props.inModal
        ? 'flex-col-stretch gap-16px'
        : 'min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto'
    "
  >
    <SchoolDetailSearch v-model:model="searchParams" @search="getDataByPage" />
    <NCard title="学校详细信息列表" :bordered="false" size="small" class="card-wrapper sm:flex-1-hidden">
      <template #header-extra>
        <TableHeaderOperation
          v-model:columns="columnChecks"
          :disabled-delete="checkedRowKeys.length === 0"
          :loading="loading"
          :show-add="hasAuth('art:schoolDetail:add')"
          :show-delete="hasAuth('art:schoolDetail:remove')"
          :show-export="hasAuth('art:schoolDetail:export')"
          @add="handleAdd"
          @delete="handleBatchDelete"
          @export="handleExport"
          @refresh="getData"
        />
      </template>
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        :columns="columns"
        :data="data"
        size="small"
        :flex-height="!appStore.isMobile && !props.inModal"
        :scroll-x="scrollX"
        :loading="loading"
        remote
        :row-key="row => row.detailId"
        :pagination="mobilePagination"
        class="sm:h-full"
      />
      <SchoolDetailOperateDrawer
        v-model:visible="drawerVisible"
        :operate-type="operateType"
        :row-data="editingData"
        :default-school-id="props.schoolId"
        @submitted="getDataByPage"
      />
    </NCard>
  </div>
</template>

<style scoped></style>
