<template>
  <div class="project-form-page">
    <ContentWrap class="page-header">
      <div class="page-header__main">
        <div class="page-header__icon">
          <Icon :icon="formType === 'create' ? 'ep:document-add' : 'ep:edit-pen'" />
        </div>
        <div>
          <h2 class="page-header__title">
            {{ formType === 'create' ? '新增项目信息' : '编辑项目信息' }}
          </h2>
          <p class="page-header__subtitle">维护客户、合同、归属部门及项目配置信息</p>
        </div>
      </div>
      <el-button size="default" @click="close">
        <Icon icon="ep:arrow-left" class="mr-5px" />返回
      </el-button>
    </ContentWrap>

    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="108px"
      size="default"
      class="project-form">
      <ContentWrap class="project-form-card">
        <div class="form-card-header">
          <div class="form-card-title">
            <span></span>
            <h3>合同信息</h3>
          </div>
          <span class="form-card-hint">客户、合同及项目周期信息</span>
        </div>
        <div class="form-card-body">
          <el-row :gutter="24">
            <el-col :xs="24" :md="12">
              <el-form-item label="客户名称" prop="manufacturerId">
                <el-select
                  v-model="formData.manufactureName"
                  clearable
                  :placeholder="t('deviceForm.mfgHolder')"
                  @clear="zzClear"
                  @click="openCustomerZz" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :md="12">
              <el-form-item :label="t('project.payment')" prop="payment">
                <el-select v-model="formData.payment" placeholder="请选择" clearable>
                  <el-option
                    v-for="dict in getStrDictOptions(DICT_TYPE.PMS_PROJECT_SETTLEMENT)"
                    :key="dict.id"
                    :label="dict.label"
                    :value="dict.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :md="12">
              <el-form-item label="合同名称" prop="contractName">
                <el-input v-model="formData.contractName" placeholder="请输入合同名称" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :md="12">
              <el-form-item label="合同编号" prop="contractCode">
                <el-input v-model="formData.contractCode" placeholder="请输入合同编号" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :md="12">
              <el-form-item label="开始时间" prop="startTime">
                <el-date-picker
                  v-model="formData.startTime"
                  type="date"
                  value-format="x"
                  placeholder="选择开始时间" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :md="12">
              <el-form-item label="完成时间" prop="endTime">
                <el-date-picker
                  v-model="formData.endTime"
                  type="date"
                  value-format="x"
                  placeholder="选择完成时间" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </ContentWrap>

      <ContentWrap class="project-form-card">
        <div class="form-card-header">
          <div class="form-card-title">
            <span></span>
            <h3>项目配置</h3>
          </div>
          <span class="form-card-hint">归属部门、责任人与项目属性</span>
        </div>
        <div class="form-card-body">
          <el-row :gutter="24">
            <el-col :xs="24" :md="12">
              <el-form-item :label="t('iotDevice.company')" prop="deptId">
                <el-tree-select
                  v-model="formData.deptId"
                  :disabled="isDeptDisabled"
                  :data="deptList"
                  :props="defaultProps"
                  check-strictly
                  node-key="id"
                  filterable
                  placeholder="请选择所属公司" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :md="12">
              <el-form-item label="项目部" prop="projectDeptId">
                <el-select
                  v-model="formData.projectDeptId"
                  :options="deptOptions"
                  :loading="deptLoading"
                  filterable
                  placeholder="请选择项目部"
                  clearable />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :md="12">
              <el-form-item label="责任人" prop="responsiblePerson">
                <div class="responsible-person-control">
                  <el-tooltip
                    v-if="selectedUserNames"
                    effect="dark"
                    placement="top"
                    :content="getFullSelectedUserNames()">
                    <span class="user-names">{{ selectedUserNames }}</span>
                  </el-tooltip>
                  <span v-else class="user-names user-names--empty">暂未选择责任人</span>
                  <el-button
                    type="primary"
                    plain
                    size="default"
                    :disabled="!formData.deptId"
                    @click="openUserDialog">
                    <Icon icon="ep:user" class="mr-5px" />选择
                  </el-button>
                </div>
                <div v-if="!formData.deptId" class="el-form-item__error">请先选择所属公司</div>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :md="12">
              <el-form-item :label="t('project.overseaFlag')" prop="overseas">
                <el-select v-model="formData.overseas" placeholder="请选择" clearable>
                  <el-option
                    v-for="dict in getIntDictOptions(DICT_TYPE.PMS_PROJECT_OVERSEA_FLAG)"
                    :key="dict.id"
                    :label="dict.label"
                    :value="dict.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :md="12">
              <el-form-item :label="t('project.overseaArea')" prop="overseasArea">
                <el-select v-model="formData.overseasArea" placeholder="请选择" clearable>
                  <el-option
                    v-for="dict in getStrDictOptions(DICT_TYPE.PMS_PROJECT_AREA)"
                    :key="dict.id"
                    :label="dict.label"
                    :value="dict.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :md="12">
              <el-form-item :label="t('project.workArea')" prop="location">
                <el-autocomplete
                  ref="workAreaAutocomplete"
                  v-model="formData.location"
                  :fetch-suggestions="querySearch"
                  :trigger-on-focus="true"
                  :disabled="!workAreaOptions.length"
                  placeholder="请输入施工区域"
                  popper-class="work-area-autocomplete"
                  @focus="handleWorkAreaFocus"
                  @select="handleSelect">
                  <template #prefix>
                    <el-icon v-if="loadingWorkAreaOptions" class="is-loading">
                      <Loading />
                    </el-icon>
                  </template>
                </el-autocomplete>
                <div v-if="!workAreaOptions.length" class="el-form-item__error">
                  暂无可用施工区域选项，请手动输入
                </div>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :md="12">
              <el-form-item label="虚拟项目" prop="contractSubject">
                <el-switch
                  v-model="formData.contractSubject"
                  active-value="Y"
                  inactive-value="N"
                  active-text="是"
                  inactive-text="否" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input
                  v-model="formData.remark"
                  placeholder="请输入备注"
                  type="textarea"
                  :rows="3" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </ContentWrap>
    </el-form>

    <CustomerList ref="customerZzFormRef" @choose="customerZzChoose" />

    <el-dialog
      v-model="userDialogVisible"
      width="920px"
      :before-close="handleUserDialogClose"
      class="user-select-dialog">
      <template #header>
        <div class="dialog-title">
          <div class="dialog-title__icon"><Icon icon="ep:user" /></div>
          <div>
            <div class="dialog-title__text">选择责任人</div>
            <div class="dialog-title__subtitle">从当前公司人员中选择项目责任人</div>
          </div>
        </div>
      </template>
      <div class="transfer-container">
        <el-transfer
          v-model="selectedUserIds"
          :data="userList"
          :titles="['可选人员', '已选人员']"
          :props="{ key: 'id', label: 'nickname' }"
          filterable
          class="transfer-component">
          <template #default="{ option }">
            <el-tooltip
              effect="dark"
              placement="top"
              :content="`${option.nickname} - ${option.deptName || '未分配部门'}`">
              <span class="transfer-option-text">
                {{ option.nickname }} - {{ option.deptName || '未分配部门' }}
              </span>
            </el-tooltip>
          </template>
        </el-transfer>
      </div>
      <template #footer>
        <el-button size="default" @click="handleUserDialogClose">取消</el-button>
        <el-button size="default" type="primary" @click="confirmUserSelection">确定</el-button>
      </template>
    </el-dialog>

    <div class="form-actions">
      <el-button size="default" type="primary" :loading="formLoading" @click="submitForm">
        <Icon icon="ep:check" class="mr-5px" />保存
      </el-button>
      <el-button size="default" @click="close">取消</el-button>
    </div>
  </div>
