package com.blueland.service.impl;


import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;

/**
 * @author 代码自动生成工具
 * @version 1.0
 * @since
 */

import java.util.*;

import javax.servlet.http.HttpServletRequest;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.blueland.bo.*;
import com.blueland.model.TPfAttachment;
import com.blueland.sdk.FileServiceHelper;
import com.blueland.sdk.bean.FileBean;
import com.blueland.sdk.bean.MessageBean;
import com.blueland.service.IAttachmentService;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.blueland.dao.AttachmentDao;

@Slf4j
@Service
public class AttachmentServiceImpl extends ServiceImpl<AttachmentDao, TPfAttachment> implements IAttachmentService {

    /**
     * 文件上传的根目录，配置文件中可定义，是所有模块文件上传的父相对路径
     */
    @Autowired
    //Attachment对应的DAO类,主要用于数据库的增删改查等操作
    private AttachmentDao attachmentDao;

    @Autowired
    private ThreadPoolTaskExecutor executor;

    /**
     * @方法名: uploadFile
     * @描述:文件上传
     * @作者:高星
     * @时间:2014-5-7 上午9:53:10
     * @参数:@param request
     * @参数:@param childDir 文件保存的子路径，个模块的文件上传到不同的子路径
     * @参数:@param params 扩展字段 用于添加自定义信息的键
     * @参数:@param values 扩展字段，用于添加自定义字段的值
     * @参数:@return Map 文件上传后返回的文件信息
     * @参数:@throws Exception
     * @返回值：Map<String,Object>
     */
    @Override
    public Map<String, Object> uploadFile(HttpServletRequest request, String childDir, String[] params,
                                          Map<String, Object[]> values) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = mRequest.getFileMap();
        String relativeuplodUrl = "";
        if (StringUtils.isNotBlank(childDir)) {
            relativeuplodUrl += childDir + "/";
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateStr = sdf.format(new Date());
        relativeuplodUrl += dateStr + "/";
        String uploadDir = "";
        uploadDir = relativeuplodUrl.replace(File.separator, "/");
        File file = new File(uploadDir);

        if (!(file.exists() && file.isDirectory())) {
            file.mkdirs();
        }

        String fileName = null;
        int i = 0;
        for (Iterator<Map.Entry<String, MultipartFile>> it = fileMap.entrySet().iterator(); it.hasNext(); i++) {

            Map.Entry<String, MultipartFile> entry = it.next();
            MultipartFile mFile = entry.getValue();

            fileName = mFile.getOriginalFilename();// 文件原名

            String storeName = rename(fileName);// 文件保存名称

            String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);// 文件名后缀

            String uploadUrl = uploadDir + "/" + fileName;// 文件保存绝对路径

            BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(uploadUrl));

