package com.cnd3b.restcontroller.system.system;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cnd3b.common.actionscore.ActionScore;
import com.cnd3b.common.data.Rows;
import com.cnd3b.common.data.SQLFactory;
import com.cnd3b.utility.Math;
import com.cnd3b.utility.WebRequest;
import com.cnd3b.utility.obs.Bucket;
import com.cnd3b.utility.obs.mpc.MediaMetaData;
import com.obs.services.model.HttpMethodEnum;
import com.obs.services.model.ObjectMetadata;
import com.cnd3b.common.Controller;
import com.cnd3b.common.data.Row;
import com.cnd3b.common.data.db.DBConnect;
import com.cnd3b.utility.obs.BucketFile;
import com.cnd3b.utility.obs.mpc.MpcFactory;
import org.apache.commons.lang.StringUtils;
import p2.pao.PaoRemote;
import p2.pao.PaoSetRemote;
import p2.util.P2Exception;
import p2.webclient.system.controller.Utility;

import java.io.File;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.*;


public class docManage extends Controller {


    /**
     * 附件文件夹根目录
     */
    public static String gen_file = "/Users/shenjingwei/Documents/代码开发/idea/DSB_CRM/p2-4.1.0_201907241548/deploy/build/pic.war/";

    public docManage(JSONObject content) {
        super(content);
    }

    public static HashMap<String, HashMap<String, String>> obsfilemap = new HashMap<>();

    /**
     * 获取文件名称
     *
     * @return
     */
    public String getFileName() {
        Bucket bucket = new Bucket(siteid);
        double fusevolume = bucket.getVolume();
        double fmaxvolume = 0;
        Rows rows = dbConnect.runSqlQuery("select fmaxvolume from tobsmag where siteid='" + siteid + "'");
        if (rows.isEmpty()) {
            return getErrReturnObject().setErrMsg("云存储空间不足").toString();
        }
        fmaxvolume = rows.get(0).getInteger("fmaxvolume");
        if (Math.mul(fmaxvolume, 1024d * 1024d * 1024d) <= fusevolume) {
            return getErrReturnObject().setErrMsg("云存储空间不足").toString();
        }
        JSONObject object = new JSONObject();
        try {
            String filename = content.getString("filename");
            String filetype = content.getString("filetype");
            String ownertable = content.getString("ownertable");
            String ownerid = content.getString("ownerid");
            String ftype = content.getString("ftype");
            HttpMethodEnum HttpMethod = HttpMethodEnum.PUT;
            if (content.containsKey("HttpMethod")) {
                if ("post".equalsIgnoreCase(content.getString("HttpMethod"))) {
                    HttpMethod = HttpMethodEnum.POST;
                } else if ("get".equalsIgnoreCase(content.getString("HttpMethod"))) {
                    HttpMethod = HttpMethodEnum.GET;
                }
            }
            String serialnumber = createMD5FileName(filename) + "." + filetype;
            BucketFile bucketFile = new BucketFile(siteid);
            String url = bucketFile.getUploadUrl(filetype, serialnumber, HttpMethod);
            bucketFile.close();

            object.put("obsfilename", serialnumber);
            object.put("obsuploadurl", url);

            HashMap<String, String> map = new HashMap<>();
            map.put("filename", filename);
            map.put("filetype", filetype);
            map.put("ownertable", ownertable);
            map.put("ownerid", ownerid);
            map.put("ftype", ftype);

            obsfilemap.put(serialnumber, map);
        } catch (Exception e) {
            return getErrReturnObject().setErrMsg(e.getMessage()).toString();
        }
        return getSucReturnObject().setData(object).toString();
    }