</template>
<script setup lang="ts">
import { IotProjectInfoApi, IotProjectInfoVO } from '@/api/pms/iotprojectinfo'
import { defaultProps } from '@/utils/tree'
import * as DeptApi from '@/api/system/dept'
import CustomerList from '@/views/pms/device/CustomerList.vue'
import { ref } from 'vue'
import { useUserStore } from '@/store/modules/user'
import { IotProjectTaskVO } from '@/api/pms/iotprojecttask'
import { useTagsViewStore } from '@/store/modules/tagsView'
import * as UserApi from '@/api/system/user'
import { UserVO } from '@/api/system/user'
import { DICT_TYPE, getIntDictOptions, getStrDictOptions, getDictLabel } from '@/utils/dict'
import { Loading } from '@element-plus/icons-vue'

/** 项目信息 表单 */
defineOptions({ name: 'IotProjectInfo' })

const { params, name } = useRoute() // 查询参数
const id = params.id
const { delView } = useTagsViewStore() // 视图操作
const { currentRoute, push } = useRouter()
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const deptList = ref<Tree[]>([]) // 树形结构
const dialogVisible = ref(true) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const taskList = ref<IotProjectTaskVO[]>([]) // 列表的数据
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const loading = ref(true) // 列表的加载中
const simpleUsers = ref<UserVO[]>([]) // 责任人列表

