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

import com.fasterxml.jackson.core.type.TypeReference;
import com.tykj.dev.device.file.entity.FileRet;
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.task.subject.vo.TaskUserVo;
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.entity.vo.WorkHandoverVo;
import com.tykj.dev.device.train.service.TrainTaskService;
import com.tykj.dev.device.train.service.WorkHandoverService;
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.service.UnitsService;
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 com.tykj.dev.misc.utils.StringSplitUtil;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collector;
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
    WorkHandoverDao workHandoverDao;

    @Autowired
    TrainTaskService trainTaskService;

    @Autowired
    UserService userService;

    @Autowired
    UnitsService unitsService;

    @Autowired
    WorkHandoverDevDao workHandoverDevDao;

    @Override
    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);
        Integer id=workHandover.getWorkHandoverId();
        List<WorkHandoverDev> workHandoverDevs=workHandoverAddVo.getWorkHandoverDevices();
        workHandoverDevs.forEach(
                workHandoverDev -> workHandoverDev.setWordId(id)
        );
        workHandoverDevDao.saveAll(workHandoverDevs);
        List<Integer> integers = new ArrayList<>();
        integers.add(securityUser.getCurrentUserInfo().getUserId());
        taskService.start(new TaskBto(StatusEnum.WORKHANDOVER1011.id, "工作交接", null, null, workHandover.getWorkHandoverId(), BusinessEnum.WORK_HANDOVER.id, securityUser.getCurrentUserInfo().getUnitsId(), 0, null, integers));

        return workHandover;
    }

    @Override
    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<>();
        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)
        );
        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);
    }
}
