package com.yihu.jw.evaluate.score.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yihu.jw.entity.base.score.BaseEvaluateDO;
import com.yihu.jw.entity.base.score.BaseEvaluateScoreDO;
import com.yihu.jw.entity.hospital.prescription.WlyyOutpatientDO;
import com.yihu.jw.entity.hospital.prescription.WlyyPrescriptionDiagnosisDO;
import com.yihu.jw.evaluate.score.dao.BaseEvaluateDao;
import com.yihu.jw.evaluate.score.dao.BaseEvaluateScoreDao;
import com.yihu.mysql.query.BaseJpaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

/**
 * Created by Trick on 2019/6/20.
 */
@Service
public class BaseEvaluateService extends BaseJpaService<BaseEvaluateDO, BaseEvaluateDao> {

    @Autowired
    private BaseEvaluateScoreDao baseEvaluateScoreDao;

    @Autowired
    private BaseEvaluateDao baseEvaluateDao;

    @Autowired
    private ObjectMapper objectMapper;

    public Boolean addEvaluateScore(String evaluateScoreJson, String evaluatesJson)throws Exception{

        BaseEvaluateScoreDO baseEvaluateScoreDO = objectMapper.readValue(evaluateScoreJson,BaseEvaluateScoreDO.class);

        List<BaseEvaluateDO> evaluateDOList = (List<BaseEvaluateDO>) com.alibaba.fastjson.JSONArray.parseArray(evaluatesJson, BaseEvaluateDO.class);

        if(evaluateDOList!=null&& evaluateDOList.size()>0){
            Double total = 0.0;
            for(BaseEvaluateDO evaluate :evaluateDOList){
                total += evaluate.getScore();
            }
            Double avg = new BigDecimal(total/evaluateDOList.size()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            baseEvaluateScoreDO.setScore(avg);
            BaseEvaluateScoreDO baseEvaluateScore = baseEvaluateScoreDao.save(baseEvaluateScoreDO);

            for(BaseEvaluateDO evaluateDO:evaluateDOList){
                evaluateDO.setRelationCode(baseEvaluateScore.getId());
            }
            baseEvaluateDao.save(evaluateDOList);

        }
        return true;
    }
}
