package com.ssm.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.PeekingIterator;
import com.ssm.core.utils.BeiSenUtils;
import com.ssm.core.utils.HttpClientUtil;
import com.ssm.core.utils.SnowflakeUtil;
import com.ssm.filter.LoginInterceptor;
import com.ssm.manage.dao.AbsenteeismRecordDao;
import com.ssm.manage.dao.BlackListDao;
import com.ssm.manage.dao.JobContentListDao;
import com.ssm.manage.dao.RegionListDao;
import com.ssm.manage.dto.BlackListDto;
import com.ssm.manage.dto.StaffTemporaryDto;
import com.ssm.manage.dto.StaffTemporaryEntrantDto;
import com.ssm.manage.entity.*;
import com.ssm.manage.mapper.AbsenteeismRecordMapper;
import com.ssm.manage.mapper.StaffTemporaryMapper;
import com.ssm.manage.mapper.StaffTemporaryUpdateMapper;
import com.ssm.manage.response.*;
import com.ssm.manage.service.*;
import com.ssm.manage.utils.Constant;
import com.ssm.manage.utils.DateUtils;
import com.ssm.manage.utils.SessionHelp;
import com.ssm.manage.utils.StringUtils;
import com.ssm.util.RedisClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * (StaffTemporary)表控制层
 *
 * @author makejava
 * @since 2023-12-19 08:59:36
 */
@RestController
@RequestMapping("staffTemporary")
@Slf4j
@Api(tags = "临时工扫码记录")
public class StaffTemporaryController {
    /**
     * 服务对象
     */
    @Autowired
    private StaffTemporaryService staffTemporaryService;
    @Autowired
    private StaffTemporaryMapper staffTemporaryMapper;
    @Autowired
    private StaffTemporaryUpdateService staffTemporaryUpdateService;
    @Autowired
    private RedisClient<StaffResponse> redisClient;

    @Autowired
    private RedisClient<String> stringRedisClient;
    @Autowired
    private BlackListDao blackListDao;
    @Autowired
    private RedisClient<StaffTemporaryVo> staffTemporaryVoRedisClient;

    @Autowired
    private RegionListDao regionListDao;
    @Autowired
    private SsmBaseStoreService ssmBaseStoreService;
    @Autowired
    private BeiSenUtils beiSenUtils;
    @Autowired
    private BeisenUserListService beisenUserListServicel;
    @Value("${zhongkong.key}")
    private String key;
    @Value("${zhongkong.host}")
    private String host;

    @Autowired
    private JobContentListDao jobContentListDao;

    @Autowired
    private StaffTemporaryUpdateMapper staffTemporaryUpdateMapper;
    @Autowired
    private AbsenteeismRecordMapper absenteeismRecordMapper;
    @Autowired
    private AbsenteeismRecordDao absenteeismRecordDao;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return
     @GetMapping("{id}")
     @ApiOperation("通过主键查询单条数据")
     //@RequiresPermissions("system:staffTemporary:query")
     public ResultVo get(@PathVariable Serializable id) {
     return this.staffTemporaryService.queryById(id);
     }
     */


    /**
     * 分页查询
     *
     * @param dto
     * @return
     */
    @PostMapping("/getList")
    @ApiOperation("分页查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码", defaultValue = "1", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页数量", defaultValue = "10", required = true)
    })
//@RequiresPermissions("system:staffTemporary:query")
    public PageResponse<StaffTemporaryVo> listPage(@RequestBody StaffTemporaryDto dto) {
        PageResponse<StaffTemporaryVo> pageResponse = new PageResponse<>();
        PageInfo<StaffTemporaryVo> pageInfo = new PageInfo<>();
        try {
            pageInfo = this.staffTemporaryService.selectPage(dto);
        } catch (Exception e) {
            log.error("SsmCollectionTypeController.selectPage", e);
            pageResponse.setCodeAndMsg(ResponseCode.FAILED);
            return pageResponse;
        }
        pageResponse.setPageInfo(pageInfo);
        pageResponse.setCodeAndMsg(ResponseCode.OK);
        return pageResponse;
    }

    /**
     * id查询
     *
     * @param id
     * @return
     */
    @GetMapping("/getById")
    @ApiOperation("id查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id",  required = true)
    })
//@RequiresPermissions("system:staffTemporary:query")
    public GenericResponse<StaffTemporary> getById(Long id) {
        GenericResponse<StaffTemporary> pageResponse = new GenericResponse<>();
        try {
            pageResponse.setData(this.staffTemporaryService.selectByPrimaryKey(id));
        } catch (Exception e) {
            log.error("SsmCollectionTypeController.selectPage", e);
            pageResponse.setCodeAndMsg(ResponseCode.FAILED);
            return pageResponse;
        }

        pageResponse.setCodeAndMsg(ResponseCode.OK);
        return pageResponse;
    }

    /**
     * 新增
     *
     * @param staffTemporary
     * @return
     */
    @PostMapping
    @ApiOperation("新增")
