package cn.com.ty.lift.business.project.service;

import cn.com.ty.lift.business.common.BeanUtils;
import cn.com.ty.lift.business.project.dao.entity.Project;
import cn.com.ty.lift.business.project.dao.entity.ProjectHistory;
import cn.com.ty.lift.business.project.dao.entity.model.request.ProjectRequest;
import cn.com.ty.lift.business.project.dao.entity.model.response.ProjectHistoryResponse;
import cn.com.ty.lift.business.project.dao.mapper.ProjectHistoryMapper;
import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @author bieao
 * @date 2020/3/10
 * @description 项目操作记录
 */
@Service
@Slf4j
public class ProjectHistoryService extends ServiceImpl<ProjectHistoryMapper, ProjectHistory> {


    @Resource
    private BeanUtils utils;

    /**
     * @param request 项目操作记录查询条件
     * @return IPage<ProjectHistory> 结果集
     * @description 查询项目操作记录列表
     * @date 2020/4/27 2:19 下午
     */
    public IPage<ProjectHistoryResponse> historyList(ProjectRequest request) {
       return baseMapper.queryProjectHistory(request.getPage(),request);
    }

    /**
     * @param oldEntry 原有项目
     * @param newEntry 修改后的项目
     * @return
     * @description 保存项目操作记录
     * @date 2020/4/28 9:52 上午
     */
    public ProjectHistory createOperaHistory(Project oldEntry, Project newEntry, Long mtCompanyId) {
        Map<String, String> resultMap = new HashMap<>();
        try {
            resultMap = utils.compareAttribute(oldEntry, newEntry);
            if (MapUtil.isEmpty(resultMap)) return null;
        } catch (NoSuchFieldException e) {
            log.error("项目操作记录保存异常", e);
        }
        ProjectHistory projectHistory = new ProjectHistory();
        projectHistory.setProjectId(oldEntry.getId());
        projectHistory.setMtCompanyId(mtCompanyId);
        projectHistory.setDescription("编辑项目信息");
        projectHistory.setName(newEntry.getProjectName());
        projectHistory.setCode(newEntry.getProjectCode());
        projectHistory.setBeforeContent(resultMap.get("before"));
        projectHistory.setAfterContent(resultMap.get("after"));
        projectHistory.setOperatorId(10000L);
        projectHistory.setOperateDate(LocalDateTime.now());
        return projectHistory;
    }
}
