package com.tykj.dev.device.train.service.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.tykj.dev.device.file.service.FilesUtil;
import com.tykj.dev.device.task.service.TaskService;
import com.tykj.dev.device.task.subject.bto.TaskBto;
import com.tykj.dev.device.train.dao.WorkHandoverDao;
import com.tykj.dev.device.train.dao.WorkHandoverDevDao;
import com.tykj.dev.device.train.entity.WorkHandover;
import com.tykj.dev.device.train.entity.WorkHandoverDev;
import com.tykj.dev.device.train.entity.vo.WorkHandoverAddVo;
import com.tykj.dev.device.train.entity.vo.WorkHandoverEndAddVo;
import com.tykj.dev.device.train.entity.vo.WorkHandoverUserVo;
import com.tykj.dev.device.train.service.TrainTaskService;
import com.tykj.dev.device.train.service.WorkHandoverService;
import com.tykj.dev.device.user.read.service.MessageService;
import com.tykj.dev.device.user.read.subject.bto.MessageBto;
import com.tykj.dev.device.user.subject.entity.SecurityUser;
import com.tykj.dev.device.user.subject.entity.User;
import com.tykj.dev.device.user.subject.entity.UserLog;
import com.tykj.dev.device.user.subject.service.UnitsService;
import com.tykj.dev.device.user.subject.service.UserLogService;
import com.tykj.dev.device.user.subject.service.UserService;
import com.tykj.dev.misc.base.BusinessEnum;
import com.tykj.dev.misc.base.StatusEnum;
import com.tykj.dev.misc.exception.ApiException;
import com.tykj.dev.misc.utils.JacksonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * @author zjm
 * @version 1.0.0
 * @ClassName WorkHandoverServiceImpl.java
 * @Description TODO
 * @createTime 2020年09月17日 16:09:00
 */
@Service
@Slf4j
public class WorkHandoverServiceImpl implements WorkHandoverService {
    @Autowired
    TaskService taskService;

    @Autowired
    UserLogService userLogService;

    @Autowired
    WorkHandoverDao workHandoverDao;

    @Autowired
    TrainTaskService trainTaskService;

    @Autowired
    UserService userService;

    @Autowired
    MessageService messageService;

    @Autowired
    UnitsService unitsService;

