package cn.com.ty.lift.ud.expertComment.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import cn.com.ty.lift.common.model.PushMessage;
import cn.com.ty.lift.common.model.PushUserInfo;
import cn.com.ty.lift.ud.chat.mapper.LiftCaseMapper;
import cn.com.ty.lift.ud.chat.mapper.entity.LiftCaseEntity;
import cn.com.ty.lift.ud.expertComment.controller.query.ExpertCommentQuery;
import cn.com.ty.lift.ud.expertComment.mapper.ExpertCommentMapper;
import cn.com.ty.lift.ud.expertComment.mapper.entity.ExpertCommentEntity;
import cn.com.ty.lift.ud.expertComment.mapper.entity.ScoreInfo;
import cn.com.ty.lift.ud.expertComment.service.IExpertCommentService;
import cn.com.ty.lift.ud.operation.mapper.entity.ExpertLevelSettingEntity;
import cn.com.ty.lift.ud.operation.service.IExpertLevelSettingService;
import cn.com.ty.lift.ud.userAccount.service.IUserAccountService;
import cn.com.ty.lift.ud.userInfo.mapper.UserInfoMapper;
import cn.com.ty.lift.ud.userInfo.mapper.entity.UserInfoEntity;
import cn.com.ty.lift.ud.userInfo.service.IUserInfoService;
import cn.com.xwy.boot.web.dto.RestResponse;

/**
 * 诊单评论 -ServiceImpl
 *
 * @author Xson
 * @date 2020-05-06
 */
@Service
@Transactional
public class ExpertCommentServiceImpl extends ServiceImpl<ExpertCommentMapper, ExpertCommentEntity>
    implements IExpertCommentService {

    @Autowired
    private ExpertCommentMapper expertCommentMapper;

    private @Autowired LiftCaseMapper caseMapper;

    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;
    
    private @Autowired IUserAccountService iUserAccountService;
    
    @Autowired
    private IExpertLevelSettingService iExpertLevelSettingService;

    @Autowired
    private IUserInfoService iUserInfoService;

    @Autowired
    private UserInfoMapper userInfoMapper;

    /**
     * 多表查询
     *
     * @param query
     * @return
     */
    @Override
    public RestResponse selectByExample(ExpertCommentQuery query) {
        IPage page = query.page();
        List<ExpertCommentEntity> list = expertCommentMapper.selectByQuery(query.condition(), query);
        page.setRecords(list);
        int total = expertCommentMapper.countByQuery(query.condition());
        page.setTotal(total);
        return RestResponse.success(page, "查询成功");
    }

    /**
     * 批量显示或者屏蔽
     *
     * @param ids
     * @param status
     */
    @Override
    public void updateByIds(List<Long> ids, Integer status) {
        for (Long id : ids) {
            ExpertCommentEntity que = new ExpertCommentEntity();
            que.setId(id);
            que.setStatuz(status);
            expertCommentMapper.updateById(que);
        }
    }

    /**
     * 获取专家评论
     * 
     * @param query
     * @return
     */
    @Override
    public RestResponse getExpertComment(ExpertCommentQuery query) {
        IPage page = query.page();
        List<ExpertCommentEntity> list = expertCommentMapper.getExpertComment(query.condition(), query);
        page.setRecords(list);
        int total = expertCommentMapper.countAllByQuery(query.condition());
        page.setTotal(total);
        return RestResponse.success(page, "查询成功");
    }

    /**
     * 重写新增的方法
     *
     * @param entity
     * @return
     */
    @Override
    public RestResponse saveComment(ExpertCommentEntity entity) {
        LiftCaseEntity selectById = caseMapper.selectById(entity.getLifeCaseId());
        if(null == selectById){
            RestResponse.fail("对应的诊单不存在");
        }
        // 计算本次评论的平均星数
        int averageScore = (int)Math.floor((entity.getTech() + entity.getResponseSpeed() + entity.getAttitude()) / 3);
        // 专家评论表新增数据
        entity.setStatuz(0);
        entity.setAverageScore(averageScore);
        expertCommentMapper.insert(entity);
        // 根据专家评论升级规则，修改 user_info 中的专家总积分 level_total_score
        // 根据星数查询获得的积分
        RestResponse latestVersion = iExpertLevelSettingService.getLatestVersion();
        ExpertLevelSettingEntity data = (ExpertLevelSettingEntity)latestVersion.getData();
        int score = 0;
        if (null != data) {
            switch (averageScore) {
                case 1:
                    score = data.getScoreOne();
                    break;
                case 2:
                    score = data.getScoreTwo();
                    break;
                case 3:
                    score = data.getScoreThree();
                    break;
                case 4:
                    score = data.getScoreFour();
                    break;
                case 5:
                    score = data.getScoreFive();
                    break;
                default:
                    score = 0;
                    break;
            }
        }
        // 修改 user_info 中的专家总积分 level_total_score，并修改专家星级
        UserInfoEntity expertInfo = iUserInfoService.getByUserId(entity.getExpertId());
        userInfoMapper.updateAverageScore(expertInfo.getUserId(),expertInfo.getAverageScore());
        if(null != expertInfo){
            int nowTotalScore = score;
            if(null != expertInfo.getLevelTotalScore()){
                int levelTotalScore = expertInfo.getLevelTotalScore();
                //目前的专家总积分
                nowTotalScore = levelTotalScore + score;
            }
            //判断专家是否升星
            if(nowTotalScore < data.getLeveiTwo()){
                iUserInfoService.addExpertScore(nowTotalScore, entity.getExpertId(),1);
            }else if(nowTotalScore >= data.getLeveiTwo() && nowTotalScore < data.getLevelThree()){
                iUserInfoService.addExpertScore(nowTotalScore, entity.getExpertId(),2);
            }else if(nowTotalScore >= data.getLevelThree() && nowTotalScore < data.getLevelFour()){
                iUserInfoService.addExpertScore(nowTotalScore, entity.getExpertId(),3);
            }else if(nowTotalScore >= data.getLevelFour() && nowTotalScore < data.getLevelFive()){
                iUserInfoService.addExpertScore(nowTotalScore, entity.getExpertId(),4);
            }else if(nowTotalScore >= data.getLevelFive()){
                iUserInfoService.addExpertScore(nowTotalScore, entity.getExpertId(),5);
            }

        }
        // 对应诊单状态改为 已完成
        if (selectById.getDataTable() == 1) {
            //问诊评价操作与归档操作互换，因此归档是状态为5，评价是状态6
//            caseMapper.updateStatusById(selectById.getId(), 5);
            caseMapper.updateStatusById(selectById.getId(), 6);
        } else {
            caseMapper.updateStatusById(selectById.getId(), 6);
        }
        
        PushUserInfo pushUserInfo =
            iUserAccountService.getPushUserInfoByUserId(selectById.getChargerId().toString());
        PushMessage pushMessage = PushMessage.orderChargeStatus("用戶有新评价");
        pushMessage.sendTokenOnPlatform(jmsMessagingTemplate, pushUserInfo);
        return RestResponse.success(null, "新增成功");
    }

    /**
     * 根据专家ID查询评论个数和总分
     * @param userId
     * @return
     */
    @Override
    public ScoreInfo getScoreByExpertId(Long userId) {
        ScoreInfo score = expertCommentMapper.getScoreByExpertId(userId);
        //num = 0 时 totalScore = null
        if(score.getTotalScore() == null || score.getNum() == 0 ){
            score = null;
        }
        return score ;
    }

    @Override
    public List<ExpertCommentEntity> getCommentByUserId(Long expertId) {
        return expertCommentMapper.getCommentByUserId(expertId);
    }

}
