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

import com.mortals.framework.common.Rest;
import com.mortals.framework.service.impl.AbstractCRUDCacheServiceImpl;
import com.mortals.xhx.common.code.StaffStatusEnum;
import com.mortals.xhx.common.utils.BeanUtil;
import com.mortals.xhx.module.staff.model.StaffLeaveEntity;
import com.mortals.xhx.module.staff.model.StaffLeaveQuery;
import com.mortals.xhx.module.staff.model.StaffQuery;
import com.mortals.xhx.module.staff.service.StaffLeaveService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mortals.framework.service.impl.AbstractCRUDServiceImpl;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.xhx.module.staff.dao.StaffDao;
import com.mortals.xhx.module.staff.model.StaffEntity;
import com.mortals.xhx.module.staff.service.StaffService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

import java.util.Date;

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

    @Autowired
    private StaffLeaveService staffLeaveService;

    @Override
    public Rest<Void> leave(StaffEntity staffEntity, Context context) {
        //离职
        StaffEntity condition = new StaffEntity();
        condition.setId(staffEntity.getId());
        condition.setStaffStatus(StaffStatusEnum.离职.getValue());
        condition.setUpdateTime(new Date());
        condition.setUpdateUserId(this.getContextUserId(context));
        this.update(condition, context);

        StaffEntity staffCache = this.getCache(staffEntity.getId().toString());
        StaffLeaveEntity staffLeaveEntity = staffLeaveService.selectOne(new StaffLeaveQuery().name(staffCache.getName()).phoneNumber(staffCache.getPhoneNumber()));
        if (ObjectUtils.isEmpty(staffLeaveEntity)) {
            StaffLeaveEntity staffLeave = new StaffLeaveEntity();
            staffLeave.initAttrValue();
            BeanUtils.copyProperties(staffCache, staffLeave, BeanUtil.getNullPropertyNames(staffCache));
            staffLeave.setId(null);
            staffLeave.setCreateTime(new Date());
            staffLeaveService.save(staffLeave, context);
        }
        return Rest.ok();
    }
}