package jnpf.attendance.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jnpf.attendance.mapper.UserPhoneMapper;
import jnpf.attendance.service.CommonSettingService;
import jnpf.attendance.service.UsualPhoneService;
import jnpf.base.ActionResult;
import jnpf.base.service.SuperServiceImpl;
import jnpf.entity.attendance.AttendanceCommonSetting;
import jnpf.entity.attendance.AttendanceUserPhone;
import jnpf.enums.attendance.SettingGroup;
import jnpf.model.attendance.dto.CancelPhoneDto;
import jnpf.model.attendance.dto.UsualPhoneDto;
import jnpf.model.attendance.dto.UsualPhoneQueryDto;
import jnpf.model.attendance.dto.UsualPhoneSettingDto;
import jnpf.model.attendance.vo.attendance.UsualPhonePageVo;
import jnpf.permission.V2UserApi;
import jnpf.permission.vo.v2.user.UserBoundVO;
import jnpf.util.ConstantUtil;
import jnpf.util.DateUtil;
import jnpf.util.FtbUtil;
import jnpf.util.UserProvider;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 常用设备服务实现
 *
 * @author yanwenfu
 * @create 2025-09-18
 */
@Service
public class UsualPhoneServiceImpl extends SuperServiceImpl<UserPhoneMapper, AttendanceUserPhone> implements UsualPhoneService {

    @Resource
    private CommonSettingService commonSettingService;
    @Resource
    private UserPhoneMapper userPhoneMapper;
    @Autowired
    private V2UserApi v2UserApi;

