<template>
  <div class="filler-data-page custom-page">
    <div class="page-content">
      <div class="header-section">
        <el-button type="primary" @click="handleAdd">
          新增
        </el-button>
      </div>

      <div class="table-section">
        <div class="table-toolbar">
          <el-button icon="el-icon-refresh" size="small" @click="handleRefresh">
            刷新
          </el-button>
        </div>
        <el-table :data="tableData" border style="width: 100%">
          <el-table-column type="index" label="序号" width="90" align="center" />
          <el-table-column prop="department" label="责任部门" align="center">
            <template slot-scope="scope">
              {{ formatDepartmentDisplay(scope.row.department) }}
            </template>
          </el-table-column>
          <el-table-column prop="subsystem" label="子系统" align="center" />
          <el-table-column prop="partsName" label="零部件名称" align="center" />
          <el-table-column prop="username" label="填写人" width="250" align="center" />
          <el-table-column label="操作" width="200" align="center">
            <template slot-scope="scope">
              <a
                href="javascript:void(0)"
                class="el-link el-link--primary"
                @click.stop="handleEdit(scope.row)"
              >
                修改
              </a>
              <span class="link-separator"></span>
              <a
                href="javascript:void(0)"
                class="el-link el-link--primary"
                @click.stop="handleDelete(scope.row, scope.$index)"
              >
                删除
              </a>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-section">
          <el-pagination
            :current-page="pagination.currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pagination.pageSize"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="500px"
      :close-on-click-modal="false"
      :modal="false"
      @close="handleDialogClose"
    >
      <el-form ref="form" :model="formData" :rules="formRules" label-width="100px">
        <el-form-item label="责任部门:" prop="department">
          <el-input
            v-model="formData.selectDeptName"
            placeholder="请选择责任部门"
            readonly
            style="width: 100%"
            @click.native="handleOpenDepartmentDialog"
          >
            <i
              slot="suffix"
              class="el-input__icon el-icon-search"
              style="cursor: pointer;"
              @click.stop="handleOpenDepartmentDialog"
            ></i>
          </el-input>
        </el-form-item>
        <el-form-item label="子系统:" prop="subsystem">
          <el-select
            v-model="formData.subsystem"
            placeholder="请选择子系统"
            clearable
            style="width: 100%"
            @change="handleSubsystemChange"
          >
            <el-option
              v-for="item in subsystemList"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="零部件名称:" prop="partsName">
          <el-select
            v-model="formData.partsName"
            placeholder="请选择零部件名称"
            clearable
            style="width: 100%"
            :disabled="!formData.subsystem"
          >
            <el-option
              v-for="item in partsNameList"
              :key="item"
              :label="item === '/' ? '/' : item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="填写人:" prop="filler">
          <el-select
            v-model="formData.filler"
            placeholder="请输入填写人姓名进行搜索"
            style="width: 100%"
            clearable
            multiple
            filterable
            remote
            reserve-keyword
            :remote-method="handleRemoteSearch"
            :loading="userLoading"
            class="handler-select"
            @change="handleFillerChange"
          >
            <el-option
              v-for="person in userOptions"
              :key="person.userNumber"
              :value="person.userId"
              :label="person.username"
            >
              <span class="username-text">{{ person.username }}</span>
              <span class="user-id-text">{{ person.userNumber }}</span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleDialogClose">
          取消
        </el-button>
        <el-button type="primary" @click="handleSubmit">
          确定
        </el-button>
      </div>
    </el-dialog>

    <!-- 部门选择弹窗 -->
    <el-dialog
      title="选择责任部门"
      :visible.sync="departmentDialogVisible"
      width="500px"
      :close-on-click-modal="false"
      append-to-body
      @close="handleDepartmentDialogClose"
    >
      <el-input
        v-model="departmentTreeFilterText"
        size="small"
        placeholder="请输入部门名称进行搜索"
        clearable
        class="department-tree-search"
      >
        <i slot="prefix" class="el-input__icon el-icon-search"></i>
      </el-input>
      <el-tree
        ref="departmentTree"
        :data="departmentList"
        :props="{ children: 'children', label: 'name' }"
        node-key="id"
        :filter-node-method="filterDepartmentNode"
        highlight-current
        :expand-on-click-node="false"
        class="department-tree"
        @node-click="handleDepartmentNodeClick"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleDepartmentDialogClose">
          取消
        </el-button>
        <el-button type="primary" :disabled="!selectedDepartmentId" @click="handleDepartmentDialogConfirm">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import api from '@/api'
