<template>
  <div class="manager-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="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="subsystem">
          <el-select
            v-model="formData.subsystem"
            placeholder="请选择子系统"
            clearable
            style="width: 100%"
          >
            <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="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="responsible">
          <el-select
            v-model="formData.responsible"
            placeholder="请输入责任人姓名进行搜索"
            style="width: 100%"
            clearable
            :disabled="!formData.selectDeptId"
            filterable
            remote
            reserve-keyword
            :remote-method="handleRemoteSearch"
            :loading="userLoading"
            class="handler-select"
            @change="handleResponsibleChange"
          >
            <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'
import { getUserId } from '@/utils'
export default {
  name: 'ManagerData',
  data() {
    return {
      tableData: [],
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      dialogVisible: false,
      dialogMode: 'add', // 'add' 或 'edit'
      currentEditIndex: -1,
      formData: {
        department: '', // 级联选择器绑定的部门ID
        subsystem: '', // 子系统
        responsible: '', // 责任人用户ID（用于提交）
        responsibleName: '', // 责任人姓名（用于自动完成显示）
        selectDeptId: '', // 选中的部门ID（用于搜索责任人）
        selectDeptName: '', // 选中的部门名称（用于提交）
        userId: '', // 用户ID（编辑时使用）
        rowId: '', // 行ID（编辑时使用）
        departmentId: '' // 部门ID（编辑时使用）
      },
      formRules: {
        department: [
          { required: true, message: '请选择责任部门', trigger: 'change' }
        ],
        subsystem: [
          { required: true, message: '请输入子系统', trigger: 'blur' }
        ],
        responsible: [
          { required: true, message: '请选择责任人', trigger: 'change' }
        ]
      },
      subsystemList: [],
      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) {
      this.$refs.departmentTree.filter(val)
    }
  },
  mounted() {
    this.loadDepartmentList()
    this.loadManagerData()
    this.isResponsible()
    this.loadSubsystemList()
  },
  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)
        })
    },
    isResponsible() {
      const userId = getUserId()
      if (!userId) {
        console.error('无法获取用户ID')
        return
      }
      const request = {
        ...api.IS_RESPONSIBLE,
        params: {
          userId: userId
        },
        disableSuccessMsg: true
      }
      this.$request(request)
        .asyncThen((resp) => {
          console.log(resp)
          if (resp && resp.data) {
            if (resp.data) {
              this.isResponsible = true
            } else {
              this.isResponsible = false
            }
            localStorage.setItem('isResponsible', this.isResponsible)
          } else {
            this.isResponsible = false
          }
        })
        .asyncErrorCatch((err) => {
          console.error('判断是否是责任人失败:', err)
        })
    },
    loadManagerData() {
      const request = {
        ...api.GET_MANAGER_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: '',
        responsible: '',
        responsibleName: '',
        selectDeptId: '',
        selectDeptName: '',
        userId: '',
        rowId: '',
        departmentId: ''
      }
      this.userOptions = []
      this.userLoading = false
      this.dialogVisible = true
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.clearValidate()
        }
      })
    },
    handleEdit(row) {
      this.dialogMode = 'edit'
      // 设置表单数据，确保级联选择器和选择器能正确回显
      // 初始化已选择的人员选项
      if (row.userId) {
        this.userOptions = [{
          userId: row.userId,
          username: row.username || row.userId,
          userNumber: row.userNumber || row.userId
        }]
      } else {
        this.userOptions = []
      }
      // 设置表单数据，确保级联选择器和选择器能正确回显
      this.formData = {
        department: row.departmentId || '', // 级联选择器需要部门ID
        subsystem: row.subsystem || '', // 子系统
        responsible: row.userNumber || row.userId || '', // 责任人 userNumber（用于 el-select 的 value）
        responsibleName: 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: '',
        responsible: '',
        responsibleName: '',
        selectDeptId: '',
        selectDeptName: '',
        userId: '',
        rowId: '',
        departmentId: ''
      }
      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.dialogMode === 'add') {
            // 新增
            const request = {
              ...api.SAVE_MANAGER_DATA,
              params: {
                departmentId: this.formData.selectDeptId,
                department: this.formData.selectDeptName,
                subsystem: Array.isArray(this.formData.subsystem) ? this.formData.subsystem.join(',') : this.formData.subsystem,
                userId: this.formData.userId || this.formData.responsible
              }
            }
            this.$request(request)
            this.loadManagerData()
          } else {
            // 修改
            const request = {
              ...api.EDIT_MANAGER_DATA,
              params: {
                departmentId: this.formData.selectDeptId,
                department: this.formData.selectDeptName,
                subsystem: Array.isArray(this.formData.subsystem) ? this.formData.subsystem.join(',') : this.formData.subsystem,
                userId: this.formData.responsible,
                rowId: this.formData.rowId
              }
            }
            this.$request(request)
              .asyncThen((resp) => {
                // this.$message.success('修改成功')
                this.handleDialogClose()
                // 刷新列表数据
                this.loadManagerData()
              })
              .asyncErrorCatch((err) => {
                console.error('修改失败:', err)
                this.$message.error('修改失败')
              })
          }
          this.handleDialogClose()
          // 刷新列表数据
          this.loadManagerData()
        }
      })
    },
    // 打开部门选择弹窗
    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.responsible = ''
        this.formData.responsibleName = ''
        this.formData.userId = ''
        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 (!this.formData.selectDeptId) {
        this.userOptions = []
        return
      }

      // 如果查询为空，保留已选择的人员信息
      if (!query || query.trim() === '') {
        if (this.formData.responsible) {
          // 从现有 options 中查找已选择的人员信息
          const selectedOptions = this.userOptions.filter((opt) => opt.userNumber === this.formData.responsible)
          this.userOptions = selectedOptions
        } else {
          this.userOptions = []
        }
        return
      }

      this.userLoading = true
      const trimmedQuery = query.trim()

      // const request = {
      //   ...api.SELECT_USER_BY_DEPT,
      //   params: {
      //     departmentId: this.formData.selectDeptId,
      //     key: trimmedQuery
      //   },
      //   disableSuccessMsg: true
      // }
      const request = {
        ...api.GET_ALLUSERS,
        params: {
          name: trimmedQuery
        },
        disableSuccessMsg: true
      }

      this.$request(request)
        .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 的数据

          // 获取已选择的 userNumber
          const selectedUserNumber = this.formData.responsible

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

          // 去重：使用 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
        })
        .asyncErrorCatch((err) => {
          console.error('搜索责任人失败:', err)
          // 搜索失败时，保留已选择的人员信息
          if (this.formData.responsible) {
            const selectedOptions = this.userOptions.filter((opt) => opt.userNumber === this.formData.responsible)
            this.userOptions = selectedOptions
          } else {
            this.userOptions = []
          }
          this.userLoading = false
        })
    },
    // 处理责任人选择变化
    handleResponsibleChange(selectedUserNumber) {
      // selectedUserNumber 是选中的 userNumber
      // v-model 已经自动更新了 formData.responsible
      // 更新 responsibleName 用于显示
      if (selectedUserNumber) {
        const selectedOption = this.userOptions.find((opt) => opt.userNumber === selectedUserNumber)
        if (selectedOption) {
          this.formData.responsibleName = selectedOption.username
          // 同时更新 userId（用于提交）
          this.formData.userId = selectedOption.userId
        }
      } else {
        this.formData.responsibleName = ''
        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.loadManagerData()
            })
            .asyncErrorCatch((err) => {
              console.error('删除失败:', err)
              this.$message.error('删除失败')
            })
        })
        .catch(() => {
          // 取消删除
        })
    },
    // 处理每页条数变化
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.pagination.currentPage = 1 // 重置到第一页
      this.loadManagerData()
    },
    // 处理当前页变化
    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.loadManagerData()
    },
    // 处理刷新
    handleRefresh() {
      this.pagination.currentPage = 1
      this.loadManagerData()
    },
    // 格式化部门显示：只显示最后一个节点
    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>
.manager-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;
}
.handler-select {
  width: 100%;
}
.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;
  margin-right: 30px;
  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>