const deptLoading = ref(false)
const deptOptions = ref<any[]>([])

const user = useUserStore().getUser

const userdeptId = user.deptId

async function loadDept(deptId?: number) {
  deptLoading.value = true
  try {
    const res = await DeptApi.specifiedSimpleDepts(deptId ?? userdeptId)
    deptOptions.value = res
      .map((item: any) => ({
        label: item.name,
        value: item.id,
        raw: item
      }))
      .filter((item) => item.raw.type === '2')
  } catch (error) {
  } finally {
    deptLoading.value = false
  }
}

onMounted(() => {
  loadDept()
})

// 添加责任人相关变量
const userDialogVisible = ref(false)
const userList = ref([]) // 所有用户列表
const selectedUserIds = ref([]) // 选中的用户ID
const selectedUserNames = ref('') // 选中的用户名称显示
const selectedUserList = ref([]) // 存储选中的用户对象列表

// 添加 workAreaOptions 引用和加载状态
const workAreaOptions = ref<any[]>([])
const loadingWorkAreaOptions = ref(false)
const workAreaAutocomplete = ref() // 添加对el-autocomplete的引用
// currentDictLabel 响应式变量
const currentDictLabel = ref('') // 存储当前项目对应的施工区域字典类型

const formData = ref({
  id: undefined,
  deptId: undefined,
  deptName: undefined,
  contractName: undefined,
  contractCode: undefined,
  contractSubject: 'N', // 添加虚拟项目字段，默认值为'N'
  workloadTotal: undefined,
  workloadFinish: undefined,
  startTime: undefined,
  endTime: undefined,
  location: undefined,
  technique: undefined,
  payment: undefined,
  overseas: undefined,
  overseasArea: undefined,
  remark: undefined,
  dictType: undefined,
  projectDeptId: undefined,
  userName: useUserStore().getUser.name,
  userId: useUserStore().getUser.userId
})

watch(
  () => formData.value.deptId,
  (newVal) => {
    loadDept(newVal)
  }
)

const close = () => {
  delView(unref(currentRoute))
  push({ name: 'iotProjectInfo', params: {} })
}

const queryParams = reactive({
  projectId: undefined
})
const formRules = reactive({
  manufacturerId: [{ required: true, message: '客户不能为空', trigger: 'blur' }],
  payment: [{ required: true, message: '结算方式不能为空', trigger: 'blur' }],
  contractName: [{ required: true, message: '合同名称不能为空', trigger: 'blur' }],
  contractCode: [{ required: true, message: '合同编码不能为空', trigger: 'blur' }],
  workloadTotal: [{ required: true, message: '工作量总数不能为空', trigger: 'blur' }],
  startTime: [{ required: true, message: '开始时间不能为空', trigger: 'blur' }],
  endTime: [{ required: true, message: '结束时间不能为空', trigger: 'blur' }]
})
const formRef1 = ref() // 表单 Ref
const openForm = (type: string, id?: number) => {
  formRef1.value.open(type, id)
}
const zzClear = () => {
  formData.value.manufacturerId = undefined
  formData.value.manufactureName = undefined
}

