package com.goafanti.order.service.impl;

import com.goafanti.common.bo.Result;
import com.goafanti.common.dao.AdminProjectStatisticsMapper;
import com.goafanti.common.dao.TOrderNewMapper;
import com.goafanti.common.dao.TOrderTaskMapper;
import com.goafanti.common.dao.TaskScoreMapper;
import com.goafanti.common.model.AdminProjectStatistics;
import com.goafanti.common.model.TOrderNew;
import com.goafanti.common.model.TOrderTask;
import com.goafanti.common.model.TaskScore;
import com.goafanti.common.utils.excel.NewExcelUtil;
import com.goafanti.core.mybatis.BaseMybatisDao;
import com.goafanti.core.mybatis.page.Pagination;
import com.goafanti.order.bo.TOrderTaskBo;
import com.goafanti.order.bo.TaskScore.InputTaskScore;
import com.goafanti.order.bo.TaskScore.OutAdminTaskScore;
import com.goafanti.order.service.TaskScoreService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

/**
 * 项目评分列表(TaskScore)表服务实现类
 *
 * @author makejava
 * @since 2024-09-27 11:51:57
 */
@Service("taskScoreService")
public class TaskScoreServiceImpl extends BaseMybatisDao<TaskScoreMapper> implements TaskScoreService {
    @Resource
    private TaskScoreMapper taskScoreMapper;
    @Resource
    private TOrderTaskMapper tOrderTaskMapper;
    @Resource
    private TOrderNewMapper tOrderNewMapper;
    @Resource
    private AdminProjectStatisticsMapper adminProjectStatisticsMapper;
    @Value(value = "${upload.path}")
    private final String	uploadPath			= null;



    @Override
    public Pagination<OutAdminTaskScore> list(InputTaskScore in) {
        return (Pagination<OutAdminTaskScore>) findPage("findAdminTaskScoreList",
                "findAdminTaskScoreCount", in, in.getPageNo(), in.getPageSize());
    }




    @Override
    public Object updateByTid(TaskScore taskScore) {
        TaskScore taskScore2 = taskScoreMapper.queryByTid(taskScore.getTid());
        if (taskScore2==null){
            this.insert(taskScore);
        }else {
            taskScore.setId(taskScore2.getId());
             this.taskScoreMapper.update(taskScore);
        }
        //修改项目评分
        getTOrderTask(taskScore);
        //计算项目与订单评分与状态
        updateTOrderNewByTid(taskScore.getTid());
        //为当事人计算评分
        updateAdminByTid(taskScore.getTid());
        return taskScore;
    }

    private void getTOrderTask(TaskScore taskScore) {
        int scoreNumber = taskScore.getServiceAttitude() + taskScore.getProfessionalism() + taskScore.getPublicImage()
                + taskScore.getResponsiveness() + taskScore.getCommunicationSkills();

        if (taskScore.getMonthlyReport()!=null)scoreNumber+= taskScore.getMonthlyReport();
        if (taskScore.getYearReport()!=null)scoreNumber+= taskScore.getYearReport();
        TOrderTask taskTask = new TOrderTask();
        taskTask.setId(taskScore.getTid());
        taskTask.setScoreNumber(scoreNumber);
        taskTask.setScoreStatus(2);
        tOrderTaskMapper.update(taskTask);

    }

    /**
     * 跟进项目编号修改管理员评分
     * @param tid 项目编号
     */
    @Override
    public void updateAdminByTid(Integer tid) {
        List<TOrderTaskBo> tOrderTaskBos = tOrderTaskMapper.selectAdminTaskByTid(tid);
        //项目数量
        pushAdminProjectStatistics(tOrderTaskBos, null);
    }

