package com.jeeplus.business.drive.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeeplus.business.drive.domain.DriveMaintain;
import com.jeeplus.business.drive.mapper.DriveMaintainMapper;
import com.jeeplus.business.drive.service.dto.DriveMaintainDTO;
import com.jeeplus.common.TokenProvider;
import com.jeeplus.core.query.QueryWrapperGenerator;
import com.jeeplus.sys.domain.WorkAttachmentInfo;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.feign.IWorkAttachmentApi;
import com.jeeplus.sys.service.dto.UserDTO;
import com.jeeplus.utils.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.util.*;

import static com.baomidou.mybatisplus.core.toolkit.Wrappers.update;

@Service
public class DriveMaintainService {

    @Resource
    private DriveMaintainMapper driveMaintainMapper;

    /**
     * 车辆维护列表
     * @param driveMaintainDTO
     * @param page
     * @return
     */
    public IPage<DriveMaintainDTO> findPageList(DriveMaintainDTO driveMaintainDTO, Page<DriveMaintainDTO> page) throws Exception {
        QueryWrapper<DriveMaintainDTO> queryWrapper = QueryWrapperGenerator.buildQueryCondition(driveMaintainDTO, DriveMaintainDTO.class);
        queryWrapper.eq("a.del_flag",0);
        //车牌号查询
        if (StringUtils.isNotBlank(driveMaintainDTO.getDriveNumber())){
            queryWrapper.like("di.drive_number",driveMaintainDTO.getDriveNumber());
        }
        //维护类型
        if (StringUtils.isNotBlank(driveMaintainDTO.getDriveMaintainType())){
            queryWrapper.eq("a.drive_maintain_type",driveMaintainDTO.getDriveMaintainType());
        }
        //维护时间
        if (driveMaintainDTO.getDates() != null && driveMaintainDTO.getDates().length>0){
            queryWrapper.between("a.start_time",driveMaintainDTO.getDates()[0],driveMaintainDTO.getDates()[1]).or().between("a.end_time",driveMaintainDTO.getDates()[0],driveMaintainDTO.getDates()[1]);
        }
        IPage<DriveMaintainDTO> pageList=driveMaintainMapper.findPageList(page,queryWrapper);
        return pageList;
    }

    /**
     * 新增或修改
     * @param driveMaintainDTO
     * @return
     */
    public String save(DriveMaintainDTO driveMaintainDTO) {
        if (StringUtils.isNotBlank(driveMaintainDTO.getId())){
            return update(driveMaintainDTO);
        }
        return add(driveMaintainDTO);
    }