const customerZzChoose = (row) => {
  formData.value.manufacturerId = row.id
  // zzLabel.value = row.name
  formData.value.manufactureName = row.name
}
const customerZzFormRef = ref()
const openCustomerZz = () => {
  customerZzFormRef.value.open()
}

// 格式化用户名称显示
const formatUserNames = (users) => {
  if (!users || users.length === 0) return ''

  const names = users.map((user) => user.nickname)

  if (names.length <= 2) {
    return names.join(', ')
  } else {
    return `${names[0]}, ${names[1]}...`
  }
}

// 根据用户ID获取用户信息
const fetchUserInfoByIds = async (userIds) => {
  if (!userIds || userIds.length === 0) {
    selectedUserList.value = []
    selectedUserNames.value = ''
    return
  }

  try {
    const params = {
      userIds: userIds
    }
    const response = await UserApi.companyDeptsEmployee(params) // 假设有这个API
    selectedUserList.value = response
    selectedUserNames.value = formatUserNames(response)
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败')
  }
}

// 添加处理施工区域获取焦点的方法
const handleWorkAreaFocus = async () => {
  // 如果已经有选项数据，直接显示下拉框
  if (workAreaOptions.value.length > 0) {
    // 使用Element Plus提供的方法触发下拉框
    try {
      // 直接调用el-autocomplete的focus方法
      if (workAreaAutocomplete.value && typeof workAreaAutocomplete.value.focus === 'function') {
        workAreaAutocomplete.value.focus()
      }
    } catch (error) {
      console.error('触发下拉框显示失败:', error)
    }
    return
  }

  // 如果没有选项数据，尝试加载
  if (formData.value.deptId && !loadingWorkAreaOptions.value) {
    await loadWorkAreaOptions(formData.value.deptId)
    // 加载完成后尝试显示下拉框
    if (workAreaOptions.value.length > 0) {
      try {
        if (workAreaAutocomplete.value && typeof workAreaAutocomplete.value.focus === 'function') {
          workAreaAutocomplete.value.focus()
        }
      } catch (error) {
        console.error('触发下拉框显示失败:', error)
      }
    }
  }
}

// 根据部门ID获取部门名称
const getDeptNames = (deptIds) => {
  if (!deptIds || deptIds.length === 0) return ''

  const names = []
  const findDept = (list, id) => {
    for (const item of list) {
      if (item.id === id) {
        names.push(item.name)
        return true
      }
      if (item.children && findDept(item.children, id)) {
        return true
      }
    }
    return false
  }

  deptIds.forEach((id) => findDept(deptList.value, id))
  return names.join(', ')
}

// 计算属性：判断部门选择框是否应该禁用
const isDeptDisabled = computed(() => {
  return formType.value === 'update' || deptList.value.length === 1
})

// 打开用户选择对话框
const openUserDialog = async () => {
  try {
    // 获取用户列表，传递部门ID参数
    const params = {
      deptIds: [formData.value.deptId] // 将部门ID转换为数组格式
    }
    // 获取用户列表
    const response = await UserApi.companyDeptsEmployee(params)
    userList.value = response

    // 设置当前已选中的用户
    selectedUserIds.value = formData.value.responsiblePerson || []

    userDialogVisible.value = true
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  }
}

// 确认用户选择
const confirmUserSelection = () => {
  // 更新表单数据
  formData.value.responsiblePerson = [...selectedUserIds.value]

  // 更新显示的用户名称
  // updateSelectedUserNames();

  selectedUserList.value = userList.value.filter((user) => selectedUserIds.value.includes(user.id))
  // 更新显示的用户名称
  selectedUserNames.value = formatUserNames(selectedUserList.value)

  userDialogVisible.value = false
}

