/*
 * Author: wangjian
 * 生成ServiceImpl
 */
package com.tofly.gpsboot.service.maintain.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tofly.api.UserClent;
import com.tofly.common.oauth.exception.ToflyDeniedException;
import com.tofly.common.oauth.util.SecurityUtils;
import com.tofly.gpsboot.common.Constant;
import com.tofly.gpsboot.common.system.DispatchStatusEnum;
import com.tofly.gpsboot.common.system.FileTableEnum;
import com.tofly.gpsboot.exception.BusinessException;
import com.tofly.gpsboot.mapper.maintain.EventMangeMapper;
import com.tofly.gpsboot.service.comm.IFileInfoService;
import com.tofly.gpsboot.service.maintain.DispatchService;
import com.tofly.gpsboot.service.maintain.EventMangeService;
import com.tofly.gpsboot.util.ToflyJsonUtil;
import com.tofly.pojo.User;
import com.tofly.pojo.maintain.Dispatch;
import com.tofly.pojo.maintain.EventMange;
import com.tofly.pojo.maintain.dto.EventMangeDto;
import com.tofly.pojo.maintain.vo.DispatchVo;
import com.tofly.pojo.maintain.vo.EventMangeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 
 *
 * @author wangzhun
 * @date Wed May 11 00:00:00 CST 2022
 */
@Service("eventMangeService")
public class EventMangeServiceImpl extends ServiceImpl<EventMangeMapper, EventMange> implements EventMangeService {
@Autowired
private UserClent userClent;
@Autowired
private  IFileInfoService fileInfoService;
@Autowired
private IFileInfoService iFileInfoService;
@Autowired
private DispatchService dispatchService;
    @Value("${xrty.ftp.eventMange}")
    private String eventMangeFilePath;

    public List<EventMangeVo> viewConversion(List<EventMange> infoList) {
        List<EventMangeVo> infoVoList = new ArrayList<>();
        infoList.forEach(info ->{
            EventMangeVo eventMangeVo = JSONObject.parseObject(JSON.toJSONString(info),EventMangeVo.class);
            // 人员查询
            String reciveUser = info.getReciveUser();

            List<Map> userListMap= findUserByIds(reciveUser);
            eventMangeVo.setReciveUserMap(userListMap);
            if (!StringUtils.isEmpty(info.getUploadFileids())) {
                eventMangeVo.setFilePathList(iFileInfoService.getFilePathList(Arrays.stream(info.getUploadFileids().split(Constant.CSV)).map(s -> Long.parseLong(s.trim()))
                        .collect(Collectors.toList())));
            }
            //查询该时间 是否有派工信息
            Dispatch one = dispatchService.getOne(Wrappers.<Dispatch>lambdaQuery()
                    .eq(Dispatch::getType, "1").eq(Dispatch::getSourceId, eventMangeVo.getId()));
            if(null !=one){
                DispatchVo dispatchVo = ToflyJsonUtil.fromObjectToEntity(one, DispatchVo.class);

                if(null !=dispatchVo.getResolveFileIds()){
                    dispatchVo.setFilePathList(iFileInfoService.getFilePathList(Arrays.stream(dispatchVo.getResolveFileIds().split(Constant.CSV)).map(s -> Long.parseLong(s.trim()))
                            .collect(Collectors.toList())));
                }

                eventMangeVo.setDispatchVo(dispatchVo);
            }

            infoVoList.add(eventMangeVo);



        });
        return infoVoList;
    }



    @Override
    public EventMangeDto saveEventMange(List<MultipartFile> fileList, EventMangeDto eventMangeDto) throws BusinessException {

        StringBuilder fileIds=null;
        try {
            if (!fileList.isEmpty()) {
                fileIds = fileInfoService.saveFileList(fileList, eventMangeFilePath, FileTableEnum.TF_YWPN_EVENT_MANGE.getTableName());
                eventMangeDto.setUploadFileids(fileIds.toString());
            }
        }catch (Exception e){
            throw new ToflyDeniedException(e.getMessage() + ":文件上传失败");
        }
        EventMange eventMange = new EventMange();
        BeanUtils.copyProperties(eventMangeDto,eventMange);
        fillPara(eventMange);
        eventMange.setStatus(DispatchStatusEnum.UNDISPATCH.getCode());
        this.save(eventMange);
        eventMangeDto.setId(eventMange.getId());



        return  eventMangeDto;
    }
    //未传输发现人员信息的 时候 自动填充信息
    private void fillPara(EventMange eventMange) {
        if(null ==eventMange.getFindUser()){
            Long userId = SecurityUtils.getUserId();
            User result = userClent.getById(userId).getResult();
            eventMange.setFindUser(userId+"");
            eventMange.setFindPhone(result.getPhone());
            eventMange.setFindDate(new Date());
        }


    }

    @Override
    public EventMangeDto updateEventMangeById(List<MultipartFile> fileList, EventMangeDto eventMangeDto) throws BusinessException {

        StringBuilder fileIds=null;
        try {
            if (!fileList.isEmpty()) {
                //保存新添加的file
                fileIds = fileInfoService.saveFileList(fileList, eventMangeFilePath, FileTableEnum.TF_YWPN_EVENT_MANGE.getTableName());
                String s = fileIds.toString();
                String oldFile ="";
                if(!StringUtils.isEmpty(oldFile=eventMangeDto.getUploadFileids())){
                    oldFile = oldFile+","+s;
                }

                eventMangeDto.setUploadFileids(oldFile);
            }
        }catch (Exception e){
            throw new ToflyDeniedException(e.getMessage() + ":文件上传失败");
        }
        EventMange eventMange = new EventMange();
        BeanUtils.copyProperties(eventMangeDto,eventMange);

        this.updateById(eventMange);


        return  eventMangeDto;
    }

    List<Map> findUserByIds(String ids){
        if(StringUtils.isEmpty(ids)){
            return  Collections.emptyList();
        }
        return baseMapper.findEventMangeUser(ids);
    }


}
