package com.ag.demo.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Assert;
import com.ag.base.BaseService;
import com.ag.base.DefaultBussniessImpl;
import com.ag.demo.entity.WFile;
import com.ag.demo.face.IParament;
import com.ag.util.StrUtil;
import org.apache.commons.io.IOUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class FileUploadService extends BaseService {

    @Autowired
    private DefaultBussniessImpl bizDao;

    @Transactional
    public List<WFile> uploadAg(JSONObject param, HttpServletResponse response, HttpServletRequest request) throws IOException {
        Assert.isTrue(!StrUtil.isEmpty(super.getTenancyId(param)), "非法的上传文件请求！");
        Map<String, InputStream> inputMap = new HashMap<>();
        for(Map.Entry<String, Object> entry : param.entrySet()){
            if (entry.getValue() instanceof InputStream && param.has(entry.getKey()+"__name")){
                inputMap.put(param.getString(entry.getKey()+"__name"), (InputStream)entry.getValue());
            }
        }
        List<WFile> saveList = CollUtil.list(false);
        long time = System.currentTimeMillis();
        int index = 0;
        for(Map.Entry<String, InputStream> entry : inputMap.entrySet()){
            String saveName = time+"_"+index;
            WFile wFile = new WFile();
            execute(param, wFile, entry.getKey(), entry.getValue(), saveName);
            saveList.add(wFile);
            index++;
        }
        bizDao.saveAll(saveList);
        return saveList;
        //WebUtil.send(response, "1111");
    }

    private void execute(org.json.JSONObject param, WFile wFile, String oriName, InputStream input,String realName) throws IOException{
        super.setSaveUser(param, wFile);
        wFile.setFName(oriName);
        wFile.setTName(param.getString(IParament.bizType));
        wFile.setTId(param.getString(IParament.bizId));
        Assert.isTrue(StrUtil.indexOf(oriName, ".") > 0, "文件格式异常！");
        //文件类型
        String postfix = StrUtil.substringAfterLast(oriName, ".");
        Assert.isTrue(!StrUtil.equalsAnyIgnoreCase(postfix, "asp","aspx","php","jsp"), "非法的文件类型");
        /*String path = StrUtil.join(IParament.basePath, "/", wFile.getTenancyId(), "/",
                DateUtil.year(super.getNow()), "/", DateUtil.month(super.getNow()), "/",
                realName, ".", postfix);*/
        String path = getSysPath(param, realName, postfix, wFile.getTenancyId());
        wFile.setFPath(path);
        OutputStream output = FileUtil.getOutputStream(path);
        IOUtils.copy(input, output);
        output.close();
        input.close();
    }

    private String getSysPath(org.json.JSONObject param, String realName, String postfix, String tenancyId){
        String path = "";
        if (param.has("pathType") && StrUtil.equals(param.getString("pathType"), "system")){
            path = StrUtil.join(IParament.sysPath, "/",
                    DateUtil.year(super.getNow()), "/", DateUtil.month(super.getNow())+1, "/",
                    realName, ".", postfix);
        }else {
            path = StrUtil.join(IParament.tmpPath, "/", tenancyId, "/",
                    DateUtil.year(super.getNow()), "/", DateUtil.month(super.getNow()), "/",
                    realName, ".", postfix);
        }
        return path;
    }

    /*public static void main(String[] args) throws IOException {
        String oriPath = "D:\\ag_note\\中山\\专票资料(最新).txt";
        InputStream input = FileUtil.getInputStream(oriPath);
        //FileUtil.touch()
        OutputStream output = FileUtil.getOutputStream("e:\\ag_note\\中山\\专票资料(最新).txt");
        IOUtils.copy(input, output);
        output.close();
        input.close();
    }*/
}