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

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.mortals.framework.common.Rest;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.framework.model.PageInfo;
import com.mortals.framework.service.impl.AbstractCRUDCacheServiceImpl;
import com.mortals.framework.util.SecurityUtil;
import com.mortals.framework.utils.ServletUtils;
import com.mortals.xhx.base.system.idgenerator.service.IdgeneratorService;
import com.mortals.xhx.base.system.idgenerator.service.impl.IdgeneratorServiceImpl;
import com.mortals.xhx.base.system.role.model.RoleUserQuery;
import com.mortals.xhx.base.system.role.service.RoleUserService;
import com.mortals.xhx.base.system.upload.service.UploadService;
import com.mortals.xhx.base.system.user.model.UserEntity;
import com.mortals.xhx.base.system.user.service.UserService;
import com.mortals.xhx.common.code.*;
import com.mortals.xhx.common.utils.BeanUtil;
import com.mortals.xhx.module.attendance.model.*;
import com.mortals.xhx.module.attendance.service.AttendanceGroupStaffService;
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.door.model.DoorEntity;
import com.mortals.xhx.module.door.model.DoorQuery;
import com.mortals.xhx.module.door.service.DoorService;
import com.mortals.xhx.module.hik.face.model.req.img.ImgReq;
import com.mortals.xhx.module.hik.face.service.IHikFaceService;
import com.mortals.xhx.module.hik.person.model.req.person.PersonReq;
import com.mortals.xhx.module.hik.person.model.rsp.person.PersonDataInfo;
import com.mortals.xhx.module.hik.person.model.rsp.person.PersonInfo;
import com.mortals.xhx.module.hik.person.service.IHikPersonService;
import com.mortals.xhx.module.hik.staff.model.req.staff.StaffReq;
import com.mortals.xhx.module.hik.staff.model.rsp.staff.search.UserInfoItem;
import com.mortals.xhx.module.hik.staff.model.rsp.staff.search.UserInfoSearch;
import com.mortals.xhx.module.hik.staff.model.rsp.staff.search.UserSearchInfo;
import com.mortals.xhx.module.hik.staff.service.IHikStaffService;
import com.mortals.xhx.module.staff.dao.StaffDao;
import com.mortals.xhx.module.staff.dao.ibatis.StaffDaoImpl;
import com.mortals.xhx.module.staff.dao.ibatis.StaffLeaveDaoImpl;
import com.mortals.xhx.module.staff.model.*;
import com.mortals.xhx.module.staff.model.vo.StaffCheckAuthorizePdu;
import com.mortals.xhx.module.staff.model.vo.StaffInfoVo;
import com.mortals.xhx.module.staff.service.StaffLeaveService;
import com.mortals.xhx.module.staff.service.StaffPerformStatService;
import com.mortals.xhx.module.staff.service.StaffPerformSummaryService;
import com.mortals.xhx.module.staff.service.StaffService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import static com.mortals.xhx.base.system.idgenerator.service.impl.IdgeneratorServiceImpl.IdGeneratorKey.USER_KEY;

/**
 * StaffService
 * 员工基本信息 service实现
 *
 * @author zxfei
 * @date 2023-04-07
 */
@Service("staffService")
@Slf4j
public class StaffServiceImpl extends AbstractCRUDCacheServiceImpl<StaffDao, StaffEntity, Long> implements StaffService {

    @Autowired
    private UserService userService;
    @Autowired
    private DeptService deptService;
    @Autowired
    private RoleUserService roleUserService;
    @Autowired
    private IHikPersonService hikPersonService;
    @Autowired
    private AttendanceStatService attendanceStatService;
    @Autowired
    private AttendanceVacationBalanceService balanceService;
    @Autowired
    private StaffLeaveService staffLeaveService;
    @Autowired
    private DoorService doorService;
    @Autowired
    private IHikStaffService hikStaffService;
    @Autowired
    private UploadService uploadService;
    @Autowired
    private IHikFaceService hikFaceService;
    @Autowired
    private StaffPerformSummaryService staffPerformSummaryService;

    @Override
    protected String getExtKey(StaffEntity data) {
        //工号作为redis 扩展key
        return StrUtil.padPre(data.getWorkNum(), 8, "0");
    }

