package com.jeeplus.business.goOut.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.goOut.domain.GoOut;
import com.jeeplus.business.goOut.mapper.GoOutMapper;
import com.jeeplus.business.goOut.service.dto.GoOutDTO;
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 GoOutService {

    @Resource
    private GoOutMapper goOutMapper;

    @Resource
    private JyProjectMapper jyProjectMapper;

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

    }

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

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

        BeanUtils.copyProperties(goOutDTO,goOut);

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

        goOut.setId(id);
        goOut.setCreateById(userDTO.getId());
        goOut.setCreateTime(new Date());
        goOut.setUpdateById(userDTO.getId());
        goOut.setUpdateTime(new Date());
        goOut.setStartTime(goOutDTO.getStartTime());//开始时间
        goOut.setEndTime(goOutDTO.getEndTime());//结束时间
        goOut.setOutMen(goOutDTO.getOutMen());//用车人员
        goOut.setOutReason(goOutDTO.getOutReason());//用车原因
        goOut.setRemarks(goOutDTO.getRemarks());//备注
        goOut.setStatus(goOutDTO.getStatus());//状态
        goOut.setTargetCity(goOutDTO.getTargetCity());//目的地
        goOutMapper.insert(goOut);
        //保存附件
        List<WorkAttachmentInfo> files = goOutDTO.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("goOut");
            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 GoOutDTO findById(String id) {
        GoOutDTO goOutDTO = new GoOutDTO();
        GoOutDTO dto=goOutMapper.findById(id);
        BeanUtils.copyProperties(dto, goOutDTO);
        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);
                }
                goOutDTO.setProjectList(projects);
            }
            //设置出差起使时间
            if (ObjectUtil.isNotEmpty(dto.getStartTime()) && ObjectUtil.isNotEmpty(dto.getEndTime())){
                Date[] dates = new Date[2];
                dates[0]=dto.getStartTime();
                dates[1]=dto.getEndTime();
                goOutDTO.setUseDate(dates);
            }
            // 查询附件信息
            List<WorkAttachmentInfo> files = goOutMapper.findDtos(id);
            if (CollectionUtils.isNotEmpty(files)) {
                for (WorkAttachmentInfo i : files) {
                    i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(i.getBy()));
                }
                goOutDTO.setFiles(files);
            }
        }
        return goOutDTO;
    }

    /**
     * 根据id修改状态
     * @param goOutDTO
     */
    public void updateStatusById(GoOutDTO goOutDTO) {
        goOutMapper.updateStatusById(goOutDTO.getId(),goOutDTO.getStatus());
    }

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


    /**
     * 管理员修改信息
     * @param goOutDTO
     */
    public void adminEditForm(GoOutDTO goOutDTO) {
        //获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
        //修改项目信息
        String project="";
        GoOut goOut = new GoOut();

        goOut.setUpdateById(userDTO.getId());
        goOut.setUpdateTime(new Date());
        //处理关联项目项目
        if (ObjectUtil.isNotEmpty(goOutDTO.getProjectList())){
            for (JyProject jyProject : goOutDTO.getProjectList()) {
                project+=jyProject.getId()+",";
            }
            goOut.setProjectId(project.substring(0,project.lastIndexOf(",")));
        }
        goOut.setStartTime(goOutDTO.getStartTime());
        goOut.setEndTime(goOutDTO.getEndTime());
        goOut.setOutMen(goOutDTO.getOutMen());
        goOut.setOutReason(goOutDTO.getOutReason());
        goOut.setRemarks(goOutDTO.getRemarks());
        goOut.setTargetCity(goOutDTO.getTargetCity());
        goOut.setId(goOutDTO.getId());
        goOutMapper.updateInfoById(goOut);
        //修改申请附件
        List<WorkAttachmentInfo> files = goOutDTO.getFiles();
        updateFiles(files, userDTO, goOutDTO.getId());
    }
}
