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.ContractFile;
import com.jeeplus.finance.contractRegistration.domain.ContractInfo;
import com.jeeplus.finance.contractRegistration.mapper.ContractFileMapper;
import com.jeeplus.finance.contractRegistration.mapper.ContractInfoMapper;
//import com.jeeplus.pubmodules.oss.domain.WorkAttachment;
//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.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * @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.getCreateById());
            contractFile.setCreateById(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 = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
        String id = UUID.randomUUID().toString().replace("-", "");
        ContractFile file = new ContractFile();
        BeanUtils.copyProperties(contractFile, file);
        file.setId(id);
        file.setCreateById(userDTO.getId());
        file.setCreateTime(new Date());
        file.setUpdateById(userDTO.getId());
        file.setUpdateTime(new Date());
        mapper.insert(file);
        List<WorkAttachmentInfo> 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 = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
        ContractFile file = new ContractFile();
        BeanUtils.copyProperties(contractFile, file);
        file.setId(id);
        file.setUpdateById(userDTO.getId());
        file.setUpdateTime(new Date());
        mapper.updateById(file);
        List<WorkAttachmentInfo> 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<WorkAttachmentInfo> dtos = mapper.findDtos(dto.getFileId());
            List<WorkAttachmentInfo> contractInfoList = mapper.findDtos(dto.getContractInfoId());

            if (CollectionUtils.isNotEmpty(dtos)) {
                for (WorkAttachmentInfo i : dtos) {
                    i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(i.getBy()));
                }
                dto.setContractInfoList(dtos);
            }
            if (CollectionUtils.isNotEmpty(contractInfoList)){
                for (WorkAttachmentInfo i : contractInfoList){
                    i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(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<WorkAttachmentInfo> list, UserDTO userDTO, String id) {
        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, 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) {
        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);
            SpringUtil.getBean ( IWorkAttachmentApi.class ).insertWorkAttachment(map);
//            ossServiceMapper.insertWorkAttachment(i, userDTO);
            j++;
        }
    }
}
