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

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.dingtalkworkflow_1_0.models.ListProcessInstanceIdsResponse;
import com.aliyun.dingtalkworkflow_1_0.models.ListProcessInstanceIdsResponseBody;
import com.mortals.framework.common.Rest;
import com.mortals.framework.service.ICacheService;
import com.mortals.framework.util.DataUtil;
import com.mortals.framework.util.DateUtils;
import com.mortals.framework.util.ThreadPool;
import com.mortals.xhx.base.system.user.model.UserEntity;
import com.mortals.xhx.base.system.user.service.UserService;
import com.mortals.xhx.common.code.AppealResultEnum;
import com.mortals.xhx.common.code.AuditStatusEnum;
import com.mortals.xhx.common.code.ProcessInstanceEnum;
import com.mortals.xhx.common.code.YesNoEnum;
import com.mortals.xhx.common.utils.AddAttendThread;
import com.mortals.xhx.common.utils.AttendSummaryThread;
import com.mortals.xhx.module.attendance.model.AttendanceLeaveRecordQuery;
import com.mortals.xhx.module.attendance.model.AttendanceRecordHikEntity;
import com.mortals.xhx.module.attendance.model.AttendanceRecordHikQuery;
import com.mortals.xhx.module.attendance.model.vo.AttendanceSummaryQuery;
import com.mortals.xhx.module.attendance.service.AttendanceRecordHikService;
import com.mortals.xhx.module.attendance.service.AttendanceStatService;
import com.mortals.xhx.module.dingding.personal.service.IDingPersonService;
import com.mortals.xhx.module.staff.service.StaffService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
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.AttendanceLeaveRecordDao;
import com.mortals.xhx.module.attendance.model.AttendanceLeaveRecordEntity;
import com.mortals.xhx.module.attendance.service.AttendanceLeaveRecordService;

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

import static com.mortals.xhx.common.key.RedisKey.KEY_ATTENDANCE_STAT_CACHE;

/**
 * AttendanceLeaveRecordService
 * 请假记录信息 service实现
 *
 * @author zxfei
 * @date 2023-04-07
 */
@Service("attendanceLeaveRecordService")
public class AttendanceLeaveRecordServiceImpl extends AbstractCRUDServiceImpl<AttendanceLeaveRecordDao, AttendanceLeaveRecordEntity, Long> implements AttendanceLeaveRecordService {

    @Autowired
    private AttendanceStatService attendanceStatService;
    @Autowired
    private ICacheService cacheService;
    @Autowired
    private StaffService staffService;
    @Autowired
    private UserService userService;
    @Autowired
    private AttendanceRecordHikService hikService;
    @Autowired
    private IDingPersonService dingPersonService;

    @Override
    protected void updateAfter(AttendanceLeaveRecordEntity entity, Context context) throws AppException {
        super.updateAfter(entity, context);
/*        //context!=null时表示页面调用的修改，自动执行处理任务调用时context为null，无需立即汇总
        if (entity.getAuditResult() == 1 && context != null) {
            AttendanceSummaryQuery query = new AttendanceSummaryQuery();
            query.setStaffId(entity.getLeavePersonId());
            query.setSummaryTimeStart(DateUtils.getStrDate(entity.getStartTime()));
            query.setSummaryTimeEnd(DateUtils.getStrDate(entity.getEndTime()));
            cacheService.lpush(KEY_ATTENDANCE_STAT_CACHE, query);
        }*/

        doUpdateRecordAndSummary(entity, context);
    }

    @Override
    public AttendanceLeaveRecordEntity doUpdateRecord(String processInstanceId, AttendanceLeaveRecordEntity leaveRecordEntity) throws Exception {
        if (leaveRecordEntity.getAuditResult() != AppealResultEnum.审核中.getValue()) {
            //临时解决并发问题，更新的都等待一秒后再执行
            Thread.sleep(1000);
        }
        synchronized (this) {
            AttendanceLeaveRecordEntity recordEntity = this.selectOne(new AttendanceLeaveRecordQuery().remark(processInstanceId));
            if (ObjectUtils.isEmpty(recordEntity)) {
                leaveRecordEntity.setCreateTime(new Date());
                leaveRecordEntity.setCreateUserId(1L);
                this.save(leaveRecordEntity);
            } else {
                leaveRecordEntity.setId(recordEntity.getId());

                leaveRecordEntity.setUpdateUserId(1L);
                leaveRecordEntity.setUpdateTime(new Date());

                this.update(leaveRecordEntity);
            }
            return leaveRecordEntity;
        }
    }


    @Override
    protected void saveAfter(AttendanceLeaveRecordEntity entity, Context context) throws AppException {
        super.saveAfter(entity, context);

        doUpdateRecordAndSummary(entity, context);
    }

