package com.mortals.xhx.daemon.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.service.ITask;
import com.mortals.framework.service.ITaskExcuteService;
import com.mortals.xhx.busiz.rsp.DeptHikData;
import com.mortals.xhx.busiz.rsp.ListDept;
import com.mortals.xhx.busiz.rsp.ListItem;
import com.mortals.xhx.busiz.rsp.PersonHikData;
import com.mortals.xhx.module.attendance.dao.ibatis.*;
import com.mortals.xhx.module.attendance.model.AttendanceStatEntity;
import com.mortals.xhx.module.attendance.model.AttendanceVacationBalanceEntity;
import com.mortals.xhx.module.dept.dao.ibatis.DeptDaoImpl;
import com.mortals.xhx.module.dept.model.DeptEntity;
import com.mortals.xhx.module.dept.service.DeptService;
import com.mortals.xhx.module.hik.person.model.req.org.OrgListReq;
import com.mortals.xhx.module.hik.person.model.req.person.PersonReq;
import com.mortals.xhx.module.hik.person.service.IHikPersonService;
import com.mortals.xhx.module.staff.dao.ibatis.StaffDaoImpl;
import com.mortals.xhx.module.staff.model.StaffEntity;
import com.mortals.xhx.module.staff.service.StaffService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Objects;

/**
 * 同步用户
 */
@Slf4j
@Service("SyncUserTask")
public class SyncUserTaskImpl implements ITaskExcuteService {


    @Autowired
    private StaffDaoImpl staffDao;

    @Autowired
    private DeptDaoImpl deptDao;

    @Autowired
    private DeptService deptService;

    @Autowired
    private StaffService service;

    @Autowired
    private AttendanceStatDaoImpl attendanceStatDao;

    @Autowired
    private AttendanceVacationBalanceDaoImpl balanceDao;
    @Autowired
    private IHikPersonService hikPersonService;