//@RequiresPermissions("system:staffTemporary:add")
    public GenericResponse add(@RequestBody StaffTemporary staffTemporary) {
        GenericResponse genericResponse = new GenericResponse();
        int i = 0;
        try {
            staffTemporary.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
            i = this.staffTemporaryService.save(staffTemporary);
        } catch (Exception e) {
            log.error("SsmCollectionTypeController.add:", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        } else {
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
        }
        return genericResponse;
    }

    /**
     * 编辑
     *
     * @param staffTemporaryVo
     * @return
     */
    @PutMapping("/loginOut")
    @ApiOperation("编辑")
//@RequiresPermissions("system:staffTemporary:edit")
    public GenericResponse<StaffTemporaryVo> loginOut(@RequestBody StaffTemporaryVo staffTemporaryVo) {
        GenericResponse genericResponse = new GenericResponse();
        int i = 0;
        try {
            staffTemporaryVoRedisClient.delete(Constant.staffTemporary + staffTemporaryVo.getToken());
            //todo 推送北森进行更新操作
//            String beiSenToken = beiSenUtils.getToken();
        } catch (Exception e) {
            log.error("SsmCollectionTypeController.add:", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        return genericResponse;
    }

    /**
     * 编辑
     *
     * @param staffTemporaryVo
     * @return
     */
    //TODO 小程序修改
    @PutMapping("/update")
    @ApiOperation("编辑")
    @Transactional
//@RequiresPermissions("system:staffTemporary:edit")
    public GenericResponse<StaffTemporaryVo> update(@RequestBody StaffTemporaryVo staffTemporaryVo, HttpSession session) {
        GenericResponse genericResponse = new GenericResponse();
        int i = 0;

        try {
            StaffTemporary staffTemporary = new StaffTemporary();
            BeanUtils.copyProperties(staffTemporaryVo, staffTemporary);
            StaffTemporaryUpdate staffTemporaryUpdate = new StaffTemporaryUpdate();
            StaffTemporary temporary = staffTemporaryService.selectByPrimaryKey(staffTemporary.getId());
            /*if (temporary == null) {
                genericResponse.setCodeAndMsg(ResponseCode.FAILED, "账号异常，无法修改");
                return genericResponse;
            }*/
            //TODO 修改了这里
            String s = stringRedisClient.get(Constant.ruzhiPhone + temporary.getId().toString());
//            String s = stringRedisClient.get(staffTemporaryVo.getMobilePhone() + temporary.getId().toString());
            //            String s = stringRedisClient.get(Constant.ruzhiPhone + staffTemporaryVo.getId().toString());
            if (StringUtils.isEmpty(s)){
                genericResponse.setCodeAndMsg(ResponseCode.MSG,"已提交信息，无法修改");
                return genericResponse;
            }

            if ((temporary.getZhongkongDimission()!=null && temporary.getZhongkongDimission()!=1)
                    || (temporary.getBeisenDimission()!=null && temporary.getBeisenDimission()!=1)){
                genericResponse.setCodeAndMsg(ResponseCode.MSG,"目前在职，无法修改");
                stringRedisClient.delete(Constant.ruzhiPhone+staffTemporaryVo.toString());
                return genericResponse;
            }
            //todo 添加离职时不能修改限制
            if((temporary.getZhongkongDimission()!=null && temporary.getZhongkongDimission()==1)
                    || (temporary.getBeisenDimission()!=null && temporary.getBeisenDimission()==1)){
                genericResponse.setCodeAndMsg(ResponseCode.MSG,"目前为离职状态，无法修改");
                stringRedisClient.delete(Constant.ruzhiPhone+staffTemporaryVo.toString());
                return genericResponse;
            }

            // 重新设置时间
            Date ruzhiTime = staffTemporaryVo.getRuzhiTime();
            if (ruzhiTime != null) {
                if (temporary.getType() == 0) {
                    // 日结, 离职时间为当天 23:59:00
                    Date endTime = DateUtils.getEndOfDayAfter(ruzhiTime, 0);
                    staffTemporary.setEndTime(endTime);
                    temporary.setEndTime(endTime);
                }/* else if (temporary.getType() == 1) {
                    Date endTime = DateUtils.getEndOfDayAfter(ruzhiTime, 30);
                    staffTemporary.setEndTime(endTime);
                    temporary.setEndTime(endTime);
                }*/
            }
            i = this.staffTemporaryService.updateNotNull(staffTemporary);
            if (!temporary.getStaffNum().equals(staffTemporaryVo.getStaffNum())){
                Example blackExample = new Example(BlackList.class);
                blackExample.createCriteria().andEqualTo(BlackListDto.Fields.staffNum,staffTemporaryVo.getStaffNum());
                List<BlackList> blackListList = blackListDao.selectByExample(blackExample);
                if (!CollectionUtils.isEmpty(blackListList)){
                    genericResponse.setCodeAndMsg(ResponseCode.MSG,"工号："+staffTemporaryVo.getStaffNum()+"已被占用");
                    return genericResponse;
                }
                blackExample.clear();
                blackExample.createCriteria().andEqualTo(BlackListDto.Fields.staffNum,temporary.getStaffNum());
                List<BlackList> blackLists = blackListDao.selectByExample(blackExample);
                BlackList blackList = blackLists.get(0);
                blackList.setStaffNum(staffTemporaryVo.getStaffNum());
                blackList.setUrgentPhone(staffTemporaryVo.getUrgentPhone());
                blackList.setUrgentName(staffTemporaryVo.getUrgentName());
                blackList.setUrgentRelationship(staffTemporaryVo.getUrgentRelationship());
                staffTemporaryUpdate.setBlackId(blackList.getId());
                blackListDao.updateByPrimaryKey(blackList);
            }
            BeanUtils.copyProperties(temporary,staffTemporaryUpdate);
            staffTemporaryUpdate.setUpdateDate(new Date());
            staffTemporaryUpdate.setStaffTemporaryId(staffTemporaryVo.getId());
            staffTemporaryUpdate.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
            //先查询当前修改的,判断前后身份证是否一致
            if (!temporary.getIdentityCard().equals(staffTemporaryVo.getIdentityCard())) {
                Example exampleOld = new Example(BlackList.class);
                Example.Criteria criteriaOld = exampleOld.createCriteria();
                criteriaOld.andEqualTo(BlackListDto.Fields.identityCard, temporary.getIdentityCard());
                List<BlackList> blackListList = blackListDao.selectByExample(exampleOld);
                BlackList blackList = blackListList.get(0);
                Long id = blackList.getId();
                Integer type = blackList.getType();
                BeanUtils.copyProperties(staffTemporaryVo, blackList);
                blackList.setType(type);
                blackList.setId(id);
                staffTemporaryUpdate.setBlackId(id);
                blackListDao.updateByPrimaryKey(blackList);
                //删除当前的
//                BlackList blackList1 = new BlackList();
//                blackList1.setIdentityCard(temporary.getIdentityCard());
//                blackListDao.delete(blackList1);
            } else {
                //修改
                Example example = new Example(BlackList.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo(BlackListDto.Fields.identityCard, temporary.getIdentityCard());
                List<BlackList> list = blackListDao.selectByExample(example);
                BlackList blackList = list.get(0);
                Long id = blackList.getId();
                Integer type = blackList.getType();
                BeanUtils.copyProperties(staffTemporaryVo, blackList);
                blackList.setId(id);
                blackList.setType(type);
                staffTemporaryUpdate.setBlackId(id);
                blackListDao.updateByPrimaryKey(blackList);
            }
            staffTemporaryUpdateService.save(staffTemporaryUpdate);

            staffTemporaryVoRedisClient.delete(Constant.staffTemporary + staffTemporaryVo.getToken());
            stringRedisClient.delete(Constant.ruzhiPhone + temporary.getId());
            String token = UUID.randomUUID().toString();
            staffTemporaryVo.setToken(token);
            staffTemporaryVo.setBaseStores(ssmBaseStoreService.selectByPrimaryKey(staffTemporaryVo.getStoreId()));
            staffTemporaryVo.setRegionList(regionListDao.selectByPrimaryKey(staffTemporaryVo.getRegionId()));
            staffTemporaryVo.setToken(token);
            staffTemporaryVoRedisClient.set(Constant.staffTemporary + token, staffTemporaryVo, RedisClient.EXPIRE_TIME_ONE_DAY, TimeUnit.SECONDS);
            genericResponse.setData(staffTemporaryVo);
            //todo 推送北森进行更新操作
//            String beiSenToken = beiSenUtils.getToken();
            //todo 修改在这里
            stringRedisClient.delete(Constant.ruzhiPhone+staffTemporaryVo.toString());
        } catch (Exception e) {
            log.error("SsmCollectionTypeController.add:", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        } else {
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
        }
        return genericResponse;
    }

    /**
     * 新入职
     */
//    @PostMapping("/addRuzhiByWechat")
    @PostMapping("/updateRuzhiTime")
    @ApiOperation("新入职")
    public GenericResponse addEntrant(@RequestBody StaffTemporaryVo staffTemporaryVo,
                                      @RequestHeader("Token") String token) {
        GenericResponse genericResponse = new GenericResponse();
        StaffTemporaryUpdate staffTemporaryUpdate = new StaffTemporaryUpdate();

        // 参数过滤
        StaffTemporaryEntrantDto staffTempEntrantDto = new StaffTemporaryEntrantDto();
        BeanUtils.copyProperties(staffTemporaryVo, staffTempEntrantDto);

        // 校验
        Long sourceId = staffTempEntrantDto.getId();   // 是原先记录的ID
        if (sourceId == null) {
            genericResponse.setCodeAndMsg(ResponseCode.MSG, "请正确提交数据");
            return genericResponse;
        }
        Date ruzhiTime = staffTempEntrantDto.getRuzhiTime();
        if (ruzhiTime == null) {
            genericResponse.setCodeAndMsg(ResponseCode.MSG, "请填写入场时间");
            return genericResponse;
        }

        // 获取原先的记录
        StaffTemporary sourceStaffTemp = staffTemporaryService.selectByPrimaryKey(sourceId);
        if (sourceStaffTemp == null) {
            genericResponse.setCodeAndMsg(ResponseCode.MSG, "记录异常");
            return genericResponse;
        }
        // 获取原数据
        Integer sourceType = sourceStaffTemp.getType();
        Date sourceRuzhiTime = sourceStaffTemp.getRuzhiTime();
        if (sourceType == null || sourceRuzhiTime == null) {
            genericResponse.setCodeAndMsg(ResponseCode.MSG, "原记录异常");
            return genericResponse;
        }
        // 获取入职类型
        int type = Optional.ofNullable(staffTempEntrantDto.getType()).orElse(sourceType);
        // 入职操作检验
        if (DateUtils.compareDate(ruzhiTime, sourceRuzhiTime) == 0) {
            if (ObjectUtils.equals(type, sourceType)) { // 一样的入职类型, 没有新的操作
                genericResponse.setCodeAndMsg(ResponseCode.MSG, "请勿重复提交");
            } else {    // 仅入职类型不同, 不允许修改入职类型
                genericResponse.setCodeAndMsg(ResponseCode.MSG, "如需修改服务类型, 请联系相关工作人员");
            }
            return genericResponse;
        }

        // 验证身份证
        String identityCard = sourceStaffTemp.getIdentityCard();
        if (StringUtils.isBlank(identityCard)) {
            genericResponse.setCodeAndMsg(ResponseCode.MSG, "没有对应身份证信息");
            return genericResponse;
        }

        // 身份证正确, 通过身份证获取最后一次入职记录, 进行入职检验
        StaffTemporary lastRuzhiStaffTemp = staffTemporaryMapper.selectLastRuzhiByIdentityCard(identityCard);
        if (lastRuzhiStaffTemp != null) {
            Integer isZhongkong = lastRuzhiStaffTemp.getIsZhongkong();
            if (isZhongkong == null || isZhongkong == 0) { // 中控未推送
                genericResponse.setCodeAndMsg(ResponseCode.MSG, "已存在待入职记录，无法修改");
                return genericResponse;
            }
            Integer zhongkongDimission = lastRuzhiStaffTemp.getZhongkongDimission();
            if (zhongkongDimission == null || zhongkongDimission != 1) {  // 中控未离职
                genericResponse.setCodeAndMsg(ResponseCode.MSG, "目前在职，无法修改");
                return genericResponse;
            }
        }

        // 已经离职
        // 获取当天 09:00:00.000 的入职时间
        ruzhiTime = DateUtils.getDateByTime(ruzhiTime, 9);

        // 新增入职记录
        StaffTemporary newStaffTemp = new StaffTemporary();
        // 根据原本的入职信息创建新记录
        long id = new SnowflakeUtil(new Random().nextInt(1023)).nextId();
        newStaffTemp.setId(id);
        // 紧急联系人信息
        newStaffTemp.setUrgentName(sourceStaffTemp.getUrgentName());
        newStaffTemp.setUrgentPhone(sourceStaffTemp.getUrgentPhone());
        newStaffTemp.setUrgentRelationship(sourceStaffTemp.getUrgentRelationship());
        // 入职信息
        newStaffTemp.setRemark(sourceStaffTemp.getRemark());
        newStaffTemp.setScanTime(new Date());
        newStaffTemp.setRuzhiTime(ruzhiTime);
        newStaffTemp.setType(type);
        // 离职时间
        if (type == 0) {
            newStaffTemp.setEndTime(DateUtils.getEndOfDayAfter(ruzhiTime, 0));
        }/* else if (type == 1) {
            newStaffTemp.setEndTime(DateUtils.getEndOfDayAfter(ruzhiTime, 30));
        }*/
        // 月结不设置离职时间
        // 员工基本信息
        newStaffTemp.setStaffNum(sourceStaffTemp.getStaffNum());
        newStaffTemp.setStaffName(sourceStaffTemp.getStaffName());
        newStaffTemp.setEmail(sourceStaffTemp.getEmail());
        newStaffTemp.setMobilePhone(sourceStaffTemp.getMobilePhone());
        newStaffTemp.setIdentityType(sourceStaffTemp.getIdentityType());
        newStaffTemp.setIdentityCard(sourceStaffTemp.getIdentityCard());
        newStaffTemp.setSex(sourceStaffTemp.getSex());
        newStaffTemp.setStoreId(sourceStaffTemp.getStoreId());
        newStaffTemp.setRegionId(sourceStaffTemp.getRegionId());
        newStaffTemp.setFacesInformation(sourceStaffTemp.getFacesInformation());
        // 员工状态
        newStaffTemp.setState(0);
        newStaffTemp.setIsBeisen(0);
        newStaffTemp.setIsZhongkong(0);
        newStaffTemp.setIsOne(1);
        newStaffTemp.setIsUpdate(1);
        // 新增记录
        int save = staffTemporaryService.save(newStaffTemp);
        if (save != 1) {
            genericResponse.setCodeAndMsg(ResponseCode.MSG, "新增失败，请稍后重试");
            return genericResponse;
        }

        //todo 记录到修改记录表中 修改时间2024/10/21
        Example example = new Example(BlackList.class);
        example.excludeProperties("id");
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo(BlackListDto.Fields.identityCard,newStaffTemp.getIdentityCard());
        List<BlackList> blackLists = blackListDao.selectByExample(example);
        BeanUtils.copyProperties(newStaffTemp,staffTemporaryUpdate);
        staffTemporaryUpdate.setRuzhiTime(sourceStaffTemp.getScanTime());
        staffTemporaryUpdate.setUpdateDate(newStaffTemp.getScanTime());
        staffTemporaryUpdate.setStaffTemporaryId(newStaffTemp.getId());
        staffTemporaryUpdate.setBlackId(blackLists.get(0).getId());
        staffTemporaryUpdate.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        staffTemporaryUpdateMapper.insert(staffTemporaryUpdate);

        // 获取视图对象
        StaffTemporaryVo newStaffTempVo = new StaffTemporaryVo();
        BeanUtils.copyProperties(newStaffTemp, newStaffTempVo);
        // 按照原有逻辑 Token 应该被存在 StaffTemporaryVo 中, 并缓存
        newStaffTempVo.setToken(token);

        // 设置缓存, 确保原先的操作准确
        stringRedisClient.set(Constant.ruzhiPhone + id, String.valueOf(id), 10800L, TimeUnit.SECONDS);
        stringRedisClient.set(Constant.ruzhiPhoneAndTime + id, UUID.randomUUID().toString(), 10800L, TimeUnit.SECONDS);
        // 更新缓存中的信息
        staffTemporaryVoRedisClient.set(Constant.staffTemporary + token, newStaffTempVo,
                RedisClient.EXPIRE_TIME_ONE_DAY, TimeUnit.SECONDS);

        // 返回结果
        genericResponse.setData(newStaffTempVo);
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        return genericResponse;
    }

    /**
     * 编辑
     *
     * @param staffTemporary
     * @return
     */
//    @PostMapping("/updateRuzhiTime")
    @ApiOperation("编辑")
//@RequiresPermissions("system:staffTemporary:edit")
    public GenericResponse updateRuzhiTime(@RequestBody StaffTemporaryVo staffTemporary) {
        GenericResponse genericResponse = new GenericResponse();
        genericResponse.setData(staffTemporary);
        StaffTemporaryUpdate staffTemporaryUpdate = new StaffTemporaryUpdate();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        StaffTemporary temporary = new StaffTemporary();
        StaffTemporary byPrimaryKey = staffTemporaryService.selectByPrimaryKey(staffTemporary.getId());
        BeanUtils.copyProperties(byPrimaryKey,temporary);
        temporary.setRemark(staffTemporary.getRemark());
        temporary.setType(staffTemporary.getType());
        if ((temporary.getZhongkongDimission()!=null && temporary.getZhongkongDimission()!=1)
                || (temporary.getBeisenDimission()!=null && temporary.getBeisenDimission()!=1)){
            genericResponse.setCodeAndMsg(ResponseCode.MSG,"目前在职，无法修改");
            return genericResponse;
        }

        if (Objects.isNull(temporary.getRuzhiTime())){
            genericResponse.setCodeAndMsg(ResponseCode.MSG,"请填写入场时间");
            return genericResponse;
        }
        BeanUtils.copyProperties(byPrimaryKey,staffTemporaryUpdate);
        staffTemporaryUpdate.setUpdateDate(new Date());

        staffTemporaryUpdate.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        Example example = new Example(BlackList.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo(BlackListDto.Fields.identityCard, temporary.getIdentityCard());
        List<BlackList> list = blackListDao.selectByExample(example);
        BlackList blackList = list.get(0);
        staffTemporaryUpdate.setBlackId(blackList.getId());
//        BeanUtils.copyProperties(staffTemporary,temporary);
//        temporary.setIsUpdate(0);
//        temporary.setState(0);
//        temporary.setIsOne(1);
        Long oldId = staffTemporary.getId();
        temporary.setIsZhongkong(0);
        temporary.setIsBeisen(0);
        temporary.setRuzhiTime(staffTemporary.getRuzhiTime());
        long id = new SnowflakeUtil(new Random().nextInt(1023)).nextId();
        temporary.setId(id);
        staffTemporaryUpdate.setStaffTemporaryId(id);
            temporary.setZhongkongDimission(null);
            temporary.setBeisenDimission(null);
            temporary.setBeisenDimissionDate(null);

            temporary.setIsZhongkong(0);
            temporary.setSendZhongkongTime(null);
            temporary.setIsBeisen(0);
            temporary.setSendTime(null);

            temporary.setZhongkongDimissionDate(null);
            temporary.setScanTime(new Date());
            temporary.setEndType(0);
            if(temporary.getType()==0){
                SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String format1 = format.format(temporary.getRuzhiTime());
                format1 += " 23:59:00";
                try {
                    Date parse = format2.parse(format1);
                    temporary.setEndTime(parse);
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
        }

//        String dateFormat = format.format(temporary.getRuzhiTime());

        try {
            if (byPrimaryKey.getIsZhongkong()==null || byPrimaryKey.getIsZhongkong()==0){
                temporary.setId(oldId);
                String s = stringRedisClient.get(Constant.ruzhiPhoneAndTime + temporary.getId().toString());
                if (StringUtils.isNotBlank(s) && temporary.getIsZhongkong()==0){
                    genericResponse.setCodeAndMsg(ResponseCode.MSG,"已提交信息，无法修改");
                    return genericResponse;
                }
                this.staffTemporaryService.updateByPrimaryKey(temporary);
            }else {
                String s = stringRedisClient.get(Constant.ruzhiPhoneAndTime + temporary.getId().toString());
                if (StringUtils.isNotBlank(s) && temporary.getIsZhongkong()==0){
                    genericResponse.setCodeAndMsg(ResponseCode.MSG,"已提交信息，无法修改");
                    return genericResponse;
                }
                this.staffTemporaryService.save(temporary);
            }
            staffTemporaryUpdateService.save(staffTemporaryUpdate);
            stringRedisClient.set(Constant.ruzhiPhone + temporary.getId().toString(),temporary.getId().toString(),10800L,TimeUnit.SECONDS);
            stringRedisClient.set(Constant.ruzhiPhoneAndTime + temporary.getId().toString(),UUID.randomUUID().toString(),10800L,TimeUnit.SECONDS);
            BeanUtils.copyProperties(temporary,staffTemporary);
            staffTemporary.setId(temporary.getId());
            staffTemporaryVoRedisClient.set(Constant.staffTemporary + staffTemporary.getToken(),staffTemporary,RedisClient.EXPIRE_TIME_ONE_DAY, TimeUnit.SECONDS);
        } catch (Exception e) {
            log.error("SsmCollectionTypeController.add:", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        genericResponse.setData(staffTemporary);
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        return genericResponse;
    }

    /**
     * 编辑
     *
     * @param staffTemporary
     * @return
     */
    @PutMapping
    @ApiOperation("编辑")
//@RequiresPermissions("system:staffTemporary:edit")
    public GenericResponse edit(@RequestBody StaffTemporary staffTemporary, HttpSession session) {
        GenericResponse genericResponse = new GenericResponse();
        int i = 0;
        try {
            String loginAccount = SessionHelp.getLoginAccount(session);
            StaffResponse staffResponse = redisClient.get(Constant.staffKey + loginAccount);
            staffTemporary.setEndId(staffResponse.getId());
            staffTemporary.setEndName(staffResponse.getStaffName());
            staffTemporary.setEndType(1);
            i = this.staffTemporaryService.updateByPrimaryKey(staffTemporary);
        } catch (Exception e) {
            log.error("SsmCollectionTypeController.add:", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        } else {
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
        }
        return genericResponse;
    }
    /**
     * 编辑
     *
     * @param staffTemporaryVo
     * @return
     */
    @PutMapping("/updateById")
    @ApiOperation("编辑")
    @Transactional
//@RequiresPermissions("system:staffTemporary:edit")
    public GenericResponse<StaffTemporaryVo> updateById(@RequestBody StaffTemporaryVo staffTemporaryVo) {
        GenericResponse genericResponse = new GenericResponse();
        int i = 0;
        try {
            StaffTemporary staffTemporary = new StaffTemporary();
            BeanUtils.copyProperties(staffTemporaryVo, staffTemporary);
            StaffTemporaryUpdate staffTemporaryUpdate = new StaffTemporaryUpdate();
            StaffTemporary temporary = staffTemporaryService.selectByPrimaryKey(staffTemporary.getId());

            // 重新设置时间
            Date ruzhiTime = staffTemporaryVo.getRuzhiTime();
            if (ruzhiTime != null) {
                if (temporary.getType() == 0) {
                    // 日结, 离职时间为当天 23:59:00
                    Date endTime = DateUtils.getEndOfDayAfter(ruzhiTime, 0);
                    staffTemporary.setEndTime(endTime);
                    temporary.setEndTime(endTime);
                } else if (temporary.getType() == 1) {
//                    Date endTime = DateUtils.getEndOfDayAfter(ruzhiTime, 30);
                    // 月结, 入职时间设置为 null
                    Date endTime = null;
                    staffTemporary.setEndTime(endTime);
                    temporary.setEndTime(endTime);
                }
            }
            i = this.staffTemporaryService.updateNotNull(staffTemporary);
            BeanUtils.copyProperties(temporary,staffTemporaryUpdate);
            staffTemporaryUpdate.setStaffTemporaryId(staffTemporaryVo.getId());
            StaffResponse userInfo = LoginInterceptor.getCurrentUserInfo();
            staffTemporaryUpdate.setUpdateId(userInfo.getId());
            staffTemporaryUpdate.setUpdateName(userInfo.getStaffName());
            staffTemporaryUpdate.setUpdateDate(new Date());

            if (!temporary.getStaffNum().equals(staffTemporaryVo.getStaffNum())){
                if (temporary.getIsZhongkong()!=null && temporary.getIsZhongkong()==2){

                }
                Example blackExample = new Example(BlackList.class);
                blackExample.createCriteria().andEqualTo(BlackListDto.Fields.staffNum,staffTemporaryVo.getStaffNum());
                List<BlackList> blackListList = blackListDao.selectByExample(blackExample);
                if (!CollectionUtils.isEmpty(blackListList)){
                    genericResponse.setCodeAndMsg(ResponseCode.MSG,"工号："+staffTemporaryVo.getStaffNum()+"已被占用");
                    return genericResponse;
                }
                blackExample.clear();
                blackExample.createCriteria().andEqualTo(BlackListDto.Fields.staffNum,temporary.getStaffNum());
//                        .andEqualTo(BlackListDto.Fields.identityCard,temporary.getIdentityCard());
                List<BlackList> blackLists = blackListDao.selectByExample(blackExample);
                if (!CollectionUtils.isEmpty(blackLists)) {
                    BlackList blackList = blackLists.get(0);
                    blackList.setStaffNum(staffTemporaryVo.getStaffNum());
                    blackList.setUrgentPhone(staffTemporaryVo.getUrgentPhone());
                    blackList.setUrgentName(staffTemporaryVo.getUrgentName());
                    blackList.setUrgentRelationship(staffTemporaryVo.getUrgentRelationship());
                    staffTemporaryUpdate.setBlackId(blackList.getId());
                    blackListDao.updateByPrimaryKey(blackList);
                }
            }
            //先查询当前修改的,判断前后身份证是否一致
            if (!temporary.getIdentityCard().equals(staffTemporaryVo.getIdentityCard()) ||
                    (!temporary.getUrgentName().equals(staffTemporaryVo.getUrgentName())
                            || !temporary.getUrgentPhone().equals(staffTemporaryVo.getUrgentPhone())
                           || !temporary.getUrgentRelationship().equals(staffTemporaryVo.getUrgentRelationship()) )
            ) {
                Example exampleOld = new Example(BlackList.class);
                Example.Criteria criteriaOld = exampleOld.createCriteria();
                criteriaOld.andEqualTo(BlackListDto.Fields.identityCard, temporary.getIdentityCard());
                List<BlackList> blackListList = blackListDao.selectByExample(exampleOld);
                if (!CollectionUtils.isEmpty(blackListList)) {
                    BlackList blackList = blackListList.get(0);
                    Long id = blackList.getId();
                    Integer type = blackList.getType();
                    BeanUtils.copyProperties(staffTemporaryVo, blackList);
                    blackList.setType(type);
                    blackList.setId(id);
                    staffTemporaryUpdate.setBlackId(id);
                    blackListDao.updateByPrimaryKey(blackList);
                }
                //删除当前的
//                BlackList blackList1 = new BlackList();
//                blackList1.setIdentityCard(temporary.getIdentityCard());
//                blackListDao.delete(blackList1);
            } else {
                //修改
                Example example = new Example(BlackList.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo(BlackListDto.Fields.identityCard, temporary.getIdentityCard());
                List<BlackList> list = blackListDao.selectByExample(example);
                if (!CollectionUtils.isEmpty(list)) {
                    BlackList blackList = list.get(0);
                    Long id = blackList.getId();
                    Integer type = blackList.getType();
                    BeanUtils.copyProperties(staffTemporaryVo, blackList);
                    blackList.setId(id);
                    blackList.setType(type);
                    staffTemporaryUpdate.setBlackId(id);
                    blackListDao.updateByPrimaryKey(blackList);
                }
            }
            staffTemporaryUpdate.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
            staffTemporaryUpdateService.save(staffTemporaryUpdate);
            genericResponse.setData(staffTemporaryVo);
        } catch (Exception e) {
            if (e instanceof SQLIntegrityConstraintViolationException){
                genericResponse.setCodeAndMsg(ResponseCode.MSG,"用户已存在");
                return genericResponse;
            }
            log.error("SsmCollectionTypeController.add:", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        } else {
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
        }
        return genericResponse;
    }

    /**
     * 根据主键删除
     *
     * @param id 主键
     * @return
     */
    @DeleteMapping("{id}")
    @ApiOperation("根据主键删除")
//@RequiresPermissions("system:staffTemporary:delete")
    public GenericResponse delete(@PathVariable Long id) {
        GenericResponse genericResponse = new GenericResponse();
        int i = 0;
        try {

            StaffTemporary temporary = this.staffTemporaryService.selectByPrimaryKey(id);
            Example example = new Example(StaffTemporary.class);
            example.createCriteria().andEqualTo(BlackListDto.Fields.identityCard,temporary.getIdentityCard());
            List<StaffTemporary> staffTemporaryList = staffTemporaryService.selectByExample(example);
            if (!CollectionUtils.isEmpty(staffTemporaryList) && staffTemporaryList.size()==1 && (temporary.getIsZhongkong()==null || temporary.getIsZhongkong()==0)){
                Example blackExample = new Example(BlackList.class);
                blackExample.createCriteria().andEqualTo(StaffTemporaryDto.Fields.identityCard,temporary.getIdentityCard());
                List<BlackList> blackListList = blackListDao.selectByExample(blackExample);
                if (!CollectionUtils.isEmpty(blackListList)&& blackListList.size()==1){
                    blackListDao.deleteByPrimaryKey(blackListList.get(0).getId());
                }
            }
            i = this.staffTemporaryService.deleteByPrimaryKey(id);
        } catch (Exception e) {
            log.error("SsmCollectionTypeController.add:", e);
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            return genericResponse;
        }
        if (i > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.OK);
        } else {
            genericResponse.setCodeAndMsg(ResponseCode.FAILED);
        }
        return genericResponse;
    }

    /**
     * 编辑
     *
     * @return
     */
    @PutMapping("/updateByBeiSen")
    @ApiOperation("人员推送北森")
//@RequiresPermissions("system:staffTemporary:edit")
    public GenericResponse updateByBeiSen(@RequestBody List<StaffTemporaryDto> staffTemporaryDtoList, HttpSession session) {
        GenericResponse genericResponse = new GenericResponse();
        genericResponse.setCodeAndMsg(ResponseCode.OK);

        String str = "";
        for (StaffTemporaryDto staffTemporary : staffTemporaryDtoList) {
            BlackList blackList = new BlackList();
            blackList.setIdentityCard(staffTemporary.getIdentityCard());
            List<BlackList> blackListList = blackListDao.select(blackList);
            blackList = blackListList.get(0);
            if (Objects.nonNull(blackList.getBeisenUserId())){
                str += "员工"+staffTemporary.getStaffName()+"已推送北森，请前往北森系统启用";
                String loginAccount = SessionHelp.getLoginAccount(session);
                StaffResponse staffResponse = redisClient.get(Constant.staffKey + loginAccount);
                StaffTemporary temporary = new StaffTemporary();
                temporary.setId(staffTemporary.getId());
                temporary.setIsBeisen(2);
                temporary.setBeisenDimission(0);

                if (staffTemporary.getSendTime()==null){
                    temporary.setSendTime(new Date());
                }else
                {temporary.setSendTime(staffTemporary.getSendTime());}
//                    if (staffTemporary.getBeisenDimission()!=null){
//                        temporary.setBeisenDimissionDate(staffTemporary.getBeisenDimissionDate());
//                    }else temporary.setBeisenDimissionDate(new Date());
                temporary.setBeisenDimissionDate(null);
                temporary.setSendId(staffResponse.getId());
                temporary.setBeisenDeptId(staffTemporary.getBeisenDeptId());
                temporary.setBeisenDeptNum(staffTemporary.getBeisenDeptNum());
                temporary.setBeisenDeptName(staffTemporary.getBeisenDeptName());
                temporary.setSendName(staffResponse.getStaffName());
                staffTemporaryService.updateNotNull(temporary);
                continue;
            }
            String url = "https://openapi.italent.cn/TenantBaseExternal/api/v5/Employee/Create";
            Map<String, Object> map = new HashMap<>();
            Map<String, Object> map1 = new HashMap<>();
            Map<String, Object> map2 = new HashMap<>();
            map1.put("name", staffTemporary.getStaffName());
            map1.put("email", staffTemporary.getEmail());
            map1.put("originalId", blackList.getId().toString());
            map1.put("iDType", "1");
            map1.put("iDNumber", staffTemporary.getIdentityCard());
            map1.put("gender", staffTemporary.getSex());
            map1.put("mobilePhone", staffTemporary.getMobilePhone());

            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

            String dateFormart = format.format(staffTemporary.getSendTime()==null?new Date():staffTemporary.getSendTime());
            map2.put("entryDate", dateFormart);
            map2.put("probation", 0);
            map2.put("employType", 1);
            map2.put("oIdDepartment", staffTemporary.getOid());
            map2.put("jobNumber", staffTemporary.getStaffNum());


            map.put("employeeInformation", map1);
            map.put("employmentRecord", map2);
            JSONObject jsonObject = new JSONObject(map);
            JSONObject jsonobject = new JSONObject();
            jsonobject.put("param", JSON.toJSON(jsonObject));
            log.error("推送北森信息"+jsonobject);
            String token = beiSenUtils.getToken();
            try {
//                String s = "";
                String s = HttpClientUtil.doPostByBeiSen(url, jsonobject, token);
                log.error("北森返回信息："+s);
                ObjectMapper objectMapper = new ObjectMapper();
                Map<String, Object> beiMap = objectMapper.readValue(s, Map.class);
                if (beiMap.get("code").toString().equals("417")) {
                    BeisenUserList beisenUserList = new BeisenUserList();
                    BeanUtils.copyProperties(blackList, beisenUserList);
                    beisenUserList.setOriginalId(beisenUserList.getOriginalId());
                    beisenUserList.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                    beisenUserList.setInputDate(new Date());
                    beisenUserList.setFacesInformation(null);
//                genericResponse.setCodeAndMsg(ResponseCode.MSG,beiMap.get("message").toString());
                    str += beiMap.get("message").toString();
                    beisenUserListServicel.save(beisenUserList);
                }
                if (beiMap.get("code").toString().equals("200") || Objects.nonNull(blackList.getBeisenUserId())) {
                    if (Objects.isNull(blackList.getBeisenUserId())){
                        Map<String, Object> data = objectMapper.convertValue(beiMap.get("data"), Map.class);
                        blackList.setEmployeeInformationId(data.get("employeeInformationId").toString());
                        blackList.setEmploymentRecordId(data.get("employmentRecordId").toString());
                        blackList.setBeisenUserId((Integer) data.get("userId"));
                        System.out.println(data.get("userId"));
                    }

                }
                String loginAccount = SessionHelp.getLoginAccount(session);
                StaffResponse staffResponse = redisClient.get(Constant.staffKey + loginAccount);
                StaffTemporary temporary = new StaffTemporary();
                temporary.setId(staffTemporary.getId());
                temporary.setIsBeisen(2);
                temporary.setBeisenDimission(0);

                if (staffTemporary.getSendTime()==null){
                    temporary.setSendTime(new Date());
                }else
                {temporary.setSendTime(staffTemporary.getSendTime());}
//                    if (staffTemporary.getBeisenDimission()!=null){
//                        temporary.setBeisenDimissionDate(staffTemporary.getBeisenDimissionDate());
//                    }else temporary.setBeisenDimissionDate(new Date());
                temporary.setBeisenDimissionDate(null);
                temporary.setSendId(staffResponse.getId());
                temporary.setBeisenDeptId(staffTemporary.getBeisenDeptId());
                temporary.setBeisenDeptNum(staffTemporary.getBeisenDeptNum());
                temporary.setBeisenDeptName(staffTemporary.getBeisenDeptName());
                temporary.setSendName(staffResponse.getStaffName());
                blackList.setIsBeisen(1);
                blackListDao.updateByPrimaryKey(blackList);
                staffTemporaryService.updateNotNull(temporary);
            } catch (JsonMappingException e) {
                throw new RuntimeException(e);
            } catch (JsonParseException e) {
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        }
        if (str.length() > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.MSG, str);
        }
        return genericResponse;
    }

    /**
     * 分页查询
     *
     * @return
     */
    @PostMapping("/sendZhongkongDimission")
    @ApiOperation("获取考勤记录")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "pageNum", value = "页码", defaultValue = "1", required = true),
//            @ApiImplicitParam(name = "pageSize", value = "每页数量", defaultValue = "10", required = true)
//    })
//@RequiresPermissions("system:blackList:query")
    public PageResponse<JobContentListVo> sendZhongkong(@RequestBody List<StaffTemporaryVo> staffTemporaryList) {
        PageResponse<JobContentListVo> pageResponse = new PageResponse<>();
        pageResponse.setCodeAndMsg(ResponseCode.OK);
        String str = "";
        for (StaffTemporaryVo temporary : staffTemporaryList) {
            String url = "http://"+host+"/api/v2/employee/leave/?key="+key;
            Map<String, Object> map = new HashMap<>();
            map.put("pin",temporary.getStaffNum());
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            String value = format.format(temporary.getZhongkongDimissionDate());
            System.out.println(value);
            map.put("leavedate", value);
            map.put("leavetype", temporary.getLeavetype());
            map.put("reason", temporary.getReason());
            JSONObject jsonObject = new JSONObject(map);
            JSONObject jsonobject = new JSONObject();
            System.out.println(map);
            jsonobject.put("param", JSON.toJSON(jsonObject));
            String s = HttpClientUtil.doPost(url, jsonobject);
//            String s = "{\"ret\": \"0\"}";
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                Map readValue = objectMapper.readValue(s, Map.class);

                if (readValue.get("ret").toString().equals("0")){
                    temporary.setZhongkongDimission(1);
                    if (temporary.getZhongkongDimissionDate()==null) {
                        temporary.setZhongkongDimissionDate(new Date());
                    }
                    StaffTemporary temporary1 = new StaffTemporary();
                    BeanUtils.copyProperties(temporary,temporary1);
                    // 保存离职类型和离职原因
                    temporary1.setZhongkongDimissionType(temporary.getLeavetype());
                    temporary1.setZhongkongDimissionReason(temporary.getReason());

                    staffTemporaryService.updateNotNull(temporary1);
                }else {
                    String decodedString = StringEscapeUtils.unescapeJava(readValue.get("msg").toString());
                    str += "员工："+temporary.getStaffNum()+ decodedString+",";
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }


        }
        if (str.length()>0){
            pageResponse.setCodeAndMsg(ResponseCode.MSG,str);
        }
        return pageResponse;
    }

    /**
     * 分页查询
     *
     * @return
     */
    @PostMapping("/sendBeisenDimission")
    @ApiOperation("获取考勤记录")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "pageNum", value = "页码", defaultValue = "1", required = true),
//            @ApiImplicitParam(name = "pageSize", value = "每页数量", defaultValue = "10", required = true)
//    })
//@RequiresPermissions("system:blackList:query")
    public PageResponse<JobContentListVo> sendBeisenDimission(@RequestBody List<StaffTemporaryVo> staffTemporaryDtoList) throws IOException {
        PageResponse<JobContentListVo> pageResponse = new PageResponse<>();
        pageResponse.setCodeAndMsg(ResponseCode.OK);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String format1 = format.format(staffTemporaryDtoList.get(0).getBeisenDimissionDate());
        String str = "";
        List<Integer> ids = new ArrayList<>();
        List<StaffTemporaryVo>list = new ArrayList<>();
        for (StaffTemporaryVo temporary : staffTemporaryDtoList) {
            if (temporary.getBlackList().getBeisenUserId()==null){
                str += "员工："+temporary.getStaffName()+"未推送北森系统";
                continue;
            }
            String format2 = format.format(temporary.getSendTime()==null?new Date():temporary.getSendTime());
//            String format3 = format.format(new Date());
//            if (format3.equals(format2)){
//                str += "员工:"+temporary.getStaffName()+"属于当天入职，不允许当天离职";
//                continue;
//            }
            if (format1.equals(format2)) {
                str += "员工:"+temporary.getStaffName()+"属于当天入职，不允许当天离职";
                continue;
            }
            ids.add(temporary.getBlackList().getBeisenUserId());
            list.add(temporary);
        }

       if (!CollectionUtils.isEmpty(ids)) {
           Map<String, Object> map = new HashMap<>();
           map.put("userIds",ids);
           map.put("startDate", format1);
           String token = beiSenUtils.getToken();
           String url = "https://openapi.italent.cn/TenantBaseExternal/api/v5/Employee/BatchStopExternalEmpV5";
           JSONObject jsonObject = new JSONObject(map);
           JSONObject jsonObject1 = new JSONObject();
           jsonObject1.put("param", JSON.toJSON(jsonObject));
           String response = HttpClientUtil.doPostByBeiSen(url, jsonObject1, token);
           log.error("北森返回结果：" +response);
           ObjectMapper objectMapper = new ObjectMapper();
           Map<String, Object> beiMap = objectMapper.readValue(response, Map.class);
           if (beiMap.get("code").toString().equals("200") || beiMap.get("code").toString().equals("417")) {
//               log.error("已停用的："+list);
               for (StaffTemporaryVo temporary : list) {
                   StaffTemporary staffTemporary = new StaffTemporary();
                   BeanUtils.copyProperties(temporary, staffTemporary);
                   staffTemporary.setBeisenDimission(1);
                   if (staffTemporary.getBeisenDimissionDate()==null) {
                       staffTemporary.setBeisenDimissionDate(new Date());
                   }
                   staffTemporaryService.updateByBeisenDimissionDate(staffTemporary);
                   stringRedisClient.delete(Constant.ruzhiPhoneAndTime + temporary.getId());
               }
           }else {
               try {
                   str += beiMap.get("message").toString();
               }catch (Exception e){

               }
           }
       }
       if (str.length()>0){
           pageResponse.setCodeAndMsg(ResponseCode.MSG,str);
           return pageResponse;
       }
        return pageResponse;
    }

    /**
     * 分页查询
     *
     * @return
     */
    @PostMapping("/ruzhiZhongkongDimission")
    @ApiOperation("获取考勤记录")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "pageNum", value = "页码", defaultValue = "1", required = true),
//            @ApiImplicitParam(name = "pageSize", value = "每页数量", defaultValue = "10", required = true)
//    })
//@RequiresPermissions("system:blackList:query")
    public PageResponse<JobContentListVo> ruzhiZhongkongDimission(@RequestBody List< StaffTemporary> staffTemporaryList) {
        PageResponse<JobContentListVo> pageResponse = new PageResponse<>();
        pageResponse.setCodeAndMsg(ResponseCode.OK);
//        StaffResponse userInfo = LoginInterceptor.getCurrentUserInfo();
//        LoginInterceptor.clearThreadLocal();
        String str = "";
        String url = "http://"+host+"/api/v2/employee/restore/?key="+key;
        for (StaffTemporary temporary : staffTemporaryList) {
            Map<String, Object> map = new HashMap<>();
            List<String> stringList = new ArrayList<>();
            stringList.add(temporary.getStaffNum());
            map.put("userpin",stringList);
            JSONObject jsonObject = new JSONObject(map);
            JSONObject jsonobject = new JSONObject();
            jsonobject.put("param", JSON.toJSON(jsonObject));
            String s = HttpClientUtil.doPost(url, jsonobject);
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                Map readValue = objectMapper.readValue(s, Map.class);
                if (readValue.get("ret").toString().equals("0")){
                    temporary.setZhongkongDimission(0);
                    temporary.setZhongkongDimissionDate(new Date());
//                    temporary.setIsZhongkong(0);
//                    temporary.setSendZhongkongId(null);
//                    temporary.setSendZhongkongName(null);
//                    temporary.setSendZhongkongTime(null);
                    staffTemporaryService.updateByPrimaryKey(temporary);
                    stringRedisClient.delete(Constant.ruzhiPhoneAndTime + temporary.getId());
                }else {
                    String decodedString = StringEscapeUtils.unescapeJava(readValue.get("msg").toString());
                    str += decodedString;
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        }
        if (str.length()>0){
            pageResponse.setCodeAndMsg(ResponseCode.MSG,str);
        }
        return pageResponse;
    }

    /**
     * 分页查询
     *
     * @return
     */
    @PostMapping("/sendKaoqin")
    @ApiOperation("获取考勤记录")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "pageNum", value = "页码", defaultValue = "1", required = true),
//            @ApiImplicitParam(name = "pageSize", value = "每页数量", defaultValue = "10", required = true)
//    })
//@RequiresPermissions("system:blackList:query")
    public PageResponse<JobContentListVo> sendKaoqin(@RequestBody StaffTemporaryDto temporary) {
        PageResponse<JobContentListVo> pageResponse = new PageResponse<>();
        pageResponse.setCodeAndMsg(ResponseCode.OK);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String format1 = format.format(new Date());
        List<Integer> userids = new ArrayList<>();
        userids.add(temporary.getBeisenUserId());
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> map1 = new HashMap<>();
        List<Object> list = new ArrayList<>();
//        map1.put("PrimaryKey")
        map.put("Items", userids);
        map.put("startDate", format1);
        String token = beiSenUtils.getToken();
        String url = "https://openapi.italent.cn/AttendanceOpen/api/v1/SwipingCardData/PostAsync";
        JSONObject jsonObject = new JSONObject(map);
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("param", JSON.toJSON(jsonObject));

        String response = HttpClientUtil.doPostByBeiSen(url, jsonObject1, token);
        StaffTemporary staffTemporary = new StaffTemporary();
        BeanUtils.copyProperties(temporary, staffTemporary);
        staffTemporary.setBeisenDimission(1);
        staffTemporary.setBeisenDimissionDate(new Date());
        staffTemporaryService.updateNotNull(staffTemporary);
        return pageResponse;
    }

    /**
     * 分页查询
     *
     * @return
     */
    @PostMapping("/jobSendBeisen")
    @ApiOperation("获取考勤记录")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "pageNum", value = "页码", defaultValue = "1", required = true),
//            @ApiImplicitParam(name = "pageSize", value = "每页数量", defaultValue = "10", required = true)
//    })
//@RequiresPermissions("system:blackList:query")
    public PageResponse<JobContentListVo> jobSendBeisen(@RequestBody List<JobContentListVo> jobContentListVoList) throws IOException {
        PageResponse<JobContentListVo> pageResponse = new PageResponse<>();
        pageResponse.setCodeAndMsg(ResponseCode.OK);
        String str = "";
        Map<String, Object> map = new HashMap<>();
        List<Object> list = new ArrayList<>();
        List<Long> ids = new ArrayList<>();
        for (JobContentListVo jobContentListVo : jobContentListVoList) {
            if (jobContentListVo.getIsBeisen()!=null &&jobContentListVo.getIsBeisen()==1){
                continue;
            }
            if (Objects.isNull(jobContentListVo.getBlackList().getBeisenUserId())) {
                str += "员工：" + jobContentListVo.getStaffName() + "未推送北森，无法推送考勤记录";
                continue;

            }
            Map<String, Object> map1 = new HashMap<>();

            map1.put("PrimaryKey", jobContentListVo.getBlackList().getBeisenUserId());
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            map1.put("CardDateTime", format.format(jobContentListVo.getCheckTime()));
            String data = "验证方式：" + jobContentListVo.getVerify() + "，部门编码：" + jobContentListVo.getDeptNumber() +
                    "，部门名称：" + jobContentListVo.getDeptName() + "，设备编码：" + jobContentListVo.getEquipmentNum();
            map1.put("data", data);
            list.add(map1);
            ids.add(jobContentListVo.getId());
        }
        map.put("Items", list);
        map.put("DataSourceType", 14);
        map.put("PrimaryKeyType", 1);
        String token = beiSenUtils.getToken();
        String url = "https://openapi.italent.cn/AttendanceOpen/api/v1/SwipingCardData/PostAsync";
        JSONObject jsonObject = new JSONObject(map);
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("param", JSON.toJSON(jsonObject));
        System.out.println(jsonObject1.toString());
        String response = HttpClientUtil.doPostByBeiSen(url, jsonObject1, token);
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Object> beiMap = objectMapper.readValue(response, Map.class);
        System.out.println(beiMap.toString());
        if (beiMap.get("Code").toString().equals("200")) {
            for (JobContentListVo jobContentListVo : jobContentListVoList) {
                if (ids.contains(jobContentListVo.getId())) {
                    JobContentList jobContentList = new JobContentList();
                    BeanUtils.copyProperties(jobContentListVo, jobContentList);
                    jobContentList.setIsBeisen(1);
                    jobContentListDao.updateByPrimaryKey(jobContentList);
                }
            }
        }else {
           str += beiMap.get("Message").toString();

        }
        if (str.length()>0){
            pageResponse.setCodeAndMsg(ResponseCode.MSG, str);
        }
        return pageResponse;
    }


    /**
     * 根据主键删除
     *
     * @param staffTemporaryDto  主键
     * @return
     */
    @PostMapping("/deleteByList")
    @ApiOperation("根据主键删除")
//@RequiresPermissions("system:staffTemporary:delete")
    public GenericResponse delete(@RequestBody StaffTemporaryDto staffTemporaryDto) {
        GenericResponse genericResponse = new GenericResponse();
        genericResponse.setCodeAndMsg(ResponseCode.OK);
        String str = "";
        List<Long> ids = staffTemporaryDto.getIds();
        int i = 0;
        //todo 修改在这里（解决批量删除过慢）
        List<Long> delectBlacklist = new ArrayList<>();//需要删除黑白名单表的id
        List<Long> delectAbsenteeismlist = new ArrayList<>();//考勤表中需要删除的员工id staffTempId
        List<String> delectStaffTemporaryIdcard = new ArrayList<>();//记录表中需要删除的员工身份证号码
        List<Long> delectStaffTemporaryIdlist = new ArrayList<>();//记录表中的需要删除的临时工id

        for (Long id : ids) {
            StaffTemporary temporary = this.staffTemporaryService.selectByPrimaryKey(id);
            Example example = new Example(StaffTemporary.class);
            example.createCriteria().andEqualTo(BlackListDto.Fields.identityCard,temporary.getIdentityCard());
            example.selectProperties("id");
            List<StaffTemporary> staffTemporaryList = staffTemporaryService.selectByExample(example);
            if (!CollectionUtils.isEmpty(staffTemporaryList) && staffTemporaryList.size()==1){
                Example blackExample = new Example(BlackList.class);
                blackExample.createCriteria().andEqualTo(StaffTemporaryDto.Fields.identityCard,temporary.getIdentityCard());
                blackExample.selectProperties("id");
                List<BlackList> blackListList = blackListDao.selectByExample(blackExample);
                if (!CollectionUtils.isEmpty(blackListList)&& blackListList.size()==1){
                            delectBlacklist.add(blackListList.get(0).getId());
                }
            }
            //判断考勤表中是否有这条数据，有的话先删除
            delectAbsenteeismlist.add(id);
            //同步删除记录表中的记录(根据身份号删除)
            delectStaffTemporaryIdcard.add(temporary.getIdentityCard());
            //临时工表删除当前人
            delectStaffTemporaryIdlist.add(id);
        }
        //删除顺序(外键索引限制)
        // delectBlacklist -> delectAbsenteeismlist -> delectStaffTemporaryIdcard -> delectStaffTemporaryIdlist
        try {
            //删除黑白名单表
            //先判断列表中是否有数据再删
            if(!CollectionUtils.isEmpty(delectBlacklist)){
                blackListDao.delectByIds(delectBlacklist);
            }
            //判断考勤表中是否有这条数据，有的话先删除
            if(!CollectionUtils.isEmpty(delectAbsenteeismlist)){
                absenteeismRecordDao.deletByStaffId(delectAbsenteeismlist);
            }
            //同步删除记录表中的记录(根据身份号删除)
            if(!CollectionUtils.isEmpty(delectStaffTemporaryIdcard)){
                staffTemporaryUpdateMapper.delectByIdcards(delectStaffTemporaryIdcard);
            }
            //临时工表删除当前人
            if(!CollectionUtils.isEmpty(delectStaffTemporaryIdlist)){
                staffTemporaryMapper.delectByIdss(delectStaffTemporaryIdlist);
            }
        }catch (Exception e) {
                    log.error("SsmCollectionTypeController.add:", e);
                    genericResponse.setCodeAndMsg(ResponseCode.FAILED);
                    return genericResponse;
        }

//      被注释掉的原删除逻辑
//            for (Long id : ids) {
//                try {
//                    StaffTemporary temporary = this.staffTemporaryService.selectByPrimaryKey(id);
//                    Example example = new Example(StaffTemporary.class);
//                    example.createCriteria().andEqualTo(BlackListDto.Fields.identityCard,temporary.getIdentityCard());
//                    List<StaffTemporary> staffTemporaryList = staffTemporaryService.selectByExample(example);
//                    if (!CollectionUtils.isEmpty(staffTemporaryList) && staffTemporaryList.size()==1){
//                        Example blackExample = new Example(BlackList.class);
//                        blackExample.createCriteria().andEqualTo(StaffTemporaryDto.Fields.identityCard,temporary.getIdentityCard());
//                        List<BlackList> blackListList = blackListDao.selectByExample(blackExample);
//                        if (!CollectionUtils.isEmpty(blackListList)&& blackListList.size()==1){
//                            blackListDao.deleteByPrimaryKey(blackListList.get(0).getId());
////                            delectBlacklist.add(blackListList.get(0).getId());
//                        }
//                    }
//                    //判断考勤表中是否有这条数据，有的话先删除
//                    Example example1 = new Example(AbsenteeismRecord.class);
//                    example1.createCriteria().andEqualTo("staffTempId",id);
//                    absenteeismRecordMapper.deleteByExample(example1);
//                    //同步删除记录表中的记录(根据身份号删除)
//                    Example example2 = new Example(StaffTemporaryUpdate.class);
//                    example2.createCriteria().andEqualTo(BlackListDto.Fields.identityCard,temporary.getIdentityCard());
//                    staffTemporaryUpdateMapper.deleteByExample(example2);
//                    //临时工表删除当前人
//                    i = this.staffTemporaryService.deleteByPrimaryKey(id);
//
//
////                    if (!CollectionUtils.isEmpty(staffTemporaryList) && staffTemporaryList.size()==1){
////                        str = str+temporary.getStaffName()+",";
//////                        genericResponse.setCodeAndMsg(ResponseCode.MSG, temporary.getStaffName()+ "已录入临时工档案，请前往临时工档案删除！");
////                        continue;
////                    }
////            List<BlackList> blackListList = blackListDao.selectByExample(example);
////            if (!CollectionUtils.isEmpty(blackListList)){
////                genericResponse.setCodeAndMsg(ResponseCode.MSG,"已录入临时工档案，不允许删除，删除请前往临时工档案进行删除");
////                return genericResponse;
////            }
////                    i = this.staffTemporaryService.deleteByPrimaryKey(id);
//                } catch (Exception e) {
//                    log.error("SsmCollectionTypeController.add:", e);
//                    genericResponse.setCodeAndMsg(ResponseCode.FAILED);
//                    return genericResponse;
//                }
//            }
            if (StringUtils.isNotBlank(str)){
                genericResponse.setCodeAndMsg(ResponseCode.MSG, str+ "已录入临时工档案，请前往临时工档案删除！");
            }
        return genericResponse;
    }



    /**
     * 批量修改入职时间
     *
     * @param staffTemporaryVo
     * @return
     */
    @PutMapping("/updateByIds")
    @ApiOperation("编辑")
    @Transactional
//@RequiresPermissions("system:staffTemporary:edit")
    public GenericResponse<StaffTemporaryVo> updateByIds(@RequestBody StaffTemporaryVo staffTemporaryVo) {
        GenericResponse genericResponse = new GenericResponse();
        int i = 0;
        if (!CollectionUtils.isEmpty(staffTemporaryVo.getIds())) {
            try {
                staffTemporaryService.updateIsUpdateByIds(staffTemporaryVo.getRuzhiTime(),staffTemporaryVo.getType(),staffTemporaryVo.getIds());
                genericResponse.setCodeAndMsg(ResponseCode.OK);
            }catch (Exception e){
                genericResponse.setCodeAndMsg(ResponseCode.FAILED);
            }
        }
        return genericResponse;
    }

    /**
     * 编辑
     *
     * @return
     */
    @PutMapping("/sendBeiSenUpdateStatus")
    @ApiOperation("人员已推送北森，修改状态")
//@RequiresPermissions("system:staffTemporary:edit")
    public GenericResponse sendBeiSenUpdateStatus(@RequestBody List<StaffTemporaryDto> staffTemporaryDtoList, HttpSession session) {
        GenericResponse genericResponse = new GenericResponse();
        genericResponse.setCodeAndMsg(ResponseCode.OK);

        String str = "";
        for (StaffTemporaryDto staffTemporary : staffTemporaryDtoList) {
            BlackList blackList = new BlackList();
            blackList.setIdentityCard(staffTemporary.getIdentityCard());
            List<BlackList> blackListList = blackListDao.select(blackList);
            blackList = blackListList.get(0);
            String url = "https://openapi.italent.cn/TenantBaseExternal/api/v5/Employee/Create";
            Map<String, Object> map = new HashMap<>();
            Map<String, Object> map1 = new HashMap<>();
            Map<String, Object> map2 = new HashMap<>();
            map1.put("name", staffTemporary.getStaffName());
            map1.put("email", staffTemporary.getEmail());
            map1.put("originalId", blackList.getId().toString());
            map1.put("iDType", "1");
            map1.put("iDNumber", staffTemporary.getIdentityCard());
            map1.put("gender", staffTemporary.getSex());
            map1.put("mobilePhone", staffTemporary.getMobilePhone());

            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

            String dateFormart = format.format(staffTemporary.getSendTime()==null?new Date():staffTemporary.getSendTime());
            map2.put("entryDate", dateFormart);
            map2.put("probation", 0);
            map2.put("employType", 1);
            map2.put("oIdDepartment", staffTemporary.getOid());
            map2.put("jobNumber", staffTemporary.getStaffNum());


            map.put("employeeInformation", map1);
            map.put("employmentRecord", map2);
            JSONObject jsonObject = new JSONObject(map);
            JSONObject jsonobject = new JSONObject();
            jsonobject.put("param", JSON.toJSON(jsonObject));
            System.out.println(jsonobject);
            String token = beiSenUtils.getToken();
            try {
//                String s = "";
                String s = HttpClientUtil.doPostByBeiSen(url, jsonobject, token);
//                System.out.println(s);
                ObjectMapper objectMapper = new ObjectMapper();
                Map<String, Object> beiMap = objectMapper.readValue(s, Map.class);
                if (beiMap.get("code").toString().equals("417")) {
                    BeisenUserList beisenUserList = new BeisenUserList();
                    BeanUtils.copyProperties(blackList, beisenUserList);
                    beisenUserList.setOriginalId(beisenUserList.getOriginalId());
                    beisenUserList.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                    beisenUserList.setInputDate(new Date());
                    beisenUserList.setFacesInformation(null);
//                genericResponse.setCodeAndMsg(ResponseCode.MSG,beiMap.get("message").toString());
                    str += beiMap.get("message").toString();
                    beisenUserListServicel.save(beisenUserList);
                } else if (beiMap.get("code").toString().equals("200")) {
                    Map<String, Object> data = objectMapper.convertValue(beiMap.get("data"), Map.class);
                    blackList.setEmployeeInformationId(data.get("employeeInformationId").toString());
                    blackList.setEmploymentRecordId(data.get("employmentRecordId").toString());
                    blackList.setBeisenUserId((Integer) data.get("userId"));
                    System.out.println(data.get("userId"));
                    String loginAccount = SessionHelp.getLoginAccount(session);
                    StaffResponse staffResponse = redisClient.get(Constant.staffKey + loginAccount);
                    StaffTemporary temporary = new StaffTemporary();
                    temporary.setId(staffTemporary.getId());
                    temporary.setIsBeisen(2);
                    temporary.setBeisenDimission(0);

                    if (staffTemporary.getSendTime()==null){
                        temporary.setSendTime(new Date());
                    }else
                    {temporary.setSendTime(staffTemporary.getSendTime());}
//                    if (staffTemporary.getBeisenDimission()!=null){
//                        temporary.setBeisenDimissionDate(staffTemporary.getBeisenDimissionDate());
//                    }else temporary.setBeisenDimissionDate(new Date());
                    temporary.setBeisenDimissionDate(null);
                    temporary.setSendId(staffResponse.getId());
                    temporary.setBeisenDeptId(staffTemporary.getBeisenDeptId());
                    temporary.setBeisenDeptNum(staffTemporary.getBeisenDeptNum());
                    temporary.setBeisenDeptName(staffTemporary.getBeisenDeptName());
                    temporary.setSendName(staffResponse.getStaffName());

                    blackList.setIsBeisen(1);
                    blackListDao.updateByPrimaryKey(blackList);
                    this.staffTemporaryService.updateNotNull(temporary);
                }
            } catch (JsonMappingException e) {
                throw new RuntimeException(e);
            } catch (JsonParseException e) {
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        }
        if (str.length() > 0) {
            genericResponse.setCodeAndMsg(ResponseCode.MSG, str);
        }
        return genericResponse;
    }
}
