package com.mortals.xhx.daemon.task;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.mortals.framework.common.Rest;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.service.ITask;
import com.mortals.framework.service.ITaskExcuteService;
import com.mortals.xhx.base.system.user.model.UserEntity;
import com.mortals.xhx.base.system.user.model.UserQuery;
import com.mortals.xhx.base.system.user.service.UserService;
import com.mortals.xhx.common.code.AttendSourceTypeEnum;
import com.mortals.xhx.common.code.YesNoEnum;
import com.mortals.xhx.module.attendance.model.AttendanceLeaveRecordQuery;
import com.mortals.xhx.module.attendance.model.AttendanceRecordHikQuery;
import com.mortals.xhx.module.attendance.service.AttendanceGroupService;
import com.mortals.xhx.module.attendance.service.AttendanceLeaveRecordService;
import com.mortals.xhx.module.attendance.service.AttendanceStatService;
import com.mortals.xhx.module.attendance.service.AttendanceVacationBalanceService;
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.personal.service.IDingPersonService;
import com.mortals.xhx.module.door.model.DoorEntity;
import com.mortals.xhx.module.door.model.DoorQuery;
import com.mortals.xhx.module.hik.door.model.req.door.HikDoorEventReq;
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.hik.person.service.IHikPersonService;
import com.mortals.xhx.module.staff.model.StaffEntity;
import com.mortals.xhx.module.staff.service.StaffLeaveService;
import com.mortals.xhx.module.staff.service.StaffService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 同步用户
 */
@Slf4j
@Service("SyncUserTask")
public class SyncUserTaskImpl implements ITaskExcuteService {

    @Autowired
    private StaffService staffService;
    @Autowired
    private DeptService deptService;
    @Autowired
    private UserService userService;
    @Autowired
    private IDingPersonService dingPersonService;
    @Value("${hik.host:}")
    protected String hikhost;

    @Value("${source.type:''}")
    protected String sourceType;

    @Autowired
    private AttendanceGroupService groupService;

    @Autowired
    private AttendanceLeaveRecordService attendanceLeaveRecordService;

    @Override
    public void excuteTask(ITask task) throws AppException {

        if (AttendSourceTypeEnum.海康云平台.getValue().equals(sourceType)) {
            log.info("同步部门");
            deptService.syncDept(null);
            log.info("同步用户");
            staffService.syncPersons(null);
            log.info("同步钉钉usreId");
            syncDingDingUserIds();
        } else if (AttendSourceTypeEnum.海康考勤机.getValue().equals(sourceType)) {
            log.info("设备直连同步人员信息");
            staffService.syncPersonsByDevices(null);

        } else if (AttendSourceTypeEnum.钉钉.getValue().equals(sourceType)) {
            //钉钉
            log.info("同步钉钉部门");
            deptService.syncDeptByDingTalk(null);
            //同步钉钉人员
            staffService.syncPersonsByDingTalk(null);
            log.info("同步钉钉usreId");
            //syncDingDingLocalUserIds();
            log.info("钉钉直连同步人员信息");

            groupService.syncGroupByDingTalk();

            //同步最近10天请假信息
            DateTime weekStart = DateUtil.offsetDay(new Date(), -10);
            AttendanceRecordHikQuery hikQuery = new AttendanceRecordHikQuery();
            hikQuery.setAttendanceDateStart(DateUtil.format(weekStart, "yyyy-MM-dd"));
            hikQuery.setAttendanceDateEnd(DateUtil.today());
            checkDingDingEvent(hikQuery);
        } else {
            log.info("未配置考勤源类型！");
        }

    }


    private void checkDingDingEvent(AttendanceRecordHikQuery hikEntity) {
        log.info("开始同步钉钉请假事件！");
        AttendanceLeaveRecordQuery query = new AttendanceLeaveRecordQuery();
        query.setStartTimeStart(hikEntity.getAttendanceDateStart());
        query.setEndTimeEnd(hikEntity.getAttendanceDateEnd());
        query.setStaffId(hikEntity.getStaffId());

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

    }

    private void syncDingDingUserIds() {

        List<StaffEntity> staffList = staffService.getCacheList();
        List<StaffEntity> updateList = new ArrayList<>();
        for (StaffEntity staffCache : staffList) {
            if (!ObjectUtils.isEmpty(staffCache) && !ObjectUtils.isEmpty(staffCache.getPhoneNumber())) {
                String phoneNumber = staffCache.getPhoneNumber();
                if (!ObjectUtils.isEmpty(phoneNumber)) {
                    Rest<String> personByMobile = dingPersonService.getPersonByMobile(phoneNumber);
                    if (!ObjectUtils.isEmpty(personByMobile) &&
                            YesNoEnum.YES.getValue() == personByMobile.getCode()
                            && !ObjectUtils.isEmpty(personByMobile.getData())) {

                        StaffEntity updateStaff = new StaffEntity();
                        updateStaff.setId(staffCache.getId());
                        updateStaff.setDingUserId(personByMobile.getData());
                        updateList.add(updateStaff);
                    }
                }

            }
            if (!ObjectUtils.isEmpty(updateList)) {
                log.info("更新用户钉钉id信息数量：{}", updateList.size());
                staffService.update(updateList);
            }
        }
    }

    private void syncDingDingLocalUserIds() {
        try {
            List<UserEntity> userList = userService.getCacheList().stream()
                    .filter(f -> !ObjectUtils.isEmpty(f.getCustomerId()))
                    .filter(f -> ObjectUtils.isEmpty(f.getDingUserId())).collect(Collectors.toList());
            List<UserEntity> updateUserList = userList.stream().map(item -> {
                UserEntity userEntity = new UserEntity();
                userEntity.setId(item.getId());

                StaffEntity staffCache = staffService.getCache(item.getCustomerId().toString());

                if (!ObjectUtils.isEmpty(staffCache)) {
                    userEntity.setDingUserId(staffCache.getWorkNum());
                }

                userEntity.setUpdateTime(new Date());
                userEntity.setUpdateUserId(1L);
                return userEntity;
            }).filter(f -> !ObjectUtils.isEmpty(f.getDingUserId())).collect(Collectors.toList());

            if (!ObjectUtils.isEmpty(updateUserList)) {
                log.info("更新用户钉钉id信息数量：{}", updateUserList.size());
                userService.getUserDao().updateBatch(updateUserList);
            }
        } catch (Exception e) {
            log.error("同步钉钉usreId失败");
        }
    }

    @Override
    public void stopTask(ITask task) throws AppException {

    }
}
