<template>
  <el-dialog title="添加参与人员" v-model="visible" width="800px" append-to-body @close="handleClose">
<!--    <el-alert type="info" :closable="false" style="border-color: #14b8a6; background-color: #f0fdfa; color: #0d9488; height: 35px;">-->
<!--      <template #default>-->
<!--        <i class="fa fa-file-text-o mr-2" style="color: #0d9488;"> 请选择信息录入方式，并上传相关附件完成结单。</i>-->
<!--      </template>-->
<!--    </el-alert>-->
    <h4 class="text-sm font-medium text-gray-800 mb-3"></h4>
    <el-form ref="addPersonFormRef" :model="formData" :rules="finalizeRules" label-width="120px" label-position="top">
      <el-row>
        <el-col :span="12">
          <el-form-item label="工单编码"><el-input v-model="formData.workOrderProjectNo" disabled /></el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="风机编号"><el-input v-model="formData.pcsDeviceName" disabled /></el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="工单状态">
            <el-select v-model="formData.workOrderStatus" style="width: 100%" disabled>
              <el-option
                  v-for="dict in workOrderStatusOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="维保中心"><el-input v-model="formData.gxtCenter" disabled /> </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="场站"><el-input v-model="formData.pcsStationName" disabled /> </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="品牌"><el-input v-model="formData.brand" disabled /> </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="故障代码"><el-input v-model="formData.faultCode" disabled /> </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="故障条文"><el-input v-model="formData.faultBarcode" disabled /> </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="故障描述">
            <el-input
              v-model="formData.faultDesc"
              type="textarea"
              :rows="3"
              disabled
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="工作负责人" prop="teamLeaderName">
            <el-input
                v-model="formData.teamLeaderName"
                placeholder="请输入工作负责人姓名或点击选择"
                clearable
                @focus="handleTeamLeaderInputFocus"
                @blur="handleTeamLeaderInputBlur"
                @input="handleTeamLeaderInput"
                @clear="handleTeamLeaderClear"
            >
            </el-input>
            <!-- 快速检索下拉框 -->
            <div class="quick-select-dropdown" v-show="showTeamLeaderQuickSelect && quickTeamLeaderList.length > 0">
              <div
                  v-for="item in quickTeamLeaderList"
                  :key="item.userId"
                  class="quick-select-item"
                  @click="handleTeamLeaderQuickSelect(item)">
                <span class="user-name">{{ item.nickName }}</span>
                <span class="user-name">{{ item.dept.deptName }}</span>
              </div>
            </div>
            <div class="quick-select-dropdown no-data" v-show="showTeamLeaderQuickSelect && quickTeamLeaderList.length === 0 && formData.teamLeaderName && !teamLeaderLoading">
              <div>未找到匹配的人员</div>
            </div>
            <div class="quick-select-dropdown no-data" v-show="showTeamLeaderQuickSelect && teamLeaderLoading">
              <div>
                <i class="el-icon-loading"></i>
                搜索中...
              </div>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="工作班成员" prop="workGroupMemberName">
            <el-input
                v-model="formData.workGroupMemberName"
                placeholder="请选择工作班成员"
            >
              <template #append>
                <el-button @click="userSelectVisible = true" icon="User"></el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 认</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 人员选择组件 -->
  <UserSelectMulti
    v-model="userSelectVisible"
    :pre-selected-users="selectedUsers"
    :sort-dept-id="formData.pcsStationPid"
    @onSelected="onUserSelected"
  />
</template>

<script setup>
import { ref, defineProps, defineEmits, getCurrentInstance, computed, watch } from 'vue'
import preview from '@/components/FileUpload/preview.vue'
import UserSelectMulti from '@/components/userSelect/multi.vue'
import { ElMessageBox } from 'element-plus'
import {listUser, listUserData, listUserNoPermi, listLeader} from "@/api/system/user";
import MisInfoSelectSingle from "@/components/misInfoSelect/single.vue";
import {listRepairOrder} from "@/api/gxt/repairOrder.js";
import {listWorkPerson} from "@/api/gxt/misInfo.js";
import {getOrderList} from "@/api/gxt/gxtOrder.js";

// 获取当前实例
const { proxy } = getCurrentInstance()

