package com.yeejoin.precontrol.common.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yeejoin.precontrol.common.dto.StudioPageableDto;
import com.yeejoin.precontrol.common.entity.Person;
import com.yeejoin.precontrol.common.entity.Project;
import com.yeejoin.precontrol.common.entity.Task;
import com.yeejoin.precontrol.common.entity.TaskPerson;
import com.yeejoin.precontrol.common.entity.TaskWork;
import com.yeejoin.precontrol.common.entity.TaskWorkAttachment;
import com.yeejoin.precontrol.common.enums.AttachmentTypeEnum;
import com.yeejoin.precontrol.common.enums.StatusEnum;
import com.yeejoin.precontrol.common.enums.TaskPersonTypeEnum;
import com.yeejoin.precontrol.common.enums.TaskStatusEnum;
import com.yeejoin.precontrol.common.enums.TaskTypeEnum;
import com.yeejoin.precontrol.common.exception.BaseException;
import com.yeejoin.precontrol.common.mapper.TaskWorkMapper;
import com.yeejoin.precontrol.common.service.IPersonService;
import com.yeejoin.precontrol.common.service.IProjectService;
import com.yeejoin.precontrol.common.service.ITaskPersonService;
import com.yeejoin.precontrol.common.service.ITaskService;
import com.yeejoin.precontrol.common.service.ITaskWorkAttachmentService;
import com.yeejoin.precontrol.common.service.ITaskWorkService;
import com.yeejoin.precontrol.common.utils.DateUtils;
import com.yeejoin.precontrol.common.vo.TaskWorkVo;

/**
 * 服务实现类
 *
 * @author duanwei
 * @date 2022-07-07
 */
@Service
public class TaskWorkServiceImpl extends ServiceImpl<TaskWorkMapper, TaskWork> implements ITaskWorkService {

	@Autowired
	IProjectService iProjectService;

	@Autowired
	ITaskService iTaskService;

	@Autowired
	ITaskPersonService iTaskPersonService;

	@Autowired
	ITaskWorkAttachmentService iTaskWorkAttachmentService;

	@Autowired
	IPersonService iPersonService;

	/**
	 * 文件服务器地址
	 */
	@Value("${fileserver.domain}")
	String fileServerUrl;

	@Override
	public boolean save(TaskWorkVo taskWorkVo) {
		Task task = new Task();
		task.setType(TaskTypeEnum.RISK.getValue());
		task.setCreatePersonId(taskWorkVo.getCreatePersonId());
		task.setStatus(TaskStatusEnum.UNCOMPLETED.getLongType());
		task.setProjectId(taskWorkVo.getProjectId());
		Project project = iProjectService.getById(taskWorkVo.getProjectId());
		if (project == null) {
			throw new BaseException("所选项目不存在");
		}
		task.setTaskNo(DateUtils.getTimeStamp());
		task.setOrgCode(project.getOrgCode());
		task.setProjectName(project.getName());
		task.setStatus(StatusEnum.SUCCESS.getValue());
		task.setTaskNo(DateUtils.getTimeStamp());
		task.setName(taskWorkVo.getName());
		iTaskService.save(task);

		TaskWork taskWork = new TaskWork();
		BeanUtils.copyProperties(taskWorkVo, taskWork);
		taskWork.setTaskId(task.getId());
		taskWork.setProjectId(taskWorkVo.getProjectId());
		this.save(taskWork);
		
		List<TaskPerson> list = new ArrayList<TaskPerson>();
		TaskPerson cTaskPerson = new TaskPerson();
		cTaskPerson.setTaskId(task.getId());
		cTaskPerson.setPersonId(taskWorkVo.getCreatePersonId());
		cTaskPerson.setReadStatus(0L);
		cTaskPerson.setType(TaskPersonTypeEnum.CREATEPERSON.getValue());
		list.add(cTaskPerson);

		List<Long> personIds = taskWorkVo.getPersonIds();
		for (Long personId : personIds) {
			TaskPerson taskPerson = new TaskPerson();
			taskPerson.setTaskId(task.getId());
			taskPerson.setPersonId(personId);
			taskPerson.setReadStatus(1L);
			taskPerson.setType(TaskPersonTypeEnum.OTHER.getValue());
			list.add(taskPerson);
		}
		iTaskPersonService.saveBatch(list);

		List<TaskWorkAttachment> attachments = new ArrayList<TaskWorkAttachment>();
		List<String> photos = taskWorkVo.getPhotos();
		for (String path : photos) {
			TaskWorkAttachment taskWorkAttachment = new TaskWorkAttachment();
			taskWorkAttachment.setPath(path);
			taskWorkAttachment.setTaskWorkId(taskWork.getId());
			taskWorkAttachment.setType(AttachmentTypeEnum.PHOTO.getValue());
			attachments.add(taskWorkAttachment);
		}
		List<String> videos = taskWorkVo.getVideos();
		for (String path : videos) {
			TaskWorkAttachment taskWorkAttachment = new TaskWorkAttachment();
			taskWorkAttachment.setPath(path);
			taskWorkAttachment.setTaskWorkId(taskWork.getId());
			taskWorkAttachment.setType(AttachmentTypeEnum.VIDEO.getValue());
			attachments.add(taskWorkAttachment);
		}
		List<String> files = taskWorkVo.getFiles();
		for (String path : files) {
			TaskWorkAttachment taskWorkAttachment = new TaskWorkAttachment();
			taskWorkAttachment.setPath(path);
			taskWorkAttachment.setTaskWorkId(taskWork.getId());
			taskWorkAttachment.setType(AttachmentTypeEnum.FILE.getValue());
			attachments.add(taskWorkAttachment);
		}
		iTaskWorkAttachmentService.saveBatch(attachments);
		return true;
	}