    @Override
    public void excuteTask(ITask task) throws AppException {
        log.info("同步用户--部门");
        try {
            //部门同步
            //String resultDept = ArtemisPostTest.callPostApiGetDeptList();
            OrgListReq orgListReq = new OrgListReq();
            orgListReq.setPageNo(1);
            orgListReq.setPageSize(1000);
            String resultDept = hikPersonService.getOrgListTrans(orgListReq);

            JSONObject jsonObjectDept = JSON.parseObject(resultDept);
            JSONObject jsonObjectDept1 = jsonObjectDept.getJSONObject("data");
            DeptHikData deptHikData = JSONObject.parseObject(jsonObjectDept1.toJSONString(), DeptHikData.class);
            if (Objects.nonNull(deptHikData)) {
                for (ListDept listDept : deptHikData.getList()) {
                    //查询数据库信息
                    DeptEntity deptEntity = deptDao.queryDept(listDept.getOrgIndexCode());
                    DeptEntity deptEntityParent = deptDao.queryDeptParient(listDept.getParentOrgIndexCode());
                    //新增
                    if (Objects.isNull(deptEntity)) {
                        DeptEntity deptEntity1 = new DeptEntity();
                        deptEntity1.initAttrValue();
                        if (Objects.nonNull(deptEntityParent)) {
                            deptEntity1.setParentId(deptEntityParent.getId());
                        }
                        deptEntity1.setDeptName(listDept.getOrgName());
                        deptEntity1.setDeptCode(listDept.getOrgIndexCode());
                        deptEntity1.setAncestors(listDept.getOrgPath());
                        deptEntity1.setOrderNum(0);
                        deptEntity1.setRemark(listDept.getParentOrgIndexCode());
                        deptEntity1.setCreateTime(new Date());
                        deptEntity1.setCreateUserId(Long.valueOf(1));
                        deptEntity1.setUpdateTime(new Date());
                        deptEntity1.setUpdateUserId(Long.valueOf(1));
                        deptService.save(deptEntity1);
                    } else {
                        //更新
                        deptEntity.initAttrValue();
                        if (Objects.nonNull(deptEntityParent)) {
                            deptEntity.setParentId(deptEntityParent.getId());
                        }
                        deptEntity.setDeptName(listDept.getOrgName());
                        deptEntity.setDeptCode(listDept.getOrgIndexCode());
                        deptEntity.setAncestors(listDept.getOrgPath());
                        deptEntity.setCreateTime(new Date());
                        deptEntity.setPersonNum(0);
                        deptEntity.setCreateUserId(Long.valueOf(1));
                        deptService.update(deptEntity);
                    }
                }
            }
            //同步员工
            //String resultPerson = ArtemisPostTest.callPostApiGetPersonList();
            PersonReq personReq = new PersonReq();
            personReq.setPageNo(1);
            personReq.setPageSize(1000);
            String resultPerson = hikPersonService.getPersonListTrans(personReq);

            JSONObject jsonObject = JSON.parseObject(resultPerson);
            JSONObject jsonObject1 = jsonObject.getJSONObject("data");
            PersonHikData personHikData = JSONObject.parseObject(jsonObject1.toJSONString(), PersonHikData.class);
            if (Objects.nonNull(personHikData)) {
                for (ListItem list : personHikData.getList()) {
                    //根据id获取本地数据
                    StaffEntity staffEntity1 = staffDao.queryHik(list.getPersonId());
                    DeptEntity deptEntity = deptDao.queryDept(list.getOrgIndexCode());
                    AttendanceVacationBalanceEntity balanceEntity = balanceDao.queryEntity(staffEntity1.getId());
                    AttendanceStatEntity statEntity = attendanceStatDao.queryEntity(staffEntity1.getId());
                    //同步人员的考勤汇总信息
//                    //通过员工id获取考勤数据
//                    AttendanceRecordEntity attendanceRecordEntity = attendanceRecordDao.get(staffEntity1.getId());
//                    //通过考勤id统计上班迟到次数
////                    int goWorkCountDele = attendanceRecordDetailDao.goWorkCount(attendanceRecordEntity.getId());
////                    //员工id获取异常打卡所有记录
////                    int errorAttendaceCount = attendanceRecordErrorDao.errorAttendance(attendanceRecordEntity.getId());
                    //判断本地数据是否为空
                    if (Objects.isNull(staffEntity1)) {
                        //新增员工信息
                        StaffEntity staffEntity = new StaffEntity();
                        staffEntity.initAttrValue();
                        if (Objects.nonNull(staffEntity1)) {
                            staffEntity.setDeptId(deptEntity.getId());
                        }
                        staffEntity.setName(list.getPersonName());
                        staffEntity.setRemarkId(list.getPersonId());
                        staffEntity.setPicUri(list.getPersonPhoto().getPicUri());
                        staffEntity.setServerIndexCode(list.getPersonPhoto().getServerIndexCode());
                        staffEntity.setDeptName(list.getOrgName());
                        staffEntity.setSource(1);
                        staffEntity.setStatus(1);
                        staffEntity.setGender(list.getGender());
                        staffEntity.setWorkNum(list.getJobNo());
                        staffEntity.setCreateUserId(Long.valueOf(1));
                        staffEntity.setCreateTime(new Date());
                        if (list.getBirthday() != null) {
                            staffEntity.setBirthday((Date) list.getBirthday());
                        }
                        if (list.getPhoneNo() != null) {
                            staffEntity.setPhoneNumber(String.valueOf(list.getPhoneNo()));
                        }
                        service.save(staffEntity);

                        AttendanceStatEntity attendanceStatEntity = new AttendanceStatEntity();
                        attendanceStatEntity.initAttrValue();
                        attendanceStatEntity.setStaffId(staffEntity.getId());
                        attendanceStatEntity.setStaffName(staffEntity.getName());
                        attendanceStatEntity.setDeptId(staffEntity.getDeptId());
                        attendanceStatEntity.setDeptName(staffEntity.getDeptName());
                        attendanceStatEntity.setCreateTime(new Date());
                        attendanceStatEntity.setCreateUserId(Long.valueOf(1));
                        //21假
                        attendanceStatEntity.setBackToUnit(balanceEntity.getBackToUnit());
                        attendanceStatEntity.setOnDutyLeave(balanceEntity.getOnDutyLeave());
                        attendanceStatEntity.setOutOfOffice(balanceEntity.getOutOfOffice());
                        attendanceStatEntity.setShiftCompensation(balanceEntity.getShiftCompensation());
                        attendanceStatEntity.setPhysicalExamination(balanceEntity.getPhysicalExamination());
                        attendanceStatEntity.setQuarantine(balanceEntity.getQuarantine());
                        attendanceStatEntity.setBusinessTrip(balanceEntity.getBusinessTrip());
                        attendanceStatEntity.setPublicHoliday(balanceEntity.getPublicHoliday());
                        attendanceStatEntity.setSickLeave(balanceEntity.getSickLeaveDays());
                        attendanceStatEntity.setFuneralLeave(balanceEntity.getBereavementLeaveDays());
                        attendanceStatEntity.setMarriageLeave(balanceEntity.getMarriageLeaveDays());
                        attendanceStatEntity.setChildRearingLeave(balanceEntity.getChildRearingLeave());
                        attendanceStatEntity.setBreastfeedingLeaveDays(balanceEntity.getBreastfeedingLeaveDays());
                        attendanceStatEntity.setMenstrualLeaveDays(balanceEntity.getMenstrualLeaveDays());
                        attendanceStatEntity.setAnnualLeaveDays(balanceEntity.getAnnualLeaveDays());
                        attendanceStatEntity.setCompensatedLeaveDays(balanceEntity.getCompensatedLeaveDays());
                        attendanceStatEntity.setPaternityLeaveDays(balanceEntity.getPaternityLeaveDays());
                        attendanceStatEntity.setMaternityLeave(balanceEntity.getMaternityLeaveDays());
                        attendanceStatEntity.setTransferBack(balanceEntity.getTransferBack());
                        attendanceStatEntity.setHomeLeave(balanceEntity.getHomeLeave());
                        attendanceStatEntity.setPersonalLeave(balanceEntity.getPersonalLeaveDays());
//                        attendanceStatEntity.setLateTimes(goWorkCountDele);
//                        attendanceStatEntity.setNonCompliancePunch(BigDecimal.valueOf(errorAttendaceCount));
                        attendanceStatDao.insert(attendanceStatEntity);


                        AttendanceVacationBalanceEntity attendanceVacationBalanceEntity = new AttendanceVacationBalanceEntity();
                        attendanceVacationBalanceEntity.initAttrValue();
                        attendanceVacationBalanceEntity.setStaffId(staffEntity.getId());
                        attendanceVacationBalanceEntity.setStaffName(staffEntity.getName());
                        attendanceVacationBalanceEntity.setDeptId(deptEntity.getId());
                        attendanceVacationBalanceEntity.setDeptName(deptEntity.getDeptName());
                        balanceDao.insert(attendanceVacationBalanceEntity);
                        //统计各级部门员工数量
                        String ancestor = deptEntity.getAncestors().split(",", 2)[1];
                        String[] ancestors = ancestor.split(",");
                        for (String newAncestor : ancestors) {
                            DeptEntity deptEntity2 = deptService.get(Long.valueOf(newAncestor));
                            if (Objects.nonNull(deptEntity2)) {
                                deptEntity2.setPersonNum(deptEntity2.getPersonNum() + 1);
                                deptService.update(deptEntity2);
                            }
                        }

                    }
                    //本地数据不为空
                    else {
                        //更新员工信息
                        staffEntity1.initAttrValue();
                        if (Objects.nonNull(deptEntity)) {
                            staffEntity1.setDeptId(deptEntity.getId());
                        }
                        staffEntity1.setName(list.getPersonName());
                        staffEntity1.setRemarkId(list.getPersonId());
                        staffEntity1.setPicUri(list.getPersonPhoto().getPicUri());
                        staffEntity1.setServerIndexCode(list.getPersonPhoto().getServerIndexCode());
                        staffEntity1.setDeptName(list.getOrgName());
                        staffEntity1.setGender(list.getGender());
                        staffEntity1.setWorkNum(list.getJobNo());
                        staffEntity1.setCreateUserId(Long.valueOf(1));
                        staffEntity1.setCreateTime(new Date());
                        if (list.getBirthday() != null) {
                            staffEntity1.setBirthday((Date) list.getBirthday());
                        }
                        if (list.getPhoneNo() != null) {
                            staffEntity1.setPhoneNumber(String.valueOf(list.getPhoneNo()));
                        }
                        service.update(staffEntity1);
                        if (Objects.nonNull(statEntity)) {
                            statEntity.initAttrValue();
                            statEntity.setStaffId(staffEntity1.getId());
                            statEntity.setStaffName(staffEntity1.getName());
                            statEntity.setDeptId(staffEntity1.getDeptId());
                            statEntity.setDeptName(staffEntity1.getDeptName());
                            //21假
                            statEntity.setBackToUnit(balanceEntity.getBackToUnit());
                            statEntity.setOnDutyLeave(balanceEntity.getOnDutyLeave());
                            statEntity.setOutOfOffice(balanceEntity.getOutOfOffice());
                            statEntity.setShiftCompensation(balanceEntity.getShiftCompensation());
                            statEntity.setPhysicalExamination(balanceEntity.getPhysicalExamination());
                            statEntity.setQuarantine(balanceEntity.getQuarantine());
                            statEntity.setBusinessTrip(balanceEntity.getBusinessTrip());
                            statEntity.setPublicHoliday(balanceEntity.getPublicHoliday());
                            statEntity.setSickLeave(balanceEntity.getSickLeaveDays());
                            statEntity.setFuneralLeave(balanceEntity.getBereavementLeaveDays());
                            statEntity.setMarriageLeave(balanceEntity.getMarriageLeaveDays());
                            statEntity.setChildRearingLeave(balanceEntity.getChildRearingLeave());
                            statEntity.setBreastfeedingLeaveDays(balanceEntity.getBreastfeedingLeaveDays());
                            statEntity.setMenstrualLeaveDays(balanceEntity.getMenstrualLeaveDays());
                            statEntity.setAnnualLeaveDays(balanceEntity.getAnnualLeaveDays());
                            statEntity.setCompensatedLeaveDays(balanceEntity.getCompensatedLeaveDays());
                            statEntity.setPaternityLeaveDays(balanceEntity.getPaternityLeaveDays());
                            statEntity.setMaternityLeave(balanceEntity.getMaternityLeaveDays());
                            statEntity.setTransferBack(balanceEntity.getTransferBack());
                            statEntity.setHomeLeave(balanceEntity.getHomeLeave());
                            statEntity.setPersonalLeave(balanceEntity.getPersonalLeaveDays());
//                        statEntity.setLateTimes(goWorkCountDele);
//                        statEntity.setNonCompliancePunch(BigDecimal.valueOf(errorAttendaceCount));
                            attendanceStatDao.update(statEntity);
                        }

                        AttendanceVacationBalanceEntity attendanceVacationBalanceEntity = new AttendanceVacationBalanceEntity();
                        attendanceVacationBalanceEntity.initAttrValue();
                        attendanceVacationBalanceEntity.setStaffId(staffEntity1.getId());
                        attendanceVacationBalanceEntity.setStaffName(staffEntity1.getName());
                        attendanceVacationBalanceEntity.setDeptId(deptEntity.getId());
                        attendanceVacationBalanceEntity.setDeptName(deptEntity.getDeptName());
                        balanceDao.update(attendanceVacationBalanceEntity);
                        //统计各级部门员工数量
                        String ancestor = deptEntity.getAncestors().split(",", 2)[1];
                        String[] ancestors = ancestor.split(",");
                        for (String newAncestor : ancestors) {
                            DeptEntity deptEntity2 = deptService.get(Long.valueOf(newAncestor));
                            if (Objects.nonNull(deptEntity2)) {
                                deptEntity2.setPersonNum(deptEntity2.getPersonNum() + 1);
                                deptService.update(deptEntity2);
                            }
                        }
                    }


                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void stopTask(ITask task) throws AppException {

    }


}