// 定义属性
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  data: {
    type: Object,
    default: () => ({})
  },
  workOrderStatusOptions: {
    type: Array,
    default: () => ([])
  },
  onSubmit: {
    type: Function,
    default: null
  },
  listRepairOrder: {
    type: Function,
    default: null
  },
  listWorkPerson: {
    type: Function,
    default: null
  },
  listUserData: {
    type: Function,
    default: null
  },
  listMisInfo: {
    type: Function,
    default: null
  },
  infoEntryDisabled: {
    type: Boolean,
    default: false
  },
  commonKey: {
    type: Number,
    default: 0
  }
})

// 定义事件
const emit = defineEmits(['update:modelValue', 'success', 'select-mis-info'])

// 响应式数据
const visible = ref(false)
const formData = ref({})
const addPersonFormRef = ref()
const showMisNoQuickSelect = ref(false)
const quickMisNoList = ref([])
const misNoSearchTimer = ref(null)
const userSelectVisible = ref(false) // 添加人员选择组件可见性
const selectedUsers = ref([]) // 存储选中的用户
const inputUsers = ref([]) // 存储选中的用户
const flowList = ref([])
const suspendInfo = ref(null)
const resumeInfo = ref(null)
const resumeShow = ref(false)
const misInfoSelectVisible = ref(false)

// 工作负责人快速检索相关响应式数据
const showTeamLeaderQuickSelect = ref(false)
const quickTeamLeaderList = ref([])
const teamLeaderLoading = ref(false)
const teamLeaderSearchTimer = ref(null)
const allUserList = ref([]) // 存储所有设备数据用于快速检索
const lastLoadedCenterId = ref(null)

// 表单验证规则
const finalizeRules = ref({
  workGroupMemberName: [
    { required: true, message: "请选择工作班成员", trigger: "change" },
    {
      validator: async (rule, value, callback) => {
        // 如果值为空、关联MIS，直接通过验证
        if (!value || formData.value.infoEntry == '1') {
          selectedUsers.value = [];
          return callback();
        }
        try {
          inputUsers.value = []
          // 将输入的工作班成员姓名按逗号分割
          const names = value.split(',').map(name => name.trim());
          // 验证每个工作班成员是否存在于组织架构中
          for (const name of names) {
            if (name.length > 0) {
              // 检查输入中重复
              if (inputUsers.value.some(u => u.nickName === name)) {
                return callback(new Error(`工作班成员"${name}"重复，请重新输入`));
              }
              // 使用从属性传入的listUserData方法
              if (!props.listUserData) {
                return callback(new Error('系统配置错误：缺少用户数据查询方法'));
              }
              const response = await props.listUserData({nickName: name});
              if (!response.rows || response.rows.length === 0) {
                return callback(new Error(`工作班成员"${name}"非系统内人员，请重新输入`));
              }else{
                inputUsers.value.push(response.rows[0]);
              }
            } else {
              return callback(new Error(`请正确输入工作班成员名单`));
            }
          }
          selectedUsers.value = inputUsers.value;
          callback();
        } catch (error) {
          callback(new Error('验证工作班成员时发生错误'));
        }
      },
      trigger: 'blur'
    }
  ],

  teamLeaderName: [
    { required: true, message: "工作负责人不能为空", trigger: "change" }
  ],
})

// 监听modelValue变化
watch(() => props.modelValue, (val) => {
  visible.value = val
  if (val) {
    // 初始化表单数据
    formData.value = { ...props.data, selectedMembers: [] }
  }
})

// 监听props.data变化
watch(() => props.data, (newData) => {
  if (visible.value) {
    // 只有在对话框打开时才更新数据
    formData.value = { ...newData, selectedMembers: [] }
  }
}, { deep: true })

// 监听visible变化
watch(visible, (val) => {
  emit('update:modelValue', val)
  if (val) {
    // 打开对话框后重置表单验证错误
    proxy.$nextTick(() => {
      if (addPersonFormRef.value) {
        addPersonFormRef.value.clearValidate()
      }
    })
  }
})

// 关闭对话框
const handleClose = () => {
  visible.value = false
  selectedUsers.value = []
  resumeInfo.value = null
  suspendInfo.value = null
  resumeShow.value = false
}