	@Override
	public TaskWorkVo getDetailById(Long id) {
		TaskWorkVo taskWorkVo = new TaskWorkVo();
		TaskWork taskWork = this.getById(id);
		BeanUtils.copyProperties(taskWork, taskWorkVo);
		Person person = iPersonService.getById(taskWork.getCreatePersonId());
		taskWorkVo.setCreatePersonName(person != null ? person.getName() : null);
		Project project = iProjectService.getById(taskWork.getProjectId());
		taskWorkVo.setProjectName(project != null ? project.getName() : null);
		List<TaskPerson> tpersons = iTaskPersonService
				.list(new LambdaQueryWrapper<TaskPerson>().eq(TaskPerson::getTaskId, taskWork.getTaskId())
						.eq(TaskPerson::getType, TaskPersonTypeEnum.OTHER.getValue()));
		List<Long> ids = tpersons.stream().map(i -> i.getPersonId()).collect(Collectors.toList());
		if (!ids.isEmpty()) {
			List<Person> persons = iPersonService.list(new LambdaQueryWrapper<Person>().in(Person::getId, ids));
			taskWorkVo.setPersons(persons);
		}
		List<TaskWorkAttachment> list1 = iTaskWorkAttachmentService
				.list(new LambdaQueryWrapper<TaskWorkAttachment>().eq(TaskWorkAttachment::getTaskWorkId, id)
						.eq(TaskWorkAttachment::getType, AttachmentTypeEnum.PHOTO.getValue()));
		List<String> photos = list1.stream().map(i -> fileServerUrl + i.getPath()).collect(Collectors.toList());
		taskWorkVo.setPhotos(photos);
		List<TaskWorkAttachment> list2 = iTaskWorkAttachmentService
				.list(new LambdaQueryWrapper<TaskWorkAttachment>().eq(TaskWorkAttachment::getTaskWorkId, id)
						.eq(TaskWorkAttachment::getType, AttachmentTypeEnum.VIDEO.getValue()));
		List<String> videos = list2.stream().map(i -> fileServerUrl + i.getPath()).collect(Collectors.toList());
		taskWorkVo.setVideos(videos);
		List<TaskWorkAttachment> list3 = iTaskWorkAttachmentService
				.list(new LambdaQueryWrapper<TaskWorkAttachment>().eq(TaskWorkAttachment::getTaskWorkId, id)
						.eq(TaskWorkAttachment::getType, AttachmentTypeEnum.FILE.getValue()));
		List<String> files = list3.stream().map(i -> fileServerUrl + i.getPath()).collect(Collectors.toList());
		taskWorkVo.setFiles(files);
		return taskWorkVo;
	}

	@Override
	public IPage<TaskWorkVo> page(StudioPageableDto pageable, TaskWorkVo taskWorkVo) {
		if (pageable.getIsAll() == 1) {
			pageable.setCurrent(0);
			pageable.setSize(Integer.MAX_VALUE);
		}
		if (!StringUtils.isEmpty(taskWorkVo.getSort())) {
			String[] s = taskWorkVo.getSort().split(",");
			taskWorkVo.setSortName(s[0]);
			taskWorkVo.setSortOrder(s[1]!=null?s[1].replace("end", ""):null);
		}
		Page<TaskWorkVo> page = new Page<>(pageable.getCurrent(), pageable.getSize());
		return this.baseMapper.page(page, taskWorkVo);
	}
}