    private void pushAdminProjectStatistics(List<TOrderTaskBo> tOrderTaskBos, String aid) {
        if (tOrderTaskBos==null){
            tOrderTaskBos=tOrderTaskMapper.selectAdminTaskByAid(aid);
        }
        int htSatCount = 0,htSatScoreCount = 0,htSatNotScoreCount = 0,
                memberCount=0,memberScoreCount = 0,memberNotScoreCount = 0;
        BigDecimal ht_satSum=new BigDecimal(0);
        BigDecimal hySum=new BigDecimal(0);
        for (TOrderTaskBo tOrderTaskBo : tOrderTaskBos) {
            if (aid ==null) aid =tOrderTaskBo.getTaskReceiver();
            if (tOrderTaskBo.getcSort()==3||tOrderTaskBo.getcSort()==9){
                htSatCount++;
                if (tOrderTaskBo.getScoreStatus()==1){
                    htSatNotScoreCount++;
                }else if (tOrderTaskBo.getScoreStatus()==2){
                    htSatScoreCount++;
                ht_satSum=ht_satSum.add(new BigDecimal(tOrderTaskBo.getScoreNumber()));
                }

            }else  if (tOrderTaskBo.getcSort()==6) {
                memberCount++;
                if (tOrderTaskBo.getScoreStatus()==1){
                    memberNotScoreCount++;
                }else if (tOrderTaskBo.getScoreStatus()==2){
                    memberScoreCount++;
                    hySum=hySum.add(new BigDecimal(tOrderTaskBo.getScoreNumber()));
                }

            }
        }
        BigDecimal htSatScoreAverage = BigDecimal.ZERO;
        BigDecimal memberScoreAverage = BigDecimal.ZERO;
        if (htSatScoreCount>0)htSatScoreAverage=ht_satSum.divide(new BigDecimal(htSatScoreCount),2, RoundingMode.HALF_UP);
        if (memberScoreCount>0)memberScoreAverage=hySum.divide(new BigDecimal(memberScoreCount),2, RoundingMode.HALF_UP);
        AdminProjectStatistics adminProjectStatistics = adminProjectStatisticsMapper.queryByAid(aid);
        AdminProjectStatistics aps=new AdminProjectStatistics();
        aps.setAid(aid);
        aps.setHtSatCount(htSatCount);
        aps.setHtSatScoreAverage(htSatScoreAverage.doubleValue());
        aps.setHtSatNotScoreCount(htSatNotScoreCount);
        aps.setHtSatScoreCount(htSatScoreCount);
        aps.setMemberScoreAverage(memberScoreAverage.doubleValue());
        aps.setMemberScoreCount(memberScoreCount);
        aps.setMemberNotScoreCount(memberNotScoreCount);
        aps.setMemberCount(memberCount);
        if (adminProjectStatistics==null){
            adminProjectStatisticsMapper.insert(aps);
        }else {
            aps.setId(adminProjectStatistics.getId());
            adminProjectStatisticsMapper.update(aps);
        }
    }



    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public TaskScore queryById(Integer id) {
        return this.taskScoreMapper.queryById(id);
    }


    /**
     * 新增数据
     *
     * @param taskScore 实例对象
     * @return 实例对象
     */
    @Override
    public TaskScore insert(TaskScore taskScore) {
        this.taskScoreMapper.insert(taskScore);
        return taskScore;
    }

    /**
     * 修改数据
     *
     * @param taskScore 实例对象
     * @return 实例对象
     */
    @Override
    public TaskScore update(TaskScore taskScore) {
        this.taskScoreMapper.update(taskScore);
        return this.queryById(taskScore.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.taskScoreMapper.deleteById(id) > 0;
    }

    /**
     * 根据项目编号，更新订单评分状态
     * @param tid 项目编号
     */
    @Override
    public void updateTOrderNewByTid(Integer tid) {
        List<TOrderTask> tOrderTasks = tOrderTaskMapper.selectTasksByTid(tid);
        if (!tOrderTasks.isEmpty()){
            String orderNo=null;
            int count=0;
            int completeCount = 0;
            int notSum = 0;
            for (TOrderTask e : tOrderTasks) {
                if (orderNo==null&&e.getOrderNo() != null)orderNo=e.getOrderNo();
                if (e.getScoreStatus()==0)count++;
                if (e.getScoreStatus()==1)notSum++;
                if (e.getScoreStatus()==2)completeCount++;
            }
            TOrderNew tOrderNew = new TOrderNew();
            tOrderNew.setOrderNo(orderNo);
            tOrderNew.setScoreStatus(0);
            if (notSum==0){
                //没有未评分，全部不是是无，全部已评分是已完成
                if (count==tOrderTasks.size()){
                    tOrderNew.setScoreStatus(0);
                }else if (completeCount>0){
                    tOrderNew.setScoreStatus(3);
                }
            }else if (notSum>0){
                //有未评分默认是待评分，有已完成是部分评分
                tOrderNew.setScoreStatus(1);
                if (completeCount>0){
                    tOrderNew.setScoreStatus(2);
                }
            }
            tOrderNewMapper.update(tOrderNew);
        }

    }

    @Override
    public TaskScore queryByTid(Integer tid) {
        return taskScoreMapper.queryByTid(tid);
    }

    @Override
    public Result listExport(InputTaskScore params) {
        List<OutAdminTaskScore> list = (List<OutAdminTaskScore>) findList("findAdminTaskScoreList",params, 1, 99999);
        pushRemarks(list);
        NewExcelUtil excel = new NewExcelUtil(OutAdminTaskScore.class);
        return excel.exportExcel(list, "人员评分列表", uploadPath);
    }

    private void pushRemarks(List<OutAdminTaskScore> list) {
        for (OutAdminTaskScore e : list) {
            List<TaskScore> taskScores = taskScoreMapper.selectRemarkByAid(e.getId());
            StringBuilder remark=new StringBuilder();
            if (!taskScores.isEmpty()){
                for (TaskScore e2 : taskScores) {
                    if (e2.getRemarks()!=null){
                        remark.append(e2.getRemarks()).append("\r\n");
                    }
                }
            }
            e.setRemarks(remark.toString());
        }
    }

}
