<template>
  <div class="app-container">
    <el-row :gutter="20">
      <splitpanes :horizontal="appStore.device === 'mobile'" class="default-theme">
        <!--机构数据-->
        <!-- <pane size="16">
          <el-col>
            <div class="head-container">
              <el-input v-model="deptName" placeholder="请输入机构名称" clearable prefix-icon="Search"
                style="margin-bottom: 20px" />
            </div>
            <div class="head-container">
              <el-tree :data="deptOptions" :props="{ label: 'label', children: 'children' }"
                :expand-on-click-node="false" :filter-node-method="filterNode" ref="deptTreeRef" node-key="id"
                highlight-current default-expand-all @node-click="handleNodeClick" />
            </div>
          </el-col>
        </pane> -->
        <pane size="100">
          <el-col>
            <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
              <el-form-item label="校区名称" prop="name">
                <el-select
                        v-model="queryParams.id"
                        placeholder="请选择或输入校区名称"
                        filterable
                        clearable
                        style="width: 200px"
                >
                  <el-option
                          v-for="campus in allCampusList"
                          :key="campus.id"
                          :label="campus.name"
                          :value="campus.id"
                  />
                </el-select>
              </el-form-item>
              <!-- <el-form-item label="学校类型" prop="examTypes">
                <el-select v-model="queryParams.examTypes" placeholder="请选择学校类型" clearable style="width: 170px">
                  <el-option
                          v-for="dict in exam_type"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                  />
                </el-select>
              </el-form-item> -->
              <el-form-item label="省市区" prop="areaIds">
                <AddressSelect class="w-[198px]" v-model="areaIds" />
              </el-form-item>

              <!-- <el-form-item label="状态" prop="status">
                <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 170px">
                  <el-option v-for="dict in bool_values" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </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"
                  v-hasPermi="['dz:campus:add']">新增</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
                  v-hasPermi="['dz:campus:edit']">修改</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
                  v-hasPermi="['dz:campus:remove']">删除</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="warning" plain icon="Download" @click="handleExport"
                  v-hasPermi="['dz:campus:export']">导出</el-button>
              </el-col>
              <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>

            </el-row>

            <el-table v-loading="loading" :data="campusList" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column label="ID" align="center" prop="id" width="80" />
              <el-table-column label="名称" align="center" prop="name" />
              <!--              <el-table-column label="机构ID" align="center" prop="deptId" />-->
              <el-table-column label="归属机构" align="center" key="deptName" prop="dept.deptName"
                :show-overflow-tooltip="true" />
              <!--              <el-table-column label="省份" align="center" prop="location" />-->

              <!--              <el-table-column label="省" align="center" prop="pro" />-->
              <!--              <el-table-column label="市" align="center" prop="city" />-->
              <!--              <el-table-column label="区" align="center" prop="area" />-->
              <!-- <el-table-column label="所属地区" align="center" prop="proCityAreaName" /> -->
<!--              <el-table-column label="状态" align="center" prop="status">-->
<!--                <template #default="scope">-->
<!--                  <dict-tag :options="bool_values" :value="scope.row.status" />-->
<!--                </template>-->
<!--              </el-table-column>-->
              <!-- <el-table-column label="学校类型" align="center" prop="examTypes">
                <template #default="scope">
                  <span>{{ formatExamTypes(scope.row.examTypes) }}</span>
                </template>
              </el-table-column> -->
<!--              <el-table-column label="备注" align="center" prop="remark" />-->
              <el-table-column label="班级管理" align="center" width="120">
                <template #default="scope">
                  <el-button link type="primary" @click="handleViewClasses(scope.row)">点击查看</el-button>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width" min-width="140" fixed="right">
                <template #default="scope">
                  <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                    v-hasPermi="['dz:campus:edit']">修改</el-button>
                  <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                    v-hasPermi="['dz:campus:remove']">删除</el-button>
                </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-col>
        </pane>
      </splitpanes>
    </el-row>

    <!-- 班级管理对话框 -->
    <el-dialog title="班级管理" v-model="classesDialogOpen" width="90%" append-to-body>
      <Classes :key="selectedCampusId" :externalSchoolId="selectedCampusId" />
    </el-dialog>

    <!-- 添加或修改机构校区对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="campusRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <!--        <el-form-item label="机构ID" prop="deptId">-->
        <!--          <el-input v-model="form.deptId" placeholder="请输入机构ID" />-->
        <!--        </el-form-item>-->
        <el-form-item label="归属机构" prop="deptId">
          <el-tree-select v-model="form.deptId" :data="enabledDeptOptions"
            :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" placeholder="请选择归属机构"
            clearable check-strictly />
        </el-form-item>
        <!-- <el-form-item label="省份" prop="location">
          <el-input v-model="form.location" placeholder="请输入省份" />
        </el-form-item> -->
        <!-- <el-form-item label="省市区" prop="areaIds">
          <AddressSelect v-model="formAreaIds" style="width: 100%" />
        </el-form-item> -->
        <!--        <el-form-item label="省" prop="pro">-->
        <!--          <el-input v-model="form.pro" placeholder="请输入省" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="市" prop="city">-->
        <!--          <el-input v-model="form.city" placeholder="请输入市" />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="区" prop="area">-->
        <!--          <el-input v-model="form.area" placeholder="请输入区" />-->
        <!--        </el-form-item>-->
        <!-- <el-form-item label="学校类型" prop="examTypes">
          <el-select v-model="form.examTypes" placeholder="请选择学校类型" multiple>
            <el-option
                    v-for="dict in exam_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option v-for="dict in bool_values" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" 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>
  </div>
</template>

<script setup name="Campus">
import { listCampus, getCampus, delCampus, addCampus, updateCampus, checkCampusName } from "@/api/dz/campus"
import { debounce } from '@/utils/index';
import { deptTreeSelect } from "@/api/system/user"
import useAppStore from '@/store/modules/app'
import { Splitpanes, Pane } from "splitpanes"
import "splitpanes/dist/splitpanes.css"
import AddressSelect from '@/components/AddressSelect';
import Classes from '@/views/dz/classes/index.vue';

const { proxy } = getCurrentInstance()
const appStore = useAppStore()
const { bool_values } = proxy.useDict('bool_values')
// const { bool_values, exam_type } = proxy.useDict('bool_values', 'exam_type')
const deptName = ref("")
const deptOptions = ref(undefined)
const enabledDeptOptions = ref(undefined)

const campusList = ref([])
const allCampusList = ref([]) // 所有校区列表（用于下拉选择）
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const classesDialogOpen = ref(false) // 班级管理对话框显示状态
const selectedCampusId = ref(null) // 选中的校区ID

const dataList = ref([]);
const areaIds = ref([]); // 筛选条件中的省市区
const formAreaIds = ref([]); // 表单对话框中的省市区
let selectedIds = [];

const campusRef = ref(null);

// 先创建 data 对象，但先不定义 rules
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    id: null, // 校区ID（用于精确查询）
    name: null,
    deptId: null,
    location: null,
    pro: null,
    city: null,
    area: null,
    status: null,
    // examTypes: null,
  },
  rules: {}
})

// 名称校验函数（在 data 定义之后，可以访问 data.form）
const validateCampusName = (rule, value, callback) => {
  if (!value) {
    callback()
    return
  }
  const campusId = data.form.id || null
  checkCampusName(value, campusId).then(response => {
    if (response.data) {
      callback()
    } else {
      callback(new Error('校区名称已存在，请使用其他名称'))
    }
  }).catch(() => {
    callback()
  })
}

// 设置 rules（在 validateCampusName 定义之后）
data.rules = {
  name: [
    { required: true, message: "名称不能为空", trigger: "blur" },
    { validator: validateCampusName, trigger: "blur" }
  ]
}

const { queryParams, form, rules } = toRefs(data)
const queryRef = ref(null);
const dateRange = ref([]);

// 防抖校验函数
const debouncedValidateName = debounce((name) => {
  if (!name || !campusRef.value) return
  const campusId = form.value.id || null
  checkCampusName(name, campusId).then(response => {
    if (!response.data) {
      // 名称不唯一，触发校验错误
      campusRef.value.validateField('name', () => {})
    } else {
      // 名称唯一，清除错误
      campusRef.value.clearValidate('name')
    }
  })
}, 500)

// 监听名称变化（仅在对话框打开时校验）
watch(() => form.value.name, (newName) => {
  if (open.value && newName && newName.trim()) {
    debouncedValidateName(newName.trim())
  }
})

