package com.lz.modules.performance.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lz.common.utils.BigDecimalUtil;
import com.lz.common.utils.R;
import com.lz.common.utils.StringUtil;
import com.lz.modules.app.entity.StaffEntity;
import com.lz.modules.app.service.StaffService;
import com.lz.modules.performance.dao.ResultTaskMapper;
import com.lz.modules.performance.dao.TaskProcessRecordMapper;
import com.lz.modules.performance.dto.ResultTaskDto;
import com.lz.modules.performance.dto.TaskProcessRecordDto;
import com.lz.modules.performance.entity.ResultTask;
import com.lz.modules.performance.entity.TaskProcessRecord;
import com.lz.modules.performance.enums.ProcessRecordEnum;
import com.lz.modules.performance.req.ResultUpdateTaskReq;
import com.lz.modules.performance.res.ResultTaskDetailRes;
import com.lz.modules.performance.service.ResultTaskService;
import com.lz.modules.performance.service.TaskProcessRecordService;
import com.lz.modules.sys.entity.app.ResultDetail;
import com.lz.modules.sys.service.app.ResultDetailService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
* <p>
* 任务表 服务类
* </p>
*
* @author quyixiao
* @since 2020-12-08
*/

@Slf4j
@Service
public class ResultTaskServiceImpl extends ServiceImpl<ResultTaskMapper, ResultTask> implements ResultTaskService {


    @Autowired
	private ResultTaskMapper resultTaskMapper;
    @Autowired
	private ResultDetailService resultDetailService;;
    @Autowired
	private TaskProcessRecordService taskProcessRecordService;
    @Autowired
	private TaskProcessRecordMapper taskProcessRecordMapper;
    @Autowired
	private StaffService staffService;



	@Override
	public ResultTask selectResultTaskById(Long id){
		return resultTaskMapper.selectResultTaskById(id);
	}



	@Override
	public Long insertResultTask(ResultTask resultTask){
		return resultTaskMapper.insertResultTask(resultTask);
	}



	@Override
	public int updateResultTaskById(ResultTask resultTask){
		return resultTaskMapper.updateResultTaskById(resultTask);
	}



	@Override
	public int updateCoverResultTaskById(ResultTask resultTask){
		return resultTaskMapper.updateCoverResultTaskById(resultTask);
	}



	@Override
	public int deleteResultTaskById(Long id){
		return resultTaskMapper.deleteResultTaskById(id);
	}

	@Override
	public ResultTaskDetailRes taskDetail(Long detailId) {
		ResultTaskDetailRes res = new ResultTaskDetailRes();
		StaffEntity staffEntity = null;
		ResultDetail resultDetail = resultDetailService.selectResultDetailById(detailId);
		if(resultDetail != null){
			res.setProcessRate(resultDetail.getProcessRate());
			res.setTarget(resultDetail.getTarget());
			Long staffId = resultDetail.getStaffId();
			staffEntity = staffService.selectStaffById(staffId);
		}
		List<ResultTaskDto> resultTasks = resultTaskMapper.selectResultTaskDtosByDetailId(detailId);

		//获取最近更新记录
		if(CollectionUtils.isNotEmpty(resultTasks)){
			StaffEntity finalStaffEntity = staffEntity;
			resultTasks.forEach(resultTaskDto -> {
                TaskProcessRecordDto taskProcessRecordDto = taskProcessRecordMapper.selectTaskProcessRecordLastByTaskId(resultTaskDto.getId());
                if(taskProcessRecordDto != null){
					//resultTaskDto.setLabel(taskProcessRecordDto.getLabel());
					if(taskProcessRecordDto.getUseType()==0){
						ProcessRecordEnum byType = ProcessRecordEnum.findByType(taskProcessRecordDto.getType());
						Optional.ofNullable(byType).ifPresent(processRecordEnum -> resultTaskDto.setTypeDesc(byType.getDesc()));
						if(finalStaffEntity !=null){
							resultTaskDto.setAvatar(finalStaffEntity.getAvatar());
							resultTaskDto.setStaffName(finalStaffEntity.getName());
						}
					}
					if(taskProcessRecordDto.getUseType()==1){
						resultTaskDto.setTypeDesc(taskProcessRecordDto.getLabel());
						StaffEntity staffEntity1 = staffService.selectStaffById(taskProcessRecordDto.getStaffId());
						if(staffEntity1 !=null){
							resultTaskDto.setAvatar(staffEntity1.getAvatar());
							resultTaskDto.setStaffName(staffEntity1.getName());

						}

					}


                }

            });
		}
		res.setResultTasks(resultTasks);
		return res;
	}

