package com.artfess.device.base.manager.impl;

import com.artfess.base.manager.impl.BaseManagerImpl;
import com.artfess.base.query.PageBean;
import com.artfess.base.query.PageList;
import com.artfess.base.query.QueryFilter;
import com.artfess.device.base.dao.AppraiseDetailsDao;
import com.artfess.device.base.manager.AppraiseDetailsManager;
import com.artfess.device.base.manager.AppraiseInfoManager;
import com.artfess.device.base.manager.AppraiseItemsManager;
import com.artfess.device.base.model.AppraiseDetails;
import com.artfess.device.base.model.AppraiseInfo;
import com.artfess.device.base.model.AppraiseItems;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 绩效考核-考核详情（DEVICE_APPRAISE_DETAILS） 服务实现类
 *
 * @company 阿特菲斯信息技术有限公司
 * @author Limuhua
 * @since 2022-08-02
 */
@Service
public class AppraiseDetailsManagerImpl extends BaseManagerImpl<AppraiseDetailsDao, AppraiseDetails> implements AppraiseDetailsManager {

    @Autowired
    private AppraiseItemsManager itemsManager;
    @Autowired
    private AppraiseInfoManager infoManager;

    @Override
    public boolean save(AppraiseDetails appraiseDetails) {
        getResult(appraiseDetails);
        boolean result = super.save(appraiseDetails);
        return result;
    }
    @Override
    public boolean updateById(AppraiseDetails appraiseDetails) {
        getResult(appraiseDetails);
        boolean result = super.updateById(appraiseDetails);
        return result;
    }

    @Override
    public void getResult(AppraiseDetails appraiseDetails){
        BigDecimal score = appraiseDetails.getItemScore();
        BigDecimal weight = itemsManager.get(appraiseDetails.getItemId()).getItemVal();
        appraiseDetails.setItemResult(score.multiply(weight));
    }

    @Override
    public PageList<AppraiseDetails> query(QueryFilter<AppraiseDetails> queryFilter) {
        PageBean pageBean = queryFilter.getPageBean();
        QueryWrapper<AppraiseDetails> queryWrapper = convert2Wrapper(queryFilter, currentModelClass());
        queryWrapper.orderByDesc("item_result_");
        IPage<AppraiseDetails> result = baseMapper.queryPage(convert2IPage(pageBean), queryWrapper);
        return new PageList<>(result);
    }

    @Override
    public boolean saveOrUpdateBatch(Collection<AppraiseDetails> entityList) {
        Assert.notNull(entityList, "数据不能为空！");
        Assert.isTrue(entityList.stream().collect(Collectors.groupingBy(AppraiseDetails::getInfoId)).size()==1,"批量新增时的infoId应统一");
        return super.saveOrUpdateBatch(entityList);
    }
}
