package com.hzya.frame.sys.businessFile.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hzya.frame.basedao.service.impl.BaseService;
import com.hzya.frame.sys.businessFile.dao.IBusinessFileDao;
import com.hzya.frame.sys.businessFile.entity.BusinessFileEntity;
import com.hzya.frame.sys.businessFile.service.IBusinessFileService;
import com.hzya.frame.sys.file.upload.entity.FileResultEntity;
import com.hzya.frame.sys.file.upload.entity.FileUploadEntity;
import com.hzya.frame.sys.file.upload.service.IFileUploadService;
import com.hzya.frame.uuid.UUIDLong;
import com.hzya.frame.web.action.SessionContext;
import com.hzya.frame.web.entity.BaseResult;
import com.hzya.frame.web.entity.JsonResultEntity;
import com.hzya.frame.web.exception.BaseSystemException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @description: 文件业务关系  service
 * @tableName: sys_business_file
 * @entityName: BusinessFileEntity
 * @author: gjh
 * @history: 1.0
 */
@Service(value = "sys_business_fileService")
public class BusinessFileServiceImpl extends BaseService<BusinessFileEntity, Long> implements IBusinessFileService {
    protected IBusinessFileDao businessfileDao;

    @Autowired
    private IFileUploadService fileUploadService;

    @Autowired
    public void setBusinessFileDao(IBusinessFileDao dao) {

        this.businessfileDao = dao;
        this.dao = dao;
    }

    @Override
    public BusinessFileEntity saveBusinessFile(BusinessFileEntity entity) {
        entity.setId(String.valueOf(UUIDLong.longUUID()));
        businessfileDao.save(entity);
        return entity;
    }
    @Override
    public JsonResultEntity saveBusinessFileByJsonObj(JSONObject requestData) {
        String jsonStr =  requestData.getString("jsonStr");
        BusinessFileEntity entity = JSON.parseObject(jsonStr,BusinessFileEntity.class);
        entity.setId(String.valueOf(UUIDLong.longUUID()));
        businessfileDao.save(entity);

        return BaseResult.getSuccessMessageEntity("保存成功",entity);
    }
    @Override
    public BusinessFileEntity saveBatchBusinessFile(BusinessFileEntity entity) throws Exception {
        /** 获取传入的文件集合*/
        List<BusinessFileEntity> entityBusinessFileEntityList = null;
        String jsonStr = entity.getJsonDataStr();

        if (jsonStr != null && !"".equals(jsonStr)) {
            BusinessFileEntity businessFileEntity = JSON.parseObject(jsonStr, BusinessFileEntity.class);
            entity.setTicket_id(businessFileEntity.getTicket_id() == null ? entity.getTicket_id() : businessFileEntity.getTicket_id());
            entity.setBusiness_type(businessFileEntity.getBusiness_type());
            entityBusinessFileEntityList = businessFileEntity.getBusinessFileEntityList();
        } else {
            entityBusinessFileEntityList = entity.getBusinessFileEntityList();

        }


        if (null != entityBusinessFileEntityList && entityBusinessFileEntityList.size() > 0) {
//            UserEntity userEntity = SessionContext.getCurrentUser();
            for (BusinessFileEntity businessFileEntity : entityBusinessFileEntityList) {

                String file_business_id = businessFileEntity.getBusiness_id();
                //如果businessFileEntity内的business_id 与主表传入的不一致，说明需要重新上传附件
                if (null != file_business_id && !"".equals(file_business_id) && !file_business_id.equals(entity.getBusiness_id())) {

                    String fileSaveName = businessFileEntity.getFile_save_name();
                    FileUploadEntity oldFileEntity = new FileUploadEntity();
                    oldFileEntity.setFilesavename(fileSaveName);
                    List<FileUploadEntity> fileUploadEntityList = fileUploadService.query(oldFileEntity);
                    if (fileUploadEntityList.size() > 0) {
                        oldFileEntity = fileUploadEntityList.get(0);
                    } else {
                        throw new BaseSystemException("获取历史附件错误,请联系管理员！");
                    }
                    String oldPath = oldFileEntity.getFilepath() + "/" + fileSaveName;
                    //根据老文件获取文件，写到新的文件夹下面
                    File oldFile = new File(oldPath);
                    //获取流
                    InputStream in = new FileInputStream(oldFile);
                    //创建文件
                    MockMultipartFile mockMultipartFile = new MockMultipartFile(oldFileEntity.getFilename(), oldFileEntity.getFilename(), oldFileEntity.getType(), in);

                    FileResultEntity fileResultEntity = new FileResultEntity();
                    fileResultEntity.setBusiness_id(Long.valueOf(entity.getBusiness_id()));
                    fileResultEntity.setTicket_id(entity.getTicket_id());
                    fileResultEntity.setBusiness_type(entity.getBusiness_type());
                    fileResultEntity = fileUploadService.fileUpload(mockMultipartFile, fileResultEntity);
                    FileUploadEntity fileUploadEntity = (FileUploadEntity) fileResultEntity.getAttribute();
                    businessFileEntity.setFile_save_name(fileUploadEntity.getFilesavename());
                    businessFileEntity.setFile_name(oldFileEntity.getFilename());
                    businessFileEntity.setId(null);
                }


                businessFileEntity.setBusiness_id(entity.getBusiness_id());
                businessFileEntity.setBusiness_type(entity.getBusiness_type());
                businessFileEntity.setFile_number(entity.getFile_number());
                businessFileEntity.setTicket_id(businessFileEntity.getTicket_id() == null ? entity.getTicket_id() : businessFileEntity.getTicket_id());
                businessFileEntity.setDocuments_name(entity.getDocuments_name());
//                businessFileEntity.setCreate_user_id(userEntity.getId());
//                businessFileEntity.setUpload_user(userEntity.getView_name());
//                businessFileEntity.setModify_user_id(userEntity.getId());
                businessfileDao.saveOrUpdate(businessFileEntity);
            }
        }

        return entity;
    }