	@Override
	public R saveOrUpdateResultTask(ResultUpdateTaskReq req, Long userId) {
		Long tasklId = req.getTaskId();
		Long detailId = req.getDetailId();
		if(tasklId == null && detailId == null){
			log.error("任务保存或更新失败：tasklId, detailId都为空");
			return R.error();
		}
		ResultTask resultTask;
		if(tasklId == null){
			log.info("绩效任务新增操作。。。");
			ResultDetail resultDetail = resultDetailService.selectResultDetailById(req.getDetailId());
			if(!userId.equals(resultDetail.getStaffId())){
				log.info("非本人任务不能添加");
				return R.error("非本人任务不能添加");
			}
			resultTask = new ResultTask();
			BeanUtils.copyProperties(req,resultTask);
			resultTask.setDetailId(detailId);
			resultTaskMapper.insertResultTask(resultTask);
			//将插入的id传递过去
			req.setTaskId(resultTask.getId());
			changeTaskProcess(null, req,null);
		}
		else {

			log.info("绩效任务修改操作。。。");
			resultTask = resultTaskMapper.selectResultTaskById(tasklId);
			ResultDetail resultDetail = resultDetailService.selectResultDetailById(resultTask.getDetailId());
			if(!userId.equals(resultDetail.getStaffId())){
				log.info("非本人任务不能修改");
				return R.error("非本人任务不能修改");
			}
			TaskProcessRecordDto taskProcessRecordDto = taskProcessRecordMapper.selectTaskProcessRecordLastByTaskId(tasklId);
			int i = changeTaskProcess(resultTask, req,taskProcessRecordDto);
			if(i<1){
				log.info("任务暂无变化，不做修改");
			}
			resultTask.setOrderBy(req.getOrderBy());
			resultTask.setName(req.getName());
			resultTask.setProcessRate(req.getProcessRate());
			resultTaskMapper.updateCoverResultTaskById(resultTask);

		}
		//修改总进度
		if(detailId == null){
			detailId = resultTask.getDetailId();
		}
		ResultDetail resultDetail = resultDetailService.selectResultDetailById(detailId);
		resultDetail.setProcessRate(BigDecimal.valueOf(caclateResultDetailProcess(detailId)));
		resultDetailService.updateResultDetailById(resultDetail);
		return R.ok();

	}

	//计算总进度
	private Double caclateResultDetailProcess(Long detailId){
		List<ResultTaskDto> resultTaskDtos = resultTaskMapper.selectResultTaskDtosByDetailId(detailId);
		if(CollectionUtils.isEmpty(resultTaskDtos)){
			log.info("未找到该绩效详情下得任务信息");
			return 0d;
		}
		int size = resultTaskDtos.size();
		Double rate = 0d;
		int cout = 0;
		for(ResultTaskDto dto:resultTaskDtos){
			if(1 == dto.getProcessRate()){
				cout++;
				continue;
			}
			rate = BigDecimalUtil.add(rate,dto.getProcessRate());
		}
		size = size - cout;
		if(size < 1){
			return 1d;
		}
		double result = BigDecimalUtil.div(rate, size, 4);
		return result;

	}