    @Override
    protected void updateBefore(StaffEntity entity, Context context) throws AppException {
        super.updateBefore(entity, context);
        if (!ObjectUtils.isEmpty(entity.getDeptId())) {
            DeptEntity deptEntity = deptService.get(entity.getDeptId());
            entity.setDeptName(deptEntity == null ? "" : deptEntity.getDeptName());
        }
    }

    @Override
    protected void saveBefore(StaffEntity entity, Context context) throws AppException {
        int count = this.count(new StaffQuery().workNum(entity.getWorkNum()), context);
        if (count > 0) {
            throw new AppException("工号重复！工号:" + entity.getWorkNum());
        }
        if (!ObjectUtils.isEmpty(entity.getDeptId())) {
            DeptEntity deptEntity = deptService.get(entity.getDeptId());
            entity.setDeptName(deptEntity == null ? "" : deptEntity.getDeptName());
        }
    }


    @Override
    public StaffInfoVo queryAll(Context context) {
        StaffInfoVo staffInfoVo = new StaffInfoVo();
        //在职
        StaffQuery staffQuery = new StaffQuery();
        staffQuery.setStatusList(Arrays.asList(StaffSatusEnum.正式.getValue(), StaffSatusEnum.试用.getValue()));
        List<StaffEntity> staffEntities = this.find(staffQuery);
        staffInfoVo.setInWorkStaff(staffEntities.size());
        //全职
        Map<Integer, Long> collect = staffEntities.stream().collect(Collectors.groupingBy(x -> x.getStaffType(), Collectors.counting()));
        staffInfoVo.setFullStaff(collect.getOrDefault(StaffTypeEnum.全职.getValue(), 0L).intValue());
        //实习
        staffInfoVo.setPricateStaff(collect.getOrDefault(StaffTypeEnum.实习.getValue(), 0L).intValue());
        //兼职
        staffInfoVo.setConcurrentlyStaff(collect.getOrDefault(StaffTypeEnum.兼职.getValue(), 0L).intValue());
        //试用
        staffInfoVo.setOnTrialStaff(this.find(new StaffQuery().status(StaffSatusEnum.试用.getValue())).size());
        //正式
        staffInfoVo.setFormalStaff(this.find(new StaffQuery().status(StaffSatusEnum.正式.getValue())).size());
        //待离职
        staffInfoVo.setResignationStaff(this.find(new StaffQuery().status(StaffSatusEnum.离职.getValue())).size());
        return staffInfoVo;
    }


    @Override
    public int queryAllPerson() {
        StaffQuery staffQuery = new StaffQuery();
        staffQuery.setStatusList(Arrays.asList(StaffSatusEnum.正式.getValue(), StaffSatusEnum.试用.getValue()));
        List<StaffEntity> staffEntities = this.find(staffQuery);
        return staffEntities.size();
    }

