package com.jeeplus.finance.contractRegistration.service;

import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.jeeplus.common.TokenProvider;
import com.jeeplus.finance.contractRegistration.domain.ContractFilePaper;
import com.jeeplus.finance.contractRegistration.domain.ContractInfo;
import com.jeeplus.finance.contractRegistration.mapper.ContractFilePaperMapper;
import com.jeeplus.finance.contractRegistration.mapper.ContractInfoMapper;
//import com.jeeplus.pubmodules.oss.mapper.OssServiceMapper;
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.sys.utils.UserUtils;
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.*;

/**
 * @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.getCreateById());
            filePaper.setCreateById(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 = SpringUtil.getBean ( IUserApi.class ).getByToken (TokenProvider.getCurrentToken ( ));
//        UserDTO userDTO = UserUtils.getCurrentUserDTO();
        ContractFilePaper file = new ContractFilePaper();
        BeanUtils.copyProperties(filePaper, file);
        file.setId(id);
        file.setUpdateById(userDTO.getId());
        file.setUpdateTime(new Date());
        mapper.updateById(file);
        List<WorkAttachmentInfo> 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 = SpringUtil.getBean ( IUserApi.class ).getByToken (TokenProvider.getCurrentToken ( ));
//        UserDTO userDTO = UserUtils.getCurrentUserDTO();
        String id = UUID.randomUUID().toString().replace("-", "");
        ContractFilePaper file = new ContractFilePaper();
        BeanUtils.copyProperties(filePaper, file);
        file.setId(id);
        file.setCreateById(userDTO.getId());
        file.setCreateTime(filePaper.getCreateTime());
        file.setUpdateById(userDTO.getId());
        file.setUpdateTime(new Date());
        mapper.insert(file);
        List<WorkAttachmentInfo> list = filePaper.getContractProperList();
//        if (CollectionUtils.isNotEmpty(list)) {
//            saveFiles(list, userDTO, id);
//        }
        saveFiles(list, userDTO, id,filePaper);
        return id;
    }

    /**
     * 修改附件信息
     * @param list 待修改的附件列表
     * @param userDTO 当前登录用户
     * @param id 关联id
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateFiles(List<WorkAttachmentInfo> list, UserDTO userDTO, String id,String contractInfoId) {
        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, contractInfoId, 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());
                //文件类型处理
                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);
                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,ContractFilePaper filePaper) {
        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());
            //文件类型处理
            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);
            Map<String,String> map = new HashMap<>();
            String workAttachment = JSON.toJSONString((i));
            String userDTOInfo = JSON.toJSONString((userDTO));
            map.put("workAttachment",workAttachment);
            map.put("userDTO",userDTOInfo);
            updateFiles(list, userDTO, filePaper.getId(),filePaper.getContractInfoId());
            //SpringUtil.getBean ( IWorkAttachmentApi.class ).insertWorkAttachment(map);
//            ossServiceMapper.insertWorkAttachment(i, userDTO);
            j++;
        }
    }

}