// 取消操作
const handleCancel = () => {
  visible.value = false
  selectedUsers.value = []
  resumeInfo.value = null
  suspendInfo.value = null
  resumeShow.value = false
}

// 用户选择回调函数
const onUserSelected = (users) => {
  if (users && users.length > 0) {
    // 合并用户，避免重复
    const existingNames = selectedUsers.value.map(u => u.nickName);
    const newUsers = users.filter(u => !existingNames.includes(u.nickName));
    selectedUsers.value = [...selectedUsers.value, ...newUsers];
    // 构建用户姓名列表
    const userNames = selectedUsers.value.map(user => user.nickName).join(',');
    formData.value.workGroupMemberName = userNames;
  } else {
    selectedUsers.value = [];
    formData.value.workGroupMemberName = '';
  }
  formData.value.repairOrderPersonList = selectedUsers.value.map(user => ({
    userId: user.userId,
    nickName: user.nickName,
    orderId: formData.value.id,
    orderCode: formData.value.workOrderProjectNo,
    status: 1
  }));
};

// 提交操作
// const handleSubmit = async () => {
//   if (!addPersonFormRef.value) return
//
//   await addPersonFormRef.value.validate(async (valid) => {
//     if (valid) {
//       const { realStartTime, acceptTime } = formData.value;
//       debugger
//       try {
//         debugger
//         // 根据维修方式清除不需要的字段
//         if (formData.value.repairMethod === '1') {
//           // 正常维修时清除复位方式
//           formData.value.resetMethod = undefined;
//           formData.value.workArea = Array.isArray(formData.value.workArea) ? formData.value.workArea.join(',')
//                                 : formData.value.workArea || ''
//         } else if (formData.value.repairMethod === '2') {
//           // 复位启机时清除MIS相关字段
//           formData.value.misOrderNo = undefined;
//           formData.value.realStartTime = undefined;
//           formData.value.realEndTime = undefined;
//           formData.value.workGroupMemberName = undefined;
//           formData.value.infoEntry = undefined;
//           formData.value.wwryNum = undefined;
//           formData.value.wlryNum = undefined;
//           formData.value.workArea = undefined;
//           formData.value.repairOrderPersonList = [];
//         }
//
//         // 调用父组件传入的提交函数
//         if (props.onSubmit && typeof props.onSubmit === 'function') {
//
//           flowList.value = []
//           if (formData.value.resumeTime && formData.value.resumeTime != resumeInfo.value.actionTime) { //存入新的挂起结束时间
//             resumeInfo.value.actionTime = formData.value.resumeTime
//             flowList.value.push(resumeInfo.value)
//           }
//           formData.value.repairOrderFlowList = flowList.value
//           formData.value.finalizeMethod = '2'
//           await props.onSubmit(formData.value)
//         } else {
//           throw new Error("未提供提交方法")
//         }
//
//         proxy.$modal.msgSuccess("结单成功")
//         visible.value = false
//         emit('success')
//       } catch (error) {
//         // proxy.$modal.msgError("操作失败: " + (error.message || "未知错误"))
//       }
//     }
//   })
// }

// 核心修改：提交函数 - 临时转换workArea格式，异常时恢复
const handleSubmit = async () => {
  if (!addPersonFormRef.value) return
  await addPersonFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 2. 构建提交用的临时数据（不修改原formData）
        const submitData = { ...formData.value }
        // 防止提交时候时间格式转换错误
        submitData.createTime = null
        submitData.updateTime = null
        // 5. 调用父组件提交函数（传入转换后的临时数据）
        if (props.onSubmit && typeof props.onSubmit === 'function') {
          await props.onSubmit(submitData) // 提交转换后的数据
        } else {
          throw new Error("未提供提交方法")
        }

        // 提交成功逻辑
        visible.value = false
        emit('success')
      } catch (error) {
        // 重置表单验证状态
        proxy.$nextTick(() => {
          addPersonFormRef.value.clearValidate()
        })
      }
    }
  })
}
// 工作负责人快速检索方法
/** 过滤快速检索用户列表 */
const filterQuickUserList = (keyword) => {
  debugger
  if (!allUserList.value.length) {
    loadQuickTeamLeaderList();
    return;
  }

  const lowerKeyword = keyword.toLowerCase();
  quickTeamLeaderList.value = allUserList.value.filter(item =>
      (item.nickName && item.nickName.toLowerCase().includes(lowerKeyword))
  );
}
/** 工作负责人输入框获取焦点 */
const handleTeamLeaderInputFocus = () => {
  showTeamLeaderQuickSelect.value = true
  // 如果已有输入内容，立即搜索
  if (formData.value.teamLeaderName && formData.value.teamLeaderName.trim()) {
    handleTeamLeaderInput(formData.value.teamLeaderName)
  } else {
    // 如果没有输入内容，加载默认列表
    loadQuickTeamLeaderList()
  }
}