    @Override
    public Rest<Void> syncPersons(Context context) {
        log.info("同步人员！");
        PersonReq personReq = new PersonReq();
        personReq.setPageNo(1);
        personReq.setPageSize(1000);
        Rest<PersonDataInfo> personRest = hikPersonService.getPersonList(personReq);
        if (personRest.getCode() == YesNoEnum.YES.getValue()) {
            //做差集 更新本地用户为离职员工
            StaffQuery staffQuery = new StaffQuery();
            staffQuery.setSource(SourceEnum.海康.getValue());
            staffQuery.setStatusNotList(Arrays.asList(StaffSatusEnum.离职.getValue()));
            Map<String, StaffEntity> staffCollect = this.find(staffQuery).stream().collect(Collectors.toMap(x -> x.getWorkNum(), y -> y, (o, n) -> n));

            List<PersonInfo> personInfoList = personRest.getData().getList();
            for (PersonInfo personInfo : personInfoList) {
                if (ObjectUtils.isEmpty(personInfo.getJobNo())) {
                    log.info("jobNo is null ==>{}", JSON.toJSONString(personInfo));
                    continue;
                }
                if (staffCollect.containsKey(personInfo.getJobNo())) {
                    staffCollect.remove(personInfo.getJobNo());
                }

                StaffEntity staffEntity = this.getExtCache(StrUtil.padPre(personInfo.getJobNo(), 8, "0"));
                DeptEntity deptEntity = deptService.selectOne(new DeptQuery().deptCode(personInfo.getOrgIndexCode()));
                //判断本地数据是否为空
                if (ObjectUtils.isEmpty(staffEntity)) {
                    //新增员工信息
                    staffEntity = new StaffEntity();
                    staffEntity.initAttrValue();
                    if (!ObjectUtils.isEmpty(deptEntity)) {
                        staffEntity.setDeptId(deptEntity.getId());
                        if (deptEntity.getParentId() == 71l) {
                            //市民中心id为71，代表是大厅
                            staffEntity.setSalaId(deptEntity.getId());
                            staffEntity.setSalaName(deptEntity.getDeptName());
                        } else {
                            DeptEntity salaEntity = deptService.get(deptEntity.getParentId());
                            if (!ObjectUtils.isEmpty(salaEntity)) {
                                staffEntity.setSalaId(salaEntity.getId());
                                staffEntity.setSalaName(salaEntity.getDeptName());
                            }
                        }
                    }
                    staffEntity.setName(personInfo.getPersonName());
                    staffEntity.setRemarkId(personInfo.getPersonId());
                    staffEntity.setPicUri(personInfo.getPersonPhoto() == null ? "" : personInfo.getPersonPhoto().getPicUri());
                    staffEntity.setServerIndexCode(personInfo.getPersonPhoto() == null ? "" : personInfo.getPersonPhoto().getServerIndexCode());
                    staffEntity.setDeptName(personInfo.getOrgName());
                    staffEntity.setGender(personInfo.getGender());
                    staffEntity.setWorkNum(personInfo.getJobNo());
                    staffEntity.setPhoneNumber(personInfo.getPhoneNo());
                    staffEntity.setCreateUserId(1L);
                    staffEntity.setCreateTime(new Date());
                    this.save(staffEntity);
                } else {
                    //更新
                    if (!ObjectUtils.isEmpty(deptEntity)) {
                        staffEntity.setDeptId(deptEntity.getId());
                        if (deptEntity.getParentId() == 71l) {
                            //市民中心id为71，代表是大厅
                            staffEntity.setSalaId(deptEntity.getId());
                            staffEntity.setSalaName(deptEntity.getDeptName());
                        } else {
                            DeptEntity salaEntity = deptService.get(deptEntity.getParentId());
                            if (!ObjectUtils.isEmpty(salaEntity)) {
                                staffEntity.setSalaId(salaEntity.getId());
                                staffEntity.setSalaName(salaEntity.getDeptName());
                            }
                        }
                    }
                    staffEntity.setStatus(StaffSatusEnum.正式.getValue());
                    staffEntity.setSource(SourceEnum.海康.getValue());
                    staffEntity.setName(personInfo.getPersonName());
                    staffEntity.setRemarkId(personInfo.getPersonId());
                    staffEntity.setPicUri(personInfo.getPersonPhoto() == null ? "" : personInfo.getPersonPhoto().getPicUri());
                    staffEntity.setServerIndexCode(personInfo.getPersonPhoto() == null ? "" : personInfo.getPersonPhoto().getServerIndexCode());
                    staffEntity.setDeptName(personInfo.getOrgName());
                    staffEntity.setGender(personInfo.getGender());
                    staffEntity.setWorkNum(personInfo.getJobNo());
                    staffEntity.setPhoneNumber(personInfo.getPhoneNo());
                    staffEntity.setUpdateUserId(1L);
                    staffEntity.setUpdateTime(new Date());
                    this.update(staffEntity);

                    StaffLeaveQuery staffLeaveQuery = new StaffLeaveQuery();
                    staffLeaveQuery.setWorkNum(staffEntity.getWorkNum());
                    StaffLeaveEntity staffLeaveEntity = staffLeaveService.selectOne(staffLeaveQuery, null);
                    if (!ObjectUtils.isEmpty(staffLeaveEntity)) {
                        staffLeaveService.remove(staffLeaveEntity.getId(), null);
                    }
                }

            }
            if (staffCollect.size() > 0) {
                //需要将此人员变更为离职
                staffCollect.entrySet().stream().forEach(item -> {
                    String key = item.getKey();
                    if (!ObjectUtils.isEmpty(key)) {
                        StaffEntity staff = item.getValue();
                        staff.setStatus(StaffSatusEnum.离职.getValue());
                        staff.setLeaveDate(new Date());
                        staff.setUpdateTime(new Date());
                        staff.setUpdateUserId(1L);
                        this.update(staff);

                        //新增离职人员
                        StaffLeaveEntity staffLeaveEntity = new StaffLeaveEntity();
                        staffLeaveEntity.initAttrValue();
                        staffLeaveEntity.setStaffId(staff.getId());
                        staffLeaveEntity.setStaffName(staff.getName());
                        staffLeaveEntity.setGender(staff.getGender());
                        staffLeaveEntity.setBirthday(staff.getBirthday());
                        staffLeaveEntity.setPhotoPath(staff.getPhotoPath());
                        staffLeaveEntity.setPhoneNumber(staff.getPhoneNumber());
                        staffLeaveEntity.setIdCard(staff.getIdCard());
                        staffLeaveEntity.setWorkNum(staff.getWorkNum());
                        staffLeaveEntity.setPoliticalstatus(staff.getPoliticalstatus());
                        staffLeaveEntity.setDeptId(staff.getDeptId());
                        staffLeaveEntity.setDeptName(staff.getDeptName());
                        staffLeaveEntity.setJobId(staff.getPositionId());
                        staffLeaveEntity.setJobName(staff.getPositionName());
                        staffLeaveEntity.setStaffType(staff.getStaffType());
                        staffLeaveEntity.setStatus(StaffSatusEnum.离职.getValue());
                        staffLeaveEntity.setEntryDate(staff.getCreateTime());
                        staffLeaveEntity.setLeaveDate(new Date());
                        staffLeaveEntity.setLeaveReason("");
                        staffLeaveEntity.setAuditStatus(AuditStatusEnum.通过.getValue());
                        staffLeaveEntity.setCreateUserId(1L);
                        staffLeaveEntity.setCreateTime(new Date());

                        StaffLeaveQuery staffLeaveQuery = new StaffLeaveQuery();
                        staffLeaveQuery.setWorkNum(staff.getWorkNum());

                        int count = staffLeaveService.count(staffLeaveQuery, null);
                        if (count == 0) {
                            staffLeaveService.save(staffLeaveEntity);
                        }
                        //考勤人员中有离职的 删除
//                        List<AttendanceGroupStaffEntity> attendanceGroupStaffEntities = attendanceGroupStaffService.find(new AttendanceGroupStaffQuery().staffId(staff.getId()));
//                        if (!ObjectUtils.isEmpty(attendanceGroupStaffEntities)) {
//                            attendanceGroupStaffService.removeList(attendanceGroupStaffEntities,context);
//                        }
/*                        Long[] groudStaffIds = attendanceGroupStaffService.find(new AttendanceGroupStaffQuery().staffId(staff.getId())).stream().map(i -> i.getId()).toArray(Long[]::new);
                        if (!ObjectUtils.isEmpty(groudStaffIds)) {
                            attendanceGroupStaffService.remove(groudStaffIds, null);
                        }*/
                    }
                });
            }
        }

        return Rest.ok();
    }


