<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="deptId">
                              <IeInstitutionSelect 
                                  v-model="queryParams.deptId" 
                                  placeholder="请选择平台机构" 
                                  clearable 
                                  style="width: 240px"
                                  @change="handleDeptChange"
                              />
                          </el-form-item>
                          <el-form-item label="代理商" prop="agentId">
                              <el-select
                                      v-model="queryParams.agentId"
                                      placeholder="请选择或搜索代理商"
                                      filterable
                                      clearable
                                      style="width: 240px"
                                      @keyup.enter="handleQuery"
                              >
                                  <el-option
                                          v-for="item in flatAgentOptions"
                                          :key="item.agentId"
                                          :label="item.name"
                                          :value="item.agentId"
                                  />
                              </el-select>
                          </el-form-item>
                          <!-- <el-form-item label="联系电话" prop="phonenumber">
                              <el-input
                                      v-model="queryParams.phonenumber"
                                      placeholder="请输入联系电话"
                                      clearable
                                      @keyup.enter="handleQuery"
                              />
                          </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-col>-->
<!--              </pane>-->
<!--          </splitpanes>-->
<!--      </el-row>-->
                      <el-row :gutter="10" class="mb8">
                          <el-col :span="1.5">
                              <el-button
                                      type="primary"
                                      plain
                                      icon="Plus"
                                      @click="handleAdd"
                                      v-hasPermi="['dz:agent:add']"
                              >新增</el-button>
                          </el-col>
                          <el-col :span="1.5">
                              <el-button
                                      type="info"
                                      plain
                                      icon="Sort"
                                      @click="toggleExpandAll"
                              >展开/折叠</el-button>
                          </el-col>
                          <el-col :span="1.5">
                              <el-button
                                      type="warning"
                                      plain
                                      icon="Download"
                                      @click="handleExport"
                                      v-hasPermi="['dz:agent:export']"
                              >导出</el-button>
                          </el-col>
                          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
                      </el-row>

                      <el-table
                              v-if="refreshTable"
                              v-loading="loading"
                              :data="agentList"
                              row-key="agentId"
                              :default-expand-all="isExpandAll"
                              :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
                              :row-style="getRowStyle"
                      >
                          <!--      <el-table-column label="用户ID" prop="userId" />-->
                          <el-table-column label="名称" align="center" prop="name" />
                          <el-table-column label="账号/邀请码" align="center" prop="agentId" />
                          <el-table-column label="密码" align="center" prop="password2" />
<!--                          <el-table-column label="机构" 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="phonenumber" /> -->
                          <!--      <el-table-column label="上级代理商ID" align="center" prop="parentId" />-->
<!--                          <el-table-column label="学校/校区" align="center" prop="schools" />-->
<!--                          <el-table-column label="学校/校区" align="center" prop="schoolName" />-->
                          <el-table-column label="用户ID" align="center" prop="userId" />
                          <el-table-column label="禁用状态" align="center" key="status">
                              <template #default="scope">
                                  <el-switch
                                      v-model="scope.row.status"
                                      active-value="0"
                                      inactive-value="1"
                                      @change="handleStatusChange(scope.row)"
                                  ></el-switch>
                              </template>
                          </el-table-column>
                          <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:agent:edit']">修改</el-button>
                                  <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)" v-hasPermi="['dz:agent:add']">新增</el-button>
                                  <!-- <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['dz:agent:remove']">删除</el-button> -->
                              </template>
                          </el-table-column>
                      </el-table>
                  </el-col>
              </pane>
          </splitpanes>
      </el-row>

    <!-- 添加或修改机构代理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="agentRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户ID" disabled/>
        </el-form-item>
          <el-form-item label="代理商" prop="name">
              <el-input v-model="form.name" placeholder="请输入代理商" />
          </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="phonenumber">
          <el-input v-model="form.phonenumber" placeholder="请输入联系电话" />
        </el-form-item> -->
        <el-form-item label="上级代理" prop="parentId">
          <el-tree-select
            v-model="form.parentId"
            :data="agentOptions"
            :props="{ value: 'agentId', label: 'name', children: 'children' }"
            value-key="agentId"
            placeholder="请选择上级代理商ID"
            check-strictly
          />
        </el-form-item>
<!--        <el-form-item label="负责校区" prop="schools">-->
<!--          <el-input v-model="form.schools" placeholder="请输入负责校区" />-->
<!--        </el-form-item>-->

