package com.njcn.harmonic.service.upload.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.harmonic.mapper.upload.RUploadWorkOrderMapper;
import com.njcn.harmonic.pojo.dto.upload.FeedbackInfoDTO;
import com.njcn.harmonic.pojo.param.upload.RUploadWorkOrderParam;
import com.njcn.harmonic.pojo.po.upload.RUploadWorkOrderPO;
import com.njcn.harmonic.service.upload.IRUploadWorkOrderService;
import com.njcn.system.enums.DicDataEnum;
import com.njcn.user.api.DeptFeignClient;
import com.njcn.web.enums.GWSendEnum;
import com.njcn.web.factory.PageFactory;
import com.njcn.web.pojo.param.SendParam;
import com.njcn.web.utils.GwSendUtil;
import com.njcn.web.utils.RequestUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 用于存储总部下发的工单信息 服务实现类
 * </p>
 *
 * @author cdf
 * @since 2024-06-18
 */
@Service
@RequiredArgsConstructor
public class RUploadWorkOrderServiceImpl extends ServiceImpl<RUploadWorkOrderMapper, RUploadWorkOrderPO> implements IRUploadWorkOrderService {

    private final DeptFeignClient deptFeignClient;

    @Override
    public Boolean insertWorkorderDistributeSupervise(RUploadWorkOrderParam param) {
        RUploadWorkOrderPO rUploadWorkOrderPO = new RUploadWorkOrderPO();
        BeanUtil.copyProperties(param,rUploadWorkOrderPO);
        return this.saveOrUpdate(rUploadWorkOrderPO);
    }

    @Override
    public Boolean closeWorkorderDistributeSupervise(RUploadWorkOrderParam param) {
        LambdaUpdateWrapper<RUploadWorkOrderPO> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(RUploadWorkOrderPO::getOrderId,param.getOrderContent()).set(RUploadWorkOrderPO::getClosedLoopTime, LocalDate.now());
        return this.update(updateWrapper);
    }

    @Override
    public Boolean receiveFeedbackInfo(List<String> ids) {
        List<RUploadWorkOrderPO> poList = this.listByIds(ids);
        if(poList.size()>100){
            throw new BusinessException(CommonResponseEnum.FAIL,"最多支持一百条工单同时反馈！");
        }
        long count = poList.stream().filter(item-> Objects.nonNull(item.getClosedLoopTime())).count();
        if(count>0){
            throw new BusinessException(CommonResponseEnum.FAIL,"请选择未完结的工单进行反馈！");
        }

        List<FeedbackInfoDTO> feedbackInfoDTOList = BeanUtil.copyToList(poList, FeedbackInfoDTO.class);
        SendParam sendParam = new SendParam();
        sendParam.setStats(feedbackInfoDTOList);
        Map<String,String> result = GwSendUtil.send(sendParam, GWSendEnum.WORK_ORDER_FEEDBACK);
        GwSendUtil.returnInfoMsg(ids,result);

        List<RUploadWorkOrderPO> newPoList = new ArrayList<>();
        for(RUploadWorkOrderPO rUploadWorkOrderPO : poList){
            RUploadWorkOrderPO newPo = new RUploadWorkOrderPO();
            newPo.setObjId(rUploadWorkOrderPO.getObjId());
            newPo.setFeedbackTime(LocalDate.now());
            newPo.setUploadStatus("1");
            newPo.setOrderStatus(DicDataEnum.WORK_ORDER_STATUS_HAS.getCode());
            newPo.setUploadTime(LocalDate.now());
            newPo.setIsFeedback("1");
            newPoList.add(newPo);
        }
        this.updateBatchById(newPoList);
        return true;
    }

    @Override
    public Page<RUploadWorkOrderPO> pageList(RUploadWorkOrderParam.RUploadWorkOrderQuery query) {

        List<String> deptIds = deptFeignClient.getDepSonSelfCodetByDeptId(query.getMaintainerId()).getData();


        LambdaQueryWrapper<RUploadWorkOrderPO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.between(RUploadWorkOrderPO::getDistributeTime, DateUtil.beginOfDay(DateUtil.parse(query.getSearchBeginTime(), DatePattern.NORM_DATE_PATTERN)),DateUtil.endOfDay(DateUtil.parse(query.getSearchEndTime(), DatePattern.NORM_DATE_PATTERN)))
                .eq(StrUtil.isNotBlank(query.getOrderStatus()),RUploadWorkOrderPO::getOrderStatus,query.getOrderStatus())
                .in(RUploadWorkOrderPO::getMaintainerId,deptIds)

        ;
        return this.page(new Page<>(PageFactory.getPageNum(query),PageFactory.getPageSize(query)),lambdaQueryWrapper);
    }

    @Override
    public Boolean feedBackAdd(RUploadWorkOrderParam param) {
        RUploadWorkOrderPO rUploadWorkOrderPO = new RUploadWorkOrderPO();
        BeanUtil.copyProperties(param,rUploadWorkOrderPO);
        rUploadWorkOrderPO.setObjId(param.getObjId());
        rUploadWorkOrderPO.setIsFeedback("1");
        rUploadWorkOrderPO.setFeedbackUser(RequestUtil.getUserNickname());
        rUploadWorkOrderPO.setFeedbackTime(LocalDate.now());
        rUploadWorkOrderPO.setHandlingMeasures(param.getHandlingMeasures());
        rUploadWorkOrderPO.setOrderStatus(DicDataEnum.WORK_ORDER_STATUS_ING.getCode());
        this.updateById(rUploadWorkOrderPO);
        return true;
    }
}
