package com.ssm.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ssm.core.utils.BeiSenUtils;
import com.ssm.core.utils.HttpClientUtil;
import com.ssm.core.utils.SnowflakeUtil;
import com.ssm.manage.dao.BlackListDao;
import com.ssm.manage.dao.JobContentListDao;
import com.ssm.manage.dao.StaffTemporaryDao;
import com.ssm.manage.dto.BlackListDto;
import com.ssm.manage.dto.JobContentListDto;
import com.ssm.manage.dto.StaffTemporaryDto;
import com.ssm.manage.entity.*;
import com.ssm.manage.extendEntity.CourseNegative;
import com.ssm.manage.extendEntity.RechargeNegative;
import com.ssm.manage.service.*;
import com.ssm.manage.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.io.IOException;
import java.math.BigDecimal;
import java.sql.SQLIntegrityConstraintViolationException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@EnableScheduling
@Component
@Slf4j
public class FukajinSchedule{

//    @Autowired
//    private SsmRechargeService ssmRechargeService;
//
//    @Autowired
//    private SsmAccountTradeRecordService ssmAccountTradeRecordService;
//
//    @Autowired
//    private SsmCourseService ssmCourseService;
//
//    @Autowired
//    private SsmCashService ssmCashService;


    @Autowired
    private SsmBaseStoreService ssmBaseStoreService;

    @Autowired
    private CourseMoneyService courseMoneyService;
    @Autowired
    private RechargeMoneyService rechargeMoneyService;

    @Autowired
    private SsmNegativeCardService ssmNegativeCardService;
    @Autowired
    private BlackListDao blackListDao;
    @Autowired
    private JobContentListDao jobContentListDao;
    @Autowired
    private StaffTemporaryDao staffTemporaryDao;
    @Autowired
    private BeiSenUtils beiSenUtils;



