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

import cn.com.ty.lift.business.common.BeanUtils;
import cn.com.ty.lift.business.contract.dao.entity.Contracts;
import cn.com.ty.lift.business.contract.dao.entity.ContractsHistory;
import cn.com.ty.lift.business.contract.dao.entity.model.request.ContractRequest;
import cn.com.ty.lift.business.contract.dao.entity.model.response.ContractsHistoryResponse;
import cn.com.ty.lift.business.contract.dao.mapper.ContractsHistoryMapper;
import cn.hutool.core.map.MapUtil;
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/1/8
 * @description 合同历史记录业务层
 */
@Service
@Slf4j
public class ContractHistoryService extends ServiceImpl<ContractsHistoryMapper, ContractsHistory> {

    @Resource
    private BeanUtils utils;

    /**
     * @param request 合同编号
     * @return IPage<ContractsHistory> 合同历史记录
     * @description 根据合同编号查询合同历史记录
     * @date 2020/1/8 11:37 上午
     */
    public IPage<ContractsHistoryResponse> list(ContractRequest request) {
       return baseMapper.queryContractHistory(request.getPage(),request.getContractId());
    }

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