    /**
     * 获取文件名称
     *
     * @return
     */
    public String getFileNames() {
        Bucket bucket = new Bucket(siteid);
        double fusevolume = bucket.getVolume();
        double fmaxvolume = 0;
        Rows rows = dbConnect.runSqlQuery("select fmaxvolume from tobsmag where siteid='" + siteid + "'");
        if (rows.isEmpty()) {
            return getErrReturnObject().setErrMsg("云存储空间不足").toString();
        }
        fmaxvolume = rows.get(0).getInteger("fmaxvolume");
        if (Math.mul(fmaxvolume, 1024d * 1024d * 1024d) <= fusevolume) {
            return getErrReturnObject().setErrMsg("云存储空间不足").toString();
        }
        JSONArray returnarray = new JSONArray();

        JSONArray filesArray = content.getJSONArray("files");
        for (int i = 0; i < filesArray.size(); i++) {
            try {
                JSONObject fileobject = filesArray.getJSONObject(i);
                String filename = fileobject.getString("filename");
                String filetype = fileobject.getString("filetype");
                String ownertable = fileobject.getString("ownertable");
                String ownerid = fileobject.getString("ownerid");
                String ftype = fileobject.getString("ftype");
                HttpMethodEnum HttpMethod = HttpMethodEnum.PUT;
                if (content.containsKey("HttpMethod")) {
                    if ("post".equalsIgnoreCase(content.getString("HttpMethod"))) {
                        HttpMethod = HttpMethodEnum.POST;
                    } else if ("get".equalsIgnoreCase(content.getString("HttpMethod"))) {
                        HttpMethod = HttpMethodEnum.GET;
                    }
                }

                String serialnumber = createMD5FileName(filename) + "." + filetype;
                BucketFile bucketFile = new BucketFile(siteid);
                String url = bucketFile.getUploadUrl(filetype, serialnumber, HttpMethod);
                bucketFile.close();
                JSONObject object = new JSONObject();
                object.put("obsfilename", serialnumber);
                object.put("obsuploadurl", url);
                object.put("filename", filename);
                object.put("filetype", filetype);
                object.put("ftype", ftype);

                returnarray.add(object);

                HashMap<String, String> map = new HashMap<>();
                map.put("filename", filename);
                map.put("filetype", filetype);
                map.put("ownertable", ownertable);
                map.put("ownerid", ownerid);
                map.put("ftype", ftype);

                obsfilemap.put(serialnumber, map);
            } catch (Exception e) {
                return getErrReturnObject().setErrMsg(e.getMessage()).toString();
            }
        }
        return getSucReturnObject().setData(returnarray).toString();
    }

    public static void main(String[] args) {
        String a = "{\n" +
                "    \"accesstoken\": \"5a00a368632119fdc2a660422fa34095\",\n" +
                "    \"classname\": \"system.system.docManage\",\n" +
                "    \"method\": \"getFileName\",\n" +
                "    \"content\": {\n" +
                "        \"userid\":\"11730\",\n" +
                "        \"filename\": \"aa.mp4\",\n" +
                "        \"filetype\": \"mp4\",\n" +
                "        \"ownertable\": \"\",\n" +
                "        \"ownerid\": \"\",\n" +
                "        \"ftype\": \"\"\n" +
                "    }\n" +
                "}";
        WebRequest webRequest = new WebRequest();
        for (int i = 0; i < 20; i++) {
            String b = webRequest.doPost(a, " http://121.37.141.210:8080/samex/rest/webclientrest");
        }

    }

    public String changeFilesName() {
        JSONArray files = content.getJSONArray("files");
        ArrayList<String> sqllist = new ArrayList<String>();
        for (Object o : files) {
            JSONObject file = (JSONObject) o;
            long tattachmentid = file.getLong("tattachmentid");
            String fdocument = file.getString("fdocument");
            String ownertable = file.getString("ownertable");
            long ownerid = file.getLong("ownerid");

            SQLFactory sql = new SQLFactory(this, "附件名称调整");
            sql.addParameter("siteid", siteid);
            sql.addParameter("tattachmentid", tattachmentid);
            sql.addParameter("fdocument", fdocument);
            sql.addParameter("ownertable", ownertable);
            sql.addParameter("ownerid", ownerid);
            sqllist.add(sql.getSQL());
        }
        String status = dbConnect.runSqlUpdate(sqllist);
        if ("true".equals(status)) {
            return getSucReturnObject().toString();
        } else {
            return getErrReturnObject().toString();
        }
    }

