<template>
  <view class="select-person-modal">
    <view class="slot-content" @click.stop="openModal">
      <slot></slot>
    </view>
    <u-popup :show="show" mode="center" :round="8" @close="close">
      <view class="modal-content">
        <view class="title">
          <text>选择人员</text>
          <u-icon name="close" color="#666666" size="20" @click="close" />
        </view>

        <view class="title-cell">
          <SelectData ref="selectData" @search="searchUsers" @searchViewShowEvent="searchViewShowHandler" />
        </view>

        <view class="title-cell" v-if="!searchViewShow && selectedUsers && selectedUsers.length">
          <view class="title-text">{{ `已选人员(${selectedUsers.length}人)` }}</view>
          <list-user :data="selectedUsers" :show-delete="true" @delete="handleRemoveSelectedUser" />
        </view>

        <view class="title-cell" v-if="searchViewShow">
          <view style="margin-bottom: 15px;" v-if="addUsers && addUsers.length">
            <view class="title-text">
              {{ `添加人员(${addUsers.length}人)` }}
            </view>
            <list-user :data="addUsers" :show-delete="true" @delete="handleRemoveAddUser" />
          </view>

          <view class="title-text">
            {{ `搜索结果(${searchResults.length}人)` }}
          </view>
          <list-user v-if="searchResults && searchResults.length" :data="searchResults" :show-delete="false"
            @delete="handleRemoveSearchResult" @click="handleSearchResultClick" />
          <view v-else class="empty">
            <text v-if="searchKeyword">暂无搜索结果</text>
            <text v-else>请输入关键词搜索</text>
          </view>
        </view>

        <view class="footer-btn">
          <view v-if="searchViewShow" class="custom-btn-normal" @click="appendUsers"
            :class="{ disabled: addUsers.length === 0 }">添加人员</view>
          <view v-else class="custom-btn-normal" @click="confirmSelection"
            :class="{ disabled: selectedUsers.length === 0 }">确认选择</view>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import SelectData from '@/pages/attendance/components/SelectData'
import UserAvatar from '@/pages/attendance/components/UserAvatar'
import { formatName } from '@/utils/formatUtils'
import {
  getUserList,
} from "@/api/attendance/attendance"
export default {
  components: { SelectData, UserAvatar },
  props: {
    // 初始选中的人员列表
    value: {
      type: Array,
      default: () => []
    },
    // 是否多选
    multiple: {
      type: Boolean,
      default: true
    },
    // 占位符文本
    placeholder: {
      type: String,
      default: '点击选择人员'
    },
    // 是否禁用
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      show: false,
      selectedUsers: [], // 选中的人员
      searchResults: [], // 搜索结果
      addUsers: [], // 待添加的人员
      searchViewShow: false,
      searchKeyword: ''
    }
  },
  watch: {
    value: {
      handler(newValue) {
        this.selectedUsers = [...newValue]
      },
      immediate: true
    },
    show(newValue) {
      if (newValue) {
        this.searchViewShow = false
        this.searchResults = []
        this.addUsers = []
        this.searchKeyword = ''
        if (this.$refs.selectData) {
          this.$refs.selectData.clearInput()
        }
      }
    }
  },
  methods: {
    openModal() {
      if (this.disabled) return
      this.show = true
    },
    close() {
      this.show = false
    },

    searchViewShowHandler(show) {
      this.searchViewShow = show || this.addUsers.length
    },

    // 搜索用户
    async searchUsers(keyword) {
   
      this.searchKeyword = keyword.trim()
      if (!this.searchKeyword) {
        this.searchResults = []
        return
      }

      try {
        const response = await getUserList({
          nickName: this.searchKeyword,
          status: '0'
        })
        

        if (response && response.code === 200) {
          this.searchResults = (response.rows || []).map(item => ({
            ...item,
            nickName: formatName(item.nickName),
            // 确保包含部门信息
            deptName: item.dept?.deptName || item.deptName || ''
          }))
        } else {
          this.searchResults = []
          uni.showToast({
            title: '搜索失败，请重试',
            icon: 'none',
            duration: 2000
          })
        }
      } catch (error) {
        this.searchResults = []
        uni.showToast({
          title: '搜索失败，请重试',
          icon: 'none',
          duration: 2000
        })
      }
    },

    // 选择待添加人员
    selectAddUser(user) {
      const index = this.addUsers.findIndex(item => item.userId === user.userId)
      if (index >= 0) {
        this.addUsers.splice(index, 1)
      } else {
        this.addUsers.push(user)
      }
    },

    // 添加人员到选中列表
    appendUsers() {
      if (this.addUsers.length) {
        this.addUsers.forEach(user => {
          // 确保添加的人员数据包含部门信息
          const userWithDept = {
            ...user,
            dept_name: user.dept?.deptName || user.deptName || ''
          };
          this.selectUser(userWithDept, false)
        })
        this.addUsers = []
        this.searchViewShow = false
        if (this.$refs.selectData) {
          this.$refs.selectData.clearInput()
        }
      }
    },

    // 移除选中人员
    removeSelectedUser(user, onlyCheck = false) {
      const index = this.selectedUsers.findIndex(item => item.userId === user.userId)
      if (index >= 0) {
        if (!onlyCheck) {
          this.selectedUsers.splice(index, 1)
        }
        return undefined
      }
      return user
    },

    // 处理删除已选人员
    handleRemoveSelectedUser({ deletedItem, index, newData }) {
      this.selectedUsers = newData
    },

    // 处理删除待添加人员
    handleRemoveAddUser({ deletedItem, index, newData }) {
      this.addUsers = newData
    },

    // 处理删除搜索结果（虽然不应该有删除操作，但为了完整性）
    handleRemoveSearchResult({ deletedItem, index, newData }) {
      this.searchResults = newData
    },

    // 选择人员处理
    selectUser(user, unique = true) {
      const addItem = this.removeSelectedUser(user, !unique)
      if (addItem) {
        this.selectedUsers.push(addItem)
      }
    },

    // 确认选择
    confirmSelection() {
      if (this.selectedUsers.length === 0) {
        uni.showToast({
          title: '请选择至少一位人员',
          icon: 'none'
        })
        return
      }

    
      this.$emit('change', this.selectedUsers)
      this.$emit('confirm', this.selectedUsers)

      this.show = false

      uni.showToast({
        title: `已选择${this.selectedUsers.length}人`,
        icon: 'success',
        duration: 1500
      })
    },

    // 处理搜索结果点击
    handleSearchResultClick({ clickedItem, index, data }) {
      if (clickedItem) {
        this.selectAddUser(clickedItem)
      }
    },
  }
}
</script>

<style lang="scss" scoped>
.select-person-modal {
  .slot-content {
    display: inline-block;
  }

  .empty {
    text-align: center;
    padding: 20px;
    color: #999;
    font-size: 14px;
  }

  .modal-content {
    width: 90vw;
    max-height: 75vh;
    padding: 10px 0;
    overflow-y: auto;

    .title {
      height: 24px;
      font-weight: 400;
      font-size: 18px;
      color: #333333;
      line-height: 21px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 15px;
      box-sizing: border-box;
      border-bottom: 1px solid #f0f0f0;
    }

    .title-cell {
      padding: 15px;

      .title-text {
        font-size: 16px;
        font-weight: 500;
        color: #333;
        margin-bottom: 12px;
      }
    }

    .footer-btn {
      padding: 15px;
      border-top: 1px solid #f0f0f0;


    }
  }
}
</style>