<!--
 * @Description: 批量修改责任人弹窗
-->
<template>
  <div>
    <x-modal
      :append-to-body="true"
      :destroy-on-close="true"
      :modalVisible.sync="visible"
      :wrapper-class="'batch-modify-responsible-modal'"
      :title="modalTitle"
      :width="600"
    >
      <div class="batch-modify-content">
        <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%"
              @change="handleSubsystemChange"
            >
              <el-option
                v-for="item in subsystemList"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item v-if="dispatchType === 'update_param'" label="零部件名称:" prop="partsName">
            <el-select
              v-model="formData.partsName"
              placeholder="请选择零部件名称"
              clearable
              multiple
              style="width: 100%"
              :disabled="!formData.subsystem"
              @change="handlePartsNameChange"
            >
              <el-option
                v-for="item in availablePartsNames"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="部门:" prop="department">
            <el-select
              v-model="formData.department"
              placeholder="请选择部门"
              clearable
              style="width: 100%"
              :disabled="dispatchType === 'update_param' ? (!formData.subsystem || !formData.partsName || !Array.isArray(formData.partsName) || formData.partsName.length === 0) : !formData.subsystem"
              @change="handleDepartmentChange"
            >
              <el-option
                v-for="dept in availableDepartments"
                :key="dept.department"
                :label="formatDepartmentDisplay(dept.department)"
                :value="dept.department"
              />
            </el-select>
          </el-form-item>
          <el-form-item v-if="dispatchType !== 'update_param'" label="现责任人:">
            <el-input
              v-model="formData.currentResponsibleName"
              disabled
              placeholder="暂无责任人"
              readonly
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item :label="dispatchType === 'update_param' ? '人员:' : '责任人:'" prop="userId">
            <el-select
              v-model="formData.userId"
              :placeholder="dispatchType === 'update_param' ? '请输入人员姓名进行搜索' : '请输入责任人姓名进行搜索'"
              style="width: 100%"
              clearable
              :disabled="!formData.department"
              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>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="closeModal">
            取消
          </el-button>
          <el-button type="primary" :loading="submitting" @click="handleSubmit">
            确定
          </el-button>
        </div>
      </template>
    </x-modal>
  </div>
</template>

