package com.zhongshu.card.server.core.service.openAPI.attendance;

import com.github.microservice.components.data.base.util.PageEntityUtil;
import com.github.microservice.net.ResultContent;
import com.zhongshu.card.client.model.attendance.LeaveApprovalModel;
import com.zhongshu.card.client.openApi.params.AddLeaveOpenApiParam;
import com.zhongshu.card.client.openApi.params.PageLeaveOpenApiParam;
import com.zhongshu.card.server.core.dao.attendance.LeaveApprovalDao;
import com.zhongshu.card.server.core.domain.attendance.LeaveApproval;
import com.zhongshu.card.server.core.service.attendance.LeaveService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class LeaveOpenApiService {

    @Autowired
    LeaveApprovalDao leaveApprovalDao;

    @Autowired
    LeaveService leaveService;

    public ResultContent<String> add(AddLeaveOpenApiParam param){
        LeaveApproval leaveApproval = new LeaveApproval();
        BeanUtils.copyProperties(param, leaveApproval, "id");
        leaveApprovalDao.save(leaveApproval);
        return ResultContent.buildContent(leaveApproval.getId());
    }

    public ResultContent<String> update(LeaveApproval param){
        if (StringUtils.isBlank(param.getId())){
            return ResultContent.buildFail("id不能为空");
        }
        LeaveApproval leaveApproval = new LeaveApproval();
        com.zhongshu.card.server.core.util.BeanUtils.copyPropertiesWithoutNull(param, leaveApproval);
        leaveApprovalDao.save(leaveApproval);
        return ResultContent.buildSuccess(leaveApproval.getId());
    }

    public ResultContent delete(String id){
        leaveApprovalDao.deleteById(id);
        return ResultContent.buildSuccess(id);
    }

    public ResultContent<LeaveApprovalModel> findOneById(String id){
        if (StringUtils.isBlank(id)){
            return ResultContent.buildFail("id不能为空");
        }
        LeaveApproval leaveApproval = leaveApprovalDao.findTopById(id);
        if (leaveApproval == null){
            return ResultContent.buildFail("数据不存在");
        }
        LeaveApprovalModel model = leaveService.toModel(leaveApproval);
        return ResultContent.buildContent(model);
    }

    public ResultContent<Page<LeaveApprovalModel>> page(Pageable pageable, PageLeaveOpenApiParam param){
        Page<LeaveApproval> page = leaveApprovalDao.openApiPage(pageable, param);
        Page<LeaveApprovalModel> leaveApprovalModels = PageEntityUtil.concurrent2PageModel(page, it -> {
            return leaveService.toModel(it);
        });
        return ResultContent.buildSuccess(leaveApprovalModels);
    }


}