/** 查询机构校区列表 */
function getList() {
  loading.value = true
  let areaObj = { pro: areaIds.value?.[0] || '', city: areaIds.value?.[1] || '', area: areaIds.value?.[2] || '' };
  // 如果选择了校区ID，则根据ID精确查询，清空name参数
  let params = { ...proxy.addDateRange(queryParams.value), ...areaObj }
  if (params.id) {
    params.name = null // 如果选择了ID，则不再使用name查询
  } else {
    params.id = null // 如果没有选择ID，则清空id参数
  }
  listCampus(params).then(response => {
    campusList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

/** 加载所有校区列表（用于下拉选择） */
function loadAllCampusList() {
  listCampus({ pageNum: 1, pageSize: 9999, campus: true }).then(response => {
    allCampusList.value = response.rows || []
  })
}

/** 通过条件过滤节点  */
const filterNode = (value, data) => {
  if (!value) return true
  return data.label.indexOf(value) !== -1
}

/** 根据名称筛选机构树 */
watch(deptName, val => {
  proxy.$refs["deptTreeRef"].filter(val)
})

/** 查询机构下拉树结构 */
function getDeptTree() {
  deptTreeSelect().then(response => {
    deptOptions.value = response.data
    enabledDeptOptions.value = filterDisabledDept(JSON.parse(JSON.stringify(response.data)))
  })
}

/** 过滤禁用的机构 */
function filterDisabledDept(deptList) {
  return deptList.filter(dept => {
    if (dept.disabled) {
      return false
    }
    if (dept.children && dept.children.length) {
      dept.children = filterDisabledDept(dept.children)
    }
    return true
  })
}

/** 节点单击事件 */
function handleNodeClick(data) {
  queryParams.value.deptId = data.id
  handleQuery()
}

/** 查询机构代理下拉树结构 */
function getTreeselect() {
  listAgent().then(response => {
    agentOptions.value = []
    const data = { agentId: 0, name: '顶级节点', children: [] }
    data.children = proxy.handleTree(response.data, "agentId", "parentId")
    agentOptions.value.push(data)
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    deptId: null,
    location: null,
    remark: null,
    pro: null,
    city: null,
    area: null,
    status: null,
    // examTypes: [],
    createTime: null,
    updateTime: null
  }
  // 清空表单中的省市区选择
  formAreaIds.value = []
  if (campusRef.value) {
    campusRef.value.resetFields()
    campusRef.value.clearValidate()
  }
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  // 清空机构ID
  queryParams.value.deptId = undefined
  // 清空机构名称
  deptName.value = ""
  // 取消树节点的选中状态
  // proxy.$refs.deptTreeRef.setCurrentKey(null)
  proxy.resetForm("queryRef")
  // 清空校区ID（下拉选择框的值）
  queryParams.value.id = null
  // 清空省市区选择
  areaIds.value = []

  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加机构校区"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getCampus(_id).then(response => {
    form.value = response.data
    // 将 examTypes 字符串转换为数组（如果是逗号分隔的字符串）
    // if (form.value.examTypes && typeof form.value.examTypes === 'string') {
    //   form.value.examTypes = form.value.examTypes.split(',').filter(item => item.trim())
    // } else if (!form.value.examTypes) {
    //   form.value.examTypes = []
    // }
    // 将省市区数据转换为 formAreaIds 数组格式，用于 AddressSelect 组件回显
    // 按照顺序构建数组：[省, 市, 区]，只包含有值的部分
    const areaArray = []
    if (form.value.pro) {
      areaArray.push(form.value.pro)
      if (form.value.city) {
        areaArray.push(form.value.city)
        if (form.value.area) {
          areaArray.push(form.value.area)
        }
      }
    }
    formAreaIds.value = areaArray
    open.value = true
    title.value = "修改机构校区"
  })
}

/** 提交按钮 */
function submitForm() {
  campusRef.value.validate(valid => {
    if (valid) {
      // 构建省市区对象（使用表单中的 formAreaIds）
      let areaObj = {
        pro: formAreaIds.value?.[0] || '',
        city: formAreaIds.value?.[1] || '',
        area: formAreaIds.value?.[2] || ''
      };

      // 处理 examTypes：如果是数组，转换为逗号分隔的字符串
      // let examTypesValue = form.value.examTypes
      // if (Array.isArray(examTypesValue)) {
      //   examTypesValue = examTypesValue.length > 0 ? examTypesValue.join(',') : null
      // } else if (!examTypesValue) {
      //   examTypesValue = null
      // }

      // 合并表单数据和省市区数据
      const submitData = {
        ...form.value,
        ...areaObj
        // examTypes: examTypesValue
      };

      if (form.value.id != null) {
        // updateCampus(form.value).then(response => {
        updateCampus(submitData).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        // addCampus(form.value).then(response => {
        addCampus(submitData).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除机构校区编号为"' + _ids + '"的数据项？').then(function () {
    return delCampus(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('dz/campus/export', {
    ...queryParams.value
  }, `campus_${new Date().getTime()}.xlsx`)
}

/** 格式化学校类型显示 */
// function formatExamTypes(examTypes) {
//   if (!examTypes) return ''
//   // 将字符串按逗号分割
//   const types = String(examTypes).split(',').map(item => item.trim()).filter(item => item)
//   if (types.length === 0) return ''
//   // 根据字典查找对应的标签
//   const labels = types.map(type => {
//     const dictItem = exam_type.value.find(item => item.value === type)
//     return dictItem ? dictItem.label : type
//   })
//   // 用英文逗号连接
//   return labels.join(',')
// }

/** 查看班级管理 */
function handleViewClasses(row) {
  selectedCampusId.value = row.id
  classesDialogOpen.value = true
}

onMounted(() => {
  getDeptTree()
  loadAllCampusList() // 加载所有校区列表
  getList()
})
</script>