<script>
import api from '@/api'
export default {
  name: 'BatchModifyResponsibleModal',
  props: {
    responsiblePersons: {
      type: Array,
      default: () => []
    },
    fillerPersons: {
      type: Array,
      default: () => []
    },
    dispatchType: {
      type: String,
      default: 'todo' // 'todo' 表示分发责任人，'update_param' 表示分发填写人
    },
    versionData: {
      type: Object,
      default: () => ({})
    },
    currentVersionId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      visible: false,
      submitting: false,
      formData: {
        subsystem: '',
        partsName: [], // 零部件名称（仅用于批量修改填写人，多选）
        department: '',
        currentResponsibleId: '', // 现责任人的ID（用于判断是新增还是修改）
        currentResponsibleName: '', // 现责任人名称（只读显示）
        currentFillerId: '', // 现填写人的ID（用于判断是新增还是修改）
        currentFillerName: '', // 现填写人名称（只读显示）
        userId: '', // 新责任人的userId（用于 el-select 的 v-model）
        userNumber: '', // 新责任人的userNumber（用于提交）
        username: '', // 新责任人的username（用于显示）
        rowId: '' // 如果有现责任人，用于修改时的rowId
      },
      subsystemList: [],
      availablePartsNames: [], // 根据子系统筛选出的零部件名称列表（仅用于批量修改填写人）
      availableDepartments: [], // 根据子系统筛选出的部门列表
      allManagerData: [], // 所有责任人数据（用于查找现责任人和部门）
      departmentTreeData: [], // 部门树数据（用于根据部门名称查找部门ID）
      userOptions: [], // 人员选项列表
      userLoading: false // 人员搜索loading状态
    }
  },
  computed: {
    modalTitle() {
      return this.dispatchType === 'update_param' ? '批量修改填写人' : '批量修改责任人'
    },
    formRules() {
      const rules = {
        subsystem: [
          { required: true, message: '请选择子系统', trigger: 'change' }
        ],
        userId: [
          { required: true, message: this.dispatchType === 'update_param' ? '请选择人员' : '请选择责任人', trigger: 'change' }
        ]
      }
      // 添加部门验证（两种模式都需要）
      rules.department = [
        { required: true, message: '请选择部门', trigger: 'change' }
      ]
      // 如果是批量修改填写人，添加零部件名称验证
      if (this.dispatchType === 'update_param') {
        rules.partsName = [
          {
            required: true,
            type: 'array',
            min: 1,
            message: '请至少选择一个零部件名称',
            trigger: 'change'
          }
        ]
      }
      return rules
    }
  },
  methods: {
    // 格式化部门显示：只显示最后一个节点
    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
    },
    showModal() {
      // 重置表单数据
      this.formData = {
        subsystem: '',
        partsName: [],
        department: '',
        currentResponsibleId: '',
        currentResponsibleName: '',
        currentFillerId: '',
        currentFillerName: '',
        userId: '',
        userNumber: '',
        username: '',
        rowId: ''
      }
      this.availablePartsNames = []
      this.availableDepartments = []
      this.userOptions = []
      this.userLoading = false
      // 加载子系统列表和部门树数据
      this.loadSubsystemList()
      this.loadDepartmentTree()
      // 如果是批量修改责任人，才加载所有责任人数据（用于查找现责任人）
      if (this.dispatchType !== 'update_param') {
        this.loadAllManagerData()
      }
      this.visible = true
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.clearValidate()
        }
      })
    },
    closeModal() {
      this.visible = false
      this.formData = {
        subsystem: '',
        partsName: [],
        department: '',
        currentResponsibleId: '',
        currentResponsibleName: '',
        currentFillerId: '',
        currentFillerName: '',
        userId: '',
        userNumber: '',
        username: '',
        rowId: ''
      }
      this.availablePartsNames = []
      this.availableDepartments = []
      this.userOptions = []
      this.userLoading = false
    },
    // 加载子系统列表
    loadSubsystemList() {
      const request = {
        ...api.GET_SUBSYSTEM_LIST,
        disableSuccessMsg: true
      }
      this.$request(request)
        .asyncThen((resp) => {
          if (resp && resp.data) {
            this.subsystemList = resp.data
          } else {
            this.subsystemList = []
          }
        })
        .asyncErrorCatch((err) => {
          console.error('加载子系统列表失败:', err)
          this.subsystemList = []
        })
    },
    // 加载所有责任人数据（用于查找现责任人和部门）
    loadAllManagerData() {
      const request = {
        ...api.GET_MANAGER_DATA,
        params: {
          pageNumber: 1,
          pageSize: 9999 // 获取所有数据
        },
        disableSuccessMsg: true
      }
      this.$request(request)
        .asyncThen((resp) => {
          if (resp && resp.data) {
            this.allManagerData = resp.data.result || []
          } else {
            this.allManagerData = []
          }
        })
        .asyncErrorCatch((err) => {
          console.error('加载责任人数据失败:', err)
          this.allManagerData = []
        })
    },
    // 处理子系统选择变化
    handleSubsystemChange(subsystem) {
      // 清空零部件名称、部门和现责任人/现填写人
      this.formData.partsName = []
      this.formData.department = ''
      this.formData.currentResponsibleId = ''
      this.formData.currentResponsibleName = ''
      this.formData.currentFillerId = ''
      this.formData.currentFillerName = ''
      this.formData.rowId = ''
      this.formData.userId = ''
      this.formData.userNumber = ''
      this.formData.username = ''
      this.availablePartsNames = []
      this.availableDepartments = []
      this.userOptions = []
      // 根据子系统筛选零部件名称和部门列表
      if (subsystem) {
        const currentVersionData = this.versionData[this.currentVersionId] || {}
        const partsNameSet = new Set()
        const departmentSet = new Set()

        // 遍历所有零部件名称（partsName）
        Object.keys(currentVersionData).forEach((partsName) => {
          const params = currentVersionData[partsName] || []
          // 遍历该零部件下的所有参数
          params.forEach((param) => {
            // 检查参数是否属于选中的子系统
            if (param.subsystemName === subsystem) {
              // 如果是批量修改填写人，收集零部件名称（包括 /）
              if (this.dispatchType === 'update_param') {
                const paramPartsName = param.partsName || partsName
                if (paramPartsName) {
                  partsNameSet.add(paramPartsName)
                }
              }
              // 收集部门名称（两种模式都需要）
              if (param.department) {
                departmentSet.add(param.department)
              }
            }
          })
        })

        // 如果是批量修改填写人，设置零部件名称列表（添加 / 作为默认项）
        if (this.dispatchType === 'update_param') {
          const partsNamesArray = Array.from(partsNameSet).sort()
          // 如果 / 不在列表中，添加到开头
          if (!partsNamesArray.includes('/')) {
            partsNamesArray.unshift('/')
          }
          this.availablePartsNames = partsNamesArray
          // 对于批量修改填写人，部门列表应该在选择了零部件名称之后才筛选
          this.availableDepartments = []
        } else {
          // 批量修改责任人：设置部门列表（转换为数组格式）
          this.availableDepartments = Array.from(departmentSet).map((dept) => ({
            department: dept
          }))
        }
      } else {
        this.availablePartsNames = []
        this.availableDepartments = []
      }
    },
    // 处理零部件名称选择变化（仅用于批量修改填写人）
    handlePartsNameChange(partsNames) {
      // partsNames 现在是数组
      // 清空部门、现填写人和新填写人
      this.formData.department = ''
      this.formData.currentFillerId = ''
      this.formData.currentFillerName = ''
      this.formData.userId = ''
      this.formData.userNumber = ''
      this.formData.username = ''
      this.availableDepartments = []
      this.userOptions = []
      // 根据子系统和零部件名称筛选部门列表
      if (partsNames && Array.isArray(partsNames) && partsNames.length > 0 && this.formData.subsystem) {
        this.filterDepartmentsByPartsName()
      }
    },
    // 根据子系统和零部件名称筛选部门列表（仅用于批量修改填写人）
    filterDepartmentsByPartsName() {
      if (!this.formData.subsystem || !this.formData.partsName || !Array.isArray(this.formData.partsName) || this.formData.partsName.length === 0) {
        this.availableDepartments = []
        return
      }

      const currentVersionData = this.versionData[this.currentVersionId] || {}
      const departmentSet = new Set()

      // 遍历所有零部件名称（partsName）
      Object.keys(currentVersionData).forEach((dataPartsName) => {
        const params = currentVersionData[dataPartsName] || []
        // 遍历该零部件下的所有参数
        params.forEach((param) => {
          // 检查参数是否属于选中的子系统和任意一个选中的零部件名称
          const paramPartsName = param.partsName || dataPartsName
          if (
            param.subsystemName === this.formData.subsystem &&
            this.formData.partsName.includes(paramPartsName) &&
            param.department
          ) {
            departmentSet.add(param.department)
          }
        })
      })

      // 转换为数组格式
      this.availableDepartments = Array.from(departmentSet).map((dept) => ({
        department: dept
      }))
    },
    // 处理部门选择变化
    handleDepartmentChange(department) {
      // 清空现责任人和新责任人
      this.formData.currentResponsibleId = ''
      this.formData.currentResponsibleName = ''
      this.formData.rowId = ''
      this.formData.userId = ''
      this.formData.userNumber = ''
      this.formData.username = ''
      this.userOptions = []
      // 如果是批量修改填写人，不需要查找现填写人
      if (this.dispatchType === 'update_param') {
        return
      }
      // 根据子系统和部门查找现责任人（仅用于批量修改责任人）
      if (department && this.formData.subsystem) {
        const matchedItem = this.allManagerData.find((item) => {
          // 检查子系统是否匹配
          const itemSubsystems = item.subsystem ? item.subsystem.split(',') : []
          return (
            itemSubsystems.includes(this.formData.subsystem) &&
            item.department === department
          )
        })
        if (matchedItem) {
          // 找到现责任人
          this.formData.currentResponsibleId = matchedItem.userId || matchedItem.userNumber || ''
          this.formData.currentResponsibleName = matchedItem.username || ''
          this.formData.rowId = matchedItem.rowId || ''
        } else {
          // 没有现责任人
          this.formData.currentResponsibleId = ''
          this.formData.currentResponsibleName = ''
          this.formData.rowId = ''
        }
      }
    },
    // 远程搜索责任人/填写人
    handleRemoteSearch(query) {
      // 两种模式都需要检查部门
      if (!this.formData.department) {
        this.userOptions = []
        return
      }
      if (!query || query.trim() === '') {
        if (this.formData.userId) {
          const selectedOptions = this.userOptions.filter((opt) => opt.userId === this.formData.userId)
          this.userOptions = selectedOptions
        } else {
          this.userOptions = []
        }
        return
      }
      this.userLoading = true
      const trimmedQuery = query.trim()
      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
          }
          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
          const selectedUserId = this.formData.userId
          const selectedOptions = this.userOptions.filter(
            (opt) => opt.userId && opt.userId === selectedUserId
          )
          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.userId) {
            const selectedOptions = this.userOptions.filter((opt) => opt.userId === this.formData.userId)
            this.userOptions = selectedOptions
          } else {
            this.userOptions = []
          }
          this.userLoading = false
        })
    },
    // 处理责任人选择变化
    handleResponsibleChange(selectedUserId) {
      if (selectedUserId) {
        const selectedOption = this.userOptions.find((opt) => opt.userId === selectedUserId)
        if (selectedOption) {
          this.formData.userId = selectedOption.userId
          this.formData.userNumber = selectedOption.userNumber || selectedOption.userId
          this.formData.username = selectedOption.username || ''
        } else {
          // 如果 userOptions 中没有找到，可能是选项列表被清空了，但 userId 已经设置
          // 这种情况下，使用 userId 作为 userNumber（降级处理）
          console.warn('未找到选中的用户选项，userId:', selectedUserId)
          this.formData.userId = selectedUserId
          this.formData.userNumber = selectedUserId
          this.formData.username = ''
        }
      } else {
        this.formData.userId = ''
        this.formData.userNumber = ''
        this.formData.username = ''
      }
    },
    // 提交表单
    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 验证必填字段
          if (!this.formData.subsystem) {
            this.$message.warning('请选择子系统')
            return
          }
          if (!this.formData.department) {
            this.$message.warning('请选择部门')
            return
          }
          if (!this.formData.userId) {
            const fieldName = this.dispatchType === 'update_param' ? '人员' : '责任人'
            this.$message.warning(`请选择${fieldName}`)
            return
          }

          // 如果是批量修改填写人，不调用接口，直接触发确认事件
          if (this.dispatchType === 'update_param') {
            // 验证零部件名称
            if (!this.formData.partsName || !Array.isArray(this.formData.partsName) || this.formData.partsName.length === 0) {
              this.$message.warning('请至少选择一个零部件名称')
              return
            }
            // 确保所有必要参数都有值
            // 如果 userNumber 为空，使用 userId 作为 userNumber（降级处理）
            const confirmData = {
              subsystem: this.formData.subsystem,
              partsName: this.formData.partsName, // 现在是数组
              department: this.formData.department,
              userId: this.formData.userId, // 确保传递userId
              userNumber: this.formData.userNumber || this.formData.userId, // 如果没有 userNumber，使用 userId
              username: this.formData.username || ''
            }
            console.log('批量修改填写人 - 提交数据:', confirmData)
            this.submitting = false
            this.closeModal()
            this.$emit('confirm', confirmData)
            return
          }

          // 批量修改责任人：根据是否有现责任人，决定调用新增还是修改接口
          if (this.formData.currentResponsibleId && this.formData.rowId) {
            // 有现责任人，调用修改接口
            const request = {
              ...api.EDIT_MANAGER_DATA,
              params: {
                departmentId: this.getDepartmentIdByDepartment(this.formData.department),
                department: this.formData.department,
                subsystem: this.formData.subsystem,
                userId: this.formData.userId, // 使用 userNumber
                rowId: this.formData.rowId
              }
            }
            this.$request(request)
              .asyncThen((resp) => {
                this.submitting = false
                this.closeModal()
                // 触发父组件刷新责任人列表
                this.$emit('refresh-responsible-persons')
                this.$emit('confirm', {
                  subsystem: this.formData.subsystem,
                  department: this.formData.department,
                  oldResponsiblePersonId: this.formData.currentResponsibleId,
                  newResponsiblePersonId: this.formData.userNumber,
                  userId: this.formData.userId // 传递 userId
                })
              })
              .asyncErrorCatch((err) => {
                console.error('修改失败:', err)
                this.$message.error('修改失败，请重试')
                this.submitting = false
              })
          } else {
            // 没有现责任人，调用新增接口
            const request = {
              ...api.SAVE_MANAGER_DATA,
              params: {
                departmentId: this.getDepartmentIdByDepartment(this.formData.department),
                department: this.formData.department,
                subsystem: this.formData.subsystem,
                userId: this.formData.userId
              }
            }
            this.$request(request)
              .asyncThen((resp) => {
                this.submitting = false
                this.closeModal()
                // 触发父组件刷新责任人列表
                this.$emit('refresh-responsible-persons')
                this.$emit('confirm', {
                  subsystem: this.formData.subsystem,
                  department: this.formData.department,
                  oldResponsiblePersonId: '',
                  newResponsiblePersonId: this.formData.userNumber,
                  userId: this.formData.userId // 传递 userId
                })
              })
              .asyncErrorCatch((err) => {
                console.error('新增失败:', err)
                this.$message.error('新增失败，请重试')
                this.submitting = false
              })
          }
          this.submitting = false
        }
      })
    },
    // 加载部门树数据（用于根据部门名称查找部门ID）
    loadDepartmentTree() {
      const request = {
        ...api.QUERY_ORG_TREE,
        disableSuccessMsg: true
      }
      this.$request(request)
        .asyncThen((resp) => {
          let result = []
          if (resp && resp.data) {
            result = resp.data.result || resp.data.data || resp.data || []
          }
          this.departmentTreeData = this.formatDepartmentTreeData(result)
        })
        .asyncErrorCatch((err) => {
          console.error('加载部门树失败:', err)
          this.departmentTreeData = []
        })
    },
    // 格式化部门树数据
    formatDepartmentTreeData(data) {
      if (!Array.isArray(data)) {
        return []
      }
      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))
    },
    // 根据部门名称获取部门ID（从部门树中查找）
    getDepartmentIdByDepartment(department) {
      if (!department || !this.departmentTreeData || this.departmentTreeData.length === 0) {
        // 如果部门树没有加载，尝试从 allManagerData 中查找
        if (this.allManagerData && this.allManagerData.length > 0) {
          const matchedItem = this.allManagerData.find((item) => item.department === department)
          return matchedItem ? (matchedItem.departmentId || '') : ''
        }
        return ''
      }
      // 递归查找部门ID
      const findDepartmentId = (nodes, targetName) => {
        for (const node of nodes) {
          // 检查完整路径或节点名称是否匹配
          const pathName = this.getDepartmentPathName(node.id)
          if (pathName === targetName || node.name === targetName) {
            return node.id
          }
          if (node.children && node.children.length > 0) {
            const result = findDepartmentId(node.children, targetName)
            if (result) {
              return result
            }
          }
        }
        return null
      }
      const deptId = findDepartmentId(this.departmentTreeData, department)
      if (deptId) {
        return deptId
      }
      // 如果找不到，尝试从 allManagerData 中查找
      if (this.allManagerData && this.allManagerData.length > 0) {
        const matchedItem = this.allManagerData.find((item) => item.department === department)
        return matchedItem ? (matchedItem.departmentId || '') : ''
      }
      return ''
    },
    // 获取部门路径名称（从根到当前节点的完整路径）
    getDepartmentPathName(deptId) {
      if (!deptId || !this.departmentTreeData || this.departmentTreeData.length === 0) {
        return ''
      }
      const findPath = (nodes, targetId, path = []) => {
        for (const node of nodes) {
          const currentPath = [...path, node.name]
          if (node.id === targetId) {
            return currentPath.join('-')
          }
          if (node.children && node.children.length > 0) {
            const result = findPath(node.children, targetId, currentPath)
            if (result) {
              return result
            }
          }
        }
        return null
      }
      return findPath(this.departmentTreeData, deptId) || ''
    }
  }
}
</script>

<style lang="scss">
.batch-modify-responsible-modal {
  .batch-modify-content {
    padding: 20px 0;

    .el-form {
      .el-form-item {
        margin-bottom: 20px;
      }
    }
  }

  .dialog-footer {
    text-align: right;
    padding-top: 20px;
  }

  .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;
}
</style>
