package com.cnd3b.restcontroller.singleagent.webclient.archives;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cnd3b.common.Controller;
import com.cnd3b.common.D3bException;
import com.cnd3b.common.data.Row;
import com.cnd3b.common.data.Rows;
import com.cnd3b.common.data.RowsMap;
import com.cnd3b.common.data.SQLFactory;
import com.cnd3b.common.data.db.DataPool;
import p2.pao.PaoRemote;
import p2.pao.PaoSetRemote;
import p2.util.P2Exception;

import java.util.Calendar;

public class archives_ad extends Controller {
    public archives_ad(JSONObject content) {
        super(content);
    }

    /**
     * 推广素材列表查询
     *
     * @return
     */
    public String query_archivesList() {
        /**
         *排序条件设置
         */
        String[] sortfield = {"t1.checkdate", "t1.fvisitors", "t1.fshares"};
        String sort = getSort(sortfield, "t1.checkdate desc");

        /**
         * 过滤条件设置
         */
        StringBuffer where = new StringBuffer(" 1=1 ");
        String fmyarchives = "0";
        if (content.containsKey("where")) {
            JSONObject whereObject = content.getJSONObject("where");
            if (whereObject.containsKey("condition") && !"".equals(whereObject.getString("condition"))) {
                where.append(" and(");
                where.append("t1.ftitle like'%").append(whereObject.getString("condition")).append("%' ");
                where.append("or t1.fnotes like'%").append(whereObject.getString("condition")).append("%' ");
                where.append(")");
            }
            if (whereObject.containsKey("fclass1") && !"".equals(whereObject.getString("fclass1"))) {
                where.append(" and fclass1=").append("'").append(whereObject.getString("fclass1")).append("'");
            }
            if (whereObject.containsKey("fclass2") && !"".equals(whereObject.getString("fclass2"))) {
                where.append(" and fclass2=").append("'").append(whereObject.getString("fclass2")).append("'");
            }
            if (whereObject.containsKey("fmycollection") && whereObject.getBooleanValue("fmycollection")) {
                where.append(" and t2.tarchives_ad_colid is not null");
            }
            if (whereObject.containsKey("fmyarchives") && whereObject.getBooleanValue("fmyarchives")) {
                where.append(" and t1.tagentsid='").append(tagentsid).append("' ");
                fmyarchives = "1";
            } else {
                where.append(" and t1.fstatus='发布' and t1.tagentsid is null");
                if (fisadministrator) {
                    where.append(" and t1.fagentcanread=1");
                } else {
                    where.append(" and t1.fagentsalercanread=1");
                }
            }
        }
        SQLFactory factory = new SQLFactory(this, "推广素材列表查询", pageSize, pageNumber, sort);
        factory.addParameter("siteid", siteid);
        factory.addParameter("tenterprise_userid", userid);
        factory.addParameter_SQL("where", where);
        Rows rows = dbConnect.runSqlQuery(factory.getSQL());
        for (Row row : rows) {
            row.put("fmyarchives", fmyarchives);
        }
        return getSucReturnObject().setDataByPaging(rows, sortfield).setFinalDo(DataPool.defaultdatalife, 1);
    }

    /**
     * 推广素材主界面查询
     *
     * @return
     */
    public String query_archivesMain() throws P2Exception {
        String tarchives_adid = content.getString("tarchives_adid");
        SQLFactory sqlFactory = new SQLFactory(this, "推广素材主界面查询");
        sqlFactory.addParameter("siteid", siteid);
        sqlFactory.addParameter("tenterprise_userid", userid);
        sqlFactory.addParameter("tarchives_adid", tarchives_adid);
        Rows rows = dbConnect.runSqlQuery(sqlFactory.getSQL());
        for (Row row : rows) {
            //标签
            String[] flable = dbConnect.runSqlQuery("select flable from tarchives_ad_tag where siteid='" + siteid + "' and tarchives_adid='" + tarchives_adid + "'").toArray("flable");
            row.put("tag", flable);
            Rows fcontent = dbConnect.runSqlQuery("select fcontent from tarchives_ad where siteid='" + siteid + "' and tarchives_adid='" + tarchives_adid + "'");
            row.put("fcontent", fcontent.get(0).getString("fcontent"));
        }
        /**
         * 阅读量+1
         */
        dbConnect.runSqlUpdate("update tarchives_ad set fvisitors=isnull(fvisitors,0)+1 where siteid='" + siteid + "' and tarchives_adid=" + content.getString("tarchives_adid"));

        PaoSetRemote tarchives_ad_userdataSet = getP2ServerSystemPaoSet("tarchives_ad_userdata");
        PaoRemote tarchives_ad_userdata = tarchives_ad_userdataSet.addAtEnd();
        tarchives_ad_userdata.setValue("siteid", siteid, 11L);
        tarchives_ad_userdata.setValue("tarchives_adid", tarchives_adid, 11L);
        tarchives_ad_userdata.setValue("tenterprise_userid", userid, 11L);
        tarchives_ad_userdata.setValue("createby", username, 11L);
        Calendar calendar = Calendar.getInstance();
        tarchives_ad_userdata.setValue("createdate", calendar.getTime(), 11L);
        calendar.add(Calendar.MINUTE, 5);
        tarchives_ad_userdata.setValue("closedate", calendar.getTime(), 11L);
        tarchives_ad_userdataSet.save();

        return getSucReturnObject().setData(rows).toString();
    }

    /**
     * 拉新名单
     *
     * @return
     */
    public String shareStatistics_custlist() {
        /**
         *排序条件设置
         */
        String[] sortfield = {"t1.changedate desc"};
        String sort = getSort(sortfield, "t1.changedate desc");

        SQLFactory factory = new SQLFactory(this, "推广素材分享统计_拉新名单", pageSize, pageNumber, sort);
        factory.addParameter("siteid", siteid);
        factory.addParameter("tenterprise_userid", userid);
        Rows rows = dbConnect.runSqlQuery(factory.getSQL());
        return getSucReturnObject().setDataByPaging(rows, sortfield).setFinalDo(DataPool.defaultdatalife, 1);
    }

    /**
     * 推广素材标签查询
     *
     * @return
     */
    public String query_tagList() {
        SQLFactory sql = new SQLFactory(this, "推广素材系统标签查询");
        sql.addParameter("siteid", siteid);
        Rows rows = dbConnect.runSqlQuery(sql.getSQL());
        return getSucReturnObject().setData(rows).saveToDataPool().toString();
    }

    /**
     * 推广素材新增或修改
     *
     * @return
     */
    public String archivesInsertOrModify() throws D3bException, P2Exception {
        long tarchives_adid = content.getLongValue("tarchives_adid");//推广素材ID，新增时默认传0
        String fclass1 = content.getString("fclass1");//一级类别
        String fclass2 = content.getString("fclass2");//二级类别
        String ftitle = content.getString("ftitle", "tarchives_ad.ftitle", "素材标题");//推广素材标题
        String fnotes = content.getString("fnotes", "tarchives_ad.fnotes", "素材备注");//推广素材备注
        String fcontent = content.getString("fcontent", "tarchives_ad.fcontent", "正文");//富文本
        JSONArray tag = content.getJSONArray("tag");//标签

        PaoSetRemote tarchives_adSet = getP2ServerSystemPaoSet("tarchives_ad", "siteid='" + siteid + "' and tagentsid='" + tagentsid + "' and tarchives_adid='" + tarchives_adid + "'");
        PaoRemote tarchives_ad = null;
        if (tarchives_adid <= 0 || tarchives_adSet.isEmpty()) {
            tarchives_ad = tarchives_adSet.addAtEnd();
            tarchives_ad.setValue("siteid", siteid, 11L);//企业ID
            tarchives_ad.setValue("tenterprise_userid", userid, 11L);//用户ID
            tarchives_ad.setValue("createby", username, 11L);//录入人
            tarchives_ad.setValue("createdate", sysdate, 11L);//录入时间
            tarchives_ad.setValue("fstatus", "新建", 11L);//推广素材状态
            tarchives_ad.setValue("tagentsid", tagentsid, 11L);
            tarchives_adid = tarchives_ad.getLong("tarchives_adid");
        } else {
            tarchives_ad = tarchives_adSet.getPao(0);
        }
        tarchives_ad.setValue("fclass1", fclass1, 11L);
        tarchives_ad.setValue("fclass2", fclass2, 11L);
        tarchives_ad.setValue("ftitle", ftitle, 11L);
        tarchives_ad.setValue("fnotes", fnotes, 11L);
        tarchives_ad.setValue("fcontent", fcontent, 11L);
        tarchives_ad.setValue("changeby", username);//修改人
        tarchives_ad.setValue("changedate", sysdate);//修改时间
        /**
         * 标签
         */
        dbConnect.runSqlUpdate("delete from tarchives_ad_tag where siteid='" + siteid + "' and tarchives_adid=" + tarchives_adid);
        PaoSetRemote tarchives_ad_tagSet = tarchives_ad.getPaoSet("$tarchives_ad_tag", "tarchives_ad_tag");
        for (Object o : tag) {
            String flable = (String) o;
            PaoRemote tarchives_ad_tag = tarchives_ad_tagSet.addAtEnd();
            tarchives_ad_tag.setValue("siteid", siteid, 11L);
            tarchives_ad_tag.setValue("flable", flable, 11L);
            tarchives_ad_tag.setValue("tarchives_adid", tarchives_adid, 11L);
        }
        content.put("tarchives_adid", tarchives_adid);
        saveDataLog(tarchives_ad);
        tarchives_adSet.save();

        return query_archivesMain();
    }


    /**
     * 推广素材提交
     *
     * @return
     */
    public String archivesSubmit() {
        String tarchives_adid = content.getString("tarchives_adid");//推广素材ID，新增时默认传0

        SQLFactory factory = new SQLFactory(this, "推广素材提交");
        factory.addParameter("siteid", siteid);
        factory.addParameter("tagentsid", tagentsid);
        factory.addParameter("tarchives_adid", tarchives_adid);
        factory.addParameter("submitby", username);
        String status = dbConnect.runSqlUpdate(factory.getSQL());
        if (status.equals("true")) {
            return getSucReturnObject().toString();
        } else {
            return getErrReturnObject().setErrMsg(status).toString();
        }
    }


    /**
     * 推广素材收藏
     *
     * @return
     */
    public String archivesCollection() throws P2Exception {
        String tarchives_adid = content.getString("tarchives_adid");//推广素材ID
        String iscollection = content.getString("iscollection");//是否收藏，1收藏，0取消收藏

        PaoSetRemote tarchives_ad_collectionSet = getP2ServerSystemPaoSet("tarchives_ad_collection", "siteid='" + siteid + "' and tenterprise_userid='" + userid + "' and tarchives_adid='" + tarchives_adid + "'");
        PaoRemote tarchives_ad_collection = null;
        if (tarchives_ad_collectionSet.isEmpty() && iscollection.equals("1")) {
            tarchives_ad_collection = tarchives_ad_collectionSet.addAtEnd();
            tarchives_ad_collection.setValue("siteid", siteid, 11L);//企业ID
            tarchives_ad_collection.setValue("tenterprise_userid", userid, 11L);//用户ID
            tarchives_ad_collection.setValue("fcollectiondate", sysdate, 11L);//录入时间
            tarchives_ad_collection.setValue("tarchives_adid", tarchives_adid, 11L);
        } else if (!tarchives_ad_collectionSet.isEmpty() && !iscollection.equals("1")) {
            tarchives_ad_collectionSet.deleteAll();
        }
        tarchives_ad_collectionSet.save();
        return getSucReturnObject().toString();
    }

    /**
     * 推广素材类型查询
     *
     * @return
     */
    public String getArchivesClass() {
        SQLFactory sqlFactory = new SQLFactory(this, "推广素材分类查询");
        sqlFactory.addParameter("siteid", siteid);
        RowsMap rowsmap = dbConnect.runSqlQuery(sqlFactory.getSQL()).toRowsMap("ftypemx");
        JSONArray array = new JSONArray();
        for (String ftypemx : rowsmap.keySet()) {
            JSONObject object = new JSONObject();
            object.put("fclass1", ftypemx);
            object.put("fclass2", rowsmap.get(ftypemx).toArray("fvalue"));
            array.add(object);
        }
        return getSucReturnObject().setData(array).saveToDataPool().toString();
    }


    /**
     * 推广素材删除
     *
     * @return
     */
    public String archiveDelete() {
        SQLFactory sqlFactory = new SQLFactory(this, "推广素材删除");
        sqlFactory.addParameter("siteid", siteid);
        sqlFactory.addParameter("tarchives_adid", content.getString("tarchives_adid"));

        String result = dbConnect.runSqlUpdate(sqlFactory.getSQL());
        if ("true".equals(result)) {
            return getSucReturnObject().toString();
        } else {
            return getErrReturnObject().setErrMsg(result).toString();
        }
    }

    /**
     * 推广素材分享
     *
     * @return
     */
    public String archiveShare() throws P2Exception {
        String tarchives_adid = content.getString("tarchives_adid");//推广素材ID
        String fchannel = content.getString("fchannel");//分享渠道
        /**
         * 分享量+1
         */
        dbConnect.runSqlUpdate("update tarchives_ad set fshares=isnull(fshares,0)+1 where siteid='" + siteid + "' and tarchives_adid=" + content.getString("tarchives_adid"));
        PaoSetRemote tarchives_ad_shareSet = getP2ServerSystemPaoSet("tarchives_ad_share");
        PaoRemote tarchives_ad_share = tarchives_ad_shareSet.addAtEnd();
        tarchives_ad_share.setValue("siteid", siteid, 11L);//企业ID
        tarchives_ad_share.setValue("tenterprise_userid", userid, 11L);//用户ID
        tarchives_ad_share.setValue("tarchives_adid", tarchives_adid, 11L);//推广素材ID
        tarchives_ad_share.setValue("fchannel", fchannel, 11L);//分享渠道
        tarchives_ad_share.setValue("createby", username, 11L);//分享人
        tarchives_ad_share.setValue("createdate", getDateTime(), 11L);//分享时间
        tarchives_ad_shareSet.save();

        return getSucReturnObject().toString();
    }

}