    /**
     * 生成前两个月的负卡金并插入到数据库当中
     *负卡金定时任务完成
     */
//    @Scheduled(cron = "0 0 0 1 * ?")
//    @Scheduled(cron = "0 0/1 * * * ?")
    @Transactional
    public void hello(){

        //求出前两个月的日期；
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.MONTH,calendar.get(Calendar.MONTH)-2);
//        calendar.set(Calendar.MONTH,calendar.get(Calendar.MONTH)-3);
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
        String lastTwoMonth = simpleDateFormat1.format(calendar.getTime());
        Date parse = null;
        try {
            parse = simpleDateFormat1.parse(lastTwoMonth);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        calendar.setTime(parse);
        calendar.set(Calendar.DAY_OF_MONTH,calendar.getActualMaximum(Calendar.DATE));
        String endTimeStr = simpleDateFormat1.format(calendar.getTime());
        calendar.set(Calendar.DAY_OF_MONTH,calendar.getActualMinimum(Calendar.DATE));
        String startTimeStr = simpleDateFormat1.format(calendar.getTime());
        startTimeStr = startTimeStr + " 00:00:00";
        endTimeStr = endTimeStr + " 23:59:59";

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date startTime = null;
        Date endTime = null;
        try {
            startTime = dateFormat.parse(startTimeStr);
            endTime = dateFormat.parse(endTimeStr);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        String start = simpleDateFormat1.format(startTime);

        log.error(startTime+"--"+endTime);
        //查询所有的门店
        List<BaseStore> baseStoreList = ssmBaseStoreService.select(null);
        //查询前三个月的结存
        calendar.set(Calendar.MONTH,calendar.get(Calendar.MONTH)-1);
        String rechargeDate = simpleDateFormat1.format(calendar.getTime());
        List<RechargeMoney> rechargeMoneyList = rechargeMoneyService.selectByDate(rechargeDate);
        List<CourseMoney> courseMoneyList = courseMoneyService.selectByDate(rechargeDate);
        List<RechargeMoney> rechargeInsert = new ArrayList<>();
        List<CourseMoney> courseInsert = new ArrayList<>();

        for (BaseStore baseStore : baseStoreList) {
            //获取前三个月的充值与疗程支出
            RechargeMoney rechargeMoney = getRechargeMoney(rechargeMoneyList,baseStore.getId());
            CourseMoney courseMoney = getCourseMoeny(courseMoneyList,baseStore.getId());

            //查询前两个月的充值支出收入
            RechargeNegative rechargeNegative = ssmNegativeCardService.rechargeDayStatisticByDate(baseStore.getId(), startTime, endTime);

            //查询前两个月的疗程支出收入
            CourseNegative courseNegative = ssmNegativeCardService.CourseDayStatisticByDate(baseStore.getId(), startTime, endTime);


            RechargeMoney rechargeMoenyInsert = getInsertRechargeMoney(rechargeMoney,rechargeNegative);
            rechargeMoenyInsert.setStoreId(baseStore.getId());
            rechargeMoenyInsert.setDate(startTime);
            rechargeMoenyInsert.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
            rechargeInsert.add(rechargeMoenyInsert);


            CourseMoney courseMoneyInsert = getInsertCourseMoney(courseMoney,courseNegative);
            courseMoneyInsert.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
            courseMoneyInsert.setDate(startTime);
            courseMoneyInsert.setStoreId(baseStore.getId());
            courseInsert.add(courseMoneyInsert);
        }
//        List<RechargeMoney> rechargeMoneyList1 = rechargeMoneyService.selectByDate(start);
////        List<CourseMoney> courseMoneyList1 = courseMoneyService.selectByDate(start);
//        if(rechargeMoneyList1!=null &&rechargeMoneyList1.size()>0){
//            return;
//        }
        //保存


        rechargeMoneyService.saveList(rechargeInsert);

//        List<RechargeMoney> select = rechargeMoneyService.selectAll();
        courseMoneyService.saveList(courseInsert);
//        List<CourseMoney> list = courseMoneyService.selectAll();
        log.info("负卡金定时任务完成");

    }
    @Value("${zhongkong.key}")
    private String key;
    @Value("${zhongkong.host}")
    private String host;

    /**
     * 每日中控临时工自动离职
     */
//    @Scheduled(cron = "0 0 3 * * ?")
    @Scheduled(cron = "0 30 2 * * ?")
//    @Scheduled(cron = "0 0/1 * * * ?")
//    @Transactional
    public void zhongkonglizhi() throws IOException, ParseException {
        //调中控 // 获取今天的日期
        LocalDate today = LocalDate.now();
        // 获取昨天的日期
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        LocalDate yesterday = today.minusDays(1);
        String time = yesterday.toString();
        String starttime = time+" 00:00:00";
        String endtime = time+" 23:59:59";
        Date startTime = format.parse(starttime);
        Date endTime = format.parse(endtime);
        Example staffExample = new Example(StaffTemporary.class);
        Example.Criteria staffExampleCriteria = staffExample.createCriteria();
        staffExampleCriteria.andEqualTo("type",0);
        staffExampleCriteria.andBetween("endTime", startTime, endTime);
        staffExampleCriteria.andNotEqualTo("zhongkongDimission",1);
        List<StaffTemporary> staffTemporaries = staffTemporaryDao.selectByExample(staffExample);
        log.error("需要中控离职的员工："+staffTemporaries.stream().map(StaffTemporary::getId).collect(Collectors.toList()));
        String lizhiStaffName = "";
        if (!CollectionUtils.isEmpty(staffTemporaries)){
            List<StaffTemporary> temporaryList = staffTemporaries.stream().filter(item -> item.getIsZhongkong() != 0)
                    .collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(temporaryList)) {
//                这里原本是取隔一天2点半离职的，现在直接取取当天离职，方便生成考勤异常统计。
                Date leaveDate = endTime;

                for (StaffTemporary staffTemporary : temporaryList) {
//                    Long storeId = 369234373443874816L;
                    String url = "http://" + host + "/api/v2/employee/leave/?key=" + key;
                    Map<String, Object> mapnew = new HashMap<>();
                    mapnew.put("pin", staffTemporary.getStaffNum());
                    // 重新设置离职时间
                    staffTemporary.setEndTime(leaveDate);
                    mapnew.put("leavedate", format2.format(leaveDate));

                    // 记录离职原因和离职类型
                    int leavetype = 2;
                    mapnew.put("leavetype", leavetype);
                    String reason = "系统自动离职";
                    mapnew.put("reason", reason);
                    staffTemporary.setZhongkongDimissionType(leavetype);
                    staffTemporary.setZhongkongDimissionReason(reason);

                    JSONObject jsonObject = new JSONObject(mapnew);
                    JSONObject jsonobject = new JSONObject();
                    jsonobject.put("param", JSON.toJSON(jsonObject));
                    String response = HttpClientUtil.doPost(url, jsonobject);
                    lizhiStaffName += staffTemporary.getStaffName() + ", ";
                    staffTemporary.setZhongkongDimission(1);
                    staffTemporary.setZhongkongDimissionDate(new Date());
                    staffTemporaryDao.updateByPrimaryKey(staffTemporary);
                }
            }
        }

        log.error("每日中控自动离职的员工："+lizhiStaffName);
    }