    @Autowired
    WorkHandoverDevDao workHandoverDevDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public WorkHandover createWorkHandover(WorkHandoverAddVo workHandoverAddVo, SecurityUser securityUser) {
        log.info("[workHandover] 新建工作交接");
//        WorkHandover
        WorkHandover workHandover=new WorkHandover();

        if (workHandoverAddVo.getInUserName()!=null) {
            workHandover.setInUserName(workHandoverAddVo.getInUserName());
        }
        if (workHandoverAddVo.getLeadershipName()!=null) {
            workHandover.setLeadershipName(workHandoverAddVo.getLeadershipName());
        }
        workHandover.setWorkHandoverUsers(JacksonUtil.toJSon(workHandoverAddVo.getWorkHandoverUserVoList()));
        workHandover.setStatus(1);
        workHandover.setInitiateUserId(securityUser.getCurrentUserInfo().getUserId());
        //创建workHandoverDB 存储数据库
        workHandover = workHandoverDao.save(workHandover);
        List<Integer> integers = new ArrayList<>();
        integers.add(securityUser.getCurrentUserInfo().getUserId());
        TaskBto taskBto= taskService.start(new TaskBto(StatusEnum.WORKHANDOVER1011.id, "工作交接", null, null, workHandover.getWorkHandoverId(), BusinessEnum.WORK_HANDOVER.id, securityUser.getCurrentUserInfo().getUnitsId(), 0, null, integers));
        addMessage(new MessageBto(taskBto.getId(),taskBto.getBusinessType(),"发起工作交接业务",gainThisUser(securityUser.getCurrentUserInfo().getUserId(),securityUser.getCurrentUserInfo().getUnitsId()),workHandover.getWorkHandoverId().toString()));
        return workHandover;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public WorkHandover endWorkHandover(WorkHandoverEndAddVo workHandoverEndAddVo) {
        //更新workHamdoverDb状态
        WorkHandover workHandover;
        Optional<WorkHandover> workHandoverOptional = workHandoverDao.findById(workHandoverEndAddVo.getWorkHandoverId());
        if (workHandoverOptional.isPresent()) {
            workHandover = workHandoverOptional.get();
        } else {
            log.info("[WorkHandover] 未找到id：{} 工作交接业务", workHandoverEndAddVo.getWorkHandoverId());
            throw new ApiException(ResponseEntity.status(500).body("未找到id为" + workHandoverEndAddVo.getWorkHandoverId() + " 工作交接业务"));
        }
        workHandover.setInUserName(workHandoverEndAddVo.getInUserName());
        workHandover.setLeadershipName(workHandoverEndAddVo.getLeadershipName());
        workHandover.setStatus(2);
        workHandover.setFile(FilesUtil.stringFileToList(workHandoverEndAddVo.getFileLists()));
        workHandover = workHandoverDao.save(workHandover);
        //把移交人的所有代办任务和跟踪任务替换名称，换成交接人
        //推入完结状态
        TaskBto taskBto = trainTaskService.selectFatherIsNullAndBillidAndBillType(workHandover.getWorkHandoverId(), BusinessEnum.WORK_HANDOVER.id);
        taskService.moveToEnd(taskBto);
        //拿到工作交接人员对象组
        List<WorkHandoverUserVo> workHandoverUserVoList=JacksonUtil.readValue(workHandover.getWorkHandoverUsers(), new TypeReference<List<WorkHandoverUserVo>>() {});
        List<Integer> integerList=new ArrayList<>();
        if (workHandoverUserVoList != null) {
            workHandoverUserVoList.forEach(
                    workHandoverUserVo -> workHandoverUserVo.getHandoverUserIds().forEach(
                            integerId ->{
                                integerList.add(integerId);
                                taskService.workHandover(integerId,workHandoverUserVo.getTurnOverUserIds());
                            }
                    )
            );
        }
        //把交接人账号状态改为冻结
        List<User> users= userService.findAllUserIdInUser(integerList);
        users.forEach(
                user -> {
                    user.setIsDel(1);
                    userLogService.save(new UserLog(user.getUserId(),new Date(),"交接成功完成，账号冻结"));
                }
        );
        //保存装备信息列表
        Integer id=workHandover.getWorkHandoverId();
        List<WorkHandoverDev> workHandoverDevs=workHandoverEndAddVo.getWorkHandoverDevices();
        workHandoverDevs.forEach(
                workHandoverDev -> workHandoverDev.setWordId(id)
        );
        workHandoverDevDao.saveAll(workHandoverDevs);
        userService.saveAll(users);
        return workHandover;
    }

    @Override
    public WorkHandover findById(Integer workHandoverId) {
        Optional<WorkHandover> optionalWorkHandover = workHandoverDao.findById(workHandoverId);
        if (optionalWorkHandover.isPresent()) {
            WorkHandover workHandover = optionalWorkHandover.get();
            workHandover.setFileRets(FilesUtil.stringFileToList(workHandover.getFile()));
            workHandover.setWorkHandoverDevs(workHandoverDevDao.findAllByWordId(workHandover.getWorkHandoverId()));
            workHandover.setWorkHandoverUserVoList(JacksonUtil.readValue(workHandover.getWorkHandoverUsers(), new TypeReference<List<WorkHandoverUserVo>>() {}));
            workHandover.getWorkHandoverUserVoList().forEach(
                    workHandoverUserVo -> {
                        workHandoverUserVo.setTurnOverUser(userService.findByUser(workHandoverUserVo.getTurnOverUserIds()));
                        workHandoverUserVo.setHandoverUsers(userService.findAllUserIdInUser(workHandoverUserVo.getHandoverUserIds()));
                    }
            );
            return workHandover;
        } else {
            throw new ApiException(ResponseEntity.status(500).body("没有这个id:" + workHandoverId));
        }
    }

    @Override
    public List<User> handedList(SecurityUser securityUser) {
        return userService.findAllByUnite(securityUser.getCurrentUserInfo().getUnitsId());
    }

    @Override
    public List<User> handover(List<Integer> userIds) {

        return userService.findAllUserIdInUser(userIds);
    }

    private void addMessage(MessageBto messageBto){
        messageService.add(messageBto);
    }

    /**
     * 根据单位id查询用户 去除用户id
     * @param userId
     * @param unitId
     * @return
     */
    private List<Integer> gainThisUser(Integer userId,Integer unitId){
        return userService.findAllByUnite(unitId).stream().filter(user -> !user.getUserId().equals(userId)).map(User::getUserId).collect(Collectors.toList());
    }

    /**
     * 根据单位id查询用户id集合
     * @param unitId
     * @return
     */
    private List<Integer> findUnitId(Integer unitId){
        return userService.findAllByUnite(unitId).stream().map(User::getUserId).collect(Collectors.toList());
    }
}