    @Override
    protected void saveAfter(StaffEntity entity, Context context) throws AppException {
        super.saveAfter(entity, context);
        //初始化
        int count = balanceService.count(new AttendanceVacationBalanceQuery().staffId(entity.getId()), context);
        if (count == 0) {
            AttendanceVacationBalanceEntity balanceEntity = new AttendanceVacationBalanceEntity();
            balanceEntity.initAttrValue();
            balanceEntity.setStaffId(entity.getId());
            balanceEntity.setStaffName(entity.getName());
            balanceEntity.setDeptId(entity.getDeptId());
            balanceEntity.setDeptName(entity.getDeptName());
            balanceEntity.setSalaId(entity.getSalaId());
            balanceEntity.setSalaName(entity.getSalaName());
            balanceEntity.setCreateUserId(1L);
            balanceEntity.setCreateTime(new Date());
            balanceService.save(balanceEntity);
        }
        AttendanceStatQuery attendanceStatQuery = new AttendanceStatQuery();
        attendanceStatQuery.setYear(DateUtil.year(new Date()));
        attendanceStatQuery.setMonth(DateUtil.month(new Date()) + 1);
        attendanceStatQuery.setDay(DateUtil.dayOfMonth(new Date()));
        attendanceStatQuery.setStaffId(entity.getId());
        int count1 = attendanceStatService.count(attendanceStatQuery, context);
        if (count1 == 0) {
            AttendanceStatEntity attendanceStatEntity = new AttendanceStatEntity();
            attendanceStatEntity.initAttrValue();
            attendanceStatEntity.setStaffId(entity.getId());
            attendanceStatEntity.setStaffName(entity.getName());
            attendanceStatEntity.setDeptId(entity.getDeptId());
            attendanceStatEntity.setDeptName(entity.getDeptName());
            attendanceStatEntity.setPhoneNumer(entity.getPhoneNumber());
            attendanceStatEntity.setYear(DateUtil.year(new Date()));
            attendanceStatEntity.setMonth(DateUtil.month(new Date()) + 1);
            attendanceStatEntity.setDay(DateUtil.dayOfMonth(new Date()));
            attendanceStatEntity.setCreateUserId(1L);
            attendanceStatEntity.setCreateTime(new Date());
            attendanceStatService.save(attendanceStatEntity);
        }
        try {
            UserEntity userEntity = new UserEntity();
            if (ObjectUtils.isEmpty(entity.getLoginName())) {
                //姓名加工号作为登录名
                entity.setLoginName(entity.getName() + entity.getWorkNum());
            }
            if (ObjectUtils.isEmpty(entity.getLoginPwd())) {
                //设置初始密码
                entity.setLoginPwd("123456");
            }
            userEntity.setLoginName(StrUtil.cleanBlank(entity.getLoginName()));
            userEntity.setRealName(entity.getName());
            userEntity.setUserType(UserType.WORK_PERSON.getValue());
            userEntity.setSiteIds("1");
            userEntity.setAreaCodes("511500000000");
            userEntity.setMobile(entity.getPhoneNumber());
            userEntity.setStatus(UserStatus.NORMAL.getValue());
            userEntity.setCreateUserId(this.getContextUserId(context));
            userEntity.setCreateTime(new Date());
            userEntity.setCustomerId(entity.getId());

            userEntity.setLoginPwd(SecurityUtil.md5DoubleEncoding(entity.getLoginPwd()));
            int insert = userService.getUserDao().insert(userEntity);
            if (insert > 0) {
                RoleUserQuery roleUserQuery = new RoleUserQuery();
                roleUserQuery.setUserId(userEntity.getId());
                roleUserQuery.setRoleIdList(Arrays.asList(4L));
                roleUserService.assignRoleToUser(roleUserQuery);
            }

        } catch (Exception e) {
            log.error("保存系统用户异常!", e);
        }

    }


