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

import com.jeeplus.sys.service.dto.UserDTO;
import com.jeeplus.sys.utils.UserUtils;
import com.jeeplus.test.cw.contractRegistration.domain.ContractFile;
import com.jeeplus.test.cw.contractRegistration.domain.ContractFilePaper;
import com.jeeplus.test.cw.contractRegistration.domain.ContractInfo;
import com.jeeplus.test.cw.contractRegistration.mapper.ContractFilePaperMapper;
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.service.dto.WorkAttachmentDto;
import org.flowable.editor.language.json.converter.util.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.BeanUtils;

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

/**
 * @author: 王强
 * @create: 2022-11-29 14:21
 **/
@Service
public class ContractFilePaperService {

    @Resource
    private OssServiceMapper ossServiceMapper;

    @Resource
    private ContractFilePaperMapper mapper;

    @Resource
    private ContractInfoMapper infoMapper;

    public String saveInfo(ContractFilePaper filePaper) throws Exception {

        ContractFilePaper info = mapper.selectFilePaperByContractInfoId(filePaper.getId());
        if (null != info) {
            filePaper.setFileCreateName(filePaper.getCreateBy());
            filePaper.setCreateBy(filePaper.getCreateId());
            infoMapper.updatefiledPaperTypeById(info.getContractInfoId(),filePaper.getFiledPaperType());
            return update(filePaper, info.getId());
        }else {
            return add(filePaper);
        }
    }

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

    }

    public ContractFilePaper findByContractInfoId(String id) {
        return mapper.selectFilePaperByContractInfoId(id);
    }

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

    /**
     * 合同登记新增
     */
    @Transactional(rollbackFor = Exception.class)
    public String add(ContractFilePaper filePaper) throws Exception{
        //获取当前登录人信息
        UserDTO userDTO = UserUtils.getCurrentUserDTO();
        String id = UUID.randomUUID().toString().replace("-", "");
        ContractFilePaper file = new ContractFilePaper();
        BeanUtils.copyProperties(filePaper, 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 = filePaper.getContractProperList();
        if (CollectionUtils.isNotEmpty(list)) {
            saveFiles(list, userDTO, id);
        }
        return id;
    }

    /**
     * 修改附件信息
     * @param list 待修改的附件列表
     * @param userDTO 当前登录用户
     * @param id 关联id
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateFiles(List<WorkAttachmentDto> list, UserDTO userDTO, String id,String contractInfoId) {
        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, contractInfoId, 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++;
        }
    }

}
