<template>
    <view class="teamMemberModal">
        <view class="slot-content">
            <view class="title">工作区域/班组成员</view>
            <view class="content" v-if="selectedMember.length > 0">
                <view class="title-cell">
                    <view class="title-text">工作区域</view>
                    <view class="terminal-list">
                        {{ selectedMember[0].terminlName || '航站楼' }}
                    </view>
                </view>
                <view class="member-cell" v-if="selectedMember && selectedMember.length">
                    <view class="title-text">班组成员</view>
                    <view class="personnel-list">
                        <view class="personnel-item" v-for="item of selectedMember" :key="item.userId">
                            <view class="personnel-img">
                                <UserAvatar :userName="item.userName" :avatarLink="item.avatar" />
                            </view>
                            <view class="personnel-name">{{ item.userName }}</view>
                        </view>
                    </view>
                </view>
            </view>
            <view v-else :class="{ 'custom-btn': true, 'disabled': (!attendanceInfo.checkInTime||(attendanceInfo.checkInTime && attendanceInfo.checkOutTime)) }" @click="openModal">
                维护工作区域/班组成员</view>
        </view>
        <u-popup :show="show" mode="center" :round="8">
            <view class="modal-content">
                <view class="title">
                    <text>班组成员</text>
                    <u-icon name="close" color="#666666" size="20" @click="close" />
                </view>

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

                <view class="title-cell" v-if="searchViewShow">
                    <view style="margin-bottom: 15px;" v-if="addWorkUsers && addWorkUsers.length">
                        <view class="title-text">
                            {{ `添加人员(${addWorkUsers.length}人)` }}
                        </view>
                        <view class="personnel-list" v-if="addWorkUsers && addWorkUsers.length">
                            <view class="personnel-item" v-for="item of addWorkUsers" :key="item.userId"
                                @click="selectAddUser(item)">
                                <view class="personnel-img">
                                    <UserAvatar :userName="item.nickName" :avatarLink="item.avatar" />
                                </view>
                                <view class="personnel-name">{{ item.nickName }}</view>
                                <view class="personnel-close">
                                    <u-icon name="close" color="#666666" size="14" />
                                </view>
                            </view>
                        </view>
                    </view>
                    <view class="title-text">
                        {{ `搜索结果(${allUsers.length}人)` }}
                    </view>
                    <view class="personnel-list" v-if="allUsers && allUsers.length">
                        <view class="personnel-item" v-for="item of allUsers" :key="item.userId"
                            @click="selectAddUser(item)">
                            <view class="personnel-img">
                                <UserAvatar :userName="item.nickName" :avatarLink="item.avatar" />
                            </view>
                            <view class="personnel-name">{{ item.nickName }}</view>
                        </view>
                    </view>
                    <view v-else class="empty"></view>
                </view>

                <view class="title-cell" v-if="!searchViewShow && teamMembers && teamMembers.length">
                    <view class="title-text">{{ `班组成员(${teamMembers.length}人)` }}</view>
                    <view class="personnel-list">
                        <view class="personnel-item" v-for="item of teamMembers" :key="item.userId">
                            <view class="personnel-img">
                                <UserAvatar :userName="item.nickName" :avatarLink="item.avatar" />
                            </view>
                            <view class="personnel-name">{{ item.nickName }}</view>
                            <view class="personnel-close" @click="removeMember(item)">
                                <u-icon name="close" color="#666666" size="14" />
                            </view>
                        </view>
                    </view>
                </view>

                <view class="title-cell" v-if="!searchViewShow">
                    <view class="title-text">工作区域</view>
                    <view class="terminal-list">
                        <view class="terminal-item" v-for="terminal in channelList" :key="terminal.value"
                            :class="{ active: selectedTerminal === terminal.value }"
                            @click="selectTerminal(terminal.value)">
                            {{ terminal.text }}
                        </view>
                    </view>
                </view>

                <view class="footer-btn">
                    <view v-if="searchViewShow" class="custom-btn-normal" @click="appendWorkUsers"
                        :class="{ disabled: addWorkUsers.length === 0 }">
                        <text>添加人员</text>
                    </view>
                    <view v-else class="custom-btn-normal" @click="confirm"
                        :class="{ disabled: !selectedTerminal || loading }">
                        <text v-if="loading">处理中...</text>
                        <text v-else>确认</text>
                    </view>
                </view>
            </view>
        </u-popup>
    </view>
</template>

<script>
import UserAvatar from './UserAvatar'
import { dataConfigTree, memberList, addMember, getUserList } from "@/api/attendance/attendance"
import { formatName } from '@/utils/formatUtils'
import SelectData from './SelectData'
import moment from 'moment'
export default {
    components: { UserAvatar, SelectData },
    props: {
        userInfo: {
            type: Object,
            default: () => { }
        },
        attendanceInfo: {
            type: Object,
            default: () => ({
                attendanceDate: '', // 当前日期
                checkInTime: '', //上班打卡时间
                checkOutTime: '', //下班打卡时间
                items: [], // 打开记录 第一条为最早上班打卡时间 最后一条为最晚下班打卡时间
            })
        },
    },
    data() {
        return {
            show: false,
            searchText: '',
            selectedTerminal: '',
            teamMembers: [],//新增里面显示的member
            channelList: [],
            selectedMember: [],//已选择班组数据

            userOptions: [],
            allUsers: [],//所有的人员
            searchViewShow: false,//搜索人员
            addWorkUsers: [], // 额外添加的人员 
            teamUsers: [],//同组用户,
            loading: false // 防止重复点击的loading状态
        }
    },
    computed: {
        notkezhang() {
            // console.log(!this.userInfo.roles || !this.userInfo.roles.includes('kezhang'), "!this.userInfo.roles || !this.userInfo.roles.includes('kezhang')")
            return !this.userInfo.roles || !this.userInfo.roles.includes('kezhang')
        },
    },
    mounted() {
        this.invokerDataConfigTree(3)
        console.log(this.userInfo, "userInfo")

        //获取选中的成员
        this.getSelectedMember()
    },
    methods: {
        selectAddUser(selectItem) { // 移除额外添加人员
            console.log(selectItem, "selectItem", this.addWorkUsers)

            const index = this.addWorkUsers.findIndex(item => item.userId === selectItem.userId)
            if (index >= 0) {
                this.addWorkUsers.splice(index, 1)
            } else {
                this.addWorkUsers.push(selectItem)
            }
        },
        appendWorkUsers() {
            console.log("appendWorkUsers", this.addWorkUsers, this.teamMembers)
            if (this.addWorkUsers.length) {
                this.addWorkUsers.forEach(item => {
                    if (!this.teamMembers.some(member => member.userId === item.userId)) {
                        this.teamMembers.push(item)
                    }
                })
                this.addWorkUsers = []
                this.searchViewShow = false
                this.$refs.selectData.clearInput()
            }
        },
        searchViewShowHandler(show) { // 是否展示搜索用户界面

            if (this.addWorkUsers.length) {
                this.searchViewShow = show || this.addWorkUsers.length
            } else {
                this.searchViewShow = true
            }
        },
        //获取默认的teammember
        getTeamMember() {

            this.loadTeamUsers().then(() => {
                // 选中全组人员  
                this.teamMembers = this.teamUsers
            })
        },
        // 加载同组用户
        async loadTeamUsers() {
            try {
                const currentUserInfo = this.userInfo || {}
                const currentUserDeptId = currentUserInfo.deptId || currentUserInfo.teamsId;
                // 调用用户列表接口，传递deptId获取同组用户
                const response = await getUserList({
                    deptId: currentUserDeptId, // 🔥 使用从getInfo获取的deptId
                    status: '0', // 只获取正常状态的用户
                    pageSize: 100
                });

                if (response && response.code === 200) {
                    this.teamUsers = (response.rows || []).map(item => {
                        return {
                            ...item,
                            nickName: formatName(item.nickName)
                        }
                    })
                } else {
                    throw new Error(response.msg || '获取同组用户失败');
                }
            } catch (error) {
                uni.showToast({
                    title: '加载同组用户失败',
                    icon: 'none',
                    duration: 2000
                });
                // 设置空数组，避免页面报错
                this.teamUsers = [];
            }
        },
        //回显member
        getSelectedMember() {

            memberList({
                attendanceTeamId: this.userInfo.teamsId,
                attendanceDate: moment().format('YYYY-MM-DD')
            }).then(res => {

                this.selectedMember = res.data || []
                this.$emit('update-member', this.selectedMember)
            })



        },
        //新增时候显示的member
        async initMember() {
            const currentUserInfo = this.userInfo || {}
            const currentUserDeptId = currentUserInfo.deptId || currentUserInfo.teamsId;
            // 调用用户列表接口，传递deptId获取同组用户
            const response = await getUserList({
                deptId: currentUserDeptId, // 🔥 使用从getInfo获取的deptId
                status: '0', // 只获取正常状态的用户
                pageSize: 100
            });
            console.log(response, "response")
            if (response && response.code === 200) {
                this.userOptions = (response.rows || []).map(item => ({
                    ...item,
                    value: item.userId,
                    text: formatName(item.nickName)
                }));
            } else {
                throw new Error(response.msg || '获取同组用户失败');
            }
        },
        handleUserSelect(selected) {
            this.teamMembers = this.userOptions
                .filter(option => selected.map(item => item.value).includes(option.value))
                .map(option => ({
                    ...option,
                    userId: option.value,
                    nickName: option.text,
                    avatar: ''
                }));
        },
        convertTree(list = []) {
            return list.map(node => ({
                text: node.label,
                value: node.code,
                children: node.children ? this.convertTree(node.children) : null
            }))
        },
        invokerDataConfigTree(level) {
            return dataConfigTree(level).then(res => {
                this.channelList = this.convertTree(res.data || [])
                console.log(this.channelList, "this.channelList")
            }).catch(() => {
                this.channelList = []
            })
        },
        //搜索用户
        async searchUsers(value) {

            const keyword = value.trim();
            if (!keyword) {
                this.allUsers = [];
                return;
            }
            try {
                // 调用用户搜索接口，不限制部门
                const response = await getUserList({
                    nickName: keyword,    // 按昵称搜索
                    status: '0', // 只获取正常状态的用户
                    pageSize: 100        // 只获取正常状态的用户
                });
                if (response && response.code === 200) {
                    this.allUsers = (response.rows || []).map(item => {
                        return {
                            ...item,
                            nickName: formatName(item.nickName)
                        }
                    });
                } else {
                    this.allUsers = [];
                }
            } catch (error) {
                this.allUsers = [];
                uni.showToast({
                    title: '搜索失败，请重试',
                    icon: 'none',
                    duration: 2000
                });
            }
        },
        close() {
            if(this.searchViewShow){
                this.searchViewShow = false;
                return;
            }

            this.show = false
        },
        removeMember(member) {
            this.teamMembers = this.teamMembers.filter(item => item.userId !== member.userId)

        },
        selectTerminal(terminal) {
            this.selectedTerminal = terminal
        },
        confirm() {
            if (!this.selectedTerminal) return;
            this.loading = true;
            let selectTerminal = this.channelList.find(item => item.value === this.selectedTerminal)
            let res = this.teamMembers.map(item => {
                return {
                    ...item,
                    nickName: item.nickName.replace(/\s+/g, ""),
                    attendanceTeamId: this.userInfo.teamsId,
                    attendanceTeamName: this.userInfo.teamsName,
                    terminlCode: selectTerminal.value,
                    terminlName: selectTerminal.text,
                    userName: item.nickName.replace(/\s+/g, ""),
                    userId: item.userId,
                }
            })

            addMember(res).then(res => {
                uni.showToast({ title: '提交成功', icon: 'success' });
                this.close()
                this.getSelectedMember()
                return res;
            }).finally(() => {
                this.loading = false
            })
        },
        openModal() {
            if ((!this.attendanceInfo.checkInTime||(this.attendanceInfo.checkInTime && this.attendanceInfo.checkOutTime))) {
                return;
            }
            this.show = true;
            this.initMember()
            this.getTeamMember()
        }
    }
}
</script>

