package com.mortals.xhx.module.attendance.service.impl;

import com.dingtalk.api.response.OapiAttendanceGetsimplegroupsResponse;
import com.mortals.framework.common.Rest;
import com.mortals.framework.model.PageInfo;
import com.mortals.framework.util.DataUtil;
import com.mortals.xhx.common.code.AttendanceTypeEnum;
import com.mortals.xhx.common.code.YesNoEnum;
import com.mortals.xhx.module.attendance.model.*;
import com.mortals.xhx.module.attendance.service.AttendanceGroupFixedworkService;
import com.mortals.xhx.module.dingding.attendance.service.IDingAttenanceService;
import com.mortals.xhx.module.staff.model.StaffEntity;
import com.mortals.xhx.module.staff.service.StaffService;
import org.springframework.stereotype.Service;
import com.mortals.framework.service.impl.AbstractCRUDServiceImpl;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.xhx.module.attendance.dao.AttendanceGroupDao;
import com.mortals.xhx.module.attendance.service.AttendanceGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import com.mortals.xhx.module.attendance.service.AttendanceGroupStaffService;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * AttendanceGroupService
 * 考勤组信息 service实现
 *
 * @author zxfei
 * @date 2023-04-08
 */
@Service("attendanceGroupService")
public class AttendanceGroupServiceImpl extends AbstractCRUDServiceImpl<AttendanceGroupDao, AttendanceGroupEntity, Long> implements AttendanceGroupService {
    @Autowired
    private AttendanceGroupStaffService attendanceGroupStaffService;

    @Autowired
    private AttendanceGroupStaffService groupStaffService;
    @Autowired
    private AttendanceGroupFixedworkService fixedworkService;

    @Autowired
    private IDingAttenanceService dingAttenanceService;

    @Autowired
    private StaffService staffService;


    @Override
    protected void saveAfter(AttendanceGroupEntity entity, Context context) throws AppException {
        if (!ObjectUtils.isEmpty(entity.getAttendanceGroupStaffList())) {
            entity.getAttendanceGroupStaffList().stream().peek(item -> {
                item.setGroupId(entity.getId());
                item.setGroupName(entity.getGroupName());
                item.setCreateUser(context.getUser().getLoginName());
                item.setCreateUserId(context.getUser().getId());
                item.setCreateTime(new Date());
            }).count();
            attendanceGroupStaffService.save(entity.getAttendanceGroupStaffList());
        }
        super.saveAfter(entity, context);
    }

    @Override
    protected void updateAfter(AttendanceGroupEntity entity, Context context) throws AppException {
        if (!ObjectUtils.isEmpty(entity.getAttendanceGroupStaffList())) {
            Long[] attendanceGroupStaffIds = attendanceGroupStaffService.find(new AttendanceGroupStaffQuery().groupId(entity.getId())).stream().map(AttendanceGroupStaffEntity::getId).toArray(Long[]::new);
            attendanceGroupStaffService.remove(attendanceGroupStaffIds, context);
            entity.getAttendanceGroupStaffList().stream().peek(item -> {
                item.setGroupId(entity.getId());
                item.setGroupName(entity.getGroupName());
                item.setCreateUser(context.getUser().getLoginName());
                item.setCreateUserId(context.getUser().getId());
                item.setCreateTime(new Date());
                item.setUpdateUser(context.getUser().getLoginName());
                item.setUpdateUserId(context.getUser().getId());
                item.setUpdateTime(new Date());
            }).count();
            attendanceGroupStaffService.save(entity.getAttendanceGroupStaffList());
        }
        super.updateAfter(entity, context);
    }

    @Override
    protected void removeAfter(Long[] ids, Context context, int result) throws AppException {
        List<AttendanceGroupStaffEntity> attendanceGroupStafflist = attendanceGroupStaffService.find(new AttendanceGroupStaffQuery().groupIdList(Arrays.asList(ids)));
        attendanceGroupStaffService.removeList(attendanceGroupStafflist, context);
        super.removeAfter(ids, context, result);
    }


