package com.jeeplus.test.workContract.service;

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.flowable.service.FlowTaskService;
import com.jeeplus.sys.utils.TicketQueryUtils;
import com.jeeplus.test.oss.service.OssService;
import com.jeeplus.test.program.configuration.projectList.domain.ProgramProjectListInfo;
import com.jeeplus.test.workClientInfo.domain.WorkClientInfo;
import com.jeeplus.test.workClientInfo.domain.dto.WorkClientInfosDto;
import com.jeeplus.test.workClientInfo.mapper.WorkClientInfoMapper;
import com.jeeplus.test.workClientInfo.service.WorkClientService;
import com.jeeplus.test.workContract.service.dto.WorkAttachmentDto;
import net.sf.json.JSONObject;
import org.flowable.editor.language.json.converter.util.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jeeplus.sys.service.dto.UserDTO;
import com.jeeplus.sys.utils.StringUtils;
import com.jeeplus.sys.utils.UserUtils;
import com.jeeplus.test.mould.service.SerialnumTplService;
import com.jeeplus.test.oss.domain.WorkAttachment;
import com.jeeplus.test.oss.mapper.OssServiceMapper;
import com.jeeplus.test.workContract.domain.WorkContractInfo;
import com.jeeplus.test.workContract.mapper.WorkContractInfoMapper;
import com.jeeplus.test.workContract.service.dto.WorkContractInfoDto;
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 FlowTaskService 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) {
        queryWrapper.eq("a.del_flag","0");
        if (contractDates != null) {
            queryWrapper.between("a.contract_date", contractDates[0], contractDates[1]);
        }
        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{
        //获取当前登录人信息
        UserDTO userDTO = UserUtils.getCurrentUserDTO();
        //合同编号生成
//        String serialNum = serialnumTplService.genSerialNum(userDTO.getCompanyDTO().getId(), WorkContractInfoDto.BIZ_CODE);
        String id = UUID.randomUUID().toString().replace("-", "");
        WorkContractInfo info = new WorkContractInfo();
        BeanUtils.copyProperties(workContractInfoDto, info);
        info.setId(id);
//        info.setNo(serialNum);
        info.setCreateBy(userDTO.getId());
        info.setCreateDate(new Date());
        info.setUpdateBy(userDTO.getId());
        info.setUpdateDate(new Date());
        workContractInfoMapper.insert(info);
        List<WorkAttachmentDto> list = workContractInfoDto.getWorkAttachmentList();
        if (CollectionUtils.isNotEmpty(list)) {
            saveFiles(list, userDTO, id);
        }
        return id;
    }

    /**
     * 合同登记修改
     */
    @Transactional(rollbackFor = Exception.class)
    public String update(WorkContractInfoDto workContractInfoDto) throws Exception{
        //获取当前登录人信息
        UserDTO userDTO = UserUtils.getCurrentUserDTO();
        //合同编号生成
//        String serialNum = serialnumTplService.genSerialNum(userDTO.getCompanyDTO().getId(), WorkContractInfoDto.BIZ_CODE);
        WorkContractInfo info = new WorkContractInfo();
        BeanUtils.copyProperties(workContractInfoDto, info);
//        info.setNo(serialNum);
        info.setUpdateBy(userDTO.getId());
        info.setUpdateDate(new Date());
        workContractInfoMapper.updateById(info);
        List<WorkAttachmentDto> list = workContractInfoDto.getWorkAttachmentList();
        if (CollectionUtils.isNotEmpty(list)) {
            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);
        ossServiceMapper.delete(wrapper);
        return "删除完成!";
    }

    /**
     * 合同登记查询
     */
    public WorkContractInfoDto findById(String id) {
        WorkContractInfoDto dto = new WorkContractInfoDto();
        WorkContractInfo info = workContractInfoMapper.findById(id);
        if (info != null) {
            BeanUtils.copyProperties(info, dto);
            // 查询附件信息
            List<WorkAttachmentDto> dtos = workContractInfoMapper.findDtos(id);
            if (CollectionUtils.isNotEmpty(dtos)) {
                for (WorkAttachmentDto i : dtos) {
                    i.setCreateBy(UserUtils.get(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<WorkAttachmentDto> list, UserDTO userDTO, String id) {
        int j = 1;
        for (WorkAttachmentDto dto : list) {
            WorkAttachment i = new WorkAttachment();
            //包含了url、size、name
            i.setId(UUID.randomUUID().toString().replace("-", ""));
//            i.getCreateBy().setId(userDTO.getId());
            i.setCreateDate(new Date());
//            i.getUpdateBy().setId(userDTO.getId());
            i.setUpdateDate(new Date());
            i.setDelFlag(0);
            i.setUrl(dto.getUrl());
            //文件类型处理
            List<String> strings = Arrays.asList(dto.getName().split("\\."));
            if (CollectionUtils.isNotEmpty(strings)) {
                i.setType(strings.get(1));
            }
            i.setAttachmentId(id);
            i.setAttachmentName(dto.getName());
            i.setAttachmentFlag("workcontract");
            i.setFileSize(dto.getSize());
            i.setSort(j);
            ossServiceMapper.insertWorkAttachment(i, userDTO);
            j++;
        }
    }

    /**
     * 保存附件信息
     * @param list 待保存的附件列表
     * @param userDTO 当前登录用户
     * @param id 关联id
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveFilesNew(List<WorkAttachmentDto> list, UserDTO userDTO, String id,String attachmentFlag) {
        int j = 1;
        for (WorkAttachmentDto dto : list) {
            WorkAttachment i = new WorkAttachment();
            //包含了url、size、name
            i.setId(UUID.randomUUID().toString().replace("-", ""));
//            i.getCreateBy().setId(userDTO.getId());
            i.setCreateDate(new Date());
//            i.getUpdateBy().setId(userDTO.getId());
            i.setUpdateDate(new Date());
            i.setDelFlag(0);
            i.setUrl(dto.getUrl());
            //文件类型处理
            List<String> strings = Arrays.asList(dto.getName().split("\\."));
            if (CollectionUtils.isNotEmpty(strings)) {
                i.setType(strings.get(1));
            }
            i.setAttachmentId(id);
            i.setAttachmentName(dto.getName());
            i.setAttachmentFlag(attachmentFlag);
            i.setFileSize(dto.getSize());
            i.setSort(j);
            ossServiceMapper.insertWorkAttachment(i, userDTO);
            j++;
        }
    }

    /**
     * 修改附件信息
     * @param list 待修改的附件列表
     * @param userDTO 当前登录用户
     * @param id 关联id
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateFiles(List<WorkAttachmentDto> list, UserDTO userDTO, String id) {
        int j = 1;
        String names = new String();
        //表中存在，但是传过来不存在，说明已删除，表中数据也要删除
        for (WorkAttachmentDto dto : list) {
            names = names + "," +dto.getUrl();
        }
        //查询保存的附件信息
        List<WorkAttachment> infoList = workContractInfoMapper.findList(id);
        if (CollectionUtils.isNotEmpty(infoList)) {
            for (WorkAttachment i : infoList) {
                if (!names.contains(i.getUrl())) {
                    ossServiceMapper.deleteById(i.getId());
                }
            }
        }
        //保存信息
        for (WorkAttachmentDto dto : list) {
            //判断是否存在
            Integer isExit = workContractInfoMapper.findIsExit(id, dto.getName());
            if (isExit == 0) {
                WorkAttachment i = new WorkAttachment();
                //包含了url、size、name
                i.setId(UUID.randomUUID().toString().replace("-", ""));
//                i.getCreateBy().setId(userDTO.getId());
                i.setCreateDate(new Date());
//                i.getUpdateBy().setId(userDTO.getId());
                i.setUpdateDate(new Date());
                i.setDelFlag(0);
                i.setUrl(dto.getUrl());
                //文件类型处理
                List<String> strings = Arrays.asList(dto.getName().split("\\."));
                if (CollectionUtils.isNotEmpty(strings)) {
                    i.setType(strings.get(1));
                }
                i.setAttachmentId(id);
                i.setAttachmentName(dto.getName());
                i.setAttachmentFlag("workcontract");
                i.setFileSize(dto.getSize());
                i.setSort(j);
                ossServiceMapper.insertWorkAttachment(i, userDTO);
                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<WorkAttachmentDto> dtos = workContractInfoMapper.findDtos(info.getId());
                if (CollectionUtils.isNotEmpty(dtos)) {
                    for (WorkAttachmentDto i : dtos) {
                        i.setCreateBy(UserUtils.get(i.getBy()));
                    }
                }
            }
        }
        return infoList;
    }
}