// 更新显示的用户名称
const updateSelectedUserNames = () => {
  console.log('已经保存的责任人：' + formData.value.responsiblePerson)
  if (!formData.value.responsiblePerson || formData.value.responsiblePerson.length === 0) {
    selectedUserNames.value = ''
    return
  }

  const selectedUsers = userList.value.filter((user) =>
    formData.value.responsiblePerson.includes(user.id)
  )

  const names = selectedUsers.map((user) => user.nickname)

  if (names.length <= 2) {
    selectedUserNames.value = names.join(', ')
  } else {
    selectedUserNames.value = `${names[0]}, ${names[1]}...`
  }
}

// 关闭用户选择对话框
const handleUserDialogClose = () => {
  userDialogVisible.value = false
}

const tableData = ref([
  {
    id: 1,
    wellName: '',
    wellType: '',
    location: '',
    technique: '',
    workloadDesign: '',
    deptIds: [],
    remark: '',
    editData: {},
    editing: true,
    originalData: {},
    errors: {}
  }
])
let deptInfo: any[] = ''
/** 打开弹窗 */
const open = async () => {
  resetForm()
  // 修改时，设置数据
  if (id) {
    formType.value = 'update'
    formLoading.value = true
    try {
      formData.value = await IotProjectInfoApi.getIotProjectInfo(id)

      // 如果已有责任人数据，获取用户信息并显示
      if (formData.value.responsiblePerson && formData.value.responsiblePerson.length > 0) {
        await fetchUserInfoByIds(formData.value.responsiblePerson)
        selectedUserIds.value = [...formData.value.responsiblePerson]
      }

      // 编辑页面：根据项目所属公司加载施工区域选项
      if (formData.value.deptId) {
        await loadWorkAreaOptions(formData.value.deptId)
      }
    } finally {
      formLoading.value = false
    }
  } else {
    formType.value = 'create'
    // 如果只有一个部门，则自动选中
    if (deptList.value.length === 1) {
      formData.value.deptId = deptList.value[0].id
    }
  }
}

defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const formRef = ref() // 表单 Ref
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()

  // 将当前字典类型赋值给formData
  formData.value.dictType = currentDictLabel.value

  // 提交请求
  formLoading.value = true
  try {
    // formData.value.deptId = useUserStore().getUser.deptId;
    const data = {
      projectData: formData.value as unknown as IotProjectInfoVO
      //taskList:tableData.value
    }
    if (formType.value === 'create') {
      await IotProjectInfoApi.createIotProjectInfo(data)
      message.success(t('common.createSuccess'))
    } else {
      await IotProjectInfoApi.updateIotProjectInfo(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
    close()
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    deptId: undefined,
    deptName: undefined,
    contractName: undefined,
    contractCode: undefined,
    contractSubject: 'N', // 重置时设置默认值
    workloadTotal: undefined,
    workloadFinish: undefined,
    startTime: undefined,
    endTime: undefined,
    location: undefined,
    technique: undefined,
    payment: undefined,
    userName: undefined,
    userId: undefined,
    responsiblePerson: [] // 重置责任人字段
  }
  selectedUserNames.value = ''
  formRef.value?.resetFields()
}
onMounted(async () => {
  // deptList.value = handleTree(await DeptApi.getSimpleDeptList())
  // 查询当前登录人所属的 公司级部门 如果部门列表只有一个值 默认选中
  deptList.value = await DeptApi.companyLevelDepts()

  // 如果只有一个部门，则自动选中
  if (deptList.value.length === 1) {
    formData.value.deptId = deptList.value[0].id
  }
  open()
})

const showCloumn = false
// 表格数据

// 计算正在编辑的行数
const editingRowsCount = computed(() => {
  return tableData.value.filter((row) => row.editing).length
})

// 格式化日期
const formatDate = (timestamp) => {
  const date = new Date(timestamp)
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
}

// 为编辑中的行添加特殊样式
const rowClassName = ({ row }) => {
  return row.editing ? 'editable-row' : ''
}

// 添加新行
const addNewRow = () => {
  const newId =
    tableData.value.length > 0 ? Math.max(...tableData.value.map((item) => item.id)) + 1 : 1

  const newRow = {
    id: newId,
    wellName: '',
    wellType: '',
    location: '',
    technique: '',
    workloadDesign: '',
    deptIds: [],
    remark: '',
    editing: true,
    editData: {
      wellName: '',
      wellType: '',
      location: '',
      technique: '',
      workloadDesign: '',
      deptIds: [],
      remark: ''
    },
    originalData: {},
    errors: {}
  }

  tableData.value.unshift(newRow)
}

// 编辑行
const editRow = (row) => {
  // 保存原始数据用于取消编辑时恢复
  row.originalData = { ...row }
  // 设置编辑数据
  row.editData = {
    id: row.id,
    wellName: row.wellName,
    wellType: row.wellType,
    location: row.location,
    technique: row.technique,
    workloadDesign: row.workloadDesign,
    deptIds: row.deptIds,
    remark: row.remark
  }
  // 进入编辑状态
  row.editing = true
  // 清空错误信息
  row.errors = {}
}

// 验证行数据
const validateRow = (row) => {
  row.errors = {}
  let valid = true

  if (!row.editData.wellName || row.editData.wellName.trim() === '') {
    row.errors.name = '井号不能为空'
    valid = false
  }

  if (!row.editData.wellType || row.editData.wellType.trim() === '') {
    row.errors.email = '井型不能为空'
    valid = false
  }

  return valid
}

// 保存行
const saveRow = (row) => {
  if (!validateRow(row)) return

  // 将编辑数据应用到行
  row.id = row.editData.id
  row.wellName = row.editData.wellName
  row.wellType = row.editData.wellType
  row.location = row.editData.location
  row.technique = row.editData.technique
  row.workloadDesign = row.editData.workloadDesign
  row.deptIds = row.editData.deptIds
  row.remark = row.editData.remark
  // 退出编辑状态
  row.editing = false
}

// 生成Tooltip要显示的完整责任人名称字符串
const getFullSelectedUserNames = () => {
  if (!selectedUserList.value || selectedUserList.value.length === 0) {
    return ''
  }
  return selectedUserList.value.map((user) => user.nickname).join(', ')
}

// 保存所有更改
const saveAll = () => {
  let allValid = true

  // 验证所有编辑中的行
  tableData.value.forEach((row) => {
    if (row.editing && !validateRow(row)) {
      allValid = false
    }
  })

  if (!allValid) {
    ElMessage.error('部分数据验证失败，请检查输入')
    return
  }

  // 保存所有编辑中的行
  tableData.value.forEach((row) => {
    if (row.editing) {
      row.id = row.editData.id
      row.wellName = row.editData.wellName
      row.wellType = row.editData.wellType
      row.location = row.editData.location
      row.technique = row.editData.technique
      row.workloadDesign = row.editData.workloadDesign
      row.deptIds = row.editData.deptIds
      row.remark = row.editData.remark
    }
  })

  ElMessage.success('所有更改已保存')
}

// 取消编辑
const cancelEdit = (row) => {
  // 恢复原始数据
  if (row.originalData.id) {
    row.id = row.originalData.id
    row.wellName = row.originalData.wellName
    row.wellType = row.originalData.wellType
    row.location = row.originalData.location
    row.technique = row.originalData.technique
    row.workloadDesign = row.originalData.workloadDesign
    row.deptIds = row.originalData.deptIds
    row.remark = row.originalData.remark
  } else {
    // 如果是新增行，则删除
    const index = tableData.value.indexOf(row)
    if (index !== -1) {
      tableData.value.splice(index, 1)
    }
  }

  row.editing = false
}

// 删除行
const deleteRow = (index) => {
  tableData.value.splice(index, 1)
  ElMessage.success('行已删除')
}

// 添加监听部门ID变化的方法
watch(
  () => formData.value.deptId,
  async (newDeptId, oldDeptId) => {
    // 只有当部门ID确实发生变化时才加载选项
    if (newDeptId && newDeptId !== oldDeptId) {
      await loadWorkAreaOptions(newDeptId)
    }
  }
)

// 添加立即执行的监听器，用于处理编辑页面
watch(
  () => formData.value.deptId,
  async (newDeptId) => {
    if (newDeptId) {
      await loadWorkAreaOptions(newDeptId)
    } else {
      workAreaOptions.value = []
    }
  },
  { immediate: true }
)

// 加载工作区域选项的方法
const loadWorkAreaOptions = async (deptId: number) => {
  // 如果正在加载，直接返回
  if (loadingWorkAreaOptions.value) return

  loadingWorkAreaOptions.value = true
  try {
    // 先尝试通过 getDictLabel 获取字典标签
    const dictLabel = await getDictLabel(DICT_TYPE.PMS_PROJECT_WORK_AREA, deptId)
    console.log('当前专业公司的施工区域数据字典类型：' + dictLabel)
    // 将 dictLabel 存储到 currentDictLabel
    currentDictLabel.value = dictLabel || '' // 如果没有获取到，设为空字符串

    if (dictLabel) {
      // 如果获取到标签，再获取完整的字典选项
      const dictOptions = getStrDictOptions(dictLabel)
      console.log('当前专业公司的施工区域数据字典集合长度：' + dictOptions.length)
      workAreaOptions.value = dictOptions.map((option) => ({
        value: option.label, // 使用标签作为显示值
        id: option.value // 保留原始值
      }))
    } else {
      // 如果获取不到标签，清空选项
      workAreaOptions.value = []
    }
  } catch (error) {
    console.error('获取工作区域选项失败:', error)
    workAreaOptions.value = []
  } finally {
    loadingWorkAreaOptions.value = false
  }
}

// 当没有查询字符串时返回所有选项
const querySearch = (queryString: string, cb: any) => {
  // 如果没有查询字符串，返回所有选项
  if (!queryString) {
    cb(workAreaOptions.value)
    return
  }

  // 有查询字符串时进行筛选
  const results = workAreaOptions.value.filter((option) =>
    option.value.toLowerCase().includes(queryString.toLowerCase())
  )

  // 调用 callback 返回建议列表的数据
  cb(results)
}

// 添加选择处理方法
const handleSelect = (item: any) => {
  // 这里可以根据需要处理选择后的逻辑
  console.log('选择了:', item.value)
}
</script>

<style scoped>
.project-form-page {
  display: flex;
  flex-direction: column;
  gap: 12px;
  min-height: calc(
    100vh - 20px - var(--top-tool-height) - var(--tags-view-height) - var(--app-footer-height)
  );
}

.page-header {
  margin-bottom: 0;
}

.page-header :deep(.el-card__body) {
  display: flex;
  align-items: center;
  justify-content: space-between;
  min-height: 64px;
  padding: 12px 16px;
}

.page-header__main,
.dialog-title {
  display: flex;
  align-items: center;
  min-width: 0;
}

.page-header__icon,
.dialog-title__icon {
  display: inline-flex;
  flex: 0 0 auto;
  align-items: center;
  justify-content: center;
  width: 38px;
  height: 38px;
  margin-right: 12px;
  color: var(--el-color-primary);
  background: var(--el-color-primary-light-9);
  border: 1px solid var(--el-color-primary-light-7);
  border-radius: 6px;
}

.page-header__title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  line-height: 24px;
  letter-spacing: 0;
  color: var(--el-text-color-primary);
}

