package com.jeeplus.business.evection.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.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.DriveApply;
import com.jeeplus.business.drive.service.dto.DriveApplyDTO;
import com.jeeplus.business.evection.domain.Evection;
import com.jeeplus.business.evection.mapper.EvectionMapper;
import com.jeeplus.business.evection.service.dto.EvectionDTO;
import com.jeeplus.business.project.domain.JyProject;
import com.jeeplus.business.project.mapper.JyProjectMapper;
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.*;

@Service
public class EvectionService {

    @Resource
    private EvectionMapper evectionMapper;

    @Resource
    private JyProjectMapper jyProjectMapper;

    /**
     * 出差申请列表
     * @param evectionDTO
     * @param page
     * @return
     */
    public IPage<EvectionDTO> findPageList(EvectionDTO evectionDTO, Page<EvectionDTO> page) throws Exception {
        QueryWrapper<EvectionDTO> queryWrapper = QueryWrapperGenerator.buildQueryCondition(evectionDTO, EvectionDTO.class);
        queryWrapper.eq("a.del_flag",0);
        //关联项目
        if (StringUtils.isNotBlank(evectionDTO.getProjectId())){
            queryWrapper.like("a.project_id",evectionDTO.getProjectId());
        }
        //出差人员
        if (StringUtils.isNotBlank(evectionDTO.getEvectionMen())){
            queryWrapper.like("a.evection_men",evectionDTO.getEvectionMen());
        }
        //申请人
        if (StringUtils.isNotBlank(evectionDTO.getCreateById())){
            queryWrapper.eq("a.create_by_id",evectionDTO.getCreateById());
        }
        //申请人部门
        if (StringUtils.isNotBlank(evectionDTO.getOfficeId())){
            queryWrapper.eq("so.id",evectionDTO.getOfficeId());
        }
        //目的地
        if (StringUtils.isNotBlank(evectionDTO.getTargetCity())){
            queryWrapper.eq("a.target_city",evectionDTO.getTargetCity());
        }
        //申请时间
        if (evectionDTO.getCreateDates() != null && evectionDTO.getCreateDates().length > 0) {
            queryWrapper.between("a.create_time", evectionDTO.getCreateDates()[0], evectionDTO.getCreateDates()[1]);
        }
        IPage<EvectionDTO> iPage=evectionMapper.findPageList(queryWrapper,page);
        return iPage;

    }

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

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

        BeanUtils.copyProperties(evectionDTO,evection);

        evection.setUpdateById(userDTO.getId());
        evection.setUpdateTime(new Date());
        //处理关联项目项目
        if (ObjectUtil.isNotEmpty(evectionDTO.getProjectList())){
            for (JyProject jyProject : evectionDTO.getProjectList()) {
                project+=jyProject.getProjectId()+",";
            }
            evection.setProjectId(project.substring(0,project.lastIndexOf(",")));
        }
        evectionMapper.updateById(evection);
        //修改附件
        if (CollectionUtils.isNotEmpty(evectionDTO.getFiles())){
            List<WorkAttachmentInfo> files = evectionDTO.getFiles();
            updateFiles(files, userDTO, evectionDTO.getId());
        }
        return evectionDTO.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 = evectionMapper.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 = evectionMapper.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("evection");
                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(EvectionDTO evectionDTO) {
        //获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
        Evection evection = new Evection();
        String project="";
        //处理关联项目项目
        if (ObjectUtil.isNotEmpty(evectionDTO.getProjectList())){
            for (JyProject jyProject : evectionDTO.getProjectList()) {
                project+=jyProject.getProjectId()+",";
            }
            evection.setProjectId(project.substring(0,project.lastIndexOf(",")));
        }
        //id
        String id = UUID.randomUUID().toString().replace("-", "");

        evection.setId(id);
        evection.setCreateById(userDTO.getId());
        evection.setCreateTime(new Date());
        evection.setUpdateById(userDTO.getId());
        evection.setUpdateTime(new Date());
        evection.setStartTime(evectionDTO.getStartTime());//开始时间
        evection.setEndTime(evectionDTO.getEndTime());//结束时间
        evection.setEvectionMen(evectionDTO.getEvectionMen());//用车人员
        evection.setEvectionReason(evectionDTO.getEvectionReason());//用车原因
        evection.setRemarks(evectionDTO.getRemarks());//备注
        evection.setStatus(evectionDTO.getStatus());//状态
        evection.setTargetCity(evectionDTO.getTargetCity());//目的地
        evectionMapper.insert(evection);
        //保存附件
        List<WorkAttachmentInfo> files = evectionDTO.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("evection");
            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 EvectionDTO findById(String id) {
        EvectionDTO evectionDTO = new EvectionDTO();
        EvectionDTO dto=evectionMapper.findById(id);
        BeanUtils.copyProperties(dto, evectionDTO);
        if (ObjectUtil.isNotEmpty(dto)){
            //查询项目信息
            if (StringUtils.isNotBlank(dto.getProjectId())){
                String[] split = dto.getProjectId().split(",");
                ArrayList<JyProject> projects = new ArrayList<>();
                for (String s : split) {
                    JyProject jyProject=jyProjectMapper.getById(s);
                    projects.add(jyProject);
                }
                evectionDTO.setProjectList(projects);
            }
            //设置出差起使时间
            if (ObjectUtil.isNotEmpty(dto.getStartTime()) && ObjectUtil.isNotEmpty(dto.getEndTime())){
                Date[] dates = new Date[2];
                dates[0]=dto.getStartTime();
                dates[1]=dto.getEndTime();
                evectionDTO.setUseDate(dates);
            }
            // 查询附件信息
            List<WorkAttachmentInfo> files = evectionMapper.findDtos(id);
            if (CollectionUtils.isNotEmpty(files)) {
                for (WorkAttachmentInfo i : files) {
                    i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(i.getBy()));
                }
                evectionDTO.setFiles(files);
            }
        }
        return evectionDTO;
    }

    /**
     * 根据id修改状态
     * @param evectionDTO
     */
    public void updateStatusById(EvectionDTO evectionDTO) {
        evectionMapper.updateStatusById(evectionDTO.getId(),evectionDTO.getStatus());
    }

    /**
     * 根据id进行删除
     * @param id
     * @return
     */
    public String deleteById(String id) {
        evectionMapper.deleteById(id);
        return "操作成功";
    }


    /**
     * 管理员修改信息
     * @param evectionDTO
     */
    public void adminEditForm(EvectionDTO evectionDTO) {
        //获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
        //修改项目信息
        String project="";
        Evection evection = new Evection();
        evection.setUpdateById(userDTO.getId());
        evection.setUpdateTime(new Date());
        //处理关联项目项目
        if (ObjectUtil.isNotEmpty(evectionDTO.getProjectList())){
            for (JyProject jyProject : evectionDTO.getProjectList()) {
                project+=jyProject.getId()+",";
            }
            evection.setProjectId(project.substring(0,project.lastIndexOf(",")));
        }
        evection.setStartTime(evectionDTO.getStartTime());
        evection.setEndTime(evectionDTO.getEndTime());
        evection.setEvectionMen(evectionDTO.getEvectionMen());
        evection.setEvectionReason(evectionDTO.getEvectionReason());
        evection.setRemarks(evectionDTO.getRemarks());
        evection.setTargetCity(evectionDTO.getTargetCity());
        evection.setId(evectionDTO.getId());
        evectionMapper.updateInfoById(evection);
        //修改申请附件
        List<WorkAttachmentInfo> files = evectionDTO.getFiles();
        updateFiles(files, userDTO, evectionDTO.getId());
    }
}