    @Override
    public List<BusinessFileEntity> listQueryBusinessFilesByGroup(BusinessFileEntity entity) {
        return businessfileDao.listQueryBusinessFiles(entity);
    }

    @Override
    public List<BusinessFileEntity> queryBusinessFileByServiceType(BusinessFileEntity entity) {
        /** 返回的附件集合*/
        List<BusinessFileEntity> returnBusinessFiles = new ArrayList<BusinessFileEntity>();
        String str = entity.getTicketAllJsonStr();

        List<String> ticketAllServiceEntities = null;
        if (null == str || "".equals(str)) {
            return returnBusinessFiles;
        } else {
            ticketAllServiceEntities = JSON.parseArray(str, String.class);
        }
        if (null == ticketAllServiceEntities || ticketAllServiceEntities.size() == 0) {
            return returnBusinessFiles;
        } else {
            entity.setTicketAllServiceEntities(ticketAllServiceEntities);
            returnBusinessFiles = businessfileDao.queryBusinessFileByServiceType(entity);
        }

        return returnBusinessFiles;
    }

    @Override
    public BusinessFileEntity validateTicketFiles(BusinessFileEntity entity) {
        Long ticket_id = entity.getTicket_id();

        /** 根据单票的ID获取单票下的所有的附件*/
        BusinessFileEntity queryBusinessFileEntity = new BusinessFileEntity();
        queryBusinessFileEntity.setTicket_id(ticket_id);
        List<BusinessFileEntity> entityBusinessFileEntityList = businessfileDao.query(queryBusinessFileEntity);
        if (entityBusinessFileEntityList.size() == 0) {
            throw new BaseSystemException("单票ID：" + ticket_id + "未查询到可打包下载的附件！");
        }
        entity.setBusinessFileEntityList(entityBusinessFileEntityList);

        return entity;
    }

    @Override
    public BusinessFileEntity saveBusinessFileToGuarantee(BusinessFileEntity entity) {
        /** 获取当前登陆人*/
         /** 获取file转成的集合JSON字符串*/
        String fileInfo = entity.getFileInfo();
        /** 转成对象*/
        BusinessFileEntity businessFileEntity = JSON.parseObject(fileInfo, BusinessFileEntity.class);
        /** 获取file集合*/
        List<BusinessFileEntity> businessFileEntityList = businessFileEntity.getBusinessFileEntityList();
        if (null != businessFileEntityList && businessFileEntityList.size() > 0) {
            for (BusinessFileEntity fileEntity : businessFileEntityList) {
//                if (fileEntity.getId() == null) {
//                    fileEntity.setCreate_user_id(userEntity.getId());
//                    fileEntity.setModify_user_id(userEntity.getId());
//                    fileEntity.setOrg_id(userEntity.getOrg_id());
//                    fileEntity.setCompany_org_id(userEntity.getCompany_org_id());
//                    fileEntity.setBusiness_type(entity.getBusiness_type());
//                    fileEntity.setBusiness_id(entity.getBusiness_id());
//                    fileEntity.setUpload_user(userEntity.getView_name());
//                    businessfileDao.saveOrUpdate(fileEntity);
//                }
            }
            entity.setBusinessFileEntityList(businessFileEntityList);
        }


        return entity;
    }
}
