package com.jeeplus.test.cw.contractRegistration.service;

import com.jeeplus.sys.service.dto.UserDTO;
import com.jeeplus.sys.utils.StringUtils;
import com.jeeplus.sys.utils.UserUtils;
import com.jeeplus.test.cw.contractRegistration.domain.ContractFile;
import com.jeeplus.test.cw.contractRegistration.domain.ContractInfo;
import com.jeeplus.test.cw.contractRegistration.mapper.ContractFileMapper;
import com.jeeplus.test.cw.contractRegistration.mapper.ContractInfoMapper;
import com.jeeplus.test.oss.domain.WorkAttachment;
import com.jeeplus.test.oss.mapper.OssServiceMapper;
import com.jeeplus.test.workContract.domain.WorkContractFile;
import com.jeeplus.test.workContract.service.dto.WorkAttachmentDto;
import com.jeeplus.test.workContract.service.dto.WorkContractFileDto;
import org.flowable.editor.language.json.converter.util.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author: 王强
 * @create: 2022-11-10 16:12
 **/
@Service
public class ContractFileService {

    @Resource
    private ContractFileMapper mapper;

    @Resource
    private ContractInfoMapper infoMapper;

    @Resource
    private OssServiceMapper ossServiceMapper;

    /**
     * 根据id修改status
     */
    public void updateStatusById(ContractFile contractFile) {
        ContractInfo infoById = infoMapper.getInfoById(contractFile.getId());
        if (null != infoById){
            infoMapper.updatefiledTypeById(contractFile.getId(),contractFile.getFiledType());
            mapper.updateStatusById(contractFile.getId(), contractFile.getFiledType());
        } else {
            ContractFile file = mapper.getById(contractFile.getId());
            infoMapper.updatefiledTypeById(file.getContractInfoId(),contractFile.getFiledType());
            mapper.updateStatusById(contractFile.getId(), contractFile.getFiledType());
        }

    }

    public String saveInfo(ContractFile contractFile) throws Exception {
//        if (StringUtils.isNotEmpty(contractFile.getId())) {
//
//        }
        ContractFile info = mapper.selectFileByContractInfoId(contractFile.getId());
        if (null != info) {
            contractFile.setFileCreateName(contractFile.getCreateBy());
            contractFile.setCreateBy(contractFile.getCreateId());
            infoMapper.updatefiledTypeById(info.getContractInfoId(),contractFile.getFiledType());
            return update(contractFile, info.getId());
        }else {
            return add(contractFile);
        }
    }

    /**
     * 合同登记新增
     */
    @Transactional(rollbackFor = Exception.class)
    public String add(ContractFile contractFile) throws Exception{
        //获取当前登录人信息
        UserDTO userDTO = UserUtils.getCurrentUserDTO();
        String id = UUID.randomUUID().toString().replace("-", "");
        ContractFile file = new ContractFile();
        BeanUtils.copyProperties(contractFile, file);
        file.setId(id);
        file.setCreateBy(userDTO.getId());
        file.setCreateDate(new Date());
        file.setUpdateBy(userDTO.getId());
        file.setUpdateDate(new Date());
        mapper.insert(file);
        List<WorkAttachmentDto> list = contractFile.getContractInfoList();
        if (CollectionUtils.isNotEmpty(list)) {
            saveFiles(list, userDTO, id);
        }
        return id;
    }

    /**
     * 合同登记归档修改
     */
    @Transactional(rollbackFor = Exception.class)
    public String update(ContractFile contractFile, String id) {
        //获取当前登录人信息
        UserDTO userDTO = UserUtils.getCurrentUserDTO();
        ContractFile file = new ContractFile();
        BeanUtils.copyProperties(contractFile, file);
        file.setId(id);
        file.setUpdateBy(userDTO.getId());
        file.setUpdateDate(new Date());
        mapper.updateById(file);
        List<WorkAttachmentDto> list = contractFile.getContractInfoList();
        if (CollectionUtils.isNotEmpty(list)) {
            updateFiles(list, userDTO, file.getId());
        }else {
            //删除文件信息
            mapper.deleteFileInfo(file.getId());
        }
        return file.getId();
    }

    public ContractFile findById(String id) {
        ContractFile dto = mapper.findById(id);
        if (dto == null){
            dto = mapper.findByInfoId(id);
        }
        if (dto != null){
            // 查询归档附件信息
            List<WorkAttachmentDto> dtos = mapper.findDtos(dto.getFileId());
            List<WorkAttachmentDto> contractInfoList = mapper.findDtos(dto.getContractInfoId());

            if (CollectionUtils.isNotEmpty(dtos)) {
                for (WorkAttachmentDto i : dtos) {
                    i.setCreateBy(UserUtils.get(i.getBy()));
                }
                dto.setContractInfoList(dtos);
            }
            if (CollectionUtils.isNotEmpty(contractInfoList)){
                for (WorkAttachmentDto i : contractInfoList){
                    i.setCreateBy(UserUtils.get(i.getBy()));
                }
                dto.setContractProperList(contractInfoList);
            }

        }
        return dto;
    }

    public ContractFile findByContractInfoId(String id) {
        return mapper.selectFileByContractInfoId(id);
    }

    /**
     * 修改附件信息
     * @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 = mapper.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 = mapper.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("cwWorkContract");
                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 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("cwWorkContract");
            i.setFileSize(dto.getSize());
            i.setSort(j);
            ossServiceMapper.insertWorkAttachment(i, userDTO);
            j++;
        }
    }
}
