package com.mortals.xhx.busiz;


import cn.hutool.core.codec.Base64;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.annotation.UnAuth;
import com.mortals.framework.common.Rest;
import com.mortals.framework.model.Context;
import com.mortals.framework.service.ICacheService;
import com.mortals.framework.util.DateUtils;
import com.mortals.framework.utils.ServletUtils;
import com.mortals.xhx.base.system.idgenerator.service.IdgeneratorService;
import com.mortals.xhx.base.system.upload.service.UploadService;
import com.mortals.xhx.base.system.user.model.UserEntity;
import com.mortals.xhx.base.system.user.model.UserQuery;
import com.mortals.xhx.base.system.user.service.UserService;
import com.mortals.xhx.busiz.h5.rsp.ApiResp;
import com.mortals.xhx.common.code.ApiRespCodeEnum;
import com.mortals.xhx.common.code.YesNoEnum;
import com.mortals.xhx.module.attendance.model.AttendanceRecordHikEntity;
import com.mortals.xhx.module.attendance.model.AttendanceRecordHikQuery;
import com.mortals.xhx.module.attendance.service.AttendanceRecordHikService;
import com.mortals.xhx.module.dept.model.DeptEntity;
import com.mortals.xhx.module.dept.model.DeptQuery;
import com.mortals.xhx.module.dept.service.DeptService;
import com.mortals.xhx.module.hik.door.model.req.door.DoorEventReq;
import com.mortals.xhx.module.hik.door.model.rsp.door.DoorEventDataInfo;
import com.mortals.xhx.module.hik.door.service.IHikDoorService;
import com.mortals.xhx.module.hik.face.model.req.img.ImgReq;
import com.mortals.xhx.module.hik.face.service.IHikFaceService;
import com.mortals.xhx.module.perform.service.PerformPerposeStaffService;
import com.mortals.xhx.module.staff.model.StaffEntity;
import com.mortals.xhx.module.staff.model.StaffQuery;
import com.mortals.xhx.module.staff.service.StaffService;
import com.mortals.xhx.module.workman.model.WorkmanEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 设备
 *
 * @author: zxfei
 * @date: 2021/8/24 20:28
 */
@RestController
@Slf4j
@RequestMapping("/test")
public class TestController {

    @Autowired
    private IdgeneratorService idgeneratorService;

    @Autowired
    private ICacheService cacheService;
    @Autowired
    private StaffService staffService;
    @Autowired
    private UserService userService;
    @Autowired
    private IHikFaceService faceService;
    @Autowired
    private UploadService uploadService;
    @Autowired
    private DeptService deptService;

    @Autowired
    private PerformPerposeStaffService performPerposeStaffService;

    @Autowired
    private AttendanceRecordHikService recordHikService;

    @Autowired
    private IHikDoorService hikDoorService;

    /**
     * 同步指定日期的海康数据
     *
     * @param req
     * @return
     */
    @PostMapping("hik")
    public String register(@RequestBody TestReq req) {
        log.info("【测试消息】【请求体】-->  " + JSONObject.toJSONString(req));


        DoorEventReq doorEventReq = new DoorEventReq();
        List<Integer> eventTypes = new ArrayList<>();
        eventTypes.add(196885);
        eventTypes.add(196887);
        eventTypes.add(196893);
        eventTypes.add(196888);
        eventTypes.add(196889);
        eventTypes.add(196890);
        eventTypes.add(196891);
        doorEventReq.setEventTypes(eventTypes);

        doorEventReq.setStartTime(req.getCreateTimeStart());
        doorEventReq.setEndTime(req.getCreateTimeEnd());
        doorEventReq.setPageNo(1);
        doorEventReq.setPageSize(1);

        Rest<DoorEventDataInfo> doorEventsRest = hikDoorService.getDoorEvents(doorEventReq);
        log.info("doorEventsRest:{} msg:{}", doorEventsRest.getCode(), doorEventsRest.getMsg());
        if (doorEventsRest.getCode() == YesNoEnum.YES.getValue()) {
            //分页获取考勤数据
            Integer total = doorEventsRest.getData().getTotal();
            int pageCount = PageUtil.totalPage(total, 1000);
            for (int i = 1; i <= pageCount; i++) {
                doorEventReq.setPageNo(i);
                doorEventReq.setPageSize(1000);
                doorEventsRest = hikDoorService.getDoorEvents(doorEventReq);
                log.info("doorEventsRest:{} msg:{},page:{}", doorEventsRest.getCode(), doorEventsRest.getMsg(), doorEventReq.getPageNo());
                getDoorEvents(doorEventsRest);
            }
        }
        return "ok";
    }