/** 工作负责人输入框失去焦点 */
const handleTeamLeaderInputBlur = () => {
  // 延迟隐藏下拉框，确保点击选项能触发
  setTimeout(() => {
    showTeamLeaderQuickSelect.value = false
  }, 200)
}

/** 工作负责人输入事件 - 实时搜索 */
const handleTeamLeaderInput = (value) => {
  const searchText = value.trim()

  if (!searchText) {
    quickTeamLeaderList.value = []
    showTeamLeaderQuickSelect.value = false
    return
  }

  showTeamLeaderQuickSelect.value = true

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

  // 设置新的定时器，防抖处理（300ms）
  // teamLeaderSearchTimer.value = setTimeout(() => {
  // searchTeamLeaderList(searchText)
  filterQuickUserList(searchText)
  // }, 300)
}

/** 搜索工作负责人列表 */
const searchTeamLeaderList = async (keyword) => {
  if (!keyword) {
    quickTeamLeaderList.value = []
    return
  }

  teamLeaderLoading.value = true
  try {
    const response = await listLeader({
      nickName: keyword,
      // 可以根据需要添加其他搜索条件
      status: '0' // 只搜索启用状态的用户
    })

    quickTeamLeaderList.value = response.data || []

  } catch (error) {
    console.error('搜索工作负责人失败:', error)
    proxy.$modal.msgError('搜索失败，请重试')
    quickTeamLeaderList.value = []
  } finally {
    teamLeaderLoading.value = false
  }
}

/** 加载快速检索工作负责人列表 */
const loadQuickTeamLeaderList = async () => {
  // 如果已有所有用户数据，且是同一个维保中心，直接使用
  if (allUserList.value.length > 0 && lastLoadedCenterId.value === formData.value.gxtCenterId) {
    quickTeamLeaderList.value = allUserList.value;
    return;
  }

  // 记录当前维保中心ID
  lastLoadedCenterId.value = formData.value.gxtCenterId;

  teamLeaderLoading.value = true
  try {
    // 加载当前部门下的用户列表
    const response = await listLeader({
      deptId: -1, // 通过后台配置部门
      status: '0'
    })
    allUserList.value = response.data || []
    quickTeamLeaderList.value = allUserList.value;
  } catch (error) {
    console.error('加载工作负责人列表失败:', error)
    allUserList.value = []
  } finally {
    teamLeaderLoading.value = false
  }
}

/** 快速选择工作负责人 */
const handleTeamLeaderQuickSelect = (item) => {
  formData.value.teamLeaderId = item.userId
  formData.value.teamLeaderName = item.nickName
  showTeamLeaderQuickSelect.value = false
}

/** 清空工作负责人 */
const handleTeamLeaderClear = () => {
  formData.value.teamLeaderId = undefined
  formData.value.teamLeaderName = ''
  quickTeamLeaderList.value = []
  showTeamLeaderQuickSelect.value = false
}

</script>

<style scoped>
/* 表单中的列间距调整 */
:deep(.el-col) {
  padding-left: 5px;
  padding-right: 5px;
}
.quick-select-dropdown {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  z-index: 1000;
  max-height: 200px;
  overflow-y: auto;
  background: white;
  border: 1px solid #dcdfe6;
  border-top: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.quick-select-item {
  padding: 8px 12px;
  cursor: pointer;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.quick-select-item:hover {
  background-color: #f5f7fa;
}

.no-data {
  text-align: center;
  padding: 10px;
  color: #909399;
}

/* 穿透修改组件内部输入框的对齐方式（关键） */
:deep(.input-number-left .el-input__inner) {
  text-align: left !important; /* !important 覆盖组件默认的居中 */
}
</style>