<style lang="scss" scoped>
.teamMemberModal {
    .slot-content {

        width: 100%;
        background: #FFFFFF;
        box-shadow: 0px 4px 10px 0px rgba(0, 0, 0, 0.08);
        border-radius: 16px 16px 16px 16px;
        border: 1px solid #F0F8FF;
        padding: 15px;
        box-sizing: border-box;

        .title {
            height: 48rpx;
            font-weight: 400;
            font-size: 33rpx;
            color: #333333;
            line-height: 42rpx;
            display: flex;
            justify-content: space-between;
            align-items: center;
            // padding: 30rpx;
            box-sizing: border-box;
        }

        .content {
            // padding: 0 46rpx;


            .title-cell {
                display: flex;
                height: 36px;
                line-height: 36px;
                justify-content: space-between;
                color: #222222;
                font-size: 27rpx;
                // padding: 10rpx 0;

                .terminal-list {
                    color: #6C6C6C;
                }
            }

            .member-cell {
                display: flex;


                color: #222222;
                font-size: 27rpx;

                flex-direction: column;

                .title-text {
                    height: 36px;
                    line-height: 36px;
                }

                .personnel-list {
                    display: flex;
                    flex-wrap: wrap;
                    row-gap: 19rpx;
                    column-gap: 19rpx;

                    .personnel-item {
                        width: fit-content;
                        height: 68rpx;
                        background: #F0F0F0;
                        border-radius: 12rpx;
                        display: flex;
                        align-items: center;
                        column-gap: 12rpx;
                        padding: 0 10rpx;

                        .personnel-img {
                            width: 48rpx;
                            height: 48rpx;
                            border-radius: 12rpx;
                            overflow: hidden;
                        }

                        .personnel-name {
                            width: fit-content;
                            font-weight: 400;
                            font-size: 26rpx;
                            color: #3D3D3D;
                            text-align: left;
                            font-style: normal;
                            text-transform: none;
                        }

                        .personnel-close {
                            width: 32rpx;
                        }
                    }
                }
            }
        }

    }

    .modal-content {
        width: 90vw;
        max-height: 75vh;
        padding: 20rpx 0;

        .title {
            height: 48rpx;
            font-weight: 400;
            font-size: 36rpx;
            color: #333333;
            line-height: 42rpx;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 30rpx;
            box-sizing: border-box;
        }

        .search-box {
            padding: 20rpx 30rpx;
        }

        .title-cell {
            padding: 20rpx 30rpx;
            box-sizing: border-box;

            .title-text {
                height: 32rpx;
                font-weight: 400;
                font-size: 28rpx;
                color: #333333;
                line-height: 32rpx;
                text-align: left;
                margin-bottom: 28rpx;
                text-indent: 10rpx;
            }
        }

        .personnel-list {
            display: flex;
            flex-wrap: wrap;
            row-gap: 16rpx;
            column-gap: 12rpx;

            .personnel-item {
                width: fit-content;
                height: 68rpx;
                background: #F0F0F0;
                border-radius: 12rpx;
                display: flex;
                align-items: center;
                column-gap: 12rpx;
                padding: 0 10rpx;

                .personnel-img {
                    width: 48rpx;
                    height: 48rpx;
                    border-radius: 12rpx;
                    overflow: hidden;
                }

                .personnel-name {
                    width: fit-content;
                    font-weight: 400;
                    font-size: 26rpx;
                    color: #3D3D3D;
                    text-align: left;
                    font-style: normal;
                    text-transform: none;
                }

                .personnel-close {
                    width: 32rpx;
                }
            }
        }

        .terminal-list {
            display: flex;
            flex-direction: row;
            gap: 20rpx;

            .terminal-item {
                padding: 20rpx;
                border: 1px solid #ddd;
                border-radius: 12rpx;
                text-align: center;
                cursor: pointer;
                transition: all 0.3s;

                &.active {
                    background-color: #f0f0f0;
                    border-color: #2196F3;
                }

                &:hover {
                    background-color: #f5f5f5;
                }
            }
        }

        .footer-btn {
            padding: 20rpx 30rpx;


        }
    }
}
</style>