<script setup lang="tsx">
import { ref } from 'vue';
import { NButton, NDivider, NPopover } from 'naive-ui';
import { useBoolean } from '@sa/hooks';
import { fetchBatchDeleteSchool, fetchGetSchoolList } from '@/service/api/art/school';
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 SchoolOperateDrawer from './modules/school-operate-drawer.vue';
import SchoolImportModal from './modules/school-import-modal.vue';
import SchoolSearch from './modules/school-search.vue';
import SchoolSubTableModal from './modules/school-sub-table-modal.vue';

defineOptions({
  name: 'SchoolList'
});

type SchoolSubModuleType =
  | 'schoolName'
  | 'schoolCampus'
  | 'schoolCollege'
  | 'schoolMajor'
  | 'schoolEnrollPlan'
  | 'schoolDorm'
  | 'schoolMedia'
  | 'schoolTag';

type SchoolSubModuleButton = {
  key: SchoolSubModuleType;
  label: string;
};

const appStore = useAppStore();
const { download } = useDownload();
const { hasAuth } = useAuth();
const { bool: importVisible, setTrue: openImportModal } = useBoolean();
const subTableModalVisible = ref(false);
const currentSchoolId = ref<CommonType.IdType | null>(null);
const currentSchoolName = ref('');
const currentSchoolData = ref<Api.Art.School | null>(null);
const currentSubModule = ref<SchoolSubModuleType>('schoolName');

const subModuleButtons: SchoolSubModuleButton[] = [
  { key: 'schoolName', label: '名称管理' },
  { key: 'schoolCampus', label: '校区管理' },
  { key: 'schoolCollege', label: '学院管理' },
  { key: 'schoolMajor', label: '专业管理' },
  { key: 'schoolEnrollPlan', label: '招生计划' },
  { key: 'schoolDorm', label: '宿舍管理' },
  { key: 'schoolMedia', label: '媒体管理' }
];

const searchParams = ref<Api.Art.SchoolSearchParams>({
  pageNum: 1,
  pageSize: 10,
  mainCode: null,
  mainName: null,
  shortName: null,
  schoolIcon: null,
  province: null,
  city: null,
  district: null,
  universityType: null,
  educationLevel: null,
  schoolNature: null,
  supervisorDept: null,
  establishYear: null,
  campusAreaMu: null,
  maleRatio: null,
  femaleRatio: null,
  params: {}
});

const { columns, columnChecks, data, getData, getDataByPage, loading, mobilePagination, scrollX } =
  useNaivePaginatedTable({
    api: () => fetchGetSchoolList(searchParams.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: 'schoolId',
        title: '学校主键ID',
        align: 'center',
        minWidth: 120
      },
      {
        key: 'mainCode',
        title: '学校编码(国标代码)',
        align: 'center',
        minWidth: 120
      },
      {
        key: 'mainName',
        title: '学校主名称',
        align: 'center',
        minWidth: 120
      },
      {
        key: 'shortName',
        title: '学校简称',
        align: 'center',
        minWidth: 120
      },
      {
        key: 'schoolIcon',
        title: '院校图标',
        align: 'center',
        minWidth: 120
      },
      {
        key: 'province',
        title: '省份',
        align: 'center',
        minWidth: 120
      },
      {
        key: 'city',
        title: '城市',
        align: 'center',
        minWidth: 120
      },
      {
        key: 'district',
        title: '区县',
        align: 'center',
        minWidth: 120
      },
      {
        key: 'universityType',
        title: '大学类型',
        align: 'center',
        minWidth: 120
      },
      {
        key: 'educationLevel',
        title: '学历层次',
        align: 'center',
        minWidth: 120
      },
      {
        key: 'schoolNature',
        title: '办学性质',
        align: 'center',
        minWidth: 120
      },
      {
        key: 'supervisorDept',
        title: '主管部门',
        align: 'center',
        minWidth: 120
      },
      {
        key: 'establishYear',
        title: '建校时间(年)',
        align: 'center',
        minWidth: 120
      },
      {
        key: 'campusAreaMu',
        title: '占地面积(亩)',
        align: 'center',
        minWidth: 120
      },
      {
        key: 'maleRatio',
        title: '男生比例(%)',
        align: 'center',
        minWidth: 120
      },
      {
        key: 'femaleRatio',
        title: '女生比例(%)',
        align: 'center',
        minWidth: 120
      },
      {
        key: 'remark',
        title: '备注',
        align: 'center',
        minWidth: 120
      },
      {
        key: 'operate',
        fixed: 'right',
        title: $t('common.operate'),
        align: 'center',
        width: 220,
        render: row => {
          const renderDivider = () => {
            if (!hasAuth('art:school:edit') || !hasAuth('art:school:remove')) {
              return null;
            }
            return <NDivider vertical />;
          };

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

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

          const subTableButton = () => {
            return (
              <NPopover trigger="click" placement="bottom-end">
                {{
                  trigger: () => (
                    <NButton size="tiny" tertiary type="primary" class="rounded-14px px-10px">
                      子表管理
                    </NButton>
                  ),
                  default: () => (
                    <div class="grid grid-cols-3 w-276px gap-8px lt-sm:grid-cols-2 lt-sm:w-188px">
                      {subModuleButtons.map(item => (
                        <NButton
                          key={item.key}
                          size="tiny"
                          quaternary
                          type="primary"
                          class="justify-center"
                          onClick={() => openSubModule(row, item.key)}
                        >
                          {item.label}
                        </NButton>
                      ))}
                    </div>
                  )
                }}
              </NPopover>
            );
          };

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

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

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

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

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

function handleExport() {
  download('/art/school/export', searchParams.value, `学校基础信息主表_${new Date().getTime()}.xlsx`);
}

function handleImport() {
  openImportModal();
}

function openSubModule(row: Api.Art.School, moduleType: SchoolSubModuleType) {
  currentSchoolId.value = row.schoolId;
  currentSchoolName.value = row.mainName || row.shortName || String(row.schoolId);
  currentSchoolData.value = row;
  currentSubModule.value = moduleType;
  subTableModalVisible.value = true;
}
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <SchoolSearch 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:school:add')"
          :show-delete="hasAuth('art:school:remove')"
          :show-export="hasAuth('art:school:export')"
          @add="handleAdd"
          @delete="handleBatchDelete"
          @export="handleExport"
          @refresh="getData"
        >
          <template #after>
            <NButton v-if="hasAuth('art:school:import')" size="small" ghost @click="handleImport">
              <template #icon>
                <icon-material-symbols-upload-rounded class="text-icon" />
              </template>
              {{ $t('common.import') }}
            </NButton>
          </template>
        </TableHeaderOperation>
      </template>
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        :columns="columns"
        :data="data"
        size="small"
        :flex-height="!appStore.isMobile"
        :scroll-x="scrollX"
        :loading="loading"
        remote
        :row-key="row => row.schoolId"
        :pagination="mobilePagination"
        class="sm:h-full"
      />
      <SchoolOperateDrawer
        v-model:visible="drawerVisible"
        :operate-type="operateType"
        :row-data="editingData"
        @submitted="getDataByPage"
      />
      <SchoolImportModal v-model:visible="importVisible" @submitted="getDataByPage" />
    </NCard>
    <SchoolSubTableModal
      v-model:visible="subTableModalVisible"
      :school-id="currentSchoolId"
      :school-name="currentSchoolName"
      :school-data="currentSchoolData"
      :active-module="currentSubModule"
    />
  </div>
</template>

<style scoped></style>
