<template>
  <div class="part-box is-filter">
    <el-form inline>
      <el-form-item label="姓名">
        <el-input
          v-model.trim="searchModel.name"
          placeholder="请输入"
          clearable
        >
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="toPage(1)">查询</el-button>
        <el-button type="success" status="success" @click="onAdd"
          >新建</el-button
        >
        <el-button
          v-if="schoolStatusInfo.syncEnable"
          :loading="loading || schoolStatusInfo.running"
          @click="onSync"
        >
          机构同步
        </el-button>
      </el-form-item>
    </el-form>
  </div>
  <div class="part-box">
    <el-table class="page-table" :data="dataList" border stripe>
      <el-table-column prop="name" label="名称" />
      <el-table-column prop="code" label="代码" />
      <el-table-column prop="subCode" label="子机构代码" width="100" />
      <el-table-column prop="doubleTrack" label="双评轨迹" width="100">
        <template #default="scope">
          {{ scope.row.doubleTrack ? '开启' : '关闭' }}
        </template>
      </el-table-column>
      <el-table-column prop="province" label="省份" />
      <el-table-column prop="city" label="城市" />
      <el-table-column label="操作" width="300">
        <template #default="scope">
          <el-button type="primary" link @click="onEdit(scope.row)">
            修改
          </el-button>
          <el-button type="primary" link @click="onEditAdmin(scope.row)">
            编辑管理员
          </el-button>
          <el-button type="primary" link @click="onEditRoleAuth(scope.row)">
            角色权限
          </el-button>
          <el-button type="primary" link @click="onSplitCourse(scope.row)">
            科目拆分
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="pagination.pageNumber"
      v-model:page-size="pagination.pageSize"
      :layout="pagination.layout"
      :total="pagination.total"
      @size-change="pageSizeChange"
      @current-change="toPage"
    />
  </div>

  <!-- 编辑学校 -->
  <ModifySchool
    ref="modifySchoolRef"
    :row-data="curRow"
    :status-info="schoolStatusInfo"
    @modified="getList"
  />
  <!-- 编辑学校管理员 -->
  <ModifySchoolAdmin ref="modifySchoolAdminRef" :row-data="curRow" />

  <!-- ImportDialog -->
  <ImportDialog
    ref="importDialogRef"
    title="科目拆分"
    upload-url="/api/admin/site/import"
    :upload-data="uploadData"
    :format="['xls', 'xlsx']"
    :download-handle="() => downloadExport('splitCourseTemplate')"
    download-filename="科目拆分模板.xlsx"
    :auto-upload="false"
    :before-submit-handle="beforeSubmitHandle"
    @upload-success="importSuccess"
  >
    <el-form ref="formRef" label-width="100px">
      <el-form-item label="名称">
        <el-input :value="curRow.name" readonly disabled />
      </el-form-item>
      <el-form-item label="考试" prop="exam">
        <SelectExam v-model="importExamId" size="large" />
      </el-form-item>
    </el-form>
  </ImportDialog>
</template>

<script setup lang="ts">
  import { computed, reactive, ref, onMounted } from 'vue';
  import { useRoute } from 'vue-router';
  import { ElMessage } from 'element-plus';
  import { schoolListPage, syncSchool, getSchoolStatusInfo } from '@/api/admin';
  import {
    SchoolItem,
    SchoolListFilter,
    SchoolStatusInfo,
  } from '@/api/types/admin';
  import useTable from '@/hooks/table';
  import useLoading from '@/hooks/loading';
  import { downloadExport } from '@/utils/download-export';

  import ModifySchool from './ModifySchool.vue';
  import ModifySchoolAdmin from './ModifySchoolAdmin.vue';

  defineOptions({
    name: 'SchoolManage',
  });

  const route = useRoute();

  // 学校状态信息
  const schoolStatusInfo = ref<SchoolStatusInfo>({} as SchoolStatusInfo);
  async function getSchoolStatus() {
    schoolStatusInfo.value = await getSchoolStatusInfo();
  }

  const searchModel = reactive<SchoolListFilter>({
    name: '',
  });

  const { dataList, pagination, getList, toPage, pageSizeChange } =
    useTable<SchoolItem>(schoolListPage, searchModel, true);

  // table action
  const curRow = ref({} as SchoolItem);
  const modifySchoolRef = ref();
  function onEdit(row: SchoolItem) {
    curRow.value = row;
    modifySchoolRef.value?.open();
  }
  function onAdd() {
    curRow.value = {} as SchoolItem;
    modifySchoolRef.value?.open();
  }

  const modifySchoolAdminRef = ref();
  function onEditAdmin(row: SchoolItem) {
    curRow.value = row;
    modifySchoolAdminRef.value?.open();
  }
  function onEditRoleAuth(row: SchoolItem) {
    route.push({
      name: 'RoleManage',
      params: {
        schoolId: row.id,
      },
    });
  }
  // 同步
  const { loading, setLoading } = useLoading();
  async function onSync() {
    if (loading.value) return;

    setLoading(true);
    try {
      const res = await syncSchool();
      if (res.success) {
        ElMessage.success('同步成功');
      } else {
        ElMessage.error(res.message);
      }
    } catch (error) {
      console.log(error);
    } finally {
      setLoading(false);
    }
  }

  // 科目拆分
  const importDialogRef = ref();
  const importExamId = ref(0);
  const uploadData = computed(() => {
    return {
      examId: importExamId.value,
      schoolId: curRow.value.id,
    };
  });
  function onSplitCourse(row: SchoolItem) {
    curRow.value = row;
    importDialogRef.value?.open();
  }

  async function beforeSubmitHandle() {
    if (!importExamId.value) {
      ElMessage.error('请选择考试');
      return Promise.reject(new Error('请选择考试'));
    }

    return Promise.resolve();
  }

  function importSuccess() {
    importDialogRef.value?.close();
  }

  onMounted(() => {
    getSchoolStatus();
  });
</script>
