package com.jeeplus.centrecareful.approvalType.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.LambdaQueryWrapper;
import com.jeeplus.centrecareful.approvalType.domain.ZsReimbursementTypeInfo;
import com.jeeplus.centrecareful.approvalType.mapper.ZsReimbursementTypeMapper;
import com.jeeplus.common.TokenProvider;
import com.jeeplus.core.domain.BaseEntity;
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.flowable.editor.language.json.converter.util.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * @author: 王强
 * @create: 2022-11-25 09:13
 **/
@Service
public class ZsReimbursementTypeService {

    @Resource
    private ZsReimbursementTypeMapper mapper;

    public List<ZsReimbursementTypeInfo> list(ZsReimbursementTypeInfo info) {
        LambdaQueryWrapper<ZsReimbursementTypeInfo> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(info.getName())) {
            wrapper.like(ZsReimbursementTypeInfo::getName, info.getName());
        }
        if (info.getSort() != null) {
            wrapper.like(ZsReimbursementTypeInfo::getSort, info.getSort());
        }
//        wrapper.eq(ZsReimbursementTypeInfo::getBusinessType, "1");

        wrapper.eq(BaseEntity::getDelFlag, 0);
        wrapper.orderByAsc(ZsReimbursementTypeInfo::getSort);
        return mapper.selectList(wrapper);
    }

    public List<ZsReimbursementTypeInfo> bxList(ZsReimbursementTypeInfo info) {
        LambdaQueryWrapper<ZsReimbursementTypeInfo> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(info.getName())) {
            wrapper.like(ZsReimbursementTypeInfo::getName, info.getName());
        }
        if (ObjectUtil.isNotEmpty(info)) {
            if (StringUtils.isNotBlank(info.getLike())){
                wrapper.likeRight(ZsReimbursementTypeInfo::getSort,info.getLike());
            }
        }
        if (info.getSort() != null) {
            wrapper.like(ZsReimbursementTypeInfo::getSort, info.getSort());
        }

        wrapper.eq(BaseEntity::getDelFlag, 0);
        wrapper.orderByAsc(ZsReimbursementTypeInfo::getSort);
        return mapper.selectList(wrapper);
    }

    public List<ZsReimbursementTypeInfo> cgList(ZsReimbursementTypeInfo info) {
        LambdaQueryWrapper<ZsReimbursementTypeInfo> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(info.getName())) {
            wrapper.like(ZsReimbursementTypeInfo::getName, info.getName());
        }
        if (info.getSort() != null) {
            wrapper.like(ZsReimbursementTypeInfo::getSort, info.getSort());
        }

        wrapper.eq(BaseEntity::getDelFlag, 0);
        wrapper.orderByAsc(ZsReimbursementTypeInfo::getSort);
        return mapper.selectList(wrapper);
    }

    public String save(ZsReimbursementTypeInfo info) {
        // parentId未传值，则表示一级菜单
        if(StringUtils.isEmpty(info.getParentId())) {
            info.setParentId("0");
        }
        // 保存数据
        if (StringUtils.isNotEmpty(info.getId())) {
            return update(info);
        }
        return add(info);
    }

    /**
     * 新增
     * @param info
     * @return
     */
    public String add(ZsReimbursementTypeInfo info) {
        // 判断名称是否已存在
        Integer isExist = mapper.checkNameIsExist(info.getName(), info.getParentId());
        if (isExist > 0) {
            return "false";
        }
        // 获取当前登录人信息
        UserDTO userDto = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
        // 生成id值
        String id = UUID.randomUUID().toString().replace("-", "");
        info.setId(id);
        info.setCreateById(userDto.getId());
        info.setCreateTime(new Date());
        info.setUpdateById(userDto.getId());
        info.setUpdateTime(new Date());
        info.setDelFlag(0);
        // 生成序号/层级
        getNo(info);
        mapper.insert(info);
        return "操作完成";
    }

    /**
     * 修改
     * @param info
     * @return
     */
    public String update(ZsReimbursementTypeInfo info) {
        // 获取当前登录人信息
        UserDTO userDto = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
        info.setUpdateById(userDto.getId());
        info.setUpdateTime(new Date());

        mapper.updateById(info);
        return "操作完成";
    }

    /**
     * 生成序号/层级
     * @param info
     * @return
     */
    public ZsReimbursementTypeInfo getNo(ZsReimbursementTypeInfo info) {
        ZsReimbursementTypeInfo parentInfo = null;
        if (!"0".equals(info.getParentId())) {
            //根据parentId查询父节点信息
            LambdaQueryWrapper<ZsReimbursementTypeInfo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(BaseEntity::getDelFlag, 0);
            wrapper.eq(BaseEntity::getId, info.getParentId());
            parentInfo = mapper.selectOne(wrapper);
        }
        //查询序号
        Integer no = mapper.getNo(info.getParentId());
        // 该层级下有数据，正常返回序号值
        if (no != null) {
            info.setSort(no);
        } else {
            // 父节点存在，根据父节点序号生成；不存在，则表示无上级层级，从1开始
            if (parentInfo != null) {
                String s = parentInfo.getSort() + "01";
                info.setSort(Integer.parseInt(s));
            } else {
                info.setSort(1);
            }
        }
        // 生成层级
        //查询层级
        Integer level = mapper.getLevel(info.getParentId());
        if (level != null) {
            info.setLevel(level.toString());
        } else {
            // 父节点存在，根据父节点level生成，不存在，则表示无上级层级，从1开始
            if (parentInfo != null) {
                Integer i = Integer.parseInt(parentInfo.getLevel())+1;
                info.setLevel(i.toString());
            } else {
                info.setLevel("1");
            }
        }
        return info;
    }

    /**
     * 修改附件信息
     * @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 = mapper.findList(id);
        if (CollectionUtils.isNotEmpty(infoList)) {
            for (WorkAttachmentInfo i : infoList) {
                if (!names.contains(i.getUrl())) {
//                    ossServiceMapper.deleteById(i.getId());
                    SpringUtil.getBean ( IWorkAttachmentApi.class ).deleteById(i.getId());
                }
            }
        }
        //保存信息
        for (WorkAttachmentInfo dto : list) {
            //判断是否存在
            Integer isExit = mapper.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());
                //文件类型处理
                String fileName = dto.getName();
                List<String> strings = Arrays.asList(fileName.split("\\."));
                // 检查文件名是否有后缀
                if (CollectionUtil.isNotEmpty(strings) && strings.size() > 1) {
                    // 获取最后一个部分作为文件类型
                    i.setType(strings.get(strings.size() - 1));
                } else {
                    // 如果没有后缀或文件名无效，设置一个默认类型或空
                    i.setType("");
                }
                i.setAttachmentId(id);
                i.setAttachmentName(dto.getName());
                i.setAttachmentFlag("cwWorkContract");
                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);
//                ossServiceMapper.insertWorkAttachment(i, userDTO);
                j++;
            }
        }
    }

    /**
     * 修改附件信息
     * @param list 待修改的附件列表
     * @param userDTO 当前登录用户
     * @param id 关联id
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateFiles(List<WorkAttachmentInfo> list, UserDTO userDTO, String id, String attachmentFlag) {
        int j = 1;
        String names = new String();
        //表中存在，但是传过来不存在，说明已删除，表中数据也要删除
        for (WorkAttachmentInfo dto : list) {
            names = names + "," +dto.getUrl();
        }
        //查询保存的附件信息
        List<WorkAttachmentInfo> infoList = mapper.findListByIdAndAttachmentFlag(id,attachmentFlag);
        if (CollectionUtils.isNotEmpty(infoList)) {
            for (WorkAttachmentInfo i : infoList) {
                if (!names.contains(i.getUrl())) {
//                    ossServiceMapper.deleteById(i.getId());
                    SpringUtil.getBean ( IWorkAttachmentApi.class ).deleteById(i.getId());
                }
            }
        }
        //保存信息
        for (WorkAttachmentInfo dto : list) {
            //判断是否存在
            Integer isExit = mapper.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());
                //文件类型处理
                String fileName = dto.getName();
                List<String> strings = Arrays.asList(fileName.split("\\."));
                // 检查文件名是否有后缀
                if (CollectionUtil.isNotEmpty(strings) && strings.size() > 1) {
                    // 获取最后一个部分作为文件类型
                    i.setType(strings.get(strings.size() - 1));
                } else {
                    // 如果没有后缀或文件名无效，设置一个默认类型或空
                    i.setType("");
                }
                i.setAttachmentId(id);
                i.setAttachmentName(dto.getName());
                i.setAttachmentFlag(attachmentFlag);
                i.setFileSize(dto.getSize());
                i.setRemarks(dto.getRemarks());
                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);
//                ossServiceMapper.insertWorkAttachment(i, userDTO);
                j++;
            }
        }
    }

    /**
     * 保存附件信息
     * @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());
            //文件类型处理
            String fileName = dto.getName();
            List<String> strings = Arrays.asList(fileName.split("\\."));
            // 检查文件名是否有后缀
            if (CollectionUtil.isNotEmpty(strings) && strings.size() > 1) {
                // 获取最后一个部分作为文件类型
                i.setType(strings.get(strings.size() - 1));
            } else {
                // 如果没有后缀或文件名无效，设置一个默认类型或空
                i.setType("");
            }
            i.setAttachmentId(id);
            i.setAttachmentName(dto.getName());
            i.setAttachmentFlag("cwWorkContract");
            i.setFileSize(dto.getSize());
            i.setSort(j);
            i.setRemarks(dto.getRemarks());
//            ossServiceMapper.insertWorkAttachment(i, userDTO);
            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++;
        }
    }

    /**
     * 保存附件信息
     * @param list 待保存的附件列表
     * @param userDTO 当前登录用户
     * @param id 关联id
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveFiles(List<WorkAttachmentInfo> list, UserDTO userDTO, String id, String attachmentFlag) {
        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());
            //文件类型处理
            String fileName = dto.getName();
            List<String> strings = Arrays.asList(fileName.split("\\."));
            // 检查文件名是否有后缀
            if (CollectionUtil.isNotEmpty(strings) && strings.size() > 1) {
                // 获取最后一个部分作为文件类型
                i.setType(strings.get(strings.size() - 1));
            } else {
                // 如果没有后缀或文件名无效，设置一个默认类型或空
                i.setType("");
            }
            i.setAttachmentId(id);
            i.setAttachmentName(dto.getName());
            i.setAttachmentFlag(attachmentFlag);
            i.setFileSize(dto.getSize());
            i.setSort(j);
//            ossServiceMapper.insertWorkAttachment(i, userDTO);
            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++;
        }
    }
}
