package com.jeeplus.business.drive.service;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.annotation.InterceptorIgnore;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.DriveAccount;
import com.jeeplus.business.drive.domain.DriveApply;
import com.jeeplus.business.drive.mapper.DriveAccountMapper;
import com.jeeplus.business.drive.mapper.DriveApplyMapper;
import com.jeeplus.business.drive.service.dto.DriveAccountDTO;
import com.jeeplus.business.drive.service.dto.DriveApplyDTO;
import com.jeeplus.business.drive.service.dto.DriveDTO;
import com.jeeplus.business.meetingRoom.domain.MeetingRoom;
import com.jeeplus.business.project.domain.JyProject;
import com.jeeplus.business.project.mapper.JyProjectMapper;
import com.jeeplus.business.project.service.JyProjectService;
import com.jeeplus.business.project.service.dto.JyProjectDTO;
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 com.sun.mail.imap.protocol.ID;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

@Service
public class DriveApplyService {

    @Resource
    private DriveApplyMapper driveApplyMapper;

    @Resource
    private DriveAccountMapper driveAccountMapper;

    @Resource
    private JyProjectService jyProjectService;

    @Resource
    private JyProjectMapper jyProjectMapper;


    /**
     * 用车申请列表
     * @param driveApplyDTO
     * @param page
     * @return
     */
    public IPage<DriveApplyDTO> findPageList(DriveApplyDTO driveApplyDTO, Page<DriveApplyDTO> page) throws Exception {
        QueryWrapper<DriveApplyDTO> queryWrapper = QueryWrapperGenerator.buildQueryCondition(driveApplyDTO, DriveApplyDTO.class);
        queryWrapper.eq("a.del_flag",0);
        //用车项目
        if (StringUtils.isNotBlank(driveApplyDTO.getProjectId())){
            queryWrapper.like("a.project_id",driveApplyDTO.getProjectId());
        }
        //用车人员
        if (StringUtils.isNotBlank(driveApplyDTO.getUseMen())){
            queryWrapper.like("a.use_men",driveApplyDTO.getUseMen());
        }
        //申请人
        if (StringUtils.isNotBlank(driveApplyDTO.getCreateById())){
            queryWrapper.eq("a.create_by_id",driveApplyDTO.getCreateById());
        }
        //申请人部门
        if (StringUtils.isNotBlank(driveApplyDTO.getOfficeId())){
            queryWrapper.eq("so.id",driveApplyDTO.getOfficeId());
        }
        IPage<DriveApplyDTO> iPage=driveApplyMapper.findPageList(queryWrapper,page);
        return iPage;
    }

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