    /**
     * 每日北森临时工自动停用
     */
//    @Scheduled(cron = "0 0 3 * * ?")
    @Scheduled(cron = "0 30 2 * * ?")
//    @Scheduled(cron = "0 0/1 * * * ?")
//    @Transactional
    public void beisenlizhi() throws IOException, ParseException {
        //调中控 // 获取今天的日期
        LocalDate today = LocalDate.now();
        // 获取昨天的日期
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");
        LocalDate yesterday = today.minusDays(1);
        String time = yesterday.toString();
        String starttime = time+" 00:00:00";
        String endtime = time+" 23:59:59";
        Date startTime = format.parse(starttime);
        Date endTime = format.parse(endtime);
        Example staffExample = new Example(StaffTemporary.class);
        Example.Criteria staffExampleCriteria = staffExample.createCriteria();
        staffExampleCriteria.andEqualTo("type",0);
        staffExampleCriteria.andNotEqualTo(StaffTemporaryDto.Fields.beisenDimission,1);
        staffExampleCriteria.andBetween("endTime",startTime,endTime);
        List<StaffTemporary> staffTemporaries = staffTemporaryDao.selectByExample(staffExample);
        log.error("需要北森离职的员工："+staffTemporaries.stream().map(StaffTemporary::getId).collect(Collectors.toList()));
        String lizhiStaffName = "";
        if (!CollectionUtils.isEmpty(staffTemporaries)){
            List<String> idcardList = staffTemporaries.stream().filter(x->x.getIsBeisen()==2).map(item -> item.getIdentityCard()).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(idcardList)) {
                Example example = new Example(BlackList.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andIn(BlackListDto.Fields.identityCard, idcardList);
                List<BlackList> blackListList = blackListDao.selectByExample(example);
                List<Integer> beisenUserIdList = blackListList.stream().map(item -> item.getBeisenUserId()).collect(Collectors.toList());
                String accessToken = beiSenUtils.getToken();
                Map<String,Object> map = new HashMap<>();
                map.put("userIds",beisenUserIdList);
                map.put("startDate",format2.format(new Date()));
                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,accessToken);
                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")) {
                    for (StaffTemporary staffTemporary : staffTemporaries) {
                        lizhiStaffName += staffTemporary.getStaffName();
                        staffTemporary.setBeisenDimission(1);
                        staffTemporary.setBeisenDimissionDate(new Date());
                        staffTemporaryDao.updateByPrimaryKey(staffTemporary);
                    }
                }else {
                    try {
                        log.error("北森停用的外部人员失败原因："+beiMap.get("message").toString());
                    }catch (Exception e){

                    }
                }
            }
        }

        log.error("北森停用的外部人员："+lizhiStaffName);
    }

    /*@Value("${job.equipment.exclude.nums}")
    private String excludeEquipmentNumsStr;

    private String[] getClockInEquipmentNums() {
        String[] strings = excludeEquipmentNumsStr.split(",");
        for (int i = 0; i < strings.length; i++) {
            strings[i] = strings[i].trim();
        }
        return strings;
    }*/

    /**
     * 打卡机设备
     */
    private List<String> getClockInEquipmentNums() {
        List<String> snNum = new ArrayList<>();
        snNum.add("TBB5235000125");
        snNum.add("TBB5235000149");
        snNum.add("TBB5235000151");
        snNum.add("TBB5235000152");
        snNum.add("TBB5235000243");
        snNum.add("TBB5235000254");
        return snNum;
    }

    public Map<String, Object> requestContext(String starttime, String endtime) throws IOException {
        String url = "http://"+host+"/api/v2/transaction/get/?key="+key;
        JSONObject jsonObject = JSON.parseObject("{\"starttime\": "+"\""+starttime+"\""+
                ",\"endtime\": " +"\""+ endtime +"\""+
                " }");
        JSONObject jsonobject = new JSONObject();
        jsonobject.put("param",JSON.toJSON(jsonObject)) ;
        String response = HttpClientUtil.doPost(url, jsonobject);
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String,Object> map = objectMapper.readValue(response, Map.class);
        return map;
    }

    @Autowired
    private AbsenteeismRecordService absenteeismRecordService;

    /**
     * 每日定时获取考勤记录
     */
    @Scheduled(cron = "0 0 3 * * ?")
//    @Scheduled(cron = "0 0/1 * * * ?")
//    @Transactional
    public void getJobContextNew() throws IOException, ParseException {
        //调中控 // 获取今天的日期
//        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        LocalDate today = LocalDate.now();
        List<Long> jobIds = new ArrayList<>();
        // 获取昨天的日期
        LocalDate yesterday = today.minusDays(1);
        String time = yesterday.toString();
        String todaytime = today.toString();
        String starttime = time+" 03:00:00";
        String endtime = todaytime+" 03:00:00";
//        // 打印结果
//        log.error("今天的日期: " + starttime);
//        log.error("昨天的日期: " + endtime);
        Long storeId = 369234373443874816L;
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String,Object> map = requestContext(starttime, endtime);
        log.error("中控考勤记录"+map);

        List<String> equipmentNums = getClockInEquipmentNums();

        if (map.containsKey("ret")&&map.get("ret").toString().equals("0")){ // 请求成功
            //循环遍历map
            Map<String,Object> data = objectMapper.convertValue( map.get("data"), Map.class);
            List<Map<String,Object>> list = (List<Map<String,Object>>) data.get("items");
            for (Map<String, Object> jobMap : list) {
                Object sn = jobMap.get("sn");
                if (!equipmentNums.contains(sn)) {
//                    log.error("Exclude:{}", sn);
                    continue;   // 不在设备列表的, 直接排除
                }

                JobContentList jobContentList = new JobContentList();
                //查询员工信息
                Example example = new Example(BlackList.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo(BlackListDto.Fields.staffNum,jobMap.get("pin"));
                List<BlackList> blackLists = blackListDao.selectByExample(example);
                if (org.apache.commons.collections4.CollectionUtils.isEmpty(blackLists)){
                    continue;
                }
                BlackList blackList = blackLists.get(0);
                Example jobExampl = new Example(JobContentList.class);
                jobExampl.setOrderByClause("check_time desc");
                Date checkTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(jobMap.get("checktime").toString());

                jobContentList.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                jobContentList.setType(blackList.getType());
                jobContentList.setStaffName(blackList.getStaffName());
                jobContentList.setStaffNum(blackList.getStaffNum());
                jobContentList.setStaffId(blackList.getId());
                jobContentList.setDeptNumber(jobMap.get("deptnumber").toString());
                jobContentList.setDeptName(jobMap.get("deptname").toString());
                jobContentList.setCheckTime(checkTime);
                jobContentList.setEquipmentNum(jobMap.get("sn").toString());
                jobContentList.setEquipmentName(jobMap.get("alias").toString());
                if((Integer)jobMap.get("verify")==15)
                    jobContentList.setVerify("人脸");
                jobContentList.setSex(blackList.getSex());
                jobContentList.setMobilePhone(blackList.getMobilePhone());
                jobContentList.setIdentityCard(blackList.getIdentityCard());
                jobContentList.setStoreId(storeId);
                jobContentList.setCheckContent(jobMap.get("photograph")==null?"":jobMap.get("photograph").toString());
                jobContentList.setType(jobMap.get("stateno")==null?null:Integer.valueOf(jobMap.get("stateno").toString()));
//                jobContentList.setType(blackList.getType());
                jobContentList.setCheckContent(jobMap.get("state")==null?null:jobMap.get("state").toString());
                // 查询职员昨天到今天的数据(实际只有昨天)
                Example.Criteria jobExamplCriteria = jobExampl.createCriteria();
                jobExamplCriteria.andEqualTo(JobContentListDto.Fields.staffNum,jobMap.get("pin"));
                jobExamplCriteria.andIn(JobContentListDto.Fields.equipmentNum, equipmentNums);
                jobExamplCriteria.andBetween(JobContentListDto.Fields.checkTime, starttime, endtime);
                List<JobContentList> contentLists = jobContentListDao.selectByExample(jobExampl);
                if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(contentLists)) {
                    AtomicReference<Date> earliestTimeAtom = new AtomicReference<>(checkTime);
                    AtomicReference<Date> latestTimeAtom = new AtomicReference<>(checkTime);
                    AtomicReference<JobContentList> fullJcl = new AtomicReference<>(jobContentList);

                    // 查找最早和最晚时间
                    contentLists.forEach(jobCL -> {
                        Date ct = jobCL.getCheckTime();
                        Date checkEndTime = jobCL.getCheckEndTime();
                        Date earliestTime = earliestTimeAtom.get();
                        Date latestTime = latestTimeAtom.get();
                        if (earliestTime == null || earliestTime.after(ct)) {
                            earliestTimeAtom.set(ct);
                            fullJcl.set(jobCL);
                        }
                        if (checkEndTime != null) {
                            ct = checkEndTime;
                        }
                        if (latestTime == null || latestTime.before(ct)) {
                            latestTimeAtom.set(ct);
                        }
                    });

                    // 合并成一条,并移除其它冗余记录
                    JobContentList contentList = fullJcl.get();
                    boolean equals = jobContentList.equals(contentList);
                    if (!equals) {
                        contentLists.remove(contentList);
                    }

                    contentLists.forEach(jcl -> jobContentListDao.delete(jcl));

                    boolean contains = contentLists.contains(contentList);
                    contentList.setCheckTime(earliestTimeAtom.get());
                    contentList.setCheckEndTime(latestTimeAtom.get());
                    if (!equals || contains) {
                        jobContentListDao.updateByPrimaryKey(contentList);
                        continue;
                    }
                }

                jobIds.add(jobContentList.getId());
                try {
                    jobContentListDao.insert(jobContentList);
                }catch (Exception e){
                    if (e instanceof SQLIntegrityConstraintViolationException){
                        log.error("数据已存在,数据插入失败");
                    }
                }
            }
        } else { // 请求失败
            log.error("Request Error: {}", map);
        }
        log.error("每日考勤记录已录入系统"+jobIds);

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, -1);
        Date yesterdayTime = calendar.getTime();
        // 记录缺勤人员
        absenteeismRecordService.generateRecords(yesterdayTime);
    }

    /**
     * 每日定时获取考勤记录
     */