    private void getDoorEvents(Rest<DoorEventDataInfo> doorEventsRest) {
        //同步当前考勤数据
        List<AttendanceRecordHikEntity> attRecords = doorEventsRest.getData().getList().stream().map(item -> {
            AttendanceRecordHikEntity recordHikEntity = new AttendanceRecordHikEntity();
            recordHikEntity.initAttrValue();
            StaffEntity staffCache = staffService.getExtCache(StrUtil.padPre(item.getJobNo(), 8, "0"));
            if (ObjectUtils.isEmpty(staffCache)) {
                log.info("staff is null !staffCode:{}", item.getJobNo());
                return null;
            }

            recordHikEntity.setStaffId(staffCache.getId());
            recordHikEntity.setStaffName(staffCache.getName());
            recordHikEntity.setWorkNum(staffCache.getWorkNum());
            recordHikEntity.setDeptId(staffCache.getDeptId());
            recordHikEntity.setDeptName(staffCache.getDeptName());
            recordHikEntity.setPositionId(staffCache.getPositionId());
            recordHikEntity.setPositionName(staffCache.getPositionName());

            recordHikEntity.setAttendanceDate(item.getEventTime());
            recordHikEntity.setAttendanceAddress(item.getDoorName());
            recordHikEntity.setEventSource("门禁点");
            recordHikEntity.setRemark(item.getEventId());
            recordHikEntity.setCreateTime(item.getEventTime());
            recordHikEntity.setCreateUserName("system");
            recordHikEntity.setCreateUserId(1L);
            return recordHikEntity;
        }).filter(f -> f != null).collect(Collectors.toList());

        log.info("attRecords size:{}", attRecords.size());

        if (!ObjectUtils.isEmpty(attRecords)) {
            for (AttendanceRecordHikEntity attRecord : attRecords) {

                //recordHikService.save(attRecord);

                try {
                    recordHikService.getDao().insert(attRecord);

                }catch (Exception e){
                    log.error("异常",e);
                }


            }
        }

/*
        List<String> eventIds = attRecords.parallelStream().filter(f -> !ObjectUtils.isEmpty(f) && !ObjectUtils.isEmpty(f.getRemark())).map(i -> i.getRemark()).collect(Collectors.toList());

        //查询当天考勤记录是否有重复的 有的 则不添加
        AttendanceRecordHikQuery recordHikQuery = new AttendanceRecordHikQuery();
        recordHikQuery.setAttendanceDateStart(DateUtil.format(DateUtil.beginOfDay(new Date()), "yyyy-MM-dd"));
        recordHikQuery.setAttendanceDateEnd(DateUtil.format(DateUtil.beginOfDay(new Date()), "yyyy-MM-dd"));
        recordHikQuery.setRemarkList(eventIds);
        Set<String> eventIdSet = recordHikService.find(recordHikQuery).parallelStream().map(i -> i.getRemark()).collect(Collectors.toSet());

        List<AttendanceRecordHikEntity> saveRecordList = attRecords.stream().filter(f -> !eventIdSet.contains(f.getRemark())).collect(Collectors.toList());
        if (!ObjectUtils.isEmpty(saveRecordList)) {
            recordHikService.save(saveRecordList);
        }
        log.info("saveRecordList size:{}", saveRecordList.size());*/
    }