    /**
     * 更新汇总信息
     *
     * @param entity
     * @param context
     */
    private void doUpdateRecordAndSummary(AttendanceLeaveRecordEntity entity, Context context) {
        //请假是未来 不做处理
        int compare = DateUtil.compare(entity.getStartTime(), new Date());
        if (compare > 0) {
            //请假未来 不做处理
            return;
        }
        //更新考勤记录与异常记录
        if (AppealResultEnum.通过.getValue() == entity.getAuditResult() || AppealResultEnum.撤销审批通过.getValue() == entity.getAuditResult()) {
            AttendanceRecordHikQuery attendanceRecordHikQuery = new AttendanceRecordHikQuery();
            attendanceRecordHikQuery.setStaffId(entity.getLeavePersonId());
            //判断请假的开始日期与结束日期
            boolean in = DateUtil.isIn(new Date(), entity.getStartTime(), entity.getEndTime());
            if (in) {
                //当前日期在请假期间，计算考勤结束时间为当前时间;
                attendanceRecordHikQuery.setAttendanceDateStart(DateUtil.formatDate(entity.getStartTime()));
                attendanceRecordHikQuery.setAttendanceDateEnd(DateUtil.today());
            } else {
                attendanceRecordHikQuery.setAttendanceDateStart(DateUtil.formatDate(entity.getStartTime()));
                attendanceRecordHikQuery.setAttendanceDateEnd(DateUtil.formatDate(entity.getEndTime()));
            }
            AddAttendThread addAttendThread = new AddAttendThread(hikService, attendanceRecordHikQuery, context);
            ThreadPool.getInstance().execute(addAttendThread);
        }
    }


    @Override
    public Rest<String> syncLeaveRecord(AttendanceLeaveRecordQuery query, Context context) {
        List<AttendanceLeaveRecordEntity> waitSyncLeaveRecords = new ArrayList<>();
        Long staffId = query.getStaffId();
        List<UserEntity> userCacheList = userService.getCacheList();
        if (ObjectUtils.isEmpty(staffId)) {
            //同步所有用户
            List<UserEntity> userEntityList = userCacheList.stream()
                    .filter(f -> !ObjectUtils.isEmpty(f.getDingUserId())).collect(Collectors.toList());
            getLeaveRecordByUserList(query, userEntityList, waitSyncLeaveRecords);

        } else {
            //同步指定用户
            List<UserEntity> userEntityList = userCacheList.stream()
                    .filter(f -> !ObjectUtils.isEmpty(f.getDingUserId()))
                    .filter(f -> staffId == f.getCustomerId())
                    .collect(Collectors.toList());
            getLeaveRecordByUserList(query, userEntityList, waitSyncLeaveRecords);
        }

        if (!ObjectUtils.isEmpty(waitSyncLeaveRecords)) {
            for (AttendanceLeaveRecordEntity waitSyncLeaveRecord : waitSyncLeaveRecords) {
                dingPersonService.handleByProcessInstanceId(waitSyncLeaveRecord.getRemark());
            }
        }
        return Rest.ok();
    }

    private void getLeaveRecordByUserList(AttendanceLeaveRecordQuery query, List<UserEntity> userEntityList, List<AttendanceLeaveRecordEntity> waitSyncLeaveRecords) {
        for (UserEntity item : userEntityList) {
            String dingUserId = item.getDingUserId();
            long startTime = DateUtil.parseDateTime(query.getStartTimeStart() + " 00:00:00").getTime();
            long endTime = DateUtil.parseDateTime(query.getEndTimeEnd() + " 23:59:59").getTime();
            Long nextToken = 0L;
            long maxResults = 20L;
            for (ProcessInstanceEnum processInstanceEnum : ProcessInstanceEnum.values()) {
                try {
                    getRecords(waitSyncLeaveRecords, item, processInstanceEnum, startTime, endTime, nextToken, maxResults, dingUserId);
                } catch (Exception e) {
                    log.error("同步请假记录异常", e);
                }
            }
        }
    }

    private void getRecords(List<AttendanceLeaveRecordEntity> waitSyncLeaveRecords, UserEntity item, ProcessInstanceEnum processInstanceEnum, long startTime, long endTime, Long nextToken, long maxResults, String dingUserId) throws Exception {
        Rest<ListProcessInstanceIdsResponseBody.ListProcessInstanceIdsResponseBodyResult> rest = dingPersonService.getProcessInstanceIdByUserIds(processInstanceEnum.getValue(), startTime, endTime, nextToken, maxResults, dingUserId);
        if (YesNoEnum.YES.getValue() == rest.getCode()) {
            if (ObjectUtils.isEmpty(rest.getData().getNextToken())) {
                List<String> processInstanceList = rest.getData().getList();
                for (String process : processInstanceList) {
                    AttendanceLeaveRecordEntity leaveRecord = new AttendanceLeaveRecordEntity();
                    leaveRecord.setRemark(process);
                    leaveRecord.setStaffId(item.getCustomerId());
                    waitSyncLeaveRecords.add(leaveRecord);
                }
            } else {
                nextToken = DataUtil.converStr2Long(rest.getData().getNextToken(), 0L);
                getRecords(waitSyncLeaveRecords, item, processInstanceEnum, startTime, endTime, nextToken, maxResults, dingUserId);
            }
        }
    }
}