package com.ho.flow.service.impl;

import com.ho.common.tools.constant.CommonConstant;
import com.ho.common.tools.exception.BaseResponseCode;
import com.ho.common.tools.exception.BusinessException;
import com.ho.flow.entity.WorkOrderPlan;
import com.ho.flow.entity.WorkOrderPlanSub;
import com.ho.flow.entity.WorkOrderSub;
import com.ho.flow.feignclient.BusinessFeignClient;
import com.ho.flow.feignclient.UserFeignClient;
import com.ho.flow.mapper.WorkOrderPlanMapper;
import com.ho.flow.mapper.WorkOrderPlanSubMapper;
import com.ho.flow.service.ProcessFlowService;
import com.ho.flow.service.WorkOrderPlanService;
import com.ho.flow.vo.req.workorderplan.WorkOrderPlanAddReqVO;
import com.ho.flow.vo.req.workorderplan.WorkOrderPlanReqVO;
import com.ho.flow.vo.resp.workorderplan.WorkOrderPlanRespVO;
import com.ho.user.api.vo.req.QueryUserReqVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * @Description 工单计划实现类
 * Author yule
 * Date 2023/3/16 15:53
 */
@Service
@Slf4j
public class WorkOrderPlanServiceImpl implements WorkOrderPlanService {

    @Autowired
    WorkOrderPlanMapper workOrderPlanMapper;

    @Autowired
    WorkOrderPlanSubMapper workOrderPlanSubMapper;

    @Autowired
    BusinessFeignClient businessFeignClient;

    @Autowired
    UserFeignClient userFeignClient;

    @Autowired
    ProcessFlowService processFlowService;

    @Override
    @Transactional
    public void add(WorkOrderPlanAddReqVO vo) {
        int i = workOrderPlanMapper.insertSelective(vo);
        if (i < 0){
            throw new BusinessException(BaseResponseCode.WORK_ORDER_PLAN_ADD_ERROR);
        }
        //新增子表数据
        addWorkOrderPlanSub(vo);
        //新增工单数据
        //查询计划执行人(所有类型)
        List<WorkOrderPlanSub> workOrderPlanSubs = workOrderPlanSubMapper.selectByPid(vo.getId());
        List<String> userIds = workOrderPlanSubs.stream().filter(s -> {
            return CommonConstant.WorkOrderPlanSubType.PERSON.equals(s.getType());
        }).map(WorkOrderPlanSub::getUserId).collect(Collectors.toList());
        //查询出电站以及设备的子表数据
        List<WorkOrderSub> workOrderSubs = workOrderPlanSubs.stream().filter(s -> {
            return !CommonConstant.WorkOrderPlanSubType.PERSON.equals(s.getType());
        }).map(s -> {
            WorkOrderSub workOrderSub = new WorkOrderSub();
            BeanUtils.copyProperties(s, workOrderSub);
            workOrderSub.setSrcId(s.getSrcId().longValue());
            return workOrderSub;
        }).collect(Collectors.toList());
        processFlowService.planAddWorkOrder(vo, userIds, workOrderSubs);
    }

    @Override
    @Transactional
    public void delete(WorkOrderPlanReqVO vo) {
        //先删除工单计划数据
        int i = workOrderPlanMapper.deleteByPrimaryKey(vo.getId());
        if (i < 0){
            throw new BusinessException(BaseResponseCode.WORK_ORDER_PLAN_DELETED_ERROR);
        }
        //再删除工单计划子表数据
        int count = workOrderPlanSubMapper.deleteByPid(vo.getId());
        if (count < 0){
            throw new BusinessException(BaseResponseCode.WORK_ORDER_PLAN_DELETED_ERROR);
        }
    }

    @Override
    @Transactional
    public void update(WorkOrderPlanAddReqVO vo) {
        int i = workOrderPlanMapper.updateByPrimaryKeySelective(vo);
        if (i < 0){
            throw new BusinessException(BaseResponseCode.WORK_ORDER_PLAN_UPDATE_ERROR);
        }
        //对于关联子表数据,先删除,在新增
        int j = workOrderPlanSubMapper.deleteByPid(vo.getId());
        if (j < 0){
            throw new BusinessException(BaseResponseCode.WORK_ORDER_PLAN_UPDATE_ERROR);
        }
        //新增子表数据
        addWorkOrderPlanSub(vo);

    }

    @Override
    public WorkOrderPlanRespVO getOne(WorkOrderPlanReqVO vo) {
        //查询工单计划数据
        WorkOrderPlan workOrderPlan = workOrderPlanMapper.selectByPrimaryKey(vo.getId());
        //创建返回值对象
        WorkOrderPlanRespVO respVO = new WorkOrderPlanRespVO();
       setName(workOrderPlan,respVO);
        return respVO;
    }

    @Override
    public List<WorkOrderPlanRespVO> getAll(WorkOrderPlanReqVO vo) {

        //查询全部对象
        List<WorkOrderPlan> list = workOrderPlanMapper.selectByGroupId(vo.getGroupId());

        //创建返回值对象
        List<WorkOrderPlanRespVO> workOrderPlanRespVOList = new ArrayList<>();
        if (!list.isEmpty()) {
            for (WorkOrderPlan workOrderPlan : list) {
                WorkOrderPlanRespVO respVO = new WorkOrderPlanRespVO();
                setName(workOrderPlan,respVO);
                workOrderPlanRespVOList.add(respVO);
            }
        }

        return workOrderPlanRespVOList;
    }


    /**
     *
     */

    /**
     * 新增工单计划子表数据
     * @param vo
     */
    private void addWorkOrderPlanSub(WorkOrderPlanAddReqVO vo){
        //入参中的电站id
        List<Integer> stationIds = vo.getStationIds();
        List<WorkOrderPlanSub> srcList = new ArrayList<>();
        if (stationIds != null) {
            if (!stationIds.isEmpty()) {
                for (Integer stationId : stationIds) {
                    WorkOrderPlanSub workOrderPlanSub = new WorkOrderPlanSub();
                    workOrderPlanSub.setPid(vo.getId());
                    workOrderPlanSub.setType(CommonConstant.WorkOrderPlanSubType.STATION);
                    workOrderPlanSub.setSrcId(stationId);
                    srcList.add(workOrderPlanSub);
                }
            }
        }
        //入参中的设备id
        List<Integer> deviceIds = vo.getDeviceIds();
        if (deviceIds != null) {
            if (!deviceIds.isEmpty()) {
                for (Integer deviceId : deviceIds) {
                    WorkOrderPlanSub workOrderPlanSub = new WorkOrderPlanSub();
                    workOrderPlanSub.setPid(vo.getId());
                    workOrderPlanSub.setType(CommonConstant.WorkOrderPlanSubType.DEVICE);
                    workOrderPlanSub.setSrcId(deviceId);
                    srcList.add(workOrderPlanSub);
                }
            }
        }
        //批量新增
        int count = workOrderPlanSubMapper.insertBatch(srcList);
        if (count <= 0){
            throw new BusinessException(BaseResponseCode.WORK_ORDER_PLAN_SUB_ADD_ERROR);
        }
        //入参中的用户id
        List<WorkOrderPlanSub> userList = new ArrayList<>();
        List<String> userIds = vo.getUserIds();
        if (userIds != null) {
            if (!userIds.isEmpty()) {
                for (String userId : userIds) {
                    WorkOrderPlanSub workOrderPlanSub = new WorkOrderPlanSub();
                    workOrderPlanSub.setPid(vo.getId());
                    workOrderPlanSub.setType(CommonConstant.WorkOrderPlanSubType.PERSON);
                    workOrderPlanSub.setUserId(userId);
                    userList.add(workOrderPlanSub);
                }
            }
        }
        int i = workOrderPlanSubMapper.insertUserBatch(userList);
        if (i <= 0){
            throw new BusinessException(BaseResponseCode.WORK_ORDER_PLAN_SUB_ADD_ERROR);
        }
    }

    /**
     * 给计划工单设置设备名字和电站名字
     * @param workOrderPlan
     * @param respVO
     */
    private void setName(WorkOrderPlan workOrderPlan,WorkOrderPlanRespVO respVO){
        if (workOrderPlan != null) {
            BeanUtils.copyProperties(workOrderPlan, respVO);
            //查询工单计划所对应的子表数据
            List<WorkOrderPlanSub> list = workOrderPlanSubMapper.selectByPid(workOrderPlan.getId());
            //根据类型进行分组
            Map<Integer, List<WorkOrderPlanSub>> map = list.stream().collect(Collectors.groupingBy(WorkOrderPlanSub::getType));
            //电站类型
            List<WorkOrderPlanSub> stationList = map.get(CommonConstant.WorkOrderPlanSubType.STATION);
            if (stationList != null){
                //获取电站id集合
                List<Integer> stationIds = stationList.stream().map(WorkOrderPlanSub::getSrcId).collect(Collectors.toList());
                respVO.setStationList(stationIds);
             /*   //远程调用通过电站id查询电站
                DataResult<List<Station>> result = businessFeignClient.selectByStationIds(stationIds);
                List<Station> stations = result.getData();
                if (stations != null){
                    List<StationWorkOrder> stationWorkOrderList = stations.stream().map(s -> {
                        StationWorkOrder stationWorkOrder = new StationWorkOrder();
                        stationWorkOrder.setStationId(s.getId());
                        stationWorkOrder.setName(s.getName());
                        return stationWorkOrder;
                    }).collect(Collectors.toList());
                    respVO.setStationList(stationWorkOrderList);
                }*/
            }
            //设备类型
            List<WorkOrderPlanSub> deviceList = map.get(CommonConstant.WorkOrderPlanSubType.DEVICE);
            if (deviceList != null){
                //获取电站id集合
                List<Integer> deviceIds = deviceList.stream().map(WorkOrderPlanSub::getSrcId).collect(Collectors.toList());
                respVO.setDeviceList(deviceIds);
                //远程调用通过电站id查询电站
               /* DataResult<List<Device>> result = businessFeignClient.selectByDeviceIds(deviceIds);
                List<Device> devices = result.getData();
                if (devices != null){
                    List<DeviceWorkOrder> deviceWorkOrderList = devices.stream().map(s -> {
                        DeviceWorkOrder deviceWorkOrder = new DeviceWorkOrder();
                        deviceWorkOrder.setDeviceId(s.getId());
                        deviceWorkOrder.setName(s.getDeviceName());
                        return deviceWorkOrder;
                    }).collect(Collectors.toList());
                    respVO.setDeviceList(deviceWorkOrderList);
                }*/
            }
            //用户类型
            List<WorkOrderPlanSub> userList = map.get(CommonConstant.WorkOrderPlanSubType.PERSON);
            if (userList != null){
                List<QueryUserReqVO> queryUserReqVOS = userList.stream().map(s -> {
                    //把用户id添加到集合中
                    QueryUserReqVO queryUserReqVO = new QueryUserReqVO();
                    queryUserReqVO.setUserId(s.getUserId());
                    return queryUserReqVO;
                }).collect(Collectors.toList());
                List<String> userIds = queryUserReqVOS.stream().map(QueryUserReqVO::getUserId).collect(Collectors.toList());
                respVO.setUserList(userIds);
               /* //远程调用通过用户id查询电站
                DataResult<List<SysUser>> result = userFeignClient.queryUser(queryUserReqVOS);
                List<SysUser> users = result.getData();
                if (users != null){
                    List<UserWorkOrder> userWorkOrderList = users.stream().map(s -> {
                        UserWorkOrder userWorkOrder = new UserWorkOrder();
                        userWorkOrder.setUserId(s.getId());
                        userWorkOrder.setName(s.getRealName());
                        return userWorkOrder;
                    }).collect(Collectors.toList());
                    respVO.setUserList(userWorkOrderList);
                }*/
            }
        }
    }
}
