/*
 * 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.gpsboot.common.Constant;
import com.tofly.gpsboot.common.system.FileTableEnum;
import com.tofly.gpsboot.mapper.maintain.DispatchMapper;
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.service.maintain.FloodSeasonWService;
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.FloodSeasonW;
import com.tofly.pojo.maintain.vo.DispatchVo;
import com.tofly.pojo.maintain.vo.EventMangeVo;
import com.tofly.pojo.maintain.vo.FloodSeasonWVo;
import com.tofly.pojo.maintain.vo.UserViewVo;
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("dispatchService")
public class DispatchServiceImpl extends ServiceImpl<DispatchMapper, Dispatch> implements DispatchService {
    @Autowired
    private UserClent userClent;
    @Autowired
    private EventMangeService eventMangeService;
    @Autowired
    private FloodSeasonWService floodSeasonWService;
    @Autowired
    private IFileInfoService fileInfoService;
    @Value("${xrty.ftp.dispatch}")
    private String dispatchFilePath;
    @Override
    public  DispatchVo  entityToVo(Dispatch dispatch){
        DispatchVo dispatchVo = JSONObject.parseObject(JSON.toJSONString(dispatch),DispatchVo.class);
        // 处理人

        List<UserViewVo> userByIds = findUserByIds(dispatch.getMajorHandler());
        //只有一个人员
        if(userByIds!=null && userByIds.size()>0){
            dispatchVo.setMajorUserHandle(userByIds.get(0));
        }

        List<UserViewVo> userByIds1 = findUserByIds(dispatch.getCollaborateHanler());

        dispatchVo.setCollaborateHandlers(userByIds1);

        if("1".equals(dispatchVo.getType())){

            EventMange byId = eventMangeService.getById(dispatchVo.getSourceId());

            dispatchVo.setEventMangeVo(ToflyJsonUtil.fromObjectToEntity(byId,EventMangeVo.class));
        }else if("2".equals(dispatchVo.getType())){
            FloodSeasonW byId = floodSeasonWService.getById(dispatchVo.getSourceId());
            dispatchVo.setFloodSeasonWVo(ToflyJsonUtil.fromObjectToEntity(byId, FloodSeasonWVo.class));
        }

        if (!StringUtils.isEmpty(dispatch.getResolveFileIds())) {
            dispatchVo.setFilePathList(fileInfoService.getFilePathList(Arrays.stream(dispatch.getResolveFileIds().split(Constant.CSV)).map(s -> Long.parseLong(s.trim()))
                    .collect(Collectors.toList())));
        }


        return  dispatchVo;
    }

    /**
     * 检查事件或者汛情 是否已经派过工
     * @param dispatch
     * @return
     */
    @Override
    public Boolean checkHasDispatched(Dispatch dispatch) {

        int count = super.count((Wrappers.<Dispatch>lambdaQuery()
                .eq(Dispatch::getSourceId, dispatch.getSourceId())
                .eq(Dispatch::getType,dispatch.getType())
                .eq(Dispatch::getDelFlag, "0")
        ));

        return count>0?Boolean.TRUE:Boolean.FALSE;
    }

    @Override
    public void checkStatusChange(Dispatch dispatch) {
        //原始状态为      1待处理  2正在处理  3 已处理
        //状态变更  只能增量变更
        //获取原始状态

        Dispatch byId = this.getById(dispatch.getId());

        if(byId.getStatus().compareTo(dispatch.getStatus())>0){
            throw new  ToflyDeniedException("状态变更规则不符合，变更状态为  待处理->正在处理->已处理");
        }

    }

    @Override
    public void uploadFile(Dispatch dispatch, List<MultipartFile> fileList) {

        StringBuilder fileIds=null;
        try {
            if (!fileList.isEmpty()) {
                //保存新添加的file
                fileIds = fileInfoService.saveFileList(fileList, dispatchFilePath, FileTableEnum.TF_YWPN_DISPATCH.getTableName());
                dispatch.setResolveFileIds(fileIds.toString());
            }
        }catch (Exception e){
            throw new ToflyDeniedException(e.getMessage() + ":文件上传失败");
        }
    }

    List<UserViewVo> findUserByIds(String ids){
        if(StringUtils.isEmpty(ids)){
            return  Collections.emptyList();
        }
        List<UserViewVo> list = new ArrayList<>();
        String[] splitIds = ids.split(",");
        if(splitIds!=null && splitIds.length>0){
            for (String  splitId:splitIds){
                UserViewVo userViewVo = new UserViewVo();
                User result = userClent.getById(Long.parseLong(splitId)).getResult();
                if(result!=null){
                    userViewVo.setId(result.getId());
                    userViewVo.setUserName(result.getRealName());
                    userViewVo.setPhone(result.getPhone());
                    list.add(userViewVo);
                }

            }
        }
        return  list;
    }
}
