<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="84">
          <el-col>
            <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
                        @keyup.enter="handleQuery"
                />
              </el-form-item>
              <el-form-item label="省份" prop="location">
                <el-input
                        v-model="queryParams.location"
                        placeholder="请输入省份"
                        clearable
                        @keyup.enter="handleQuery"
                />
              </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:school:add']"
                >新增</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                        type="success"
                        plain
                        icon="Edit"
                        :disabled="single"
                        @click="handleUpdate"
                        v-hasPermi="['dz:school:edit']"
                >修改</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                        type="danger"
                        plain
                        icon="Delete"
                        :disabled="multiple"
                        @click="handleDelete"
                        v-hasPermi="['dz:school:remove']"
                >删除</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                        type="warning"
                        plain
                        icon="Download"
                        @click="handleExport"
                        v-hasPermi="['dz:school:export']"
                >导出</el-button>
              </el-col>
              <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>

            </el-row>

            <el-table v-loading="loading" :data="schoolList" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column label="ID" align="center" prop="id" />
              <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="status">
                <template #default="scope">
                  <dict-tag :options="bool_values" :value="scope.row.status"/>
                </template>
              </el-table-column>
              <el-table-column label="备注" align="center" prop="remark" />
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                  <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['dz:school:edit']">修改</el-button>
                  <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['dz:school: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="title" v-model="open" width="500px" append-to-body>
      <el-form ref="schoolRef" :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" style="width: 220px;">
          <AddressSelect class="w-[198px]" v-model="areaIds" />
        </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="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="School">
  import { listSchool, getSchool, delSchool, addSchool, updateSchool } from "@/api/dz/school"
  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';

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

  const schoolList = 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 dataList = ref([]);
  const areaIds = ref([]);
  let selectedIds = [];

  const data = reactive({
    form: {},
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      name: null,
      deptId: null,
      location: null,
      pro: null,
      city: null,
      area: null,
      status: null,
    },
    rules: {
      status: [
        { required: true, message: "状态(0:无效,1:有效)不能为空", trigger: "change" },
        { required: true, message: "机构不能为空", trigger: "change" }
      ],
    }
  })

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

  /** 查询机构校区列表 */
  function getList() {
    loading.value = true
    let areaObj = { pro: areaIds.value?.[0] || '', city: areaIds.value?.[1] || '', area: areaIds.value?.[2] || '' };
    let params = { ...proxy.addDateRange(queryParams.value), ...areaObj }
    // listSchool(queryParams.value).then(response => {
    listSchool(params).then(response => {
      schoolList.value = response.rows
      total.value = response.total
      loading.value = false
    })
  }

  /** 通过条件过滤节点  */
  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,
      createTime: null,
      updateTime: null
    }
    proxy.resetForm("schoolRef")
  }

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

  /** 重置按钮操作 */
  function resetQuery() {
    // 清空机构ID
    queryParams.value.deptId = undefined
    // 清空机构名称
    deptName.value = ""
    // 取消树节点的选中状态
    proxy.$refs.deptTreeRef.setCurrentKey(null)
    proxy.resetForm("queryRef")
    // 清空省市区选择
    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
    getSchool(_id).then(response => {
      form.value = response.data
      open.value = true
      title.value = "修改机构校区"
    })
  }

  /** 提交按钮 */
  function submitForm() {
    proxy.$refs["schoolRef"].validate(valid => {
      if (valid) {
        // 构建省市区对象
        let areaObj = {
          pro: areaIds.value?.[0] || '',
          city: areaIds.value?.[1] || '',
          area: areaIds.value?.[2] || ''
        };

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

        if (form.value.id != null) {
          updateSchool(form.value).then(response => {
            proxy.$modal.msgSuccess("修改成功")
            open.value = false
            getList()
          })
        } else {
          addSchool(form.value).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 delSchool(_ids)
    }).then(() => {
      getList()
      proxy.$modal.msgSuccess("删除成功")
    }).catch(() => {})
  }

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

  onMounted(() => {
    getDeptTree()
    getList()
  })
</script>