export default {
  name: 'FillerData',
  data() {
    return {
      tableData: [],
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      dialogVisible: false,
      dialogMode: 'add', // 'add' 或 'edit'
      currentEditIndex: -1,
      formData: {
        department: '', // 部门ID（用于表单验证）
        subsystem: '', // 子系统（单选，字符串）
        partsName: '', // 零部件名称（单选，字符串）
        filler: [], // 填写人用户ID数组（多选，用于提交）
        fillerName: '', // 填写人姓名（用于自动完成显示）
        selectDeptId: '', // 选中的部门ID（用于搜索填写人）
        selectDeptName: '', // 选中的部门名称（用于提交）
        userId: '', // 用户ID（编辑时使用）
        rowId: '', // 行ID（编辑时使用）
        departmentId: '' // 部门ID（编辑时使用）
      },
      formRules: {
        department: [{ required: true, message: '请选择责任部门', trigger: 'change' }],
        subsystem: [{ required: true, message: '请选择子系统', trigger: 'change' }],
        partsName: [{ required: true, message: '请选择零部件名称', trigger: 'change' }],
        filler: [{ required: true, message: '请选择填写人', trigger: 'change' }]
      },
      subsystemList: [],
      partsNameList: [], // 零部件名称列表
      allParametersData: {}, // 所有参数数据（用于获取零部件名称）
      fillerPersons: [],
      userOptions: [], // 人员选项列表
      userLoading: false, // 人员搜索加载状态
      departmentList: [],
      searchTimer: null, // 防抖定时器
      currentRequest: null, // 当前请求引用
      departmentDialogVisible: false, // 部门选择弹窗显示状态
      departmentTreeFilterText: '', // 部门树搜索文本
      selectedDepartmentId: '', // 选中的部门ID
      selectedDepartmentName: '', // 选中的部门名称
      selectedDepartmentNode: null // 选中的部门节点
    }
  },
  computed: {
    dialogTitle() {
      return this.dialogMode === 'add' ? '新增' : '修改'
    }
  },
  watch: {
    departmentTreeFilterText(val) {
      if (this.$refs.departmentTree) {
        this.$refs.departmentTree.filter(val)
      }
    }
  },
  mounted() {
    this.loadDepartmentList()
    this.loadFillerData()
    this.loadSubsystemList()
    this.loadAllParametersData()
  },
  beforeDestroy() {
    // 清理定时器和请求
    if (this.searchTimer) {
      clearTimeout(this.searchTimer)
      this.searchTimer = null
    }
    this.currentRequest = null
  },
  methods: {
    loadSubsystemList() {
      const request = {
        ...api.GET_SUBSYSTEM_LIST,
        disableSuccessMsg: true
      }
      this.$request(request)
        .asyncThen((resp) => {
          console.log(resp)
          if (resp && resp.data) {
            this.subsystemList = resp.data
          } else {
            this.subsystemList = []
          }
        })
        .asyncErrorCatch((err) => {
          console.error('加载子系统列表失败:', err)
        })
    },
    // 加载所有参数数据（用于获取零部件名称）
    loadAllParametersData() {
      const request = {
        ...api.GET_ALL_DATA_SYSTEAM_LIST,
        disableSuccessMsg: true
      }
      this.$request(request)
        .asyncThen((resp) => {
          if (resp && resp.data) {
            // 处理返回的数据，将数组格式转换为对象格式
            // 输入格式: [{ subsystem: "子系统名称", parameters: [{ parameterId, parameterName, partsName }] }]
            // 输出格式: { "子系统名称": [{ parameterId, parameterName, partsName, subsystem }] }
            const result = {}
            if (Array.isArray(resp.data)) {
              resp.data.forEach(item => {
                if (item.subsystem && Array.isArray(item.parameters)) {
                  result[item.subsystem] = item.parameters.map(param => ({
                    parameterId: param.parameterId || '',
                    parameterName: param.parameterName || '',
                    partsName: param.partsName || '',
                    subsystem: item.subsystem
                  }))
                }
              })
            }
            this.allParametersData = result
          } else {
            this.allParametersData = {}
          }
        })
        .asyncErrorCatch((err) => {
          console.error('获取所有参数数据失败:', err)
          this.allParametersData = {}
        })
    },
    // 处理子系统选择变化
    handleSubsystemChange(value) {
      // 清空零部件名称选择
      this.formData.partsName = ''
      // 根据选择的子系统加载对应的零部件名称列表
      if (value && this.allParametersData[value]) {
        const paramList = this.allParametersData[value]
        // 提取所有唯一的零部件名称（去重）
        const partsNameSet = new Set()
        paramList.forEach(param => {
          const partsName = param.partsName || ''
          if (partsName) {
            partsNameSet.add(partsName)
          }
        })
        // 转换为数组并排序
        this.partsNameList = Array.from(partsNameSet).sort()
      } else {
        this.partsNameList = []
      }
    },
    loadFillerData() {
      const request = {
        ...api.GET_FILLER_DATA,
        params: {
          pageNumber: this.pagination.currentPage,
          pageSize: this.pagination.pageSize
        },
        disableSuccessMsg: true
      }
      this.$request(request)
        .asyncThen((resp) => {
          // 处理返回数据，支持不同的数据结构
          if (resp && resp.data) {
            this.tableData = resp.data.result
            // 如果返回对象中有 total 字段
            this.pagination.total = resp.data.count
          } else {
            this.tableData = []
            this.pagination.total = 0
          }
        })
        .asyncErrorCatch((err) => {
          console.error('加载填写人数据失败:', err)
          this.tableData = []
          this.pagination.total = 0
        })
    },
    loadDepartmentList() {
      const request = {
        ...api.QUERY_ORG_TREE,
        // params: {
        //   departmentId: this.formData.departmentId
        // },
        disableSuccessMsg: true
      }
      this.$request(request)
        .asyncThen((resp) => {
          // 处理返回的数据，确保格式为 { id, name, children }
          let result = []
          if (resp && resp.data) {
            result = resp.data.result || resp.data.data || resp.data || []
          }
          // 格式化数据为树形结构格式
          this.departmentList = this.formatDepartmentTreeData(result)
        })
        .asyncErrorCatch((err) => {
          console.error('加载部门列表失败:', err)
          this.departmentList = []
        })
    },
    // 格式化部门树数据为树形结构格式
    formatDepartmentTreeData(data) {
      if (!Array.isArray(data)) {
        return []
      }

      // 递归格式化数据，确保每个节点都有 id 和 name 字段
      const formatNode = (node) => {
        const formatted = {
          id: node.id,
          name: node.name || node.label || '',
          children: undefined
        }

        // 如果有子节点，递归格式化
        if (node.children && Array.isArray(node.children) && node.children.length > 0) {
          formatted.children = node.children.map((child) => formatNode(child))
        }

        return formatted
      }

      return data.map((node) => formatNode(node))
    },
    handleAdd() {
      this.dialogMode = 'add'
      this.currentEditIndex = -1
      this.formData = {
        department: '',
        subsystem: '', // 子系统改为单选，字符串
        partsName: '', // 零部件名称（单选，字符串）
        filler: [], // 填写人改为多选，数组
        fillerName: '',
        selectDeptId: '',
        selectDeptName: '',
        userId: '',
        rowId: '',
        departmentId: ''
      }
      this.partsNameList = []
      this.fillerPersons = []
      this.userOptions = []
      this.userLoading = false
      this.dialogVisible = true
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.clearValidate()
        }
      })
    },
    handleEdit(row) {
      this.dialogMode = 'edit'
      // 设置表单数据，确保级联选择器和选择器能正确回显
      // 初始化已选择的人员选项
      // 编辑时，如果 row.userId 是字符串，转换为数组；如果是数组，直接使用
      let userIds = []
      if (row.userId) {
        if (Array.isArray(row.userId)) {
          userIds = row.userId
        } else if (typeof row.userId === 'string' && row.userId.includes(',')) {
          userIds = row.userId.split(',').map(id => id.trim()).filter(id => id)
        } else {
          userIds = [row.userId]
        }
      }

      // 如果有用户ID，初始化用户选项（需要从接口获取用户信息，这里先使用已有数据）
      if (userIds.length > 0) {
        // 如果 row 中有用户信息，使用它；否则需要从接口获取
        this.userOptions = userIds.map(userId => {
          // 尝试从 row 中获取用户信息（如果 row 中有多个用户的信息）
          return {
            userId: userId,
            username: row.username || userId,
            userNumber: row.userNumber || userId
          }
        })
      } else {
        this.userOptions = []
      }

      // 设置表单数据，确保级联选择器和选择器能正确回显
      // 子系统改为单选：如果 row.subsystem 是逗号分隔的字符串，取第一个；如果是数组，取第一个元素
      let subsystemValue = ''
      if (row.subsystem) {
        if (Array.isArray(row.subsystem)) {
          subsystemValue = row.subsystem[0] || ''
        } else if (typeof row.subsystem === 'string') {
          const subsystems = row.subsystem.split(',').map(s => s.trim()).filter(s => s)
          subsystemValue = subsystems[0] || ''
        }
      }

      // 加载该子系统下的零部件名称列表
      if (subsystemValue && this.allParametersData[subsystemValue]) {
        const paramList = this.allParametersData[subsystemValue]
        const partsNameSet = new Set()
        paramList.forEach(param => {
          const partsName = param.partsName || ''
          if (partsName) {
            partsNameSet.add(partsName)
          }
        })
        this.partsNameList = Array.from(partsNameSet).sort()
      } else {
        this.partsNameList = []
      }

      this.formData = {
        department: row.departmentId || '', // 部门ID（用于表单验证）
        subsystem: subsystemValue, // 子系统改为单选，字符串
        partsName: row.partsName || '', // 零部件名称
        filler: userIds, // 填写人改为多选，数组
        fillerName: row.username || '', // 填写人姓名（用于显示）
        selectDeptId: row.departmentId || '', // 选中的部门ID（用于搜索填写人）
        selectDeptName: row.department || '', // 选中的部门名称（用于提交）
        userId: row.userId || '', // 用户ID（用于提交，保留原始值）
        rowId: row.rowId || '',
        departmentId: row.departmentId || ''
      }
      this.userLoading = false
      this.dialogVisible = true
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.clearValidate()
        }
      })
    },
    handleDialogClose() {
      this.dialogVisible = false
      this.formData = {
        department: '',
        subsystem: '', // 子系统改为单选，字符串
        partsName: '', // 零部件名称（单选，字符串）
        filler: [], // 填写人改为多选，数组
        fillerName: '',
        selectDeptId: '',
        selectDeptName: '',
        userId: '',
        rowId: '',
        departmentId: ''
      }
      this.partsNameList = []
      this.fillerPersons = []
      this.userOptions = []
      this.userLoading = false
      this.currentEditIndex = -1
      // 清除定时器和请求
      if (this.searchTimer) {
        clearTimeout(this.searchTimer)
        this.searchTimer = null
      }
      this.currentRequest = null
      if (this.$refs.form) {
        this.$refs.form.clearValidate()
      }
    },
    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 验证填写人是否已选择
          if (!this.formData.filler || !Array.isArray(this.formData.filler) || this.formData.filler.length === 0) {
            this.$message.warning('请至少选择一个填写人')
            return
          }

          // 子系统改为单选，直接使用字符串
          const subsystem = this.formData.subsystem || ''
          // 零部件名称
          const partsName = this.formData.partsName || ''

          if (this.dialogMode === 'add') {
            // 新增：为每个填写人创建一条记录
            const userIds = Array.isArray(this.formData.filler) ? this.formData.filler : [this.formData.filler]
            const requests = userIds.map(userId => {
              return this.$request({
                ...api.SAVE_FILLER_DATA,
                params: {
                  departmentId: this.formData.selectDeptId,
                  department: this.formData.selectDeptName,
                  subsystem: subsystem,
                  partsName: partsName,
                  userId: userId
                },
                disableSuccessMsg: true
              })
            })

            // 等待所有请求完成
            Promise.all(requests)
              .then(() => {
                // this.$message.success('新增成功')
                this.handleDialogClose()
                this.loadFillerData()
              })
              .catch((err) => {
                console.error('新增失败:', err)
                this.$message.error('新增失败，请重试')
              })
          } else {
            // 修改：由于编辑时只能修改一条记录，这里只处理第一个填写人
            // 如果需要支持修改多个填写人，可能需要先删除旧记录再新增，或者使用其他接口
            const userId = Array.isArray(this.formData.filler) && this.formData.filler.length > 0
              ? this.formData.filler[0]
              : this.formData.filler

            const request = {
              ...api.EDIT_MANAGER_DATA,
              params: {
                departmentId: this.formData.selectDeptId,
                department: this.formData.selectDeptName,
                subsystem: subsystem,
                partsName: partsName,
                userId: userId,
                rowId: this.formData.rowId
              }
            }
            this.$request(request)
              .asyncThen((resp) => {
                // this.$message.success('修改成功')
                this.handleDialogClose()
                // 刷新列表数据
                this.loadFillerData()
              })
              .asyncErrorCatch((err) => {
                console.error('修改失败:', err)
                this.$message.error('修改失败')
              })
          }
        }
      })
    },
    // 打开部门选择弹窗
    handleOpenDepartmentDialog() {
      // 如果有已选择的部门，设置树的高亮
      if (this.formData.selectDeptId) {
        this.selectedDepartmentId = this.formData.selectDeptId
        this.selectedDepartmentName = this.formData.selectDeptName
        this.$nextTick(() => {
          if (this.$refs.departmentTree) {
            this.$refs.departmentTree.setCurrentKey(this.formData.selectDeptId)
          }
        })
      } else {
        this.selectedDepartmentId = ''
        this.selectedDepartmentName = ''
      }
      this.departmentTreeFilterText = ''
      this.departmentDialogVisible = true
    },
    // 关闭部门选择弹窗
    handleDepartmentDialogClose() {
      this.departmentDialogVisible = false
      this.departmentTreeFilterText = ''
      // 如果取消，恢复之前的选择
      if (this.formData.selectDeptId) {
        this.selectedDepartmentId = this.formData.selectDeptId
        this.selectedDepartmentName = this.formData.selectDeptName
      } else {
        this.selectedDepartmentId = ''
        this.selectedDepartmentName = ''
        this.selectedDepartmentNode = null
      }
    },
    // 确认选择部门
    handleDepartmentDialogConfirm() {
      if (this.selectedDepartmentId && this.selectedDepartmentNode) {
        // 更新表单数据
        this.formData.selectDeptId = this.selectedDepartmentId
        this.formData.selectDeptName = this.selectedDepartmentName
        this.formData.department = this.selectedDepartmentId
        // 清空填写人选择（改为数组）
        this.formData.filler = []
        this.formData.fillerName = ''
        this.userOptions = []
        // 关闭弹窗
        this.departmentDialogVisible = false
        // 清除表单验证错误
        this.$nextTick(() => {
          if (this.$refs.form) {
            this.$refs.form.clearValidate('department')
          }
        })
      }
    },
    // 处理部门树节点点击
    handleDepartmentNodeClick(data) {
      this.selectedDepartmentId = data.id
      this.selectedDepartmentName = this.getDepartmentPathName(data.id)
      this.selectedDepartmentNode = data
    },
    // 过滤部门树节点
    filterDepartmentNode(value, data) {
      if (!value) return true
      return (data.name || '').toLowerCase().includes(value.toLowerCase())
    },
    // 远程搜索填写人（用于 el-select）
    handleRemoteSearch(query) {
      // 如果查询为空，保留已选择的人员信息
      if (!query || query.trim() === '') {
        if (this.formData.filler && Array.isArray(this.formData.filler) && this.formData.filler.length > 0) {
          // 从现有 options 中查找所有已选择的人员信息（多选）
          const selectedUserIds = new Set(this.formData.filler)
          const selectedOptions = this.userOptions.filter((opt) => opt.userId && selectedUserIds.has(opt.userId))
          this.userOptions = selectedOptions
        } else {
          this.userOptions = []
        }
        return
      }

      // 清除之前的定时器
      if (this.searchTimer) {
        clearTimeout(this.searchTimer)
      }

      // 使用防抖，延迟300ms执行
      this.searchTimer = setTimeout(() => {
        const trimmedQuery = query.trim()
        if (!trimmedQuery) {
          this.userOptions = []
          return
        }

        this.userLoading = true
        const request = {
          ...api.GET_ALLUSERS,
          params: {
            name: trimmedQuery
          },
          disableSuccessMsg: true
        }

        // 保存当前请求引用
        this.currentRequest = this.$request(request)
        this.currentRequest
          .asyncThen((resp) => {
            const respData = resp && resp.data
            let result = []
            if (Array.isArray(respData)) {
              result = respData
            } else if (respData && Array.isArray(respData.result)) {
              result = respData.result
            } else if (respData && respData.data && Array.isArray(respData.data)) {
              result = respData.data
            }
            // 转换为选项格式：{userId: user.userId, username: user.username, userNumber: user.userNumber}
            const users = result
              .map((user) => ({
                userId: user.userId || user.id,
                username: user.username || user.name,
                userNumber: user.userNumber || user.userId || user.id
              }))
              .filter((user) => user.userId && user.userNumber) // 过滤掉没有 userId 或 userNumber 的数据

            // 获取已选择的 userId 数组（多选）
            const selectedUserIds = Array.isArray(this.formData.filler) ? this.formData.filler : []
            const selectedUserIdsSet = new Set(selectedUserIds)

            // 合并：已选择的人员信息（从现有 options 中获取）+ 新的搜索结果
            const selectedOptions = this.userOptions.filter(
              (opt) => opt.userId && selectedUserIdsSet.has(opt.userId)
            )

            // 去重：使用 Map 确保每个 userNumber 只出现一次
            const optionsMap = new Map()
            // 先添加已选择的选项
            selectedOptions.forEach((opt) => {
              if (opt.userNumber) {
                optionsMap.set(opt.userNumber, opt)
              }
            })
            // 再添加新的搜索结果
            users.forEach((user) => {
              if (user.userNumber && !optionsMap.has(user.userNumber)) {
                optionsMap.set(user.userNumber, user)
              }
            })
            this.userOptions = Array.from(optionsMap.values())
            this.userLoading = false
            this.currentRequest = null
          })
          .asyncErrorCatch((err) => {
            console.error('搜索填写人失败:', err)
            // 搜索失败时，保留已选择的人员信息（多选）
            if (this.formData.filler && Array.isArray(this.formData.filler) && this.formData.filler.length > 0) {
              const selectedUserIdsSet = new Set(this.formData.filler)
              const selectedOptions = this.userOptions.filter((opt) => opt.userId && selectedUserIdsSet.has(opt.userId))
              this.userOptions = selectedOptions
            } else {
              this.userOptions = []
            }
            this.userLoading = false
            this.currentRequest = null
          })
      }, 300)
    },
    // 处理填写人选择变化
    handleFillerChange(selectedUserIds) {
      // selectedUserIds 是选中的 userId 数组（多选）
      // v-model 已经自动更新了 formData.filler
      // 更新 fillerName 用于显示（显示所有选中用户的姓名，用逗号分隔）
      if (selectedUserIds && Array.isArray(selectedUserIds) && selectedUserIds.length > 0) {
        const selectedNames = selectedUserIds.map(userId => {
          const selectedOption = this.userOptions.find((opt) => opt.userId === userId)
          return selectedOption ? selectedOption.username : userId
        }).filter(name => name)
        this.formData.fillerName = selectedNames.join(', ')
        // userId 字段保留为数组格式，用于提交
        this.formData.userId = selectedUserIds
      } else {
        this.formData.fillerName = ''
        this.formData.userId = []
      }
    },
    // 根据部门id获取部门路径名称（用-连接）
    getDepartmentPathName(deptId) {
      if (!deptId || !this.departmentList || this.departmentList.length === 0) {
        return ''
      }

      // 递归查找部门节点及其路径
      const findNodePath = (nodes, targetId, path = []) => {
        for (const node of nodes) {
          const currentPath = [...path, node.name]

          if (node.id === targetId) {
            return currentPath
          }

          if (node.children && node.children.length > 0) {
            const found = findNodePath(node.children, targetId, currentPath)
            if (found) {
              return found
            }
          }
        }
        return null
      }

      const path = findNodePath(this.departmentList, deptId)
      return path ? path.join('-') : ''
    },
    handleDelete(row, index) {
      this.$confirm('确定要删除该记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const request = {
            ...api.DELETE_MANAGER_DATA,
            params: {
              rowId: row.rowId
            }
          }
          this.$request(request)
            .asyncThen((resp) => {
              // this.$message.success('删除成功')
              // 刷新列表数据
              this.loadFillerData()
            })
            .asyncErrorCatch((err) => {
              console.error('删除失败:', err)
              this.$message.error('删除失败')
            })
        })
        .catch(() => {
          // 取消删除
        })
    },
    // 处理每页条数变化
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.pagination.currentPage = 1 // 重置到第一页
      this.loadFillerData()
    },
    // 处理当前页变化
    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.loadFillerData()
    },
    // 处理刷新
    handleRefresh() {
      this.pagination.currentPage = 1
      this.loadFillerData()
    },
    // 格式化部门显示：只显示最后一个节点
    formatDepartmentDisplay(department) {
      if (!department) {
        return '平台部'
      }
      // 将 · 替换为 -
      const normalizedDept = department.replace(/·/g, '-')
      // 按 - 分割
      const parts = normalizedDept.split('-').filter(part => part.trim() !== '')
      // 只显示最后一个节点
      if (parts.length > 0) {
        return parts[parts.length - 1]
      }
      // 否则显示全部
      return normalizedDept
    }
  }
}
</script>