<!--          <el-form-item label="关联校区" prop="classIds">-->
<!--              <el-select v-model="form.schoolIds" multiple placeholder="请选择校区" style="width: 100%">-->
<!--                  <el-option-->
<!--                          v-for="item in schoolOptions"-->
<!--                          :key="item.id"-->
<!--                          :label="item.name"-->
<!--                          :value="item.id"-->
<!--                  />-->
<!--              </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="Agent">
import { listAgent, getAgent, delAgent, addAgent, updateAgent } from "@/api/dz/agent"
import { deptTreeSelect, changeUserStatus } from "@/api/system/user"
import useAppStore from '@/store/modules/app'
import { Splitpanes, Pane } from "splitpanes"
import "splitpanes/dist/splitpanes.css"
import { listAllSchool } from "@/api/dz/school"
import IeInstitutionSelect from '@/components/IeInstitutionSelect/index.vue'

const { proxy } = getCurrentInstance()
const appStore = useAppStore()

const agentList = ref([])
const agentOptions = ref([])
const flatAgentOptions = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const title = ref("")
const isExpandAll = ref(true)
const refreshTable = ref(true)
const deptName = ref("")
const deptOptions = ref(undefined)
const enabledDeptOptions = ref(undefined)
const schoolOptions = ref(undefined)

const data = reactive({
  form: {},
  queryParams: {
    userId: null,
    agentId: null,
    name: null,
    deptId: null,
    phonenumber: null,
    parentId: null,
    // schools: null,
    schoolIds: []
  },
  rules: {
  }
})

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

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

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

/** 查询机构代理列表 */
function getList() {
  loading.value = true
  listAgent(queryParams.value).then(response => {
    const dataList = response.data || []
    agentList.value = proxy.handleTree(dataList, "agentId", "parentId")
    // 从原始数据中提取代理商列表用于下拉选择
    flatAgentOptions.value = dataList.map(item => ({
      agentId: item.agentId,
      name: item.name
    }))
    loading.value = false
  })
}

/** 查询机构下拉树结构 */
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 = {
    agentId: null,
    dept: null,
    userId: null,
    name: null,
    phonenumber: null,
    parentId: null,
    // schools: null,
    schoolIds: [],
    remark: null
  }
  proxy.resetForm("agentRef")
}

/** 平台机构变化处理 */
function handleDeptChange() {
  // 清空代理商选择，因为平台机构变化后代理商列表会变化
  queryParams.value.agentId = null
  handleQuery()
}

/** 搜索按钮操作 */
function handleQuery() {
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
    // 清空机构ID
    queryParams.value.deptId = undefined
    // 清空代理商ID
    queryParams.value.agentId = undefined
    // 清空机构名称
    deptName.value = ""
    // 取消树节点的选中状态（如果树组件存在）
    if (proxy.$refs.deptTreeRef) {
        proxy.$refs.deptTreeRef.setCurrentKey(null)
    }
  proxy.resetForm("queryRef")
  handleQuery()
}

/** 新增按钮操作 */
function handleAdd(row) {
  reset()
  getTreeselect()
  //处理学校
  getSchools(row)
  if (row != null && row.agentId) {
    form.value.parentId = row.agentId
  } else {
    form.value.parentId = 0
  }
  open.value = true
  title.value = "添加机构代理"
}

/** 展开/折叠操作 */
function toggleExpandAll() {
  refreshTable.value = false
  isExpandAll.value = !isExpandAll.value
  nextTick(() => {
    refreshTable.value = true
  })
}

/** 设置表格行样式 */
function getRowStyle({ row }) {
  if (row.parentId != null && row.parentId !== 0) {
    return {
      backgroundColor: '#C4E7F8'
    }
  }
  return {}
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset()
  await getTreeselect()
  if (row != null) {
    form.value.parentId = row.parentId
  }
  getAgent(row.agentId).then(response => {
    form.value = response.data
    //处理学校
    getSchools(row)

    open.value = true
    title.value = "修改机构代理"
  })
}

function getSchools(row){
    //处理学校
    const deptId = row.deptId;
    listAllSchool(deptId).then(response => {
        schoolOptions.value= response.data
    })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["agentRef"].validate(valid => {
    if (valid) {
      if (form.value.agentId != null) {
        updateAgent(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addAgent(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除机构代理编号为"' + row.agentId + '"的数据项？').then(function() {
    return delAgent(row.agentId)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

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

/** 用户状态修改  */
function handleStatusChange(row) {
  let text = row.status === "0" ? "启用" : "禁用"
  proxy.$modal.confirm('确认要"' + text + '""' + row.name + '"用户吗?').then(function () {
    return changeUserStatus(row.userId, row.status)
  }).then(() => {
    proxy.$modal.msgSuccess(text + "成功")
  }).catch(function () {
    row.status = row.status === "0" ? "1" : "0"
  })
}

// getList()

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