package com.cnd3b.service;

import com.cnd3b.common.BaseClass;
import com.cnd3b.common.data.Row;
import com.cnd3b.common.data.Rows;
import com.cnd3b.common.data.db.DBConnect;
import com.cnd3b.common.data.db.SQLiteJDBC;
import com.cnd3b.utility.obs.BucketFile;
import p2.util.P2Exception;

import java.util.Calendar;

/**
 * 存储容量定时清理
 */
public class ObsAutoDelete extends BaseClass implements Runnable {

    @Override
    public void run() {
        if (new SQLiteJDBC().checkServicesUsed("ObsAutoDelete", true)) {
            try {
                clean();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (Calendar.getInstance().get(Calendar.HOUR_OF_DAY) == 3) {
            System.gc();
        }
    }

    public void clean() throws P2Exception {
        DBConnect dbConnect = new DBConnect();
        /**
         * 第一步，搜索出所有存在附件的表格
         */
        Rows objectrows = dbConnect.runSqlQuery("select distinct ownertable,t2.uniquecolumnname from tattachment t1 inner join PS_SYSTABLES t2 on t1.ownertable=t2.tablename");
        for (Row objectrow : objectrows) {

            String objectname = objectrow.getString("ownertable");
            String uniquecolumnname = objectrow.getString("uniquecolumnname");

            Rows tattachmentrows = dbConnect.runSqlQuery("select t1.siteid,t1.tattachmentid,t1.serialnumber,t1.fdocument,t1.serialnumber_hls from tattachment t1 left join " + objectname + " t2 on  t1.ownerid=t2." + uniquecolumnname + " inner join tobsmag t3 on t1.siteid=t3.siteid and t3.fisautoclean=1  where t1.ownertable='" + objectname + "' and t2." + uniquecolumnname + " is null");
            for (Row tattachmentrow : tattachmentrows) {
                String siteid = tattachmentrow.getString("siteid");
                String tattachmentid = tattachmentrow.getString("tattachmentid");
                String serialnumber = tattachmentrow.getString("serialnumber");
                String fdocument = tattachmentrow.getString("fdocument");
                String serialnumber_hls = tattachmentrow.getString("serialnumber_hls");
                BucketFile bucketFile = new BucketFile(siteid);
                bucketFile.deleteFile(serialnumber);

                if (!"".equalsIgnoreCase(serialnumber_hls)) {
                    bucketFile.deleteFolder(serialnumber_hls);
                }
                if (!bucketFile.doesObjectExist(serialnumber)) {
                    printInfoOut("云存储文件清理", siteid + "-表名：" + objectname + "；附件ID：" + tattachmentid + "；云存储文件名：" + serialnumber + "；文件名：" + fdocument);
                    dbConnect.runSqlUpdate("delete from tattachment where siteid='" + siteid + "' and tattachmentid=" + tattachmentid);
                }
                bucketFile.close();
            }
        }
    }
}