//    @Scheduled(cron = "0 0 3 * * ?")
//    @Scheduled(cron = "0 0/1 * * * ?")
//    @Transactional
    public void getJobContext() throws IOException, ParseException {
        //调中控 // 获取今天的日期
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        LocalDate today = LocalDate.now();
        List<Long> jobIds = new ArrayList<>();
        // 获取昨天的日期
        LocalDate yesterday = today.minusDays(1);
        String time = yesterday.toString();
        String todaytime = today.toString();
        String starttime = time+" 03:00:00";
        String endtime = todaytime+" 03:00:00";
//        // 打印结果
//        log.error("今天的日期: " + starttime);
//        log.error("昨天的日期: " + endtime);
        Long storeId = 369234373443874816L;
        String url = "http://"+host+"/api/v2/transaction/get/?key="+key;
        JSONObject jsonObject = JSON.parseObject("{\"starttime\": "+"\""+starttime+"\""+
                ",\"endtime\": " +"\""+ endtime +"\""+
                " }");
        JSONObject jsonobject = new JSONObject();
        jsonobject.put("param",JSON.toJSON(jsonObject)) ;
        String response = HttpClientUtil.doPost(url, jsonobject);
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String,Object> map = objectMapper.readValue(response, Map.class);
        log.error("中控考勤记录"+response);
        if (map.containsKey("ret")&&map.get("ret").toString().equals("0")){
            //循环遍历map
            Map<String,Object> data = objectMapper.convertValue( map.get("data"), Map.class);
            List<Map<String,Object>> list = (List<Map<String,Object>>) data.get("items");
            for (Map<String, Object> jobMap : list) {
                JobContentList jobContentList = new JobContentList();
                //查询员工信息
                Example example = new Example(BlackList.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo(BlackListDto.Fields.staffNum,jobMap.get("pin"));
                List<BlackList> blackLists = blackListDao.selectByExample(example);
                if (CollectionUtils.isEmpty(blackLists)){
                    continue;
                }
                BlackList blackList = blackLists.get(0);
                Example jobExampl = new Example(JobContentList.class);
                jobExampl.setOrderByClause("check_time desc");
                Example.Criteria jobExamplCriteria = jobExampl.createCriteria();
                jobExamplCriteria.andEqualTo(JobContentListDto.Fields.staffNum,jobMap.get("pin"));
                jobExamplCriteria.andBetween(JobContentListDto.Fields.checkTime,starttime,endtime);
                List<JobContentList> contentLists = jobContentListDao.selectByExample(jobExampl);
                if (!CollectionUtils.isEmpty(contentLists) && contentLists.size()==1){
                    JobContentList contentList = contentLists.get(0);
                    contentList.setCheckEndTime(format.parse(jobMap.get("checktime").toString()));
                    jobContentListDao.updateByPrimaryKey(contentList);
                    continue;
                }
                jobContentList.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                jobContentList.setStaffName(blackList.getStaffName());
                jobContentList.setStaffNum(blackList.getStaffNum());
                jobContentList.setStaffId(blackList.getId());
                jobContentList.setDeptNumber(jobMap.get("deptnumber").toString());
                jobContentList.setDeptName(jobMap.get("deptname").toString());
                jobContentList.setCheckTime(format.parse(jobMap.get("checktime").toString()));
                jobContentList.setEquipmentNum(jobMap.get("sn").toString());
                jobContentList.setEquipmentName(jobMap.get("alias").toString());
                if((Integer)jobMap.get("verify")==15)
                    jobContentList.setVerify("人脸");
                jobContentList.setSex(blackList.getSex());
                jobContentList.setMobilePhone(blackList.getMobilePhone());
                jobContentList.setIdentityCard(blackList.getIdentityCard());
                jobContentList.setStoreId(storeId);
                jobContentList.setCheckContent(jobMap.get("photograph")==null?"":jobMap.get("photograph").toString());
                jobContentList.setType(jobMap.get("stateno")==null?null:Integer.valueOf(jobMap.get("stateno").toString()));
                jobContentList.setCheckContent(jobMap.get("state")==null?null:jobMap.get("state").toString());
                jobIds.add(jobContentList.getId());
                try {
                    jobContentListDao.insert(jobContentList);
                }catch (Exception e){
                    if (e instanceof SQLIntegrityConstraintViolationException){
                        log.error("数据已存在,数据插入失败");
                    }
                }
            }
        } else {
            log.error("Request Error: {}", map);
        }
        log.error("每日考勤记录已录入系统"+jobIds);
    }

    /**
     * 自动推送北森
     */
    @Scheduled(cron = "0 0 4 * * ?")
//    @Scheduled(cron = "0 0/1 * * * ?")
//    @Transactional
    public void jobSendBeisen() throws IOException, ParseException {
        //调中控 // 获取今天的日期
        List<String> snNum = getClockInEquipmentNums();

        LocalDate today = LocalDate.now();
        // 获取昨天的日期
        LocalDate yesterday = today.minusDays(1);
        String time = yesterday.toString();
        String starttime = time+" 00:00:00";
        String endtime = time+" 23:59:59";
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String str = "";
        String resStr = "";
        Map<String, Object> map = new HashMap<>();
        List<Object> list = new ArrayList<>();
        Example example = new Example(JobContentList.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andBetween(JobContentListDto.Fields.checkTime,format.parse(starttime),format.parse(endtime));
        Example.Criteria exampleCriteria = example.createCriteria();
        exampleCriteria.orEqualTo("isBeisen",1);
        exampleCriteria.orIsNull("isBeisen");
        criteria.andIn(JobContentListDto.Fields.equipmentNum,snNum);
        example.and(exampleCriteria);
        List<JobContentList> jobContentListList = jobContentListDao.selectByExample(example);
        log.error("需要推送北森的考勤记录："+jobContentListList.stream().map(JobContentList::getId).collect(Collectors.toList()));
        List<Long> ids = new ArrayList<>();
        for (JobContentList jobContentListVo : jobContentListList) {
            if (jobContentListVo.getStaffId()==null){
                continue;
            }
            BlackList blackList = blackListDao.selectByPrimaryKey(jobContentListVo.getStaffId());
            if (Objects.isNull(blackList.getBeisenUserId())) {
                str += "员工：" + jobContentListVo.getStaffName() + "未推送北森，无法推送考勤记录";
                continue;
            }
            Map<String, Object> map1 = new HashMap<>();
            map1.put("PrimaryKey", blackList.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());
        }
        log.error("确认需要推送北森的考勤记录："+ids);
        if (!CollectionUtils.isEmpty(list)) {
            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));
            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")) {
                for (JobContentList jobContentList : jobContentListList) {
                    if (ids.contains(jobContentList.getId())) {
                        jobContentList.setIsBeisen(1);
                        resStr += jobContentList.getId().toString() + ",";
                        jobContentListDao.updateByPrimaryKey(jobContentList);
                    }
                }
            }
            else {
                log.error("失败原因"+beiMap.get("Message").toString());

            }
        }
        log.error("每日考勤记录已录入系统，推送的有："+resStr);
    }





    /**
     * 获取前两个月的充值负卡金
     * @param recharge
     * @param negative
     * @return
     */

    private RechargeMoney getInsertRechargeMoney(RechargeMoney recharge,RechargeNegative negative){
        RechargeMoney rechargeMoney = new RechargeMoney();
        BeanUtils.copyProperties(negative,rechargeMoney);
        rechargeMoney.setOpenning(recharge.getBalance());
        rechargeMoney.setOpenningGift(recharge.getBalanceGift());
        //收入
        BigDecimal shouru = rechargeMoney.getRechargeMoney().add(rechargeMoney.getRechargeRepay())
//                .add(rechargeMoney.getRechargeGifMoney())
//                .add(rechargeMoney.getRepayRechargeGifMoney())
//                .add(rechargeMoney.getTurnInStoreGifMoney())
                .add(rechargeMoney.getCourseTurnRecharge())
                .add(rechargeMoney.getCashRefund())
//                .add(rechargeMoney.getRefundCashGifMoney())
                .add(rechargeMoney.getGroupPurchase()).add(rechargeMoney.getInit())
                .add(rechargeMoney.getZengka());
        //赠送收入
        BigDecimal shouruGif = rechargeMoney.getRechargeGifMoney().add(rechargeMoney.getRepayRechargeGifMoney())
                .add(rechargeMoney.getTurnInStoreGifMoney()).add(rechargeMoney.getRefundCashGifMoney()).add(rechargeMoney.getZengka());


        //支出
        BigDecimal zhichu = rechargeMoney.getCourseMoney().add(rechargeMoney.getRechargeRepayMoney())
                .add(rechargeMoney.getCashMoney()).add(rechargeMoney.getCoursePromotion())
                .add(rechargeMoney.getRechargeRefundMoney()).add(rechargeMoney.getCashRechargeGifMoney())
                .add(rechargeMoney.getRefundGifMoney()).add(rechargeMoney.getTurnOutStoreGifMoney());

        //赠送支出
        BigDecimal zhichuGif = rechargeMoney.getCashRechargeGifMoney().add(rechargeMoney.getRefundGifMoney()).add(rechargeMoney.getTurnOutStoreGifMoney());


        //结存
        BigDecimal balance = rechargeMoney.getOpenning().add(shouru).subtract(zhichu);
        BigDecimal balanceGif = rechargeMoney.getOpenningGift().add(shouruGif).subtract(zhichuGif);
        rechargeMoney.setBalance(balance);
        rechargeMoney.setBalanceGift(balanceGif);
        return rechargeMoney;
    }

    /**
     * 获取前两个的疗程负卡金
     * @param course
     * @param negative
     * @return
     */
    private CourseMoney getInsertCourseMoney(CourseMoney course,CourseNegative negative){
        CourseMoney courseMoney = new CourseMoney();
        BeanUtils.copyProperties(negative,courseMoney);
        courseMoney.setOpenning(course.getBalance());
        //支出
        BigDecimal zhichu = courseMoney.getCourseRepayMoney().add(courseMoney.getCourseRepayMoney()).add(courseMoney.getCashMoney())
                .add(courseMoney.getCourseRefundMoney()).add(courseMoney.getCourseTurnCharge()).add(courseMoney.getCourseTurnStoreMoney());
        //收入
        BigDecimal shouru =  courseMoney.getCourseMoney().add(courseMoney.getCourseRepay()).add(courseMoney.getCashRefund())
                .add(courseMoney.getCoursePromotion()).add(courseMoney.getInit()).add(courseMoney.getCourseTurnStore()).add(courseMoney.getCardChange())
                .add(courseMoney.getCoursePromotionRepay());
        //结存
        if(courseMoney.getStoreId()==369276122053947392L){
            log.error(".............");
        }
        BigDecimal balance = courseMoney.getOpenning().add(shouru).subtract(zhichu);
        courseMoney.setBalance(balance);
        return courseMoney;
    }

    /**
     * 获取前三个月的疗程负卡金
     * @param courseMoneyList
     * @param storeId
     * @return
     */
    private CourseMoney getCourseMoeny(List<CourseMoney> courseMoneyList,Long storeId){
        if(courseMoneyList!=null&&courseMoneyList.size()>0){
            for (CourseMoney courseMoney : courseMoneyList) {
                if(courseMoney.getStoreId()==storeId||courseMoney.getStoreId().toString().equals(storeId.toString())){
                    return courseMoney;
                }
            }
        }
        CourseMoney courseMoney = new CourseMoney();
        courseMoney.setOpenning(BigDecimal.ZERO);
        courseMoney.setCourseMoney(BigDecimal.ZERO);
        courseMoney.setCourseRepay(BigDecimal.ZERO);
        courseMoney.setCashRefund(BigDecimal.ZERO);
        courseMoney.setCoursePromotion(BigDecimal.ZERO);
        courseMoney.setInit(BigDecimal.ZERO);
        courseMoney.setCourseTurnStore(BigDecimal.ZERO);
        courseMoney.setCardChange(BigDecimal.ZERO);
        courseMoney.setCashMoney(BigDecimal.ZERO);
        courseMoney.setCourseRefundMoney(BigDecimal.ZERO);
        courseMoney.setCourseTurnCharge(BigDecimal.ZERO);
        courseMoney.setCourseTurnStoreMoney(BigDecimal.ZERO);
        courseMoney.setCourseRepayMoney(BigDecimal.ZERO);
        courseMoney.setBalance(BigDecimal.ZERO);
        return courseMoney;
    }

    /**
     * 获取前三个月的充值负卡金
     * @param rechargeMoneyList
     * @param storeId
     * @return
     */
    private RechargeMoney getRechargeMoney(List<RechargeMoney> rechargeMoneyList,Long storeId){
            if(rechargeMoneyList!=null && rechargeMoneyList.size()>0){
                for (RechargeMoney money : rechargeMoneyList) {
                    if(money.getStoreId()==storeId || money.getStoreId().toString().equals(storeId.toString())){
                        return money;
                    }
                }
            }
            RechargeMoney rechargeMoney = new RechargeMoney();
            rechargeMoney.setCashMoney(BigDecimal.ZERO);
            rechargeMoney.setCashRechargeGifMoney(BigDecimal.ZERO);
            rechargeMoney.setCashRefund(BigDecimal.ZERO);
            rechargeMoney.setRefundCashGifMoney(BigDecimal.ZERO);
            rechargeMoney.setCourseMoney(BigDecimal.ZERO);
            rechargeMoney.setCoursePromotion(BigDecimal.ZERO);
            rechargeMoney.setCourseTurnRecharge(BigDecimal.ZERO);
            rechargeMoney.setGroupPurchase(BigDecimal.ZERO);
            rechargeMoney.setInit(BigDecimal.ZERO);
            rechargeMoney.setRechargeMoney(BigDecimal.ZERO);
            rechargeMoney.setRechargeGifMoney(BigDecimal.ZERO);
            rechargeMoney.setRechargeRefundMoney(BigDecimal.ZERO);
            rechargeMoney.setRefundGifMoney(BigDecimal.ZERO);
            rechargeMoney.setRechargeRepay(BigDecimal.ZERO);
            rechargeMoney.setRepayRechargeGifMoney(BigDecimal.ZERO);
            rechargeMoney.setTurnInStoreGifMoney(BigDecimal.ZERO);
            rechargeMoney.setTurnOutStoreGifMoney(BigDecimal.ZERO);
            rechargeMoney.setOpenning(BigDecimal.ZERO);
            rechargeMoney.setOpenningGift(BigDecimal.ZERO);
            rechargeMoney.setBalance(BigDecimal.ZERO);
            rechargeMoney.setBalanceGift(BigDecimal.ZERO);
            rechargeMoney.setRechargeRepayMoney(BigDecimal.ZERO);
            return rechargeMoney;
    }
}