<style lang="scss" scoped>
.filler-data-page {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 20px;
  background: #fff;

  .page-content {
    display: flex;
    flex-direction: column;
    gap: 16px;
  }

  .header-section {
    display: flex;
    align-items: center;
    gap: 12px;

    .comment-text {
      color: #909399;
      font-size: 14px;
    }
  }

  .table-section {
    width: 100%;

    .table-toolbar {
      display: flex;
      justify-content: flex-end;
      margin-bottom: 12px;
    }
  }

  .pagination-section {
    margin-top: 16px;
    display: flex;
    justify-content: flex-end;
  }

  .link-separator {
    margin: 0 8px;
    color: #dcdfe6;
  }

  .footer-comment {
    margin-top: 16px;

    .red-comment {
      color: #f56c6c;
      font-size: 14px;
    }
  }
}
::v-deep .el-popper {
  width: auto !important;
}
.page-content {
  width: calc(100% - 80px) !important;
}
.el-select-dropdown__item {
  display: flex !important;
  justify-content: space-between !important;
  padding-right: 20px !important;
}
.username-text {
  color: #303133 !important;
  display: inline-block;
  text-align: right !important;
}
.user-id-text {
  color: #909399 !important;
  display: inline-block;
  margin-left: 20px;
  text-align: right !important;
}
.department-tree-search {
  margin-bottom: 16px;
}
.department-tree {
  max-height: 400px;
  overflow-y: auto;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 8px;
}
</style>