    @GetMapping("updateDeptNum")
    @UnAuth
    public String updateDeptNum() {
        log.info("更新部门用户数量");
        Map<Long, Long> collect = staffService.find(new StaffQuery()).stream().collect(Collectors.groupingBy(x -> x.getDeptId(), Collectors.counting()));

        DeptEntity deptEntity1 = new DeptEntity();
        deptEntity1.setPersonNum(0);
        deptService.getDao().update(deptEntity1, new HashMap<>());

        collect.entrySet().stream().forEach(item -> {
            Long deptId = item.getKey();
            Long count = item.getValue();
            log.info("deptId:{},num:{}", deptId, count);
            DeptEntity deptEntity = deptService.get(deptId);
            if (!ObjectUtils.isEmpty(deptEntity)) {
                deptEntity.setPersonNum(count.intValue());
                deptService.update(deptEntity);
            }
        });


        for (Map.Entry<Long, Long> item : collect.entrySet()) {

            Long deptId = item.getKey();
            if (deptId == -1) continue;
            DeptEntity deptEntity = deptService.get(deptId);
            if (!ObjectUtils.isEmpty(deptEntity)) {
                //查询当前父节点的所有子部门
                DeptQuery deptQuery = new DeptQuery();
                deptQuery.setParentId(deptEntity.getParentId());

                int sum = deptService.find(new DeptQuery().parentId(deptEntity.getParentId())).stream().map(i -> i.getPersonNum()).reduce(0, Integer::sum);
                ;
                DeptEntity parentDept = deptService.get(deptEntity.getParentId());
                log.info("dept:{},sum:{}", parentDept.getDeptName(), sum);

                if (!ObjectUtils.isEmpty(parentDept)) {
                    log.info("parentDept:{},sum:{}", parentDept.getDeptName(), sum);
                    parentDept.setPersonNum(sum);
                    deptService.update(parentDept);
                    // updateDeptPersonNum(parentDept);
                }
            }


        }

/*
        //更新父部门的人数归集
        collect.entrySet().stream().forEach(item -> {
            Long deptId = item.getKey();
            DeptEntity deptEntity = deptService.get(deptId);

            if (!ObjectUtils.isEmpty(deptEntity) && !ObjectUtils.isEmpty(deptEntity.getParentId())) {
                int sum = deptService.find(new DeptQuery().parentId(deptEntity.getId())).stream().mapToInt(i -> i.getPersonNum()).sum();
                DeptEntity parentDept = deptService.get(deptEntity.getParentId());
                if (ObjectUtils.isEmpty(parentDept)) {
                    parentDept.setPersonNum(sum);
                    deptService.update(parentDept);
                    updateDeptPersonNum(parentDept);
                }
            }


            // updateDeptPersonNum(deptEntity);

        });*/
        return "ok";
    }


    public static void calculateParentValue(DeptEntity root) {
        if (root == null) {
            return;
        }

        // 递归处理叶子节点
        if (root.getChildren().isEmpty()) {
            return;
        }

        // 递归计算所有子节点的值之和
        int sum = 0;
        for (DeptEntity child : root.getChildren()) {
            calculateParentValue(child);
            sum += child.getPersonNum();
        }

        // 更新当前节点的值为所有子节点值之和
        root.setPersonNum(sum);
    }

    private void updateDeptPersonNum(DeptEntity deptEntity) {
        if (!ObjectUtils.isEmpty(deptEntity) && !ObjectUtils.isEmpty(deptEntity.getParentId())) {
            int sum = deptService.find(new DeptQuery().parentId(deptEntity.getId())).stream().mapToInt(i -> i.getPersonNum()).sum();
            DeptEntity parentDept = deptService.get(deptEntity.getParentId());
            if (ObjectUtils.isEmpty(parentDept)) {
                parentDept.setPersonNum(sum);
                deptService.update(parentDept);
                updateDeptPersonNum(parentDept);
            }
        }
    }

    //
    @GetMapping("updatePersons")
    @UnAuth
    public String updatePersons() {
        log.info("更新用户手机号码");

        cacheService.select(1);
        Map<String, String> map = cacheService.hgetAll("com:mortals:xhx:module:workman:model:WorkmanEntity");
        cacheService.select(14);
        Map<String, WorkmanEntity> userMap = new HashMap<>();

        map.entrySet().stream().forEach(item -> {
            String value = item.getValue();
            WorkmanEntity workmanEntity = JSONObject.parseObject(value, WorkmanEntity.class);
            userMap.put(workmanEntity.getName(), workmanEntity);
        });

        List<StaffEntity> staffEntities = staffService.find(new StaffQuery());
        ArrayList<StaffEntity> updateList = new ArrayList<>();

        for (StaffEntity staffEntity : staffEntities) {
            if (ObjectUtils.isEmpty(staffEntity.getPhoneNumber())) {
                WorkmanEntity workmanEntity = userMap.get(staffEntity.getName());
                if (!ObjectUtils.isEmpty(workmanEntity)) {
                    staffEntity.setPhoneNumber(workmanEntity.getMobile());
                    updateList.add(staffEntity);
                }
            }
        }
        if (!ObjectUtils.isEmpty(updateList)) {
            log.info("更新数量：" + updateList.size());
            for (StaffEntity staffEntity : updateList) {
                staffService.update(staffEntity);
                //更新绑定的系统用户手机号码
                UserQuery userQuery = new UserQuery();
                userQuery.setCustomerId(staffEntity.getId());
                UserEntity userEntity = userService.selectOne(userQuery);
                if (userEntity != null) {
                    Map<String, Object> condition = new HashMap<>(1);
                    condition.put("id", userEntity.getId());
                    Map<String, Object> data = new HashMap<>(1);
                    data.put("mobile", staffEntity.getPhoneNumber());
                    userService.getUserDao().update(data, condition);
                }
            }
        }

        return "更新数量：" + updateList.size();
    }