.page-header__subtitle,
.dialog-title__subtitle {
  margin: 2px 0 0;
  font-size: 12px;
  line-height: 18px;
  color: var(--el-text-color-secondary);
}

.project-form {
  display: flex;
  flex-direction: column;
  flex: 1;
  gap: 14px;
}

.project-form-card {
  margin-bottom: 0;
  overflow: hidden;
  border-radius: 8px;
}

.project-form-card :deep(.el-card__body) {
  padding: 0;
}

.form-card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 42px;
  padding: 0 16px;
  background: var(--el-fill-color-extra-light);
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.form-card-title {
  display: flex;
  align-items: center;
  min-width: 0;
}

.form-card-title > span {
  width: 4px;
  height: 17px;
  margin-right: 9px;
  background: var(--el-color-primary);
  border-radius: 2px;
}

.form-card-header h3 {
  margin: 0;
  font-size: 15px;
  font-weight: 600;
  line-height: 22px;
  color: var(--el-text-color-primary);
}

.form-card-hint {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  white-space: nowrap;
}

.form-card-body {
  padding: 18px 18px 2px;
}

.project-form :deep(.el-select),
.project-form :deep(.el-tree-select),
.project-form :deep(.el-date-editor),
.project-form :deep(.el-autocomplete) {
  width: 100%;
}