	//记录变更记录
	private int changeTaskProcess(ResultTask beforeResultTask,ResultUpdateTaskReq req,TaskProcessRecordDto beforeTaskProcessRecord){
		TaskProcessRecord taskProcessRecord = new TaskProcessRecord();
		BeanUtils.copyProperties(req,taskProcessRecord);
		//新增操作
		if(beforeResultTask == null){
			taskProcessRecord.setType(ProcessRecordEnum.ADD.getType());
			taskProcessRecord.setLabel("新增key Results名称：" + req.getName() + ";进度：" + BigDecimalUtil.mul(req.getProcessRate(),BigDecimal.valueOf(100)).setScale(2) + "%");
			return taskProcessRecordService.insertTaskProcessRecord(taskProcessRecord).intValue();
		}
		//判断修改了名称或进度
		int i = 0;
		String lebel = "key Results名称：" + beforeResultTask.getName();
		if(!beforeResultTask.getName().equals(req.getName())) {
			i|= (0x00000001<<0);
			lebel = lebel +  " 改为 " + req.getName() + "\n";
		}
		if(BigDecimalUtil.compareTo(beforeResultTask.getProcessRate(),req.getProcessRate())!=0){
			i|= (0x00000001<<1);
			lebel = lebel + "将进度：" +BigDecimalUtil.mul(beforeResultTask.getProcessRate(),BigDecimal.valueOf(100)).setScale(2)+ "%" + " 更新为 " + BigDecimalUtil.mul(req.getProcessRate(),BigDecimal.valueOf(100)).setScale(2)+ "%";
		}

		String remark = StringUtil.EMPTY;

		if(req.getRemark() != null){
			if(beforeTaskProcessRecord != null){
				remark = beforeTaskProcessRecord.getRemark();
			}
			if(beforeTaskProcessRecord == null ||(!req.getRemark().equals(beforeTaskProcessRecord.getRemark()))){
				i|= (0x00000001<<2);
				lebel = lebel + "将进度说明更新为: " + req.getRemark();
			}
		}


		if(i==0){
			return -1;
		}

		taskProcessRecord.setTaskId(beforeResultTask.getId());
		taskProcessRecord.setDetailId(beforeResultTask.getDetailId());
		taskProcessRecord.setType(i);
		taskProcessRecord.setLabel(lebel);
		return taskProcessRecordService.insertTaskProcessRecord(taskProcessRecord).intValue();
		/*if(!beforeResultTask.getName().equals(req.getName())){
			if(BigDecimalUtil.compareTo(beforeResultTask.getProcessRate(),req.getProcessRate())!=0){
				taskProcessRecord.setType(ProcessRecordEnum.ALL.getType());
				taskProcessRecord.setLabel("将key Results名称：" + beforeResultTask.getName() + "改为" + req.getName() + "\n"
				                           + "进度：" + BigDecimalUtil.mul(beforeResultTask.getProcessRate(),BigDecimal.valueOf(100)).setScale(2) + "%" + "改为" + BigDecimalUtil.mul(req.getProcessRate(),BigDecimal.valueOf(100)).setScale(2) + "%");
				return taskProcessRecordService.insertTaskProcessRecord(taskProcessRecord).intValue();
			}

			taskProcessRecord.setType(ProcessRecordEnum.NAME.getType());
			taskProcessRecord.setLabel("将key Results名称：" + beforeResultTask.getName() + "改为" + req.getName());
			return taskProcessRecordService.insertTaskProcessRecord(taskProcessRecord).intValue();

		}
		if(BigDecimalUtil.compareTo(beforeResultTask.getProcessRate(),req.getProcessRate())!=0){
			taskProcessRecord.setType(ProcessRecordEnum.PROCESS.getType());
			taskProcessRecord.setLabel("将" +beforeResultTask.getName() + "得进度由"  + BigDecimalUtil.mul(beforeResultTask.getProcessRate(),BigDecimal.valueOf(100)).setScale(2) + "%" + "更新为：" + BigDecimalUtil.mul(req.getProcessRate(),BigDecimal.valueOf(100)).setScale(2) + "%");
			return taskProcessRecordService.insertTaskProcessRecord(taskProcessRecord).intValue();
		}
		return -1;*/
	}



	@Override
	public List<ResultTask> selectResultTasksByDetailId(Long detailId){
		return resultTaskMapper.selectResultTasksByDetailId(detailId);
	}

	@Override
	public int deleteResultTasksByDetailId(Long detailId) {
		List<ResultTask> tasks = resultTaskMapper.selectResultTasksByDetailId(detailId);
		for (ResultTask task : tasks
		) {
			taskProcessRecordService.deleteTaskProcessRecordsByTaskId(task.getId());
		}
		return resultTaskMapper.deleteResultTasksByDetailId(detailId);
	}

	@Override
	public R deleteTask(Long taskId,Long userId) {
		ResultTask resultTask = resultTaskMapper.selectResultTaskById(taskId);
		ResultDetail resultDetail = resultDetailService.selectResultDetailById(resultTask.getDetailId());
		if(!userId.equals(resultDetail.getStaffId())){
			log.info("非本人任务不能删除");
			return R.error("非本人任务不能删除");
		}
		resultTaskMapper.deleteResultTaskById(taskId);
		TaskProcessRecord taskProcessRecord = new TaskProcessRecord();
		taskProcessRecord.setTaskId(taskId);
		taskProcessRecord.setType(ProcessRecordEnum.DELETE.getType());
		taskProcessRecord.setLabel("将" +resultTask.getName() +  "任务删除");
		taskProcessRecordService.insertTaskProcessRecord(taskProcessRecord);
		//修改总进度
		resultDetail.setProcessRate(BigDecimal.valueOf(caclateResultDetailProcess(resultTask.getDetailId())));
		resultDetailService.updateResultDetailById(resultDetail);
		return R.ok();
	}

	@Override
	public List<ResultTaskDto> selectResultTaskDtosByDetailId(Long detailId){
		return resultTaskMapper.selectResultTaskDtosByDetailId(detailId);
	}

}