    public String createMpcTask() {
        String siteid = content.getString("siteid");
        JSONArray obsfilenameArray = content.getJSONArray("obsfilenames");
        Iterator it = obsfilenameArray.iterator();
        ArrayList<String> sqllist = new ArrayList<>();
        while (it.hasNext()) {
            String obsfilename = (String) it.next();
            try {
                String mpctaskid = "";
                BucketFile bucketFile = new BucketFile(siteid);
                if (bucketFile.doesObjectExist(obsfilename)) {
                    /**
                     * 视频转码
                     */
                    if (obsfilename.endsWith("mp4") || obsfilename.endsWith("MP4")) {
                        MpcFactory mpcFactory = new MpcFactory();
                        MediaMetaData data = mpcFactory.getMetaData(siteid, obsfilename);
                        if (data != null) {
                            long bitrate = data.getBitrate();
                            long size = data.getSize();
                            if (bitrate / 1024 > 5000 || size / (1024 * 1024) > 500) {
                                System.err.println("开始进行视频转码：" + siteid + "," + obsfilename);
                                mpctaskid = mpcFactory.createMpcTask(siteid, obsfilename);
                            }
                        }
                    } else if (obsfilename.endsWith("mov") || obsfilename.endsWith("MOV")) {
                        System.err.println("开始进行视频转码：" + siteid + "," + obsfilename);
                        MpcFactory mpcFactory = new MpcFactory();
                        mpctaskid = mpcFactory.createMpcTask(siteid, obsfilename);
                    }
                }
                if (!mpctaskid.equals("")) {
                    sqllist.add("update tattachment set mpctaskid='" + mpctaskid + "' where siteid='" + siteid + "' and serialnumber='" + obsfilename + "'");
                } else {
                    sqllist.add("update tattachment set description='不转码' where siteid='" + siteid + "' and serialnumber='" + obsfilename + "'");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        String Status = dbConnect.runSqlUpdate(sqllist);
        if (Status.equals("true")) {
            return getSucReturnObject().toString();
        } else {
            return getErrReturnObject().toString();
        }
    }

    public String uploadSuccsess() {
        String obsfilename = content.getString("obsfilename");

        if (!obsfilemap.containsKey(obsfilename)) {
            return getErrReturnObject().setErrMsg("找不到对应的云存储文件").toString();
        }
        String filename = obsfilemap.get(obsfilename).get("filename");
        String filetype = obsfilemap.get(obsfilename).get("filetype");
        String ownertable = obsfilemap.get(obsfilename).get("ownertable");
        String ownerid = obsfilemap.get(obsfilename).get("ownerid");
        String ftype = obsfilemap.get(obsfilename).get("ftype");


        JSONObject resultObject = new JSONObject();
        try {

            BucketFile bucketFile = new BucketFile(siteid);
            if (!bucketFile.doesObjectExist(obsfilename)) {
                return getErrReturnObject().setErrMsg("找不到对应的云存储文件").toString();
            }
            /**
             * 获取原文件的访问地址
             */
            String obsurl = bucketFile.getFileUrl(obsfilename);
            ObjectMetadata matedata = bucketFile.getObjectMetadata(obsfilename);
            long contentlength = matedata.getContentLength();
            /**
             * 获取缩略图的访问地址
             */
            String obsurl_imageshort = "";
            String obsurl_imagecompress = "";
            if (isImage(filetype)) {
                obsurl_imageshort = bucketFile.getMinImageUrl(obsfilename);
                obsurl_imagecompress = bucketFile.getCompressImageUrl(obsfilename);
            }
            bucketFile.close();
            /**
             * 视频转码
             */
            String mpctaskid = "null";
            if (obsfilename.endsWith("mp4") || obsfilename.endsWith("MP4")) {
                MpcFactory mpcFactory = new MpcFactory();
                MediaMetaData data = mpcFactory.getMetaData(siteid, obsfilename);
                if (data != null) {
                    long bitrate = data.getBitrate();
                    long size = data.getSize();
                    if (bitrate / 1024 > 5000 || size / (1024 * 1024) > 500) {
                        System.err.println("开始进行视频转码：" + siteid + "," + obsfilename);
                        mpctaskid = mpcFactory.createMpcTask(siteid, obsfilename);
                    }
                }
            } else if (obsfilename.endsWith("mov") || obsfilename.endsWith("MOV")) {
                System.err.println("开始进行视频转码：" + siteid + "," + obsfilename);
                MpcFactory mpcFactory = new MpcFactory();
                mpctaskid = mpcFactory.createMpcTask(siteid, obsfilename);
            }
            /**
             * 本地信息插入
             */
            SQLFactory sqlFactory = new SQLFactory(this, "附件信息插入");
            sqlFactory.addParameter("tattachmentid", createTableID("tattachment", "tattachmentid"));
            sqlFactory.addParameter("siteid", siteid);
            sqlFactory.addParameter("ownertable", ownertable);
            sqlFactory.addParameter("ownerid", ownerid);
            sqlFactory.addParameter("createby", username);
            sqlFactory.addParameter("ftype", ftype);
            sqlFactory.addParameter("postfix", filetype);
            sqlFactory.addParameter("serialnumber", obsfilename);
            filename = filename.replace("'", "");
            sqlFactory.addParameter("fdocument", filename);
            sqlFactory.addParameter("fobsurl", obsurl);
            sqlFactory.addParameter("fobsurl_minimage", obsurl_imageshort);
            sqlFactory.addParameter("fobsurl_compressimage", obsurl_imagecompress);
            sqlFactory.addParameter("mpctaskid", mpctaskid);
            sqlFactory.addParameter("contentlength", contentlength);

            dbConnect.runSqlUpdate(sqlFactory.getSQL());
            obsfilemap.remove(obsfilename);
            resultObject.put("code", 1);
            resultObject.put("msg", "成功");
            if (content.getBooleanValue("fisreturnallfile")) {
                resultObject.put("data", queryDocRow(ownertable, ownerid, obsfilename));
            } else {
                resultObject.put("data", queryDocRows(ownertable, ownerid));
            }
        } catch (Exception exception) {
            resultObject.put("code", 0);
            resultObject.put("msg", exception.getMessage());
        }
        return resultObject.toString();
    }

    public String uploadSuccsess2() {
        JSONArray obsfilenamesArray = content.getJSONArray("obsfilenames");

        Iterator it = obsfilenamesArray.iterator();

        String ownertable = "";
        String ownerid = "";

        ArrayList<String> SQLlist = new ArrayList<>();

        JSONObject resultObject = new JSONObject();
        while (it.hasNext()) {
            String obsfilename = (String) it.next();
            if (!obsfilemap.containsKey(obsfilename)) {
                continue;
            }
            String filename = obsfilemap.get(obsfilename).get("filename");
            String filetype = obsfilemap.get(obsfilename).get("filetype");
            ownertable = obsfilemap.get(obsfilename).get("ownertable");
            ownerid = obsfilemap.get(obsfilename).get("ownerid");
            String ftype = obsfilemap.get(obsfilename).get("ftype");

            try {
                BucketFile bucketFile = new BucketFile(siteid);
                if (!bucketFile.doesObjectExist(obsfilename)) {
                    continue;
                }
                /**
                 * 获取原文件的访问地址
                 */
                String obsurl = bucketFile.getFileUrl(obsfilename);
                ObjectMetadata matedata = bucketFile.getObjectMetadata(obsfilename);
                long contentlength = matedata.getContentLength();
                String contenttype = matedata.getContentType();
                /**
                 * 获取缩略图的访问地址
                 */
                String obsurl_imageshort = "";
                String obsurl_imagecompress = "";
                if (isImage(filetype)) {
                    obsurl_imageshort = bucketFile.getMinImageUrl(obsfilename);
                    obsurl_imagecompress = bucketFile.getCompressImageUrl(obsfilename);
                }
                bucketFile.close();
                /**
                 * 视频转码
                 */
                String mpctaskid = "null";
                if (obsfilename.endsWith("mp4") || obsfilename.endsWith("MP4")) {
                    MpcFactory mpcFactory = new MpcFactory();
                    MediaMetaData data = mpcFactory.getMetaData(siteid, obsfilename);
                    if (data != null) {
                        long bitrate = data.getBitrate();
                        long size = data.getSize();
                        if (bitrate / 1024 > 5000 || size / (1024 * 1024) > 500) {
                            System.err.println("开始进行视频转码：" + siteid + "," + obsfilename);
                            mpctaskid = mpcFactory.createMpcTask(siteid, obsfilename);
                        }
                    }
                } else if (obsfilename.endsWith("mov") || obsfilename.endsWith("MOV")) {
                    System.err.println("开始进行视频转码：" + siteid + "," + obsfilename);
                    MpcFactory mpcFactory = new MpcFactory();
                    mpctaskid = mpcFactory.createMpcTask(siteid, obsfilename);
                }
                /**
                 * 本地信息插入
                 */
                SQLFactory sqlFactory = new SQLFactory(this, "附件信息插入");
                sqlFactory.addParameter("tattachmentid", createTableID("tattachment", "tattachmentid"));
                sqlFactory.addParameter("siteid", siteid);
                sqlFactory.addParameter("ownertable", ownertable);
                sqlFactory.addParameter("ownerid", ownerid);
                sqlFactory.addParameter("createby", username);
                sqlFactory.addParameter("ftype", ftype);
                sqlFactory.addParameter("postfix", filetype);
                sqlFactory.addParameter("serialnumber", obsfilename);
                filename = filename.replace("'", "");
                sqlFactory.addParameter("fdocument", filename);
                sqlFactory.addParameter("fobsurl", obsurl);
                sqlFactory.addParameter("fobsurl_minimage", obsurl_imageshort);
                sqlFactory.addParameter("fobsurl_compressimage", obsurl_imagecompress);
                sqlFactory.addParameter("mpctaskid", mpctaskid);
                sqlFactory.addParameter("contentlength", contentlength);

                SQLlist.add(sqlFactory.getSQL());
                obsfilemap.remove(obsfilename);
            } catch (Exception exception) {
                exception.printStackTrace();
            }
        }
        String fstatus = dbConnect.runSqlUpdate(SQLlist);
        if (fstatus.equals("true")) {
            int filecount = obsfilenamesArray.size();
            if (filecount == SQLlist.size()) {
                resultObject.put("code", 1);
                resultObject.put("msg", "成功上传" + filecount + "个文件");
            } else if (filecount > SQLlist.size() && SQLlist.size() > 0) {
                resultObject.put("code", 1);
                resultObject.put("msg", "成功上传" + SQLlist.size() + "个文件,失败" + (filecount - SQLlist.size() + "个"));
            } else if (SQLlist.size() == 0) {
                resultObject.put("code", 0);
                resultObject.put("msg", "上传失败");
            }
        } else {
            resultObject.put("code", 0);
            resultObject.put("msg", "上传失败");
        }
        resultObject.put("data", queryDocRows(ownertable, ownerid));
        return resultObject.toString();
    }


    /**
     * 获取上传附件的常用文件类型
     *
     * @return
     */
    public String getFileType(byte[] filebyte) {
        String ftype = null;
        try {
            StringBuilder builder = new StringBuilder();
            if (filebyte == null || filebyte.length <= 0) {
                return "";
            }
            String hv;
            for (byte value : filebyte) {
                // 以十六进制（基数 16）无符号整数形式返回一个整数参数的字符串表示形式，并转换为大写
                hv = Integer.toHexString(value & 0xFF).toUpperCase();
                if (hv.length() < 2) {
                    builder.append(0);
                }
                builder.append(hv);
            }
            ftype = builder.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (StringUtils.startsWith(ftype, "FFD8FF")) {
            return "JPG";
        } else if (StringUtils.startsWith(ftype, "89504E47")) {
            return "PNG";
        } else if (StringUtils.startsWith(ftype, "47494638")) {
            return "GIF";
        } else if (StringUtils.startsWith(ftype, "424D")) {
            return "BMP";
        } else if (StringUtils.startsWith(ftype, "41433130")) {
            return "DWG";
        } else if (StringUtils.startsWith(ftype, "38425053")) {
            return "PSD";
        }
        return "";
    }

    public boolean isImage(String filetype) {
        if (filetype.equalsIgnoreCase("JPG")) {
            return true;
        }
        if (filetype.equalsIgnoreCase("JPEG")) {
            return true;
        }
        return filetype.equalsIgnoreCase("PNG");
    }


    public String deleteDoc() throws P2Exception {
        String ownertable = content.getString("ownertable");
        String ownerid = content.getString("ownerid");
        String tattachmentid = content.getString("tattachmentid");

        Rows rows = dbConnect.runSqlQuery("select * from tattachment where siteid='" + siteid + "' and tattachmentid=" + tattachmentid);
        if (!rows.isEmpty()) {
            String objectname = rows.get(0).getString("serialnumber");

            BucketFile bucketFile = new BucketFile(siteid);
            bucketFile.deleteFile(objectname);

            String serialnumber_hls = rows.get(0).getString("serialnumber_hls");
            if (!"".equalsIgnoreCase(serialnumber_hls)) {
                bucketFile.deleteFolder(serialnumber_hls);
            }
            bucketFile.close();
        }

        SQLFactory delete = new SQLFactory(this, "附件信息删除");
        delete.addParameter("siteid", siteid);
        delete.addParameter("tattachmentid", tattachmentid);
        dbConnect.runSqlUpdate(delete.getSQL());

        returnObject.put("code", 1);
        returnObject.put("msg", "成功");
        returnObject.put("data", queryDocRows(ownertable, ownerid));

        return returnObject.toString();
    }

    public String queryDoc() {
        String ownertable = content.getString("ownertable");
        String ownerid = content.getString("ownerid");
        Rows rows;
        if (content.containsKey("ftype") && !"".equals(content.getString("ftype"))) {
            rows = queryDocRows(ownertable, ownerid, content.getString("ftype"));
        } else {
            rows = queryDocRows(ownertable, ownerid);
        }
        return getSucReturnObject().setData(rows).saveToDataPool().toString();
    }

    private Rows queryDocRows(String ownertable, String ownerid) {
        DBConnect dbConnect = new DBConnect();
        SQLFactory sqlFactory = new SQLFactory(this, "附件查询");
        sqlFactory.addParameter("siteid", siteid);
        sqlFactory.addParameter("ownertable", ownertable);
        sqlFactory.addParameter("ownerid", ownerid);
        return dbConnect.runSqlQuery(sqlFactory.getSQL());
    }

    private Rows queryDocRows(String ownertable, String ownerid, String ftype) {
        DBConnect dbConnect = new DBConnect();
        SQLFactory sqlFactory = new SQLFactory(this, "附件查询_按类别");
        sqlFactory.addParameter("siteid", siteid);
        sqlFactory.addParameter("ftype", ftype);
        sqlFactory.addParameter("ownertable", ownertable);
        sqlFactory.addParameter("ownerid", ownerid);
        return dbConnect.runSqlQuery(sqlFactory.getSQL());
    }

    private Rows queryDocRow(String ownertable, String ownerid, String obsfilename) {
        DBConnect dbConnect = new DBConnect();
        SQLFactory sqlFactory = new SQLFactory(this, "单附件查询");
        sqlFactory.addParameter("siteid", siteid);
        sqlFactory.addParameter("ownertable", ownertable);
        sqlFactory.addParameter("ownerid", ownerid);
        sqlFactory.addParameter("serialnumber", obsfilename);
        return dbConnect.runSqlQuery(sqlFactory.getSQL());
    }


    /**
     * 去除文件名称中的多余字符：空格、换行符、回车符等
     *
     * @param filename
     * @return
     */
    private static String createFileName(String filename) {
        StringBuilder newfilename = null;
        StringTokenizer stringTokenizer = new StringTokenizer(filename.trim());
        while (stringTokenizer.hasMoreTokens()) {
            if (newfilename == null) {
                newfilename = new StringBuilder(stringTokenizer.nextToken());
            } else {
                newfilename.append(stringTokenizer.nextToken());
            }
        }
        return newfilename.toString();
    }

    /**
     * 生成一个唯一的流水码作为云存储文件名称
     *
     * @param filename
     * @return
     * @throws IOException
     */
    private static String createMD5FileName(String filename) throws IOException {
        String date_str;
        String newfilename;
        do {
            Date date = new Date();
            date_str = (new SimpleDateFormat("yyyyMMdd")).format(date);
            long time = date.getTime();
            int random = java.lang.Math.abs((new Random()).nextInt() % 1000);
            String var3 = null;
            try {
                var3 = MessageDigest.getInstance("MD5").digest(String.valueOf(random).getBytes()).toString().replaceAll("[^a-z^A-Z^0-9]", "");
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }

            date_str = date_str + time + var3;
            newfilename = filename + File.separator + date_str;
        } while ((new File(newfilename)).exists());

        return date_str;
    }


    /**
     * 请求参数校验
     *
     * @param filename
     * @param ownertable
     * @param ownerid
     * @return
     */
    public JSONObject fileCheck(String filename, String ownertable, String ownerid) {
        JSONObject resultObject = new JSONObject();
        if (Utility.isNull(ownertable)) {
            resultObject.put("code", 0);
            resultObject.put("msg", "参数ownertable错误");
        } else if (Utility.isNull(ownerid)) {
            resultObject.put("code", 0);
            resultObject.put("msg", "参数ownerid错误");
        } else if (Utility.isNull(filename)) {
            resultObject.put("code", 0);
            resultObject.put("msg", "无法获取文件名称");
        } else if (Utility.isNull(siteid)) {
            resultObject.put("code", 0);
            resultObject.put("msg", "参数siteid错误");

        }
        return resultObject;
    }


    /**
     * 创建下载日志
     *
     * @return
     */
    public String createdownloadlog() {
        String tattachmentid = content.getString("tattachmentid");
        PaoSetRemote tattachment_downlogSet = null;
        try {
            tattachment_downlogSet = getP2ServerSystemPaoSet("tattachment_downlog");
            PaoRemote tattachment_downlog = tattachment_downlogSet.addAtEnd();
            tattachment_downlog.setValue("siteid", siteid, 11L);
            tattachment_downlog.setValue("createby", username, 11L);
            tattachment_downlog.setValue("createdate", getDateTime(), 11L);
            tattachment_downlog.setValue("tagentsid", tagentsid, 11L);
            tattachment_downlog.setValue("tattachmentid", tattachmentid, 11L);
            tattachment_downlog.setValue("tenterprise_userid", userid, 11L);
            tattachment_downlogSet.save();

            Rows rows = dbConnect.runSqlQuery("select *from tattachment where siteid='" + siteid + "' and tattachmentid='" + tattachmentid + "'");
            if (!rows.isEmpty()) {
                Row row = rows.get(0);
                String ownertable = row.getString("ownertable");
                String ownerid = row.getString("ownerid");
                if ("tarchives".equalsIgnoreCase(ownertable)) {
                    addActionScore(ActionScore.fsourcetype.下载营销智库, Long.parseLong(ownerid), "下载营销智库");
                } else if ("tnotice".equalsIgnoreCase(ownertable)) {
                    addActionScore(ActionScore.fsourcetype.下载通告附件, Long.parseLong(ownerid), "下载通告附件");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                tattachment_downlogSet.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return getSucReturnObject().toString();
    }

}