    //修改
    private String update(DriveApplyDTO driveApplyDTO) {
        //获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
        //修改项目信息
        String project="";
        DriveApply driveApply = new DriveApply();

        BeanUtils.copyProperties(driveApplyDTO,driveApply);

        driveApply.setUpdateById(userDTO.getId());
        driveApply.setUpdateTime(new Date());
        //处理关联项目项目
        if (ObjectUtil.isNotEmpty(driveApplyDTO.getProjectList())){
            for (JyProject jyProject : driveApplyDTO.getProjectList()) {
                project+=jyProject.getProjectId()+",";
            }
            driveApply.setProjectId(project.substring(0,project.lastIndexOf(",")));
        }
        driveApplyMapper.updateById(driveApply);
        //修改附件
        if (CollectionUtils.isNotEmpty(driveApplyDTO.getFiles())){
            List<WorkAttachmentInfo> files = driveApplyDTO.getFiles();
            updateFiles(files, userDTO, driveApplyDTO.getId());
        }
        return driveApplyDTO.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 = driveApplyMapper.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 = driveApplyMapper.findIsExit(id, dto.getName());
            if (isExit == 0) {
                WorkAttachmentInfo i = new WorkAttachmentInfo();
                //包含了url、size、name
                i.setId(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("driveApply");
                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 add(DriveApplyDTO driveApplyDTO) {
        //获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
        DriveApply driveApply = new DriveApply();
        String project="";
        //处理关联项目项目
        if (ObjectUtil.isNotEmpty(driveApplyDTO.getProjectList())){
            for (JyProject jyProject : driveApplyDTO.getProjectList()) {
                project+=jyProject.getProjectId()+",";
            }
            driveApply.setProjectId(project.substring(0,project.lastIndexOf(",")));
        }
        //id
        String id = UUID.randomUUID().toString().replace("-", "");

        driveApply.setId(id);
        driveApply.setCreateById(userDTO.getId());
        driveApply.setCreateTime(new Date());
        driveApply.setUpdateById(userDTO.getId());
        driveApply.setUpdateTime(new Date());
        driveApply.setUseStartTime(driveApplyDTO.getUseStartTime());//开始时间
        driveApply.setUseEndTime(driveApplyDTO.getUseEndTime());//结束时间
        driveApply.setUseMen(driveApplyDTO.getUseMen());//用车人员
        driveApply.setUseReason(driveApplyDTO.getUseReason());//用车原因
        driveApply.setRemarks(driveApplyDTO.getRemarks());//备注
        driveApply.setStatus(driveApplyDTO.getStatus());//状态
        driveApplyMapper.insert(driveApply);
        //保存附件
        List<WorkAttachmentInfo> files = driveApplyDTO.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(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("driveApply");
            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 DriveApplyDTO findById(String id) {
        DriveApplyDTO applyDTO = new DriveApplyDTO();
        DriveApplyDTO driveApplyDTO=driveApplyMapper.findById(id);
        BeanUtils.copyProperties(driveApplyDTO, applyDTO);
        if (ObjectUtil.isNotEmpty(driveApplyDTO)){
            //查询项目信息
            if (StringUtils.isNotBlank(driveApplyDTO.getProjectId())){
                String[] split = driveApplyDTO.getProjectId().split(",");
                ArrayList<JyProject> projects = new ArrayList<>();
                for (String s : split) {
                    JyProject jyProject=jyProjectMapper.getById(s);
                    projects.add(jyProject);
                }
                applyDTO.setProjectList(projects);
            }
            //设置用车起使时间
            if (ObjectUtil.isNotEmpty(driveApplyDTO.getUseStartTime()) && ObjectUtil.isNotEmpty(driveApplyDTO.getUseEndTime())){
                Date[] dates = new Date[2];
                dates[0]=driveApplyDTO.getUseStartTime();
                dates[1]=driveApplyDTO.getUseEndTime();
                applyDTO.setUseDate(dates);
            }
            // 查询附件信息
            List<WorkAttachmentInfo> files = driveApplyMapper.findDtos(id);
            if (CollectionUtils.isNotEmpty(files)) {
                for (WorkAttachmentInfo i : files) {
                    i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(i.getBy()));
                }
                applyDTO.setFiles(files);
            }
            //查询结算附件信息
            List<WorkAttachmentInfo> files1 = driveApplyMapper.findDtos(driveApplyDTO.getAccountId());
            if (CollectionUtils.isNotEmpty(files1)) {
                for (WorkAttachmentInfo i : files1) {
                    i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(i.getBy()));
                }
                applyDTO.setAccountFiles(files1);
            }
        }
        return applyDTO;
    }

    /**
     * 根据id修改状态
     * @param driveApplyDTO
     */
    public void updateStatusById(DriveApplyDTO driveApplyDTO) {
        driveApplyMapper.updateStatusById(driveApplyDTO.getId(),driveApplyDTO.getStatus());
    }

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

    /**
     * 新增或修改用车结算
     * @param driveAccountDTO
     * @return
     */

    public String saveAccountForm(DriveAccountDTO driveAccountDTO) {
        //获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
        DriveAccount driveAccount = new DriveAccount();
        driveAccount.setCreateById(userDTO.getId());
        driveAccount.setCreateTime(new Date());
        driveAccount.setUpdateById(userDTO.getId());
        driveAccount.setUpdateTime(new Date());
        driveAccount.setStartMileage(driveAccountDTO.getStartMileage());
        driveAccount.setEndMileage(driveAccountDTO.getEndMileage());
        driveAccount.setApplyId(driveAccountDTO.getApplyId());
        driveAccount.setMileageCount(driveAccountDTO.getMileageCount());
        driveAccount.setStatus(driveAccountDTO.getStatus());
        DriveAccountDTO accountDTO = driveAccountMapper.findByApplyId(driveAccountDTO.getApplyId());
        //判断结算表中是否有该条数据
        if (ObjectUtil.isNotEmpty(accountDTO)){
            driveAccount.setId(accountDTO.getId());
            driveAccountMapper.updateById(driveAccount);
            //附件
            Map<String,String> map = new HashMap<>();
            String fileList = JSON.toJSONString((driveAccountDTO.getAccountFiles()));
            String attachmentId = accountDTO.getId();
            String attachmentFlag = "driveAccount";
            map.put("fileList",fileList);
            map.put("attachmentId",attachmentId);
            map.put("attachmentFlag",attachmentFlag);
            map.put("currentToken", TokenProvider.getCurrentToken ( ));
            SpringUtil.getBean ( IWorkAttachmentApi.class ).saveOrUpdateFileList(map);

        }else {
            //id
            String id = UUID.randomUUID().toString().replace("-", "");
            driveAccount.setId(id);
            driveAccountMapper.insert(driveAccount);
            //附件
            Map<String,String> map = new HashMap<>();
            String fileList = JSON.toJSONString((driveAccountDTO.getAccountFiles()));
            String attachmentId = id;
            String attachmentFlag = "driveAccount";
            map.put("fileList",fileList);
            map.put("attachmentId",attachmentId);
            map.put("attachmentFlag",attachmentFlag);
            map.put("currentToken", TokenProvider.getCurrentToken ( ));
            SpringUtil.getBean ( IWorkAttachmentApi.class ).saveOrUpdateFileList(map);
            return id;
        }
        return accountDTO.getId();

    }

    /**
     * 根据id修改状态
     * @param driveAccountDTO
     */
    public void updateStatusByApplyId(DriveAccountDTO driveAccountDTO) {
        driveAccountMapper.updateStatusByApplyId(driveAccountDTO.getApplyId(),driveAccountDTO.getStatus());
    }

    /**
     * 管理员修改
     * @param driveDTO
     */
    public void adminEditForm(DriveDTO driveDTO) {
        //修改用车申请数据
        //获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
        //修改项目信息
        String project="";
        DriveApply driveApply = new DriveApply();
        driveApply.setUpdateById(userDTO.getId());
        driveApply.setUpdateTime(new Date());
        //处理关联项目项目
        if (ObjectUtil.isNotEmpty(driveDTO.getDriveApplyDTO().getProjectList())){
            for (JyProject jyProject : driveDTO.getDriveApplyDTO().getProjectList()) {
                project+=jyProject.getId()+",";
            }
            driveApply.setProjectId(project.substring(0,project.lastIndexOf(",")));
        }
        driveApply.setUseStartTime(driveDTO.getDriveApplyDTO().getUseStartTime());
        driveApply.setUseEndTime(driveDTO.getDriveApplyDTO().getUseEndTime());
        driveApply.setUseMen(driveDTO.getDriveApplyDTO().getUseMen());
        driveApply.setUseReason(driveDTO.getDriveApplyDTO().getUseReason());
        driveApply.setRemarks(driveDTO.getDriveApplyDTO().getRemarks());
        driveApply.setId(driveDTO.getDriveApplyDTO().getId());
        driveApplyMapper.updateInfoById(driveApply);
        //修改申请附件
        List<WorkAttachmentInfo> files = driveDTO.getDriveApplyDTO().getFiles();
        if (CollectionUtils.isNotEmpty(files)){
            updateFiles(files, userDTO, driveDTO.getDriveApplyDTO().getId());
        }


        //修改用车结算数据
        DriveAccountDTO accountDTO = driveAccountMapper.findByApplyId(driveDTO.getDriveAccountDTO().getApplyId());
        DriveAccount driveAccount = new DriveAccount();
        driveAccount.setId(accountDTO.getId());
        driveAccount.setUpdateById(userDTO.getId());
        driveAccount.setUpdateTime(new Date());
        driveAccount.setStartMileage(driveDTO.getDriveAccountDTO().getStartMileage());
        driveAccount.setEndMileage(driveDTO.getDriveAccountDTO().getEndMileage());
        driveAccount.setMileageCount(driveDTO.getDriveAccountDTO().getMileageCount());
        driveAccountMapper.updateInfoById(driveAccount);

        //附件
        Map<String,String> map = new HashMap<>();
        String fileList = JSON.toJSONString((driveDTO.getDriveAccountDTO().getAccountFiles()));
        String attachmentId = accountDTO.getId();
        String attachmentFlag = "driveAccount";
        map.put("fileList",fileList);
        map.put("attachmentId",attachmentId);
        map.put("attachmentFlag",attachmentFlag);
        map.put("currentToken", TokenProvider.getCurrentToken ( ));
        SpringUtil.getBean ( IWorkAttachmentApi.class ).saveOrUpdateFileList(map);
    }
}