    public Rest<String> syncGroupByDingTalk() {
        //保存更新考勤组
        PageInfo pageInfo = new PageInfo();
        Rest<List<OapiAttendanceGetsimplegroupsResponse.AtGroupForTopVo>> groupRest = dingAttenanceService.getAttendanceGroupList(pageInfo);

        if (YesNoEnum.YES.getValue() == groupRest.getCode()) {
            List<OapiAttendanceGetsimplegroupsResponse.AtGroupForTopVo> groupList = groupRest.getData();
            for (OapiAttendanceGetsimplegroupsResponse.AtGroupForTopVo group : groupList) {
                Long groupId = group.getGroupId();
                String groupName = group.getGroupName();
                Long memberCount = group.getMemberCount();
                String type = group.getType();
                AttendanceGroupQuery groupQuery = new AttendanceGroupQuery();
                groupQuery.setRemark(groupId.toString());
                AttendanceGroupEntity attendanceGroupEntity = this.selectOne(groupQuery);

                if (ObjectUtils.isEmpty(attendanceGroupEntity)) {
                    attendanceGroupEntity = new AttendanceGroupEntity();
                    attendanceGroupEntity.initAttrValue();
                    attendanceGroupEntity.setRemark(groupId.toString());
                    attendanceGroupEntity.setGroupName(groupName);
                    attendanceGroupEntity.setPersonNum(memberCount.intValue());
                    attendanceGroupEntity.setAttendanceType(AttendanceTypeEnum.钉钉打卡.getValue());
                    attendanceGroupEntity.setCreateTime(new Date());
                    attendanceGroupEntity.setCreateUserId(1L);
                    if ("FIXED".equalsIgnoreCase(type)) {
                        attendanceGroupEntity.setType(1);
                    } else if ("TURN".equalsIgnoreCase(type)) {
                        attendanceGroupEntity.setType(2);
                    } else if ("NONE".equalsIgnoreCase(type)) {
                        attendanceGroupEntity.setType(3);
                    }
                    this.save(attendanceGroupEntity);

                    //todo 保存考勤组班次
                   /* AttendanceGroupFixedworkEntity attendanceGroupFixedworkEntity = fixedworkService.selectOne(new AttendanceGroupFixedworkQuery().groupId(attendanceGroupEntity.getId()));
                    if(ObjectUtils.isEmpty(attendanceGroupFixedworkEntity)){
                        //todo 默认班次1
                         attendanceGroupFixedworkEntity = new AttendanceGroupFixedworkEntity();
                         attendanceGroupFixedworkEntity.initAttrValue();
                         attendanceGroupFixedworkEntity.setGroupId(attendanceGroupEntity.getId());
                         attendanceGroupFixedworkEntity.setGroupName(attendanceGroupEntity.getGroupName());
                         attendanceGroupFixedworkEntity.setMonday(1);
                         attendanceGroupFixedworkEntity.setMondayClassName("早晚");
                    }*/

                }
            }
        }

        //保存考勤组人员
        AttendanceGroupQuery attendanceGroupQuery = new AttendanceGroupQuery();
        attendanceGroupQuery.setAttendanceType(AttendanceTypeEnum.钉钉打卡.getValue());

        List<AttendanceGroupEntity> groupEntityList = this.find(attendanceGroupQuery);
        for (AttendanceGroupEntity attendanceGroupEntity : groupEntityList) {
            long groupId = DataUtil.converStr2Long(attendanceGroupEntity.getRemark(), 0L);
            Rest<List<String>> groupPersonRest = dingAttenanceService.getGroupPersons(0L, groupId);
            if (YesNoEnum.YES.getValue() == groupPersonRest.getCode()) {
                log.info("考勤组人员数量：" + groupPersonRest.getData().size());
                //获取本地已有考勤人员
                AttendanceGroupStaffQuery groupStaffQuery = new AttendanceGroupStaffQuery();
                groupStaffQuery.setGroupId(attendanceGroupEntity.getId());

                Set<Long> staffIdsSet = groupStaffService.find(groupStaffQuery).stream().map(item -> item.getStaffId()).collect(Collectors.toSet());

                List<StaffEntity> staffEntityList = groupPersonRest.getData().stream().map(workNum -> {
                    StaffEntity extCache = staffService.getExtCache(workNum);
                    if (!ObjectUtils.isEmpty(extCache)) {
                        return extCache;
                    } else {
                        log.info("未找到员工工号：" + workNum);
                        return null;
                    }
                }).collect(Collectors.toList());

   /*             StaffQuery staffQuery = new StaffQuery();
                staffQuery.setWorkNumList(groupPersonRest.getData());
                List<StaffEntity> staffEntityList = staffService.find(staffQuery);*/
                for (StaffEntity staffEntity : staffEntityList) {
                    if (!staffIdsSet.contains(staffEntity.getId())) {
                        AttendanceGroupStaffEntity groupStaffEntity = new AttendanceGroupStaffEntity();
                        groupStaffEntity.initAttrValue();
                        groupStaffEntity.setGroupId(attendanceGroupEntity.getId());
                        groupStaffEntity.setGroupName(attendanceGroupEntity.getGroupName());
                        groupStaffEntity.setStaffId(staffEntity.getId());
                        groupStaffEntity.setStaffName(staffEntity.getName());
                        groupStaffEntity.setRemark("dingTalk");
                        groupStaffEntity.setCreateTime(new Date());
                        groupStaffEntity.setCreateUserId(1L);
                        groupStaffService.save(groupStaffEntity);
                    }

                }
            }

        }

        return Rest.ok();
    }

}