    @GetMapping("downPersonsPic")
    @UnAuth
    public String downPersonsPic() {
        List<StaffEntity> staffEntities = staffService.find(new StaffQuery());
        ArrayList<StaffEntity> updateList = new ArrayList<>();
        for (StaffEntity staffEntity : staffEntities) {
            if (!ObjectUtils.isEmpty(staffEntity.getPicUri())) {
                ImgReq imgReq = new ImgReq();
                imgReq.setUrl(staffEntity.getPicUri());
                imgReq.setServerIndexCode(staffEntity.getServerIndexCode());
                //Rest<String> rest = faceService.downloadPicture(imgReq);
                try {
                    InputStream in = faceService.callPostImgs(imgReq);
                    if (!ObjectUtils.isEmpty(in)) {
                        MultipartFile file = ServletUtils.getMultipartFile(in, "snap.jpg");
                        String filePath = uploadService.saveFileUpload(file, "file/fileupload/snap/" + DateUtil.today(), null);
                        staffEntity.setPhotoPath(filePath);
                        updateList.add(staffEntity);
                    }
                } catch (Exception e) {
                    log.error("下载出错");
                }
/*
                if (YesNoEnum.YES.getValue() == rest.getCode()) {
                    byte[] bytes = Base64.decode(rest.getData());
                    if (!org.springframework.util.ObjectUtils.isEmpty(bytes)) {
                        InputStream inputStream = new ByteArrayInputStream(bytes);
                        MultipartFile file = ServletUtils.getMultipartFile(inputStream, "snap.jpg");
                        String filePath = uploadService.saveFileUpload(file, "file/fileupload/snap/" + DateUtil.today(), null);
                        staffEntity.setPhotoPath(filePath);

                        updateList.add(staffEntity);
                    }
                } else {
                    log.info("download:{}", JSON.toJSONString(rest));
                }*/
            }
        }
        if (!ObjectUtils.isEmpty(updateList)) {
            staffService.update(updateList);
        }


        return "更新数量：" + updateList.size();
    }


    @GetMapping("downPersonPic")
    @UnAuth
    public String downPersonPic() {
        List<StaffEntity> staffEntities = staffService.find(new StaffQuery());
        StaffEntity staffEntity = staffEntities.get(0);
        if (!ObjectUtils.isEmpty(staffEntity.getPicUri())) {
            ImgReq imgReq = new ImgReq();
            imgReq.setUrl(staffEntity.getPicUri());
            imgReq.setServerIndexCode(staffEntity.getServerIndexCode());
            log.info("req:{}", JSON.toJSONString(imgReq));
            //Rest<String> rest = faceService.downloadPicture(imgReq);
            try {
                InputStream in = faceService.callPostImgs(imgReq);
                if (!ObjectUtils.isEmpty(in)) {
                    MultipartFile file = ServletUtils.getMultipartFile(in, "snap.jpg");
                    String filePath = uploadService.saveFileUpload(file, "file/fileupload/snap/" + DateUtil.today(), null);
                    staffEntity.setPhotoPath(filePath);
                    return filePath;
                } else {
                    return "InputStream is null";
                }
            } catch (Exception e) {
                log.error("下载出错");
            }
        }
        return "null";
    }


    /**
     * 生成模拟数据
     * mortals_xhx_perform_perpose_staff_stat
     *
     * @return
     */
    @GetMapping("randomStatPerposeStaffData")
    @UnAuth
    public Rest<Void> randomStatPerposeStaffData() {


        return Rest.ok();
    }


    public static void main(String[] args) {

    }


}