    @Override
    protected void removeAfter(Long[] ids, Context context, int result) throws AppException {
        deptService.updateDeptNum(context);
    }


    @Override
    protected StaffEntity findBefore(StaffEntity params, PageInfo pageInfo, Context context) throws AppException {
        if (params.getDeptId() != null) {
            List<DeptEntity> deptList = deptService.getAllChildrenDept(params.getDeptId());
            if (CollectionUtils.isNotEmpty(deptList)) {
                List<Long> deptIdList = new ArrayList<>();
                deptIdList.add(params.getDeptId());
                deptList.forEach(item -> {
                    deptIdList.add(item.getId());
                });
                params.setDeptId(null);
                params.setDeptIdList(deptIdList);
            }
        }
        if (params.getStatus() == null && CollectionUtils.isEmpty(params.getStatusList())) {
            params.setStatusList(Arrays.asList(StaffSatusEnum.正式.getValue(), StaffSatusEnum.试用.getValue()));
        }
        return params;
    }

    @Override
    public int checkAuthorize(StaffCheckAuthorizePdu pdu, Context context) throws AppException {
        StaffEntity temp = this.get(pdu.getStaffId());
        if (temp == null) {
            throw new AppException("人员信息ID不正确");
        }
//        CheckTypeEnum checkTypeEnum = CheckTypeEnum.getByValue(pdu.getType());
//        if (checkTypeEnum == null) {
//            throw new AppException("考核类型不正确");
//        }
        StaffEntity update = new StaffEntity();
        update.setId(pdu.getStaffId());
        //1.考勤绩效,2.评价绩效,3.办件绩效,4.效能绩效,5.其它绩效,6.投诉绩效
//        switch (checkTypeEnum) {
//            case 考勤绩效:
//                if (temp.getAttendCheck() == 1) {
//                    update.setAttendCheck(0);
//                } else {
//                    update.setAttendCheck(1);
//                }
//                break;
//            case 评价绩效:
//                if (temp.getComplainCheck() == 1) {
//                    update.setComplainCheck(0);
//                } else {
//                    update.setComplainCheck(1);
//                }
//                if (temp.getReviewCheck() == 1) {
//                    update.setReviewCheck(0);
//                } else {
//                    update.setReviewCheck(1);
//                }
//                break;
//            case 办件绩效:
//                if (temp.getGoworkCheck() == 1) {
//                    update.setGoworkCheck(0);
//                } else {
//                    update.setGoworkCheck(1);
//                }
//                break;
//            case 效能绩效:
//                if (temp.getEffectCheck() == 1) {
//                    update.setEffectCheck(0);
//                } else {
//                    update.setEffectCheck(1);
//                }
//                break;
//            case 其它绩效:
//                if (temp.getOtherCheck() == 1) {
//                    update.setOtherCheck(0);
//                } else {
//                    update.setOtherCheck(1);
//                }
//                break;
//            default:
//                if (temp.getOtherCheck() == 1) {
//                    update.setOtherCheck(0);
//                } else {
//                    update.setOtherCheck(1);
//                }
//        }
        BeanUtils.copyProperties(pdu,update, BeanUtil.getNullPropertyNames(pdu));
        update.setUpdateTime(new Date());
        if (context.getUser() != null) {
            update.setUpdateUserId(context.getUser().getId());
        }
        //OtherCheck作为绩效总开关，启用时新增当月绩效初始值，关闭时删除当月绩效数据
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH)+1;
        StaffPerformSummaryQuery summaryQuery = new StaffPerformSummaryQuery();
        summaryQuery.setStaffId(temp.getId());
        summaryQuery.setYear(year);
        summaryQuery.setMonth(month);
        StaffPerformSummaryEntity tempSummary = staffPerformSummaryService.selectOne(summaryQuery);
        if(update.getOtherCheck() == 1){
            StaffPerformSummaryEntity staffPerformSummaryEntity = new StaffPerformSummaryEntity();
            staffPerformSummaryEntity.initAttrValue();
            staffPerformSummaryEntity.setStaffId(temp.getId());
            staffPerformSummaryEntity.setStaffName(temp.getName());
            staffPerformSummaryEntity.setDeptId(temp.getDeptId());
            staffPerformSummaryEntity.setDeptName(temp.getDeptName());
            staffPerformSummaryEntity.setSalaId(temp.getSalaId());
            staffPerformSummaryEntity.setSalaName(temp.getSalaName());
            staffPerformSummaryEntity.setYear(year);
            staffPerformSummaryEntity.setMonth(month);
            staffPerformSummaryEntity.setTotalScore(new BigDecimal(100));
            staffPerformSummaryEntity.setCreateUserId(1l);
            staffPerformSummaryEntity.setCreateTime(new Date());
            if (tempSummary == null) {
                staffPerformSummaryService.save(staffPerformSummaryEntity);
            }
        }else {
            if (tempSummary != null) {
                staffPerformSummaryService.remove(tempSummary.getId(),null);
            }
        }
        return dao.update(update);
    }

    @Override
    public void doUpdateSala() {
        List<StaffEntity> staffList = this.getAllList();
        for (StaffEntity staffEntity : staffList) {
            DeptEntity deptEntity = deptService.get(staffEntity.getDeptId());
            if (deptEntity.getParentId() == 71l) {
                //市民中心id为71，代表是大厅
                staffEntity.setSalaId(deptEntity.getId());
                staffEntity.setSalaName(deptEntity.getDeptName());
            } else {
                DeptEntity salaEntity = deptService.get(deptEntity.getParentId());
                if (!ObjectUtils.isEmpty(salaEntity)) {
                    staffEntity.setSalaId(salaEntity.getId());
                    staffEntity.setSalaName(salaEntity.getDeptName());
                }
            }
            this.update(staffEntity);
        }

    }


    @Override
    public Rest<Void> syncPersonsByDevices(Context context) {
        log.info("同步人员！");
        //todo 门禁获取人员
        StaffQuery staffQuery = new StaffQuery();
        staffQuery.setSource(SourceEnum.海康.getValue());
        staffQuery.setStatusNotList(Arrays.asList(StaffSatusEnum.离职.getValue()));
        Map<String, StaffEntity> staffCollect = this.find(staffQuery).stream().collect(Collectors.toMap(x -> x.getWorkNum(), y -> y, (o, n) -> n));

        List<DoorEntity> doorEntities = doorService.find(new DoorQuery());
        if (ObjectUtils.isEmpty(doorEntities)) return Rest.fail("未找到门禁设备！");
        try {
            for (DoorEntity doorEntity : doorEntities) {
                StaffReq staffReq = new StaffReq();
                Rest<UserSearchInfo> personCountRest = hikStaffService.getPersonCount(staffReq, doorEntity);
                if (personCountRest.getCode() == YesNoEnum.YES.getValue()) {
                    int totalNum = personCountRest.getData().getUserInfoSearch().getTotalMatches();
                    int size = 30;
                    int pages = totalNum / size;
                    for (int i = 0; i <= pages; i++) {
                        StaffReq searchReq = new StaffReq();
                        searchReq.setPageNo(i);
                        searchReq.setPageSize(size);
                        Rest<UserSearchInfo> rest = hikStaffService.getPersonList(searchReq, doorEntity);
                       log.info("page:{}, 获取人员列表：{}",i, JSON.toJSONString(rest));
                        if (rest.getCode() == YesNoEnum.YES.getValue()) {
                            //做差集 更新本地用户为离职员工
                            UserInfoSearch userInfoSearch = rest.getData().getUserInfoSearch();
                            List<UserInfoItem> userInfoList = userInfoSearch.getUserInfo();
                            for (UserInfoItem userInfoItem : userInfoList) {
                                if (ObjectUtils.isEmpty(userInfoItem.getEmployeeNo())) {
                                    log.info("EmployeeNo is null ==>{}", JSON.toJSONString(userInfoItem));
                                    continue;
                                }
                                if (staffCollect.containsKey(userInfoItem.getEmployeeNo())) {
                                    staffCollect.remove(userInfoItem.getEmployeeNo());
                                }
                                StaffEntity staffEntity = this.getExtCache(StrUtil.padPre(userInfoItem.getEmployeeNo(), 8, "0"));
                                //设置到默认部门
                                //判断本地数据是否为空
                                if (ObjectUtils.isEmpty(staffEntity)) {
                                    //新增员工信息
                                    staffEntity = new StaffEntity();
                                    staffEntity.initAttrValue();
                                    DeptQuery deptQuery = new DeptQuery();
                                    deptQuery.setParentId(0L);
                                    DeptEntity deptEntity = deptService.selectOne(deptQuery);
                                    if (!ObjectUtils.isEmpty(deptEntity)) {
                                        staffEntity.setDeptId(deptEntity.getId());
                                        staffEntity.setDeptName(deptEntity.getDeptName());
                                    }
                                    staffEntity.setName(userInfoItem.getName());
                                    staffEntity.setGender("male".equals(userInfoItem.getGender()) ? 1 : 2);
                                    staffEntity.setWorkNum(userInfoItem.getEmployeeNo());
                                    staffEntity.setStatus(StaffSatusEnum.正式.getValue());
                                    staffEntity.setCreateUserId(1L);
                                    staffEntity.setCreateTime(new Date());
                                    this.save(staffEntity);
                                } else {
                                    //更新员工状态
                                    staffEntity.setStatus(StaffSatusEnum.正式.getValue());
                                    staffEntity.setUpdateUserId(1L);
                                    staffEntity.setUpdateTime(new Date());
                                    this.update(staffEntity);
                                    StaffLeaveQuery staffLeaveQuery = new StaffLeaveQuery();
                                    staffLeaveQuery.setWorkNum(staffEntity.getWorkNum());
                                    StaffLeaveEntity staffLeaveEntity = staffLeaveService.selectOne(staffLeaveQuery, null);
                                    if (!ObjectUtils.isEmpty(staffLeaveEntity)) {
                                        staffLeaveService.remove(staffLeaveEntity.getId(), null);
                                    }
                                }
                            }
                        }
                    }
                } else {
                    log.info("人员信息为空");
                    throw new AppException(personCountRest.getMsg());
                }
            }
        } catch (Exception e) {
            log.error("同步人员信息失败", e);
            staffCollect = new HashMap<>();
        }
        if (staffCollect.size() > 0) {
            //需要将此人员变更为离职
            log.info("需要将此人员变更为离职:{}", JSON.toJSONString(staffCollect));
            staffCollect.entrySet().stream().forEach(item -> {
                String key = item.getKey();
                if (!ObjectUtils.isEmpty(key)) {
                    StaffEntity staff = item.getValue();
                    staff.setStatus(StaffSatusEnum.离职.getValue());
                    staff.setUpdateTime(new Date());
                    staff.setUpdateUserId(1L);
                    this.update(staff);

                    //新增离职人员
                    StaffLeaveEntity staffLeaveEntity = new StaffLeaveEntity();
                    staffLeaveEntity.initAttrValue();
                    staffLeaveEntity.setStaffId(staff.getId());
                    staffLeaveEntity.setStaffName(staff.getName());
                    staffLeaveEntity.setGender(staff.getGender());
                    staffLeaveEntity.setBirthday(staff.getBirthday());
                    staffLeaveEntity.setPhotoPath(staff.getPhotoPath());
                    staffLeaveEntity.setPhoneNumber(staff.getPhoneNumber());
                    staffLeaveEntity.setIdCard(staff.getIdCard());
                    staffLeaveEntity.setWorkNum(staff.getWorkNum());
                    staffLeaveEntity.setPoliticalstatus(staff.getPoliticalstatus());
                    staffLeaveEntity.setDeptId(staff.getDeptId());
                    staffLeaveEntity.setDeptName(staff.getDeptName());
                    staffLeaveEntity.setJobId(staff.getPositionId());
                    staffLeaveEntity.setJobName(staff.getPositionName());
                    staffLeaveEntity.setStaffType(staff.getStaffType());
                    staffLeaveEntity.setStatus(StaffSatusEnum.离职.getValue());
                    staffLeaveEntity.setLeaveDate(new Date());
                    staffLeaveEntity.setLeaveReason("");
                    staffLeaveEntity.setAuditStatus(AuditStatusEnum.通过.getValue());
                    staffLeaveEntity.setCreateUserId(1L);
                    staffLeaveEntity.setCreateTime(new Date());

                    StaffLeaveQuery staffLeaveQuery = new StaffLeaveQuery();
                    staffLeaveQuery.setWorkNum(staff.getWorkNum());

                    int count = staffLeaveService.count(staffLeaveQuery, null);
                    if (count == 0) {
                        staffLeaveService.save(staffLeaveEntity);
                    }
                }
            });
        }
        return Rest.ok();
    }


    @Override
    public Rest<Void> syncRegisterUsersPhotos() {
        List<StaffEntity> staffList = this.find(new StaffQuery().source(1)).stream()
                .filter(item -> ObjectUtils.isEmpty(item.getPhotoPath()))
                .filter(item -> !ObjectUtils.isEmpty(item.getPicUri())).collect(Collectors.toList());

        for (StaffEntity staff : staffList) {
            ImgReq imgReq = new ImgReq();
            imgReq.setServerIndexCode(staff.getServerIndexCode());
            imgReq.setPicUri(staff.getPicUri());
            try {
                InputStream inputStream = hikFaceService.callPostImgs(imgReq);
                if (!ObjectUtils.isEmpty(inputStream)) {
                    MultipartFile file = ServletUtils.getMultipartFile(inputStream, "photo.jpg");
                    String filePath = uploadService.saveFileUpload(file, "/file/fileupload/staff", null);
                    staff.setPhotoPath(filePath);
                    this.update(staff);
                } else {
                    log.error("获取图片异常！");
                }
            } catch (Exception e) {
                log.error("下载图片异常", e.getMessage());
            }
        }
        return Rest.ok();
    }

    public static void main(String[] args) {
        System.out.println("1" + StrUtil.padPre("125", 7, "0"));


        ArrayList<AttendanceGroupStaffEntity> attendanceGroupStaffEntities = new ArrayList<>();

        Long[] ids = attendanceGroupStaffEntities.stream().map(i -> i.getId()).toArray(Long[]::new);


        System.out.println(JSON.toJSONString(ids));

    }
}