    private String add(DriveMaintainDTO driveMaintainDTO){
        DriveMaintain maintainDTO = new DriveMaintain();

        String currentToken = TokenProvider.getCurrentToken();
        //获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(currentToken);

        //id
        String id = UUID.randomUUID().toString().replace("-", "");
        maintainDTO.setId(id);
        maintainDTO.setCreateById(userDTO.getId());
        maintainDTO.setCreateTime(new Date());
        maintainDTO.setUpdateById(userDTO.getId());
        maintainDTO.setUpdateTime(new Date());
        maintainDTO.setDriveInfoId(driveMaintainDTO.getDriveInfoId()); //车辆信息
        maintainDTO.setDriveMaintainType(driveMaintainDTO.getDriveMaintainType()); //维护类型
        maintainDTO.setStartTime(driveMaintainDTO.getStartTime()); //维护开始时间
        maintainDTO.setEndTime(driveMaintainDTO.getEndTime()); //维护结束时间
        maintainDTO.setStatus(driveMaintainDTO.getStatus());
        maintainDTO.setRemarks(driveMaintainDTO.getRemarks());
        driveMaintainMapper.insert(maintainDTO);

        //附件新增
        List<WorkAttachmentInfo> files = driveMaintainDTO.getFiles();
        if (CollectionUtil.isNotEmpty(files)) {
            saveFiles(files, userDTO, id);
        }
        return id;

    }
    /**
     * 保存附件信息
     * @param list 待保存的附件列表
     * @param userDTO 当前登录用户
     * @param id 关联id
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveFiles(List<WorkAttachmentInfo> list, UserDTO userDTO, String id) {
        int j = 1;
        for (WorkAttachmentInfo dto : list) {
            WorkAttachmentInfo i = new WorkAttachmentInfo();
            //包含了url、size、name
            i.setId(java.util.UUID.randomUUID().toString().replace("-", ""));
//            i.getCreateBy().setId(userDTO.getId());
            i.setCreateTime(new Date());
//            i.getUpdateBy().setId(userDTO.getId());
            i.setUpdateTime(new Date());
            i.setDelFlag(0);
            i.setUrl(dto.getUrl());
            //文件类型处理
            List<String> strings = Arrays.asList(dto.getName().split("\\."));
            if (CollectionUtil.isNotEmpty(strings)) {
                i.setType(strings.get(1));
            }
            i.setAttachmentId(id);
            i.setAttachmentName(dto.getName());
            i.setAttachmentFlag("driveMaintain");
            i.setFileSize(dto.getSize());
            i.setSort(j);
            Map<String,String> map = new HashMap<>();
            String workAttachment = JSON.toJSONString((i));
            String userDTOInfo = JSON.toJSONString((userDTO));
            map.put("workAttachment",workAttachment);
            map.put("userDTO",userDTOInfo);
            SpringUtil.getBean ( IWorkAttachmentApi.class ).insertWorkAttachment(map);
            j++;
        }
    }


    private String update(DriveMaintainDTO driveMaintainDTO){
        //获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
        //修改信息
        DriveMaintain driveMaintain = new DriveMaintain();

        BeanUtil.copyProperties(driveMaintainDTO,driveMaintain);

        driveMaintain.setUpdateById(userDTO.getId());
        driveMaintain.setUpdateTime(new Date());
        driveMaintainMapper.updateById(driveMaintain);
        //附件修改
        List<WorkAttachmentInfo> files = driveMaintainDTO.getFiles();
        if (CollectionUtil.isNotEmpty(files)) {
            updateFiles(files, userDTO, driveMaintainDTO.getId());
        }
        return driveMaintainDTO.getId();
    }

    /**
     * 修改附件信息
     * @param list 待修改的附件列表
     * @param userDTO 当前登录用户
     * @param id 关联id
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateFiles(List<WorkAttachmentInfo> list, UserDTO userDTO, String id) {
        int j = 1;
        String names = new String();
        //表中存在，但是传过来不存在，说明已删除，表中数据也要删除
        for (WorkAttachmentInfo dto : list) {
            names = names + "," +dto.getUrl();
        }
        //查询保存的附件信息
        List<WorkAttachmentInfo> infoList = driveMaintainMapper.findList(id);
        if (CollectionUtil.isNotEmpty(infoList)) {
            for (WorkAttachmentInfo i : infoList) {
                if (!names.contains(i.getUrl())) {
                    SpringUtil.getBean ( IWorkAttachmentApi.class ).deleteById(i.getId());
                }
            }
        }
        //保存信息
        for (WorkAttachmentInfo dto : list) {
            //判断是否存在
            Integer isExit = driveMaintainMapper.findIsExit(id, dto.getName());
            if (isExit == 0) {
                WorkAttachmentInfo i = new WorkAttachmentInfo();
                //包含了url、size、name
                i.setId(java.util.UUID.randomUUID().toString().replace("-", ""));
//                i.getCreateBy().setId(userDTO.getId());
                i.setCreateTime(new Date());
//                i.getUpdateBy().setId(userDTO.getId());
                i.setUpdateTime(new Date());
                i.setDelFlag(0);
                i.setUrl(dto.getUrl());
                //文件类型处理
                List<String> strings = Arrays.asList(dto.getName().split("\\."));
                if (CollectionUtil.isNotEmpty(strings)) {
                    i.setType(strings.get(1));
                }
                i.setAttachmentId(id);
                i.setAttachmentName(dto.getName());
                i.setAttachmentFlag("driveMaintain");
                i.setFileSize(dto.getSize());
                i.setSort(j);
                Map<String,String> map = new HashMap<>();
                String workAttachment = JSON.toJSONString((i));
                String userDTOInfo = JSON.toJSONString((userDTO));
                map.put("workAttachment",workAttachment);
                map.put("userDTO",userDTOInfo);
                SpringUtil.getBean ( IWorkAttachmentApi.class ).insertWorkAttachment(map);
                j++;
            }
        }
    }

    /**
     * 根据id查询维护信息
     * @param id
     * @return
     */
    public DriveMaintainDTO findById(String id) {
        DriveMaintainDTO maintainDTO = new DriveMaintainDTO();
        DriveMaintain driveMaintain=driveMaintainMapper.findById(id);
        BeanUtils.copyProperties(driveMaintain,maintainDTO);
        if (ObjectUtil.isNotEmpty(driveMaintain)){
            //设置起止时间
            if (ObjectUtil.isNotEmpty(driveMaintain.getStartTime()) && ObjectUtil.isNotEmpty(driveMaintain.getEndTime())) {
                Date[] dates=new Date[2];
                dates[0]=driveMaintain.getStartTime();
                dates[1]=driveMaintain.getEndTime();
                maintainDTO.setMaintainDates(dates);
            }
            // 查询附件信息
            List<WorkAttachmentInfo> files = driveMaintainMapper.findDtos(id);
            if (CollectionUtils.isNotEmpty(files)) {
                for (WorkAttachmentInfo i : files) {
                    i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(i.getBy()));
                }
                maintainDTO.setFiles(files);
            }
        }
        return maintainDTO;

    }

    /**
     * 根据id修改状态
     * @param maintainDTO
     */
    public void updateStatusById(DriveMaintainDTO maintainDTO) {
        driveMaintainMapper.updateStatusById(maintainDTO.getStatus(),maintainDTO.getId());
    }

    /**
     * 根据id进行删除
     * @param id
     * @return
     */
    public String deleteById(String id) {
        driveMaintainMapper.deleteById(id);
        //删除附件
        SpringUtil.getBean ( IWorkAttachmentApi.class ).deleteByAttachmentId(id);
        return "操作成功";
    }

    /**
     * 管理员修改
     * @param maintainDTO
     */
    public void updateInfo(DriveMaintainDTO maintainDTO) {
        //获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());

        DriveMaintain maintain = new DriveMaintain();
        //修改信息
        maintain.setUpdateById(userDTO.getId());
        maintain.setUpdateTime(new Date());
        maintain.setDriveInfoId(maintainDTO.getDriveInfoId()); //车辆信息
        maintain.setDriveMaintainType(maintainDTO.getDriveMaintainType()); //维护类型
        maintain.setStartTime(maintainDTO.getStartTime()); //维护开始时间
        maintain.setEndTime(maintainDTO.getEndTime()); //维护结束时间
        maintain.setId(maintainDTO.getId());
        maintainDTO.setRemarks(maintainDTO.getRemarks());
        driveMaintainMapper.updateInfo(maintain);

        //附件修改
        List<WorkAttachmentInfo> files = maintainDTO.getFiles();
        if (CollectionUtil.isNotEmpty(files)) {
            updateFiles(files, userDTO, maintainDTO.getId());
        }
    }
}