            int copiedBytes = FileCopyUtils.copy(mFile.getInputStream(), outputStream);// 返回值为已复制的字节数
            if (copiedBytes > 0) {
                // 固定参数值对
                map.put("fileName", fileName);
                map.put("fileSize", new File(uploadUrl).length());
                map.put("uploadUrl", relativeuplodUrl + fileName);
                map.put("contentType", suffix);
                map.put("result", "true");// 上传成功的标识
            } else {
                map.put("result", "false");// 上传失败的标识
            }
            // 自定义参数值对
            if (params != null) {
                for (String param : params) {
                    map.put(param, values.get(param)[i]);
                }
            }
        }
        return map;
    }

    public static String rename(String name) {

        // Long now = Long.parseLong(new SimpleDateFormat("yyyyMMddHHmmss")
        // .format(new Date()));
        // Long random = (long) (Math.random() * now);

        String fileName = String.valueOf(new Date().getTime());
        if (name.indexOf(".") != -1) {
            fileName += name.substring(name.lastIndexOf("."));
        }
        return fileName;
    }

    /**
     * 保存到私有云
     *
     * @param attId
     * @param uploadDirUrl
     * @param b
     */
    @Override
    public void asynFileForSyy(String attId, String uploadDirUrl, boolean b) {
//		executor.execute(new Runnable(){
//			@Override
//			public void run() {
//			
//			}
//		});

        try {
//			log.info("私有云存储文件---startTime:"+new Date());
//			log.info("私有云存储文件---fileId:"+attId+"&fileUrl:"+uploadDirUrl);
            String fileIdSyy = upload(uploadDirUrl);
            TPfAttachment atta = new TPfAttachment();
            atta.setAttId(attId);
            atta.setSdkAppId(fileIdSyy);
            attachmentDao.updateById(atta);
//			log.info("私有云存储文件---endTime:"+new Date());
        } catch (Exception e) {
//			log.error("存储私有云文档异常 ---fileId:"+attId+"&fileUrl:"+uploadDirUrl,e);
        }
    }


    public final static String PRIVATE_KEY =
            // "-----BEGIN RSA PRIVATE KEY-----\n" +
            "MIICXgIBAAKBgQDWvkiXjub57S8exgionEzUBiGTuQWw27AJvp93at1sgMJl7d6q\n"
                    + "XA7syrzKkg1I9IkxerlqJLiwO6NUk5dAqk0+6rMuN6O4FCoPERRGP45QuTjTZGHl\n"
                    + "tdi80pxInNjcHlxHDkZ0Zs2rGOOHYdme4sSaaqKN7IbNRvJ+EM0aTEyq6wIDAQAB\n"
                    + "AoGBAJNNhYgI62HHFAp891WJmZ3a8s9dHI07tR6KFuMYd/jEvhSjPZkIeuhtDWG7\n"
                    + "G8fOjglV0LgBpnqk/h22/ArMhxz+g2lHTwvfSWw7k7Ovcq918FKEHx2h5Cntmltb\n"
                    + "TqiwibgP+cF9LzBIcsaDsedaP2d0oUbINRmTc2/eNZNx8vSxAkEA863/2gsp7phT\n"
                    + "EutwmVocNQf6BkR8QjfcrhpnuFcExCffqyp8fRiUa52K0ZcWkopuPHzjSmA8THJU\n"
                    + "H0ZAR+lYSQJBAOGZwQUSX20uw+Wa1rDD6JHhv61Fje/UFRBOmVeSZThsDy4Gf0d5\n"
                    + "6dtahvNayod12/RsM/eHu/a7Eo7NjUYhMZMCQQCjj1YdL8McgCe6mkeA10f5nHoI\n"
                    + "vO0+sSoxvk2CIP50/2KVDDZ07QuqVBt6ZNRk1f/6H8WcBY5TraWjPE8nNYvpAkEA\n"
                    + "kgG/gXfNmM0ubbhTgF2adGfFdO/SF8iLxV0JMzsFFYoiHOiJkYneh1/EfVViRF9L\n"
                    + "9pnc3DPVu66BKTjxWNT8zwJAcYoCCX5q8QKFF9v+LNykUc0hePZ1FE7Al9ESu7IB\n"
                    + "SZMQzKd2MMvbwNNvyLXwp81gLcTmWO8+otKchuIEFVNczA==\n";
    public final static String APP_ID = "HYCG_SYS";

    public final static String PWD = "123456";

    public final static String APP_TOKEN = "84214c10d7d64de7adce70a87cf4f55a";

    public final static String FILE_URL = "http://192.168.1.168/doc-cloud-service/file";

    /**
     * 私有云文件上传
     *
     * @param
     * @return
     */
    public static String upload(String filePath) {
        try {
            FileBean fileBean = new FileBean();
//			fileBean.setPrivateKey(PRIVATE_KEY);
//			fileBean.setApptoken(APP_TOKEN);
            fileBean.setAppId(APP_ID);
            fileBean.setPwd(PWD);
            fileBean.setFileServiceUrl(FILE_URL);
            FileServiceHelper fileServiceHelper = new FileServiceHelper(fileBean);
            //上传
            MessageBean mbupload = new MessageBean();
            mbupload = fileServiceHelper.upload(filePath);
            String docSdkFileId = mbupload.getFileId();
            return docSdkFileId;
        } catch (Exception e) {
            e.fillInStackTrace();
//			throw new BaseException("存储私有云文档异常");
            return null;
        }
    }

    @Override
    public Page<AttachmentEntity> findPageList(AttachmentEntity attachmentEntity, Integer curPage, Integer curPageSize) {
        // TODO Auto-generated method stub
        Page<AttachmentEntity> page = new Page<>(curPage, curPageSize);
        Page<AttachmentEntity> result = attachmentDao.findPage(page, attachmentEntity);
        return result;
    }

    @Override
    public TPfAttachment get(AttachmentEntity bo) {
        return this.baseMapper.selectOne(buildQueryWrapper(bo));
    }

    private LambdaQueryWrapper<TPfAttachment> buildQueryWrapper(AttachmentEntity bo) {
        LambdaQueryWrapper<TPfAttachment> lqw = Wrappers.lambdaQuery();
        lqw.eq(ObjectUtil.isNotEmpty(bo.getAttId()), TPfAttachment::getAttId, bo.getAttId());
        lqw.eq(ObjectUtil.isNotEmpty(bo.getAppId()), TPfAttachment::getAppId, bo.getAppId());
        lqw.like(ObjectUtil.isNotEmpty(bo.getAttName()), TPfAttachment::getAttName, bo.getAttName());
        lqw.eq(ObjectUtil.isNotEmpty(bo.getAttUrl()), TPfAttachment::getAttUrl, bo.getAttUrl());
        lqw.eq(ObjectUtil.isNotEmpty(bo.getAttType()), TPfAttachment::getAttType, bo.getAttType());
        lqw.eq(ObjectUtil.isNotEmpty(bo.getBizId()), TPfAttachment::getBizId, bo.getBizId());
        lqw.like(ObjectUtil.isNotEmpty(bo.getBizName()), TPfAttachment::getBizName, bo.getBizName());
        lqw.eq(ObjectUtil.isNotEmpty(bo.getAttShow()), TPfAttachment::getAttShow, bo.getAttShow());
        lqw.eq(ObjectUtil.isNotEmpty(bo.getCreateUserId()), TPfAttachment::getCreateUserId, bo.getCreateUserId());
        lqw.eq(ObjectUtil.isNotEmpty(bo.getUpdateUserId()), TPfAttachment::getUpdateUserId, bo.getUpdateUserId());
        lqw.like(ObjectUtil.isNotEmpty(bo.getCreateUserName()), TPfAttachment::getCreateUserName, bo.getCreateUserName());
        lqw.like(ObjectUtil.isNotEmpty(bo.getUpdateUserName()), TPfAttachment::getUpdateUserName, bo.getUpdateUserName());
        lqw.like(ObjectUtil.isNotEmpty(bo.getAttRemark()), TPfAttachment::getAttRemark, bo.getAttRemark());
        lqw.eq(ObjectUtil.isNotEmpty(bo.getSdkAppId()), TPfAttachment::getSdkAppId, bo.getSdkAppId());
        return lqw;
    }

}
