package cn.iocoder.yudao.module.pms.service.inspect;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.pms.controller.admin.inspect.plan.vo.IotInspectPlanPageReqVO;
import cn.iocoder.yudao.module.pms.controller.admin.inspect.plan.vo.IotInspectPlanSaveReqVO;
import cn.iocoder.yudao.module.pms.controller.admin.inspect.route.vo.IotInspectRouteRespVO;
import cn.iocoder.yudao.module.pms.dal.dataobject.inspect.IotInspectPlanDO;
import cn.iocoder.yudao.module.pms.dal.mysql.inspect.IotInspectPlanMapper;
import cn.iocoder.yudao.module.pms.service.IotDeviceService;
import cn.iocoder.yudao.module.system.api.dept.DeptApi;
import cn.iocoder.yudao.module.system.api.dept.dto.DeptRespDTO;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.service.dept.DeptService;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.pms.enums.ErrorCodeConstant.IOT_INSPECT_PLAN_NOT_EXISTS;

/**
 * 巡检计划 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class IotInspectPlanServiceImpl implements IotInspectPlanService {

    @Resource
    private IotInspectPlanMapper iotInspectPlanMapper;
    @Autowired
    private AdminUserApi adminUserApi;
    @Resource
    private DeptService deptService;
    @Autowired
    private IotDeviceService iotDeviceService;
    @Autowired
    private DeptApi deptApi;

    @Override
    public void updateInspectPlanStatus(Long id, Integer status) {
        IotInspectPlanDO iotInspectPlanDO = iotInspectPlanMapper.selectById(id).setStatus(status);
        iotInspectPlanMapper.updateById(iotInspectPlanDO);
    }

    @Override
    public Long createIotInspectPlan(IotInspectPlanSaveReqVO createReqVO) {
        // 插入
        IotInspectPlanDO iotInspectPlan = BeanUtils.toBean(createReqVO, IotInspectPlanDO.class);
        iotInspectPlan.setDeleted(false);
        iotInspectPlan.setStatus(0);
        iotInspectPlan.setPlanCode("INPL"+ DateUtil.format(new Date(), "yyyyMMddHHmmss"));
//        iotInspectPlan.setCharge(String.join(",", createReqVO.getCharges()));
        List<Long> collect = createReqVO.getCharges().stream().map(Long::valueOf).collect(Collectors.toList());
//        String collect1 = adminUserApi.getUserList(collect).stream().map(AdminUserRespDTO::getNickname).collect(Collectors.joining(","));
//        iotInspectPlan.setChargeName(collect1);
        iotInspectPlanMapper.insert(iotInspectPlan);
        //创建定时任务
        // 返回
        return iotInspectPlan.getId();
    }

    @Override
    public void updateIotInspectPlan(IotInspectPlanSaveReqVO updateReqVO) {
        // 校验存在
        validateIotInspectPlanExists(updateReqVO.getId());
        // 更新
        IotInspectPlanDO updateObj = BeanUtils.toBean(updateReqVO, IotInspectPlanDO.class);
        //updateObj.setCharge(String.join(",", updateReqVO.getCharges()));
//        List<Long> collect = updateReqVO.getCharges().stream().map(Long::valueOf).collect(Collectors.toList());
//        String collect1 = adminUserApi.getUserList(collect).stream().map(AdminUserRespDTO::getNickname).collect(Collectors.joining(","));
//        updateObj.setChargeName(collect1);
        iotInspectPlanMapper.updateById(updateObj);
    }

    @Override
    public void deleteIotInspectPlan(Long id) {
        // 校验存在
        validateIotInspectPlanExists(id);
        // 删除
        iotInspectPlanMapper.deleteById(id);
    }

    private void validateIotInspectPlanExists(Long id) {
        if (iotInspectPlanMapper.selectById(id) == null) {
            throw exception(IOT_INSPECT_PLAN_NOT_EXISTS);
        }
    }

    @Override
    public IotInspectPlanDO getIotInspectPlan(Long id) {
        return iotInspectPlanMapper.selectById(id);
    }

    @Override
    public PageResult<IotInspectPlanDO> getIotInspectPlanPage(IotInspectPlanPageReqVO pageReqVO) {
        Set<Long> ids = new HashSet<>();
        if (Objects.nonNull(pageReqVO.getDeptId())) {
            ids = deptService.getChildDeptIdListFromCache(pageReqVO.getDeptId());
            ids.add(pageReqVO.getDeptId());
        }
        return iotInspectPlanMapper.selectPage(pageReqVO, ids);
    }

    /**
     * 设备调拨后修改巡检计划
     * @param deviceIds 多个设备
     * @param deptId 调拨后部门id
     */
    @Override
    public void syncInspectPlanData(List<Long> deviceIds, Long deptId) {
        deviceIds.forEach(e ->{
            //设备为瑞恒的话进行该调整
            String deviceCompany = iotDeviceService.getDeviceCompany(e);
            if ("rh".equals(deviceCompany)) {
                String device = "\"deviceId\":"+e;
                List<IotInspectPlanDO> listByJsonDeviceId = iotInspectPlanMapper.getListByJsonDeviceId(device);
                //遍历巡检计划
                AtomicReference<IotInspectRouteRespVO> iotInspectRouteDO = new AtomicReference<>(new IotInspectRouteRespVO());
                listByJsonDeviceId.forEach(f ->{
                    List<IotInspectRouteRespVO> routeDOS = JSON.parseArray(f.getDeviceIds(), IotInspectRouteRespVO.class);
                    List<IotInspectRouteRespVO> collect = routeDOS.stream().filter(g -> !e.equals(g.getDeviceId())).collect(Collectors.toList());
                    routeDOS.stream().filter(g -> e.equals(g.getDeviceId())).findFirst().ifPresent(iotInspectRouteDO::set);
                    //更新巡检计划的巡检明细
                    f.setDeviceIds(JSON.toJSONString(collect));
                    iotInspectPlanMapper.updateById(f);
                });
                //往新的队伍中添加该设备
                if (CollUtil.isNotEmpty(listByJsonDeviceId)) {
                    List<IotInspectPlanDO> targetPlan = iotInspectPlanMapper.selectList("dept_id", deptId);
                    if (CollUtil.isNotEmpty(targetPlan)) {
                        IotInspectPlanDO iotInspectPlanDO = targetPlan.get(0);
                        List<IotInspectRouteRespVO> routeDOS = JSON.parseArray(iotInspectPlanDO.getDeviceIds(), IotInspectRouteRespVO.class);
                        if (Objects.nonNull(iotInspectRouteDO.get())){
                            IotInspectRouteRespVO iotInspectRouteRespVO = iotInspectRouteDO.get();
                            iotInspectRouteRespVO.setDeptId(deptId);
                            DeptRespDTO dept = deptApi.getDept(deptId);
                            if (Objects.nonNull(dept)){
                                iotInspectRouteRespVO.setDeptName(dept.getName());
                            }
                            routeDOS.add(iotInspectRouteRespVO);
                        }
                        //更新巡检计划的巡检明细
                        iotInspectPlanDO.setDeviceIds(JSON.toJSONString(routeDOS));
                        iotInspectPlanMapper.updateById(iotInspectPlanDO);
                    }
                }
            }
        });
    }

}