.project-form :deep(.el-form-item) {
  margin-bottom: 18px;
}

.project-form :deep(.el-form-item__label) {
  white-space: nowrap;
}

.responsible-person-control {
  display: flex;
  align-items: center;
  gap: 10px;
  width: 100%;
  min-width: 0;
}

.user-names {
  display: block;
  height: 32px;
  min-width: 0;
  padding: 0 11px;
  overflow: hidden;
  line-height: 30px;
  color: var(--el-text-color-regular);
  text-overflow: ellipsis;
  white-space: nowrap;
  border: 1px solid var(--el-border-color);
  border-radius: 4px;
  flex: 1;
}

.user-names--empty {
  color: var(--el-text-color-placeholder);
}

.form-actions {
  position: sticky;
  bottom: 0;
  z-index: 10;
  display: flex;
  flex-direction: row-reverse;
  gap: 10px;
  align-items: center;
  min-height: 58px;
  padding: 10px 16px;
  background: var(--el-bg-color);
  border-top: 1px solid var(--el-border-color-lighter);
  box-shadow: 0 -4px 12px rgb(0 0 0 / 4%);
}

.form-actions :deep(.el-button) {
  margin-left: 0;
}

.dialog-title__text {
  font-size: 16px;
  font-weight: 600;
  line-height: 24px;
  color: var(--el-text-color-primary);
}

.user-select-dialog :deep(.el-dialog__header) {
  padding: 16px 20px;
  margin-right: 0;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.user-select-dialog :deep(.el-dialog__body) {
  padding: 18px 20px;
}

.user-select-dialog :deep(.el-dialog__footer) {
  padding: 12px 20px;
  border-top: 1px solid var(--el-border-color-lighter);
}

.transfer-container {
  width: 100%;
}

:deep(.el-transfer-panel) {
  flex: 1;
  width: auto;
}

.transfer-component {
  display: flex;
  align-items: center;
  width: 100%;
  min-width: 0;
}

.transfer-component :deep(.el-transfer__buttons) {
  flex: 0 0 auto;
  padding: 0 16px;
}

:deep(.el-transfer-panel__item) {
  display: flex;
  align-items: center;
  height: 32px;
  padding: 0 8px;
  margin: 0;
  overflow: hidden;
  line-height: 32px;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.transfer-option-text {
  display: inline-block;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

:deep(.el-transfer-panel__list) {
  width: 100%;
}

:global(.work-area-autocomplete .el-autocomplete-suggestion__list) {
  max-height: 300px;
  overflow-y: auto;
}

:global(.work-area-autocomplete .el-autocomplete-suggestion__wrap) {
  max-height: 300px;
}

@media (width <= 768px) {
  .page-header :deep(.el-card__body) {
    align-items: flex-start;
  }

  .page-header__subtitle {
    display: none;
  }

  .form-card-hint {
    display: none;
  }

  .form-card-body {
    padding-right: 12px;
    padding-left: 12px;
  }

  .user-select-dialog :deep(.el-dialog) {
    width: calc(100% - 24px) !important;
  }

  .transfer-component {
    display: block;
  }

  .transfer-component :deep(.el-transfer-panel) {
    width: 100%;
  }

  .transfer-component :deep(.el-transfer__buttons) {
    display: flex;
    justify-content: center;
    padding: 12px 0;
  }
}
</style>
