package com.storlead.centre.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.storlead.centre.entity.AttendanceSignRecordEntity;
import com.storlead.centre.mapper.AttendanceSignRecordMapper;
import com.storlead.centre.service.SystemConfigItemService;
import com.storlead.framework.common.constant.CommonConstant;
import com.storlead.framework.common.util.DateUtils;
import com.storlead.user.pojo.entity.JobEntity;
import com.storlead.user.pojo.entity.UserEntity;
import com.storlead.user.service.IUserService;
import com.storlead.user.service.impl.UserServiceImpl;
import com.storlead.wx.pojo.vo.CheckinDataBO;
import com.storlead.centre.service.AttendanceSignRecordService;
import com.storlead.framework.mybatis.service.impl.MyBaseServiceImpl;
import com.storlead.wx.service.CorpWeChatService;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * OA系统签到/签退记录表 服务实现类
 * </p>
 *
 * @author chenkq
 * @since 2026-01-04
 */
@Log4j2
@Service
public class AttendanceSignRecordServiceImpl extends MyBaseServiceImpl<AttendanceSignRecordMapper, AttendanceSignRecordEntity> implements AttendanceSignRecordService {

    @Resource
    private CorpWeChatService corpWeChatService;
    @Resource
    private SystemConfigItemService systemConfigItemService;

    @Resource
    private IUserService userService;

    @Override
    public void getSaveSignRecord() {

        LambdaQueryWrapper<UserEntity> lm = new LambdaQueryWrapper<>();
        lm.isNotNull(UserEntity::getXworkUserId);
        lm.ne(UserEntity::getXworkUserId,"");
        lm.eq(UserEntity::getIsDelete,CommonConstant.DEL_FLAG_0);
        lm.eq(UserEntity::getEnabled,1);
        List<UserEntity> userEntities = userService.list(lm);
        if (CollectionUtils.isEmpty(userEntities)) {
            return;
        }
        Map<String, UserEntity> userMap = userEntities.stream()
                .filter(u -> u.getXworkUserId() != null)
                .collect(Collectors.toMap(
                        UserEntity::getXworkUserId,
                        userEntity -> userEntity,
                        (oldVal, newVal) -> oldVal
                ));
        List<String> wxUserIds = userEntities.stream().map(UserEntity::getXworkUserId).collect(Collectors.toList());
        List<CheckinDataBO> checkins = new ArrayList<>();

        Long currentTime = System.currentTimeMillis() / 1000;
        Long starttime =  systemConfigItemService.getCheckinDataTime();
        Long endtime = currentTime;

        int batchSize = 90;
        for (int i = 0; i < wxUserIds.size(); i += batchSize) {
            int end = Math.min(i + batchSize, wxUserIds.size());
            List<String> subList = wxUserIds.subList(i, end);
            List<CheckinDataBO> batchResult = getSaveSignRecord(subList,3,starttime,endtime);
            if (batchResult != null && !batchResult.isEmpty()) {
                checkins.addAll(batchResult);
            }
        }

        LocalDateTime dateTime = timestampToLocalDateTime(endtime);
        String time = dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        log.error(endtime+"---------跑到了这里-----"+time);
        systemConfigItemService.setCheckinDataTime(endtime);
        if (CollectionUtils.isEmpty(checkins)) {
            return;
        }
        List<AttendanceSignRecordEntity> signls = appPageInfoListToAppPageTreeVoList(checkins);
        if (CollectionUtils.isEmpty(signls)) {
            return ;
        }
        for (AttendanceSignRecordEntity signRecord : signls) {
            UserEntity user = userMap.get(signRecord.getWxUserId());
            if (Objects.nonNull(user)) {
                signRecord.setUserId(user.getId());
                signRecord.setUserName(user.getRealName());
                signRecord.setDeptId(user.getDeptId());
            }
        }
        // 保存打卡记录
        this.saveBatch(signls);
    }
    /**
     * 获取打卡信息
     */
    @Override
    public List<CheckinDataBO> getSaveSignRecord(List<String> wxUserIds,Integer opencheckindatatype,Long starttime,Long endtime) {

        List<CheckinDataBO> checkinds =  corpWeChatService.getCheckinDayData(wxUserIds,starttime,endtime,opencheckindatatype);
        // 存储打卡信息
        if (CollectionUtils.isEmpty(checkinds)) {
            return null;
        }

        return checkinds;
    }

