package com.jeeplus.assess.workContract.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
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.google.common.collect.Lists;
import com.jeeplus.assess.program.configuration.projectList.domain.ProgramProjectListInfo;
import com.jeeplus.assess.workContract.domain.WorkContractInfo;
import com.jeeplus.assess.workContract.mapper.WorkContractInfoMapper;
import com.jeeplus.assess.workContract.service.dto.WorkContractInfoDto;
import com.jeeplus.common.TokenProvider;
import com.jeeplus.flowable.feign.IFlowableApi;
import com.jeeplus.sys.domain.WorkAttachmentInfo;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.feign.IWorkAttachmentApi;
import com.jeeplus.sys.service.dto.WorkAttachmentInfoDTO;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeeplus.sys.service.dto.UserDTO;
//import com.jeeplus.sys.utils.UserUtils;
//import com.jeeplus.pubmodules.serialNumTpl.service.SerialnumTplService;
//import com.jeeplus.pubmodules.oss.domain.WorkAttachment;
//import com.jeeplus.pubmodules.oss.mapper.OssServiceMapper;
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 WorkContractService {

    @Resource
    private WorkContractInfoMapper workContractInfoMapper;

//    @Resource
//    private OssServiceMapper ossServiceMapper;

//    @Resource
//    private SerialnumTplService serialnumTplService;

    @Resource
    private IFlowableApi flowTaskService;

    public String saveInfo(WorkContractInfoDto workContractInfoDto) throws Exception {
        if (StringUtils.isNotEmpty(workContractInfoDto.getId())) {
            WorkContractInfo info = workContractInfoMapper.selectById(workContractInfoDto.getId());
            if (info != null) {
                return update(workContractInfoDto);
            }
        }
        return add(workContractInfoDto);
    }

    /**
     * 客户信息列表
     * @param
     * @return
     */
    public IPage<WorkContractInfo> list(Page<WorkContractInfo> page, QueryWrapper<WorkContractInfo> queryWrapper, String clientName, String[] contractDates, String[] contractAmounts,String statusList,String status,String contractType) {
        queryWrapper.eq("a.del_flag","0");
        if (contractDates != null) {
            queryWrapper.between("a.contract_date", contractDates[0], contractDates[1]);
        }
        if (StringUtils.isNotBlank(contractType)){
            queryWrapper.eq("a.contract_type",contractType);
        }
        if (contractAmounts != null) {
            if (StringUtils.isNotEmpty(contractAmounts[0])) {
                queryWrapper.ge("a.contract_amount", contractAmounts[0]);
            }
            if (StringUtils.isNotEmpty(contractAmounts[1])) {
                queryWrapper.le("a.contract_amount", contractAmounts[1]);
            }
        }
        if (StringUtils.isNotBlank(statusList)) {
            if (statusList.contains(",")) {
                List<String> statusS = Lists.newLinkedList();
                statusS = Arrays.asList(statusList.split(","));
                queryWrapper.in("a.status", statusS);
            }else{
                queryWrapper.like("a.status", statusList);
            }
        } else {
            if (StringUtils.isNotBlank(status)) {
                queryWrapper.like("a.status", status);
            }
        }
        IPage<WorkContractInfo> pageList = workContractInfoMapper.findPageList(page, queryWrapper);
        pageList.getRecords().stream().forEach(i -> {
            // 合同登记
            if (StringUtils.isNotBlank(i.getTaskId()) && StringUtils.isNotBlank(i.getStatus())) {
                if ("2".equals(i.getStatus())) { // “审核中”的数据要获取数据审核人
                    i.setAuditUserIds(flowTaskService.getTaskAuditUsers(i.getTaskId()));  // 获取数据审核人
                }
            }
            // 合同归档
            if (StringUtils.isNotBlank(i.getTaskFiledId()) && StringUtils.isNotBlank(i.getFiledType())) {
                if ("2".equals(i.getFiledType())) { // “审核中”的数据要获取数据审核人
                    i.setAuditUserIdsFiled(flowTaskService.getTaskAuditUsers(i.getTaskFiledId()));  // 获取数据审核人
                }
            }
        });
        return pageList;
    }

    /**
     * 合同登记新增
     */
    @Transactional(rollbackFor = Exception.class)
    public String add(WorkContractInfoDto workContractInfoDto) throws Exception{
        String currentToken = TokenProvider.getCurrentToken();
        //获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(currentToken);
        //合同编号生成
//        String serialNum = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNum(userDTO.getCompanyDTO().getId(), WorkContractInfoDto.BIZ_CODE,currentToken);
        String id = UUID.randomUUID().toString().replace("-", "");
        WorkContractInfo info = new WorkContractInfo();
        BeanUtils.copyProperties(workContractInfoDto, info);
        info.setId(id);
//        info.setNo(serialNum);
        info.setCreateById(userDTO.getId());
        info.setCreateTime(new Date());
        info.setUpdateById(userDTO.getId());
        info.setUpdateTime(new Date());
        workContractInfoMapper.insert(info);
        List<WorkAttachmentInfo> list = workContractInfoDto.getWorkAttachmentList();
        if (CollectionUtil.isNotEmpty(list)) {
            saveFiles(list, userDTO, id);
        }
        return id;
    }

    /**
     * 合同登记修改
     */
    @Transactional(rollbackFor = Exception.class)
    public String update(WorkContractInfoDto workContractInfoDto) throws Exception{
        //获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
        //合同编号生成
//        String serialNum = serialnumTplService.genSerialNum(userDTO.getCompanyDTO().getId(), WorkContractInfoDto.BIZ_CODE);
        WorkContractInfo info = new WorkContractInfo();
        BeanUtils.copyProperties(workContractInfoDto, info);
//        info.setNo(serialNum);
        info.setUpdateById(userDTO.getId());
        info.setUpdateTime(new Date());
        workContractInfoMapper.updateById(info);
        List<WorkAttachmentInfo> list = workContractInfoDto.getWorkAttachmentList();
//        if (CollectionUtil.isNotEmpty(list)) {
//            updateFiles(list, userDTO, workContractInfoDto.getId());
//        }
        updateFiles(list, userDTO, workContractInfoDto.getId());
        return workContractInfoDto.getId();
    }

    /**
     * 合同登记删除
     */
    public String removeById(String id) {
        workContractInfoMapper.deleteById(id);
        // 附件删除
//        LambdaQueryWrapper<WorkAttachment> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(WorkAttachment::getAttachmentId, id);
        SpringUtil.getBean ( IWorkAttachmentApi.class ).deleteByAttachmentId(id);
        return "删除完成!";
    }

    /**
     * 合同登记查询
     */
    public WorkContractInfoDto findById(String id) {
        WorkContractInfoDto dto = new WorkContractInfoDto();
        WorkContractInfo info = workContractInfoMapper.findById(id);
        if (info != null) {
            BeanUtils.copyProperties(info, dto);
            // 查询附件信息
            List<WorkAttachmentInfo> dtos = workContractInfoMapper.findDtos(id);
            if (CollectionUtil.isNotEmpty(dtos)) {
                for (WorkAttachmentInfo i : dtos) {
                    i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(i.getBy()));
                }
            }
            dto.setWorkAttachmentList(dtos);
        }
        return dto;
    }

    /**
     * 根据id修改status
     */
    public void updateStatusById(WorkContractInfoDto workContractInfoDto) {
        workContractInfoMapper.updateStatusById(workContractInfoDto.getId(), workContractInfoDto.getStatus());
    }

    /**
     * 保存附件信息
     * @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("workcontract");
            i.setFileSize(dto.getSize());
            i.setSort(j);
            i.setRemarks(dto.getRemarks());
            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);
            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 saveFilesNew(List<WorkAttachmentInfoDTO> list, UserDTO userDTO, String id,String attachmentFlag) {
        int j = 1;
        for (WorkAttachmentInfoDTO 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);
            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 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 = workContractInfoMapper.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 = workContractInfoMapper.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("workcontract");
                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++;
            }
        }
    }

    /**
     * 修改附件信息
     * @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 = workContractInfoMapper.findListByIdAndAttachmentFlag(id,attachmentFlag);
        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 = workContractInfoMapper.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);
                j++;
            }
        }
    }

    /**
     * 关联项目
     * @param id
     * @return
     */
    public IPage<ProgramProjectListInfo> relationProjectList(String id, Page<ProgramProjectListInfo> page) {
        IPage<ProgramProjectListInfo> infos = workContractInfoMapper.relationProjectList(id, page);
        return infos;
    }


    /**
     * 根据客户id查询信息
     * @param clientId
     * @return
     */
    public List<WorkContractInfoDto> getInfoByClientId(String clientId) {
        List<WorkContractInfoDto> infoList = workContractInfoMapper.getInfoByClientId(clientId);
        if (null != infoList && infoList.size()>0) {
            for (WorkContractInfoDto info: infoList) {
                // 查询附件信息
                List<WorkAttachmentInfo> dtos = workContractInfoMapper.findDtos(info.getId());
                if (CollectionUtil.isNotEmpty(dtos)) {
                    for (WorkAttachmentInfo i : dtos) {
                        i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(i.getBy()));
                    }
                }
            }
        }
        return infoList;
    }

    /**
     * 校验合同名称是否存在
     * @param name
     * @return
     */
    public boolean checkName(String name) {
        LambdaQueryWrapper<WorkContractInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WorkContractInfo::getDelFlag,0);
        List<WorkContractInfo> workContractInfos = workContractInfoMapper.selectList(queryWrapper);
        if (CollectionUtil.isNotEmpty(workContractInfos)){
            for (WorkContractInfo workContractInfo : workContractInfos) {
                if (workContractInfo.getName().equals(name)){
                    return true;
                }
            }
        }
        return false;

    }
}
