package com.mortals.xhx.daemon.applicationservice;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.dingtalk.api.response.*;
import com.google.common.collect.Lists;
import com.mortals.framework.common.Rest;
import com.mortals.framework.model.PageInfo;
import com.mortals.framework.springcloud.service.IApplicationStartedService;
import com.mortals.framework.util.DataUtil;
import com.mortals.framework.util.ThreadPool;
import com.mortals.xhx.base.system.user.service.UserService;
import com.mortals.xhx.common.code.AttendSourceTypeEnum;
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.*;
import com.mortals.xhx.module.dept.model.DeptEntity;
import com.mortals.xhx.module.dept.model.DeptQuery;
import com.mortals.xhx.module.dept.service.DeptService;
import com.mortals.xhx.module.dingding.attendance.service.IDingAttenanceService;
import com.mortals.xhx.module.dingding.personal.service.IDingPersonService;
import com.mortals.xhx.module.hik.person.model.req.org.OrgListReq;
import com.mortals.xhx.module.hik.person.model.rsp.org.OrgDataInfo;
import com.mortals.xhx.module.hik.person.model.rsp.org.OrgInfo;
import com.mortals.xhx.module.staff.model.StaffEntity;
import com.mortals.xhx.module.staff.model.StaffQuery;
import com.mortals.xhx.module.staff.service.StaffService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

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

@Component
@Slf4j
public class StartedService implements IApplicationStartedService {

    @Autowired
    private UserService userService;


    @Autowired
    private StaffService staffService;
    @Autowired
    private DeptService deptService;

    @Autowired
    private IDingPersonService dingPersonService;

    @Autowired
    private IDingAttenanceService dingAttenanceService;
    @Autowired
    private AttendanceRecordHikService hikService;

    @Autowired
    private AttendanceGroupService groupService;

    @Autowired
    private AttendanceGroupStaffService groupStaffService;
    @Autowired
    private AttendanceGroupFixedworkService attendanceGroupFixedworkService;
    @Autowired
    private AttendanceClassService attendanceClassService;
    @Autowired
    private AttendanceClassDetailService attendanceClassDetailService;
    @Autowired
    private AttendanceLeaveRecordService attendanceLeaveRecordService;

    private void checkDingDingEvent(DateTime attendStart, DateTime attendEnd, AttendanceRecordHikQuery hikEntity) {

        log.info("开始同步钉钉请假事件！");
        long between = DateUtil.between(attendStart, attendEnd, DateUnit.DAY, true);
        AttendanceLeaveRecordQuery query = new AttendanceLeaveRecordQuery();
        query.setStartTimeStart(hikEntity.getAttendanceDateStart());
        query.setEndTimeEnd(hikEntity.getAttendanceDateEnd());
        query.setStaffId(hikEntity.getStaffId());

        new Thread(()->{
            attendanceLeaveRecordService.syncLeaveRecord(query, null);
        }).start();

/*        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                attendanceLeaveRecordService.syncLeaveRecord(query, null);
            }
        };

        ThreadPool.getInstance().execute(runnable);*/
    }

    @Override
    public void start() {
        log.info("开始服务..[配置已加载完成，并且所有框架都已经初始化]");

        //deptService.syncDeptByDingTalk(null);
        //staffService.syncPersonsByDingTalk(null);

   /*     String attendStart = "2025-03-05";

        String attendEnd = "2025-03-25";

        AttendanceRecordHikQuery hikQuery = new AttendanceRecordHikQuery();
        hikQuery.setAttendanceDateStart(attendStart);
        hikQuery.setAttendanceDateEnd(attendEnd);
        hikQuery.setStaffId(8L);


        checkDingDingEvent(DateUtil.parseDate(attendStart), DateUtil.parseDate(attendEnd), hikQuery);*/


        //  groupService.syncGroupByDingTalk();

        //获取排班信息
  /*      Rest<List<OapiAttendanceShiftListResponse.TopMinimalismShiftVo>> rest = dingAttenanceService.getShiftList(0L);

        rest.getData();
        for (OapiAttendanceShiftListResponse.TopMinimalismShiftVo datum : rest.getData()) {
            //获取排班详细信息
            dingAttenanceService.getShiftDetail(datum.getId());
        }*/

/*
        dingPersonService.getPersonsByDept(new PageInfo(), 123716132L);


        Rest<OapiV2UserGetResponse.UserGetResponse> rest = dingAttenanceService.getPersonDetail("2850143830605086304");

*/

        //保存更新考勤组
    /*    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 = groupService.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);
                    }
                    groupService.save(attendanceGroupEntity);
                }
            }
        }


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

        List<AttendanceGroupEntity> groupEntityList = groupService.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);
                    }

                }


                //增量添加

            }

        }*/


//       //获取考勤组列表



/*
        PageInfo pageInfo = new PageInfo();
        dingAttenanceService.getAttendanceGroupList(pageInfo);*/

        //staffService.syncPersonsByDingTalk(null);
/*
        AttendanceRecordHikQuery hikQuery = new AttendanceRecordHikQuery();
        hikQuery.setAttendanceDateStart("2025-03-21");
        hikQuery.setAttendanceDateEnd("2025-03-21");

        hikService.syncDoorEventsFromDingTalk(hikQuery);
*/


    }


    @Override
    public void stop() {
        log.info("停止服务..");
    }

    @Override
    public int getOrder() {
        return 10;
    }

}
