<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="园所名称" prop="name">
        <!-- <el-input
          v-model="queryParams.name"
          placeholder="请输入园所名称"
          clearable
          style="width: 240px"
        /> -->
        <el-select
            v-model="queryParams._id"
            placeholder="请选择园所名称"
            clearable
            filterable
            remote
            style="width: 200px"
         >
            <el-option v-for="s in schoolList" :key="s._id" :label="s.name" :value="s._id"/>
         </el-select>
      </el-form-item>
      <el-form-item label="联系人" prop="contacts">
        <el-input
          v-model="queryParams.contacts"
          placeholder="请输入联系人"
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item label="电话" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入电话"
          clearable
          style="width: 240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="Upload" @click="handleImport">导入</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="success" plain icon="Download" @click="handleExport">导出</el-button>
      </el-col> -->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格 -->
    <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column type="index" label="序号" width="60" align="center"
        :index="(index) => (queryParams.pageNum - 1) * queryParams.pageSize + index + 1" />
      <el-table-column label="学校ID" align="center" prop="_id" />
      <el-table-column label="学校名称" align="center" prop="name" />
      <el-table-column label="联系人" align="center" prop="contacts" />
      <el-table-column label="电话" align="center" prop="phone" />
      <el-table-column label="地址" align="center" prop="adress" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" width="150">
        <template #default="scope">
          <el-tooltip content="修改" placement="top">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加/修改弹窗 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form :model="form" :rules="rules" ref="userRef" label-width="80px">
        <el-form-item label="学校名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入学校名称" maxlength="50" />
        </el-form-item>
        <el-form-item label="联系人" prop="contacts">
          <el-input v-model="form.contacts" placeholder="请输入联系人" maxlength="30" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入电话" maxlength="20" />
        </el-form-item>
        <el-form-item label="地址" prop="adress">
          <el-input v-model="form.adress" placeholder="请输入地址" maxlength="100" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 导入弹窗 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
         <el-upload
            ref="uploadRef"
            :limit="1"
            accept=".xlsx, .xls"
            :disabled="upload.isUploading"
            :auto-upload="true"
            :before-upload="beforeUpload"
            :on-remove="handleRemove"
            drag
         >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <template #tip>
               <div class="el-upload__tip text-center">
                  <span>仅允许导入xls、xlsx格式文件。</span>
                  <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
               </div>
            </template>
         </el-upload>
      </el-dialog>
  </div>
</template>

<script setup>
import { getToken } from "@/utils/auth";
import { getCurrentInstance, ref, reactive, toRefs } from "vue";
// import { app, models } from "@/utils/mysql.js";

const { proxy } = getCurrentInstance();

const userList = ref([]);
const open = ref(false);
const loading = ref(true);
const total = ref(0);
const title = ref("");
const showSearch = ref(true);
const single = ref(true);
const multiple = ref(true);
const ids = ref([]);
const schoolList = ref([]);

/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  // updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/system/user/importData"
});

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    _id: undefined,
    contacts: undefined,
    phone: undefined
  },
  rules: {
    name: [{ required: true, message: "学校名称不能为空", trigger: "blur" }],
    phone: [{ required: true, message: "电话不能为空", trigger: "blur" }, { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号", trigger: "blur" }],
    contacts: [{ required: true, message: "联系人不能为空", trigger: "blur" }],
    // adress: [{ required: true, message: "地址不能为空", trigger: "blur" }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询用户列表 */
async function getList() {
  loading.value = true;
  const filter = { where: {} };
  if (queryParams.value._id) filter.where._id = queryParams.value._id;
  if (queryParams.value.contacts) filter.where.contacts = queryParams.value.contacts;
  if (queryParams.value.phone) filter.where.phone = queryParams.value.phone;

  const { data } = await proxy.$models.wx_school.list({
    filter,
    pageSize: queryParams.value.pageSize,
    pageNumber: queryParams.value.pageNum,
    getCount: true,
    envType: "prod"
  });

  userList.value = data.records || [];
  total.value = data.total || 0;
  loading.value = false;
}


/** 获取学校列表 */
async function getSchoolList() {
  const res = await proxy.$models.wx_school.list({ filter:{}, envType:'prod' });
  schoolList.value = res.data.records || [];
}

/** 搜索 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置 */
function resetQuery() {
  queryParams.value = { pageNum: 1, pageSize: 10, _id: undefined, contacts: undefined, phone: undefined };
  handleQuery();
}

/** 重置表单 */
function reset() {
  form.value = {
    id: undefined,
    name: "",
    phone: "",
    remark: "",
    adress: "",
    contacts: ""
  };
  proxy.resetForm("userRef");
}

/** 新增 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加学校";
}

/** 修改 */
function handleUpdate(row) {
  reset();
  form.value = { ...row };
  open.value = true;
  title.value = "修改学校";
}

/** 删除 */
function handleDelete(row) {
  proxy.$modal.confirm(`是否确认删除【${row.name}】？`).then(async () => {
    await proxy.$models.wx_school.delete({ filter: { where: { _id: { $eq: row._id } } }, envType: "prod" });
    proxy.$modal.msgSuccess("删除成功");
    getList();
  }).catch(() => {});
}

/** 导出 */
// function handleExport() {
//   proxy.download("system/user/export", queryParams.value, `school_${new Date().getTime()}.xlsx`);
// }

/** 选择变化 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item._id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}


/** 下载模板操作 */
async function importTemplate() {
  try {
    // 获取存储中的模板文件下载地址
    const res = await proxy.$apps
      // .storage()
      .getTempFileURL({
        fileList: ["cloud://honghgaier-5guiffgcf17a2eea.686f-honghgaier-5guiffgcf17a2eea-1373037829/schoolmoban.xlsx"], // 云存储里的路径
      });

      console.log(res.fileList[0].tempFileURL, 'res.fileList[0].tempFileURL');

    const fileUrl = res.fileList[0].tempFileURL;
    // 触发浏览器下载
    const a = document.createElement("a");
    a.href = fileUrl;
    a.download = `system_teacher_${Date.now()}.xlsx`;
    a.click();
  } catch (err) {
    proxy.$modal.msgError("下载失败");
  }
};

/** 上传前处理（改用腾讯云存储） */
async function beforeUpload(file) {
  upload.isUploading = true;
  try {
    // 1. file 就是原生 File 对象
    console.log(file, '上传文件对象');
    if (!(file instanceof File)) {
      throw new Error('请选择本地 Excel 文件上传');
    }

    // 2. 安全文件名
    const safeFileName = file.name.replace(/[^a-zA-Z0-9_.-]/g, '_');
    const cloudPath = `excel/teacher/${Date.now()}_${safeFileName}`;

    // 3. 上传文件
    const res = await proxy.$apps.uploadFile({
      cloudPath,
      filePath: file
    });
    console.log('上传成功 fileID:', res.fileID);

    // 4. 调用云函数解析
    const cloudResult = await proxy.$apps.callFunction({
      name: "schoolexcel",
      data: { fileID: res.fileID }
    });
    console.log('云函数返回:', cloudResult);

    const fnResult = cloudResult.result || cloudResult;
    if (fnResult.code === 0) {
      proxy.$modal.msgSuccess('导入成功');
      upload.open = false;
      getList();
    } else {
      proxy.$modal.msgError('导入失败：' + (fnResult.msg || '未知错误'));
    }
  } catch (err) {
    console.error('上传失败:', err);
    proxy.$modal.msgError('上传失败: ' + err.message);
  } finally {
    upload.isUploading = false;
  }
  return false; // 阻止默认上传
}

/** 导入 */
function handleImport() {
  upload.title = "导入学校数据";
  upload.open = true;
}

/** 移除文件 */
function handleRemove(file) {
  console.log("文件移除:", file);
}

// /** 上传进度 */
// function handleFileUploadProgress() {
//   upload.isUploading = true;
// }

// /** 上传成功 */
// function handleFileSuccess(response, file) {
//   upload.open = false;
//   upload.isUploading = false;
//   proxy.$refs["uploadRef"].handleRemove(file);
//   proxy.$alert(response.msg, "导入结果");
//   getList();
// }

// /** 提交上传文件 */
// function submitFileForm() {
//   proxy.$refs["uploadRef"].submit();
// }

/** 提交保存 */
function submitForm() {
  proxy.$refs["userRef"].validate(async valid => {
    if (valid) {
      if (form.value._id) {
        await proxy.$models.wx_school.update({
          data: form.value,
          filter: { where: { _id: { $eq: form.value._id } } },
          envType: "prod"
        });
        proxy.$modal.msgSuccess("修改成功");
      } else {
        await proxy.$models.wx_school.create({
          data: form.value,
          envType: "prod"
        });
        proxy.$modal.msgSuccess("新增成功");
      }
      open.value = false;
      getList();
    }
  });
}

/** 取消 */
function cancel() {
  open.value = false;
  reset();
}

getSchoolList();
getList();
</script>

<style lang="scss" scoped></style>