    /**
     * 获取需要同步的数据进行同步
     * @return
     */
    public List<AttendanceSignRecordEntity> getSignSyncRecord() {

        LambdaQueryWrapper<AttendanceSignRecordEntity> wq = new LambdaQueryWrapper<>();
        wq.eq(AttendanceSignRecordEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        wq.eq(AttendanceSignRecordEntity::getSyncOa,Integer.valueOf(0));
        List<AttendanceSignRecordEntity> recordls = this.list(wq);
        return recordls;
    }

   public  List<AttendanceSignRecordEntity> appPageInfoListToAppPageTreeVoList(List<CheckinDataBO> vals) {
        if (CollectionUtils.isEmpty(vals)) {
            return null;
        }
        List<AttendanceSignRecordEntity> departmentTrees = vals.stream().map(this::appPageInfoListToAppPageTreeVo).filter(obj -> !Objects.isNull(obj)).collect(Collectors.toList());
        return departmentTrees;
    }

    public  AttendanceSignRecordEntity  appPageInfoListToAppPageTreeVo(CheckinDataBO bo) {
        if (null == bo) {
            return null;
        }
        try {
            AttendanceSignRecordEntity entity = new AttendanceSignRecordEntity();

            entity.setWxUserId(bo.getUserId());
            entity.setGroupId(bo.getGroupId());
            entity.setGroupName(bo.getGroupName());
            entity.setCheckinType(bo.getCheckinType());
            entity.setExceptionType(bo.getExceptionType());
            entity.setCheckinWxTime(bo.getCheckinTime());
            LocalDateTime dateTime = timestampToLocalDateTime(bo.getCheckinTime());

            log.error(bo.getCheckinTime()+"-------打卡时间---------"+dateTime);
            DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");
            String timeStr = dateTime.format(timeFormatter);
            entity.setCheckinDate(dateTime.toLocalDate());
            entity.setCheckinTime(timeStr);
            entity.setLocationTitle(bo.getLocationTitle());
            entity.setLocationDetail(bo.getLocationDetail());
            entity.setWifiName(bo.getWifiName());
            entity.setWifiMac(bo.getWifiMac());
            if (StrUtil.isNotBlank(bo.getLat())) {
                Long lat = Long.valueOf(bo.getLat());
                Double latd = lat / 1000000.0d;
                entity.setLatitude(latd.toString());
            }
            if (StrUtil.isNotBlank(bo.getLng())) {
                Long lng = Long.valueOf(bo.getLng());
                Double lngd = lng / 1000000.0d;
                entity.setLongitude(lngd.toString());
            }

            entity.setDeviceId(bo.getDeviceId());
            // 媒体ID列表（如果是 JSON 存库，这里可序列化）
            if (!CollectionUtils.isEmpty(bo.getMediaIds())) {
                entity.setMediaIds(JSON.toJSONString(bo.getMediaIds()));
            }
            return entity;
        }catch (Exception e) {
            return null;
        }
    }

    public static LocalDateTime timestampToLocalDateTime(Long timestamp) {

        LocalDateTime dateTime = Instant.ofEpochSecond(timestamp)
                .atZone(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();

        return dateTime;
    }

    public static String timestampToLocalTime(Long timestamp) {
        String time = Instant.ofEpochMilli(timestamp)
                .atZone(ZoneId.of("Asia/Shanghai"))
                .format(DateTimeFormatter.ofPattern("HH:mm:ss"));

        log.error("时间--------"+time);
        return time;
    }


//    public ld dd() {
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//        String time = sdf.format(new Date(timestamp));
//    }

    public static void main(String[] args) {
        LocalDateTime dateTime = timestampToLocalDateTime(1767840360L);
        log.error("---------"+dateTime);
    }
}