    @Override
    public void cancelPhoneBatch(CancelPhoneDto cancelPhoneDto) {

        this.update(new LambdaUpdateWrapper<AttendanceUserPhone>()
                        .set(AttendanceUserPhone::getDeleteMark, ConstantUtil.NUM_TRUE)
                        .set(AttendanceUserPhone::getDeleteTime, DateUtil.getNowDate())
                        .set(AttendanceUserPhone::getDeleteUserId, UserProvider.getLoginUserId())
                        .in(AttendanceUserPhone::getId, cancelPhoneDto.getCancelIdList()));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateUsualPhoneSetting(UsualPhoneSettingDto usualPhoneSettingDto) {

        List<AttendanceCommonSetting> list = FtbUtil.generateCommonSetting(SettingGroup.USUAL_PHONE, usualPhoneSettingDto, UserProvider.getLoginUserId());
        // 删除数据库配置
        commonSettingService.remove(new LambdaQueryWrapper<AttendanceCommonSetting>()
                .eq(AttendanceCommonSetting::getSettingGroup, SettingGroup.USUAL_PHONE.getValue()));
        // 添加新的配置
        commonSettingService.saveBatch(list);
    }

    @Override
    public PageInfo<UsualPhonePageVo> getUsualPhonePage(UsualPhoneQueryDto queryDto) {

        if (StringUtils.isEmpty(queryDto.getUserName())) {
            // 分页查询
            PageHelper.startPage(queryDto.getCurrentPage(), queryDto.getPageSize());
            PageInfo<UsualPhonePageVo> page = new PageInfo<>(userPhoneMapper.getUsualPhoneList(null));
            if (page.getList().isEmpty()) {
                return page;
            }
            List<String> userIds = page.getList().stream().map(UsualPhonePageVo::getUserId).collect(Collectors.toList());
            List<UserBoundVO> data = v2UserApi.userListAndCopy(userIds, null, UserProvider.getUser().getTenantId());
            if (null != data && !data.isEmpty()) {
                fillUserInfo(data, page.getList());
            }
            return page;
        } else {
            List<UserBoundVO> userList = v2UserApi.userListAndCopyLikeName(queryDto.getUserName(), null, UserProvider.getUser().getTenantId());
            if (userList.isEmpty()) {
                return new PageInfo<>();
            }
            List<String> collect = userList.stream().map(UserBoundVO::getId).collect(Collectors.toList());
            PageInfo<UsualPhonePageVo> page = new PageInfo<>(userPhoneMapper.getUsualPhoneList(collect));
            if (page.getList().isEmpty()) {
                return new PageInfo<>();
            }
            fillUserInfo(userList, page.getList());
            return page;
        }
    }

    private void fillUserInfo(List<UserBoundVO> data, List<UsualPhonePageVo> list) {
        Map<String, UserBoundVO> userMap = data.stream().collect(Collectors.toMap(UserBoundVO::getId, Function.identity()));
        list.forEach(v -> {
            UserBoundVO user = userMap.get(v.getUserId());
            if (null != user) {
                v.setUserName(user.getFormCopy() ? user.getUserName() + "（离职）" : user.getUserName());
                v.setOrganizeId(user.getOrganizeId());
                v.setOrganizeName(user.getOrganizeName());
            }
        });
    }

    @Override
    public void addUsualPhone(UsualPhoneDto usualPhoneDto) {

        // 查询常用手机记录
        List<AttendanceUserPhone> phoneList = this.list(new LambdaQueryWrapper<AttendanceUserPhone>()
                .eq(AttendanceUserPhone::getUserId, usualPhoneDto.getUserId()));
        // 查询配置
        UsualPhoneSettingDto dto = getUsualPhoneSetting();
        // 判定记录是否存在 是否超出设备数量限制
        if (phoneList.size() >= dto.getUsualPhoneNum()) {
            return;
        }
        // 新增常用设备
        addNewUsualPhone(usualPhoneDto, UserProvider.getLoginUserId());
    }

    private void addNewUsualPhone(UsualPhoneDto usualPhoneDto, String userId) {

        AttendanceUserPhone userPhone = new AttendanceUserPhone();
        userPhone.setId(FtbUtil.getId());
        userPhone.setUserId(usualPhoneDto.getUserId());
        userPhone.setPhoneName(usualPhoneDto.getPhoneName());
        userPhone.setPhoneCode(usualPhoneDto.getPhoneCode());
        userPhone.setCreatorUserId(userId);
        userPhone.setLastModifyUserId(userId);
        userPhone.setDeleteMark(ConstantUtil.NUM_FALSE);
        this.save(userPhone);
    }

    @Override
    public UsualPhoneSettingDto getUsualPhoneSetting() {

        List<AttendanceCommonSetting> list = commonSettingService.list(new LambdaQueryWrapper<AttendanceCommonSetting>()
                .eq(AttendanceCommonSetting::getSettingGroup, SettingGroup.USUAL_PHONE.getValue()));
        return FtbUtil.changeListToSetting(list, UsualPhoneSettingDto.class);
    }

    @Override
    public Boolean checkUsualPhone(String phoneName, String phoneCode) {

        String userId = UserProvider.getLoginUserId();
        List<AttendanceUserPhone> phoneList = this.list(new LambdaQueryWrapper<AttendanceUserPhone>()
                .eq(AttendanceUserPhone::getUserId, userId)
                .eq(AttendanceUserPhone::getDeleteMark, ConstantUtil.NUM_FALSE));
        // 判定手机名称是否在常用列表中
        AttendanceUserPhone userPhone = phoneList.stream().filter(v -> v.getPhoneCode().equals(phoneCode)).findFirst().orElse(null);
        if (null != userPhone) {
            // 未异常
            return Boolean.FALSE;
        }
        // 判定是否超出常用设备数量
        UsualPhoneSettingDto dto = getUsualPhoneSetting();
        // 判定记录是否存在 是否超出设备数量限制
        if (phoneList.size() >= dto.getUsualPhoneNum()) {
            return Boolean.TRUE;
        }
        // 未超出数量, 新增常用设备
        addNewUsualPhone(new UsualPhoneDto(userId, phoneName, phoneCode), userId);
        return Boolean.FALSE;
    }
}
