package com.cnd3b.restcontroller.enterprise.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.ArrayList;

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

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

        /**
         * 过滤条件设置
         */
        StringBuffer where = new StringBuffer(" 1=1 ");
        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("or t1.fclass1 like'%").append(whereObject.getString("condition")).append("%' ");
                where.append("or t1.fclass2 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("'");
            }
        }
        SQLFactory factory = new SQLFactory(this, "推广素材列表查询", pageSize, pageNumber, sort);
        factory.addParameter("siteid", siteid);
        factory.addParameter_SQL("where", where);
        Rows rows = dbConnect.runSqlQuery(factory.getSQL());

        return getSucReturnObject().setDataByPaging(rows, sortfield).setFinalDo(DataPool.defaultdatalife, 1);
    }

    /**
     * 推广素材主界面查询
     *
     * @return
     */
    public String query_archivesMain() {
        String tarchives_adid = content.getString("tarchives_adid");
        SQLFactory sqlFactory = new SQLFactory(this, "推广素材主界面查询");
        sqlFactory.addParameter("siteid", siteid);
        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"));
        }
        return getSucReturnObject().setData(rows).toString();
    }

    /**
     * 推广素材新增或修改
     *
     * @return
     */
    public String archivesInsertOrModify() throws D3bException, P2Exception {
        long tarchives_adid = content.getLongValue("tarchives_adid");//推广素材ID，新增时默认传0
        if (tarchives_adid > 0) {
            if (dbConnect.runSqlQuery("select fstatus from tarchives_ad where siteid='" + siteid + "' and fstatus='新建' and tarchives_adid=" + tarchives_adid).isEmpty()) {
                return getErrReturnObject().setErrMsg("当前状态不可修改").toString();
            }
        }
        String fclass1 = content.getString("fclass1", "tarchives_ad.ftitle", "标题");//一集类别
        String fclass2 = content.getString("fclass2", "tarchives_ad.fnotes", "备注");//二集类别
        String ftitle = content.getString("ftitle");//推广素材标题
        String fnotes = content.getString("fnotes");//推广素材备注
        String fcontent = content.getString("fcontent", "tarchives_ad.fcontent", "正文");//富文本
        boolean fsalercanread = content.getBooleanValue("fsalercanread");//业务员是否可见
        boolean fagentcanread = content.getBooleanValue("fagentcanread");//经销商住账号是否可见
        boolean fagentsalercanread = content.getBooleanValue("fagentsalercanread");//经销商子账号是否可见
        JSONArray tag = content.getJSONArray("tag");//标签

        PaoSetRemote tarchives_adSet = getP2ServerSystemPaoSet("tarchives_ad", "siteid='" + siteid + "' 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);//推广素材状态
        } 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("fsalercanread", fsalercanread, 11L);
        tarchives_ad.setValue("fagentcanread", fagentcanread, 11L);
        tarchives_ad.setValue("fagentsalercanread", fagentsalercanread, 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_ad.getString("tarchives_adid"));
        saveDataLog(tarchives_ad);
        tarchives_adSet.save();

        return query_archivesMain();
    }

    /**
     * 推广素材审核
     *
     * @return
     */
    public String archivesCheck() {
        long tarchives_adid = content.getLongValue("tarchives_adid");//推广素材ID，新增时默认传0
        if (!dbConnect.runSqlQuery("select * from tarchives_ad where siteid='" + siteid + "' and fstatus='发布' and tarchives_adid=" + tarchives_adid).isEmpty()) {
            return getErrReturnObject().setErrMsg("推广素材已发布，不可重复发布！").toString();
        }
        SQLFactory factory = new SQLFactory(this, "推广素材发布");
        factory.addParameter("siteid", siteid);
        factory.addParameter("tarchives_adid", tarchives_adid);
        factory.addParameter("checkby", username);
        String status = dbConnect.runSqlUpdate(factory.getSQL());
        if (status.equals("true")) {
            SQLFactory sqlFactory = new SQLFactory(this, "推广素材主界面查询");
            sqlFactory.addParameter("siteid", siteid);
            sqlFactory.addParameter("tarchives_adid", content.getString("tarchives_adid"));
            Rows rows = dbConnect.runSqlQuery(sqlFactory.getSQL());
            if (!rows.isEmpty()) {
                String fclass1 = rows.get(0).getString("fclass1");
                String fclass2 = rows.get(0).getString("fclass2");
                String ftitle = rows.get(0).getString("ftitle");
                String tagentsid = rows.get(0).getString("tagentsid");

                SQLFactory msgfac = new SQLFactory(this, "消息插入");
                msgfac.addParameter("siteid", siteid);
                msgfac.addParameter("objectname", "tarchives_ad");
                msgfac.addParameter("objectid", tarchives_adid);
                msgfac.addParameter("fmessage", "新发布了一条【" + fclass1 + "-" + fclass2 + "】类推广素材：《" + ftitle + "》");
                dbConnect.runSqlUpdate(msgfac.getSQL());

//                if (tagentsid != null && !"null".equalsIgnoreCase(tagentsid) && !"".equals(tagentsid)) {
//                    String tenterprise_userid = rows.get(0).getString("tenterprise_userid");
//                    String submitby = rows.get(0).getString("submitby");
//                    new AgentActionScore(siteid, tagentsid, tenterprise_userid, submitby, ActionScore.fsourcetype.智库分享, Long.parseLong(tarchives_adid), "智库分享").add();
//                }
            }
            return getSucReturnObject().toString();
        } else {
            return getErrReturnObject().setErrMsg(status).toString();
        }
    }

    /**
     * 推广素材ID取消发布
     *
     * @return
     */
    public String archivesUnCheck() {
        String tarchives_adid = content.getString("tarchives_adid");//推广素材ID，新增时默认传0
        if (dbConnect.runSqlQuery("select * from tarchives_ad where siteid='" + siteid + "' and fstatus='发布' and tarchives_adid=" + tarchives_adid).isEmpty()) {
            return getErrReturnObject().setErrMsg("推广素材不在发布状态，不可取消发布！").toString();
        }
        SQLFactory factory = new SQLFactory(this, "推广素材取消发布");
        factory.addParameter("siteid", siteid);
        factory.addParameter("tarchives_adid", tarchives_adid);
        String status = dbConnect.runSqlUpdate(factory.getSQL());
        if (status.equals("true")) {
            return getSucReturnObject().toString();
        } else {
            return getErrReturnObject().setErrMsg(status).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() {
        long tarchives_adid = content.getLongValue("tarchives_adid");
        if (dbConnect.runSqlQuery("select * from tarchives_ad where siteid='" + siteid + "' and fstatus='新建' and tarchives_adid=" + tarchives_adid).isEmpty()) {
            return getErrReturnObject().setErrMsg("当前状态不可删除！").toString();
        }
        SQLFactory sqlFactory = new SQLFactory(this, "推广素材删除");
        sqlFactory.addParameter("siteid", siteid);
        sqlFactory.addParameter("tarchives_adid", tarchives_adid);

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


    /**
     * 推广素材阅读分析
     *
     * @return
     */
    public String read_analysis() {
        String tarchives_adid = content.getString("tarchives_adid");
        SQLFactory factory = new SQLFactory(this, "分析_推广素材阅读占比分析_经销商");
        factory.addParameter("siteid", siteid);
        factory.addParameter("tarchives_adid", tarchives_adid);
        Rows rows = dbConnect.runSqlQuery(factory.getSQL());
        return getSucReturnObject().setData(rows).saveToDataPool().toString();
    }

    /**
     * 推广素材阅读分析
     *
     * @return
     */
    public String read_analysis_saler() {
        String tarchives_adid = content.getString("tarchives_adid");
        SQLFactory factory = new SQLFactory(this, "分析_推广素材阅读占比分析_业务员");
        factory.addParameter("siteid", siteid);
        factory.addParameter("tarchives_adid", tarchives_adid);
        Rows rows = dbConnect.runSqlQuery(factory.getSQL());
        return getSucReturnObject().setData(rows).saveToDataPool().toString();
    }

    /**
     * 推广素材下载分析
     *
     * @return
     */
    public String download_analysis() {
        String tarchives_adid = content.getString("tarchives_adid");
        SQLFactory factory = new SQLFactory(this, "分析_推广素材下载占比分析_经销商");
        factory.addParameter("siteid", siteid);
        factory.addParameter("tarchives_adid", tarchives_adid);
        Rows rows = dbConnect.runSqlQuery(factory.getSQL());
        return getSucReturnObject().setData(rows).saveToDataPool().toString();
    }

    /**
     * 推广素材下载分析
     *
     * @return
     */
    public String download_analysis_saler() {
        String tarchives_adid = content.getString("tarchives_adid");
        SQLFactory factory = new SQLFactory(this, "分析_推广素材下载占比分析_业务员");
        factory.addParameter("siteid", siteid);
        factory.addParameter("tarchives_adid", tarchives_adid);
        Rows rows = dbConnect.runSqlQuery(factory.getSQL());
        return getSucReturnObject().setData(rows).saveToDataPool().toString();
    }

    /**
     * 未浏览用户列表
     *
     * @return
     */
    public String havenoreaduserlist() {
        /**
         *排序条件设置
         */
        String[] sortfield = {"t2.tenterprise_userid"};
        String sort = getSort(sortfield, "t2.tenterprise_userid");
        String tarchives_adid = content.getString("tarchives_adid");
        SQLFactory factory = new SQLFactory(this, "分析_推广素材未浏览经销商", pageSize, pageNumber, sort);
        factory.addParameter("siteid", siteid);
        factory.addParameter("tarchives_adid", tarchives_adid);
        Rows rows = dbConnect.runSqlQuery(factory.getSQL());
        return getSucReturnObject().setDataByPaging(rows).setFinalDo(DataPool.defaultdatalife, 1);
    }

    /**
     * 未浏览用户列表
     *
     * @return
     */
    public String havenoreaduserlist_saler() {
        /**
         *排序条件设置
         */
        String[] sortfield = {"t2.tenterprise_userid"};
        String sort = getSort(sortfield, "t2.tenterprise_userid");
        String tarchives_adid = content.getString("tarchives_adid");
        SQLFactory factory = new SQLFactory(this, "分析_推广素材未浏览业务员", pageSize, pageNumber, sort);
        factory.addParameter("siteid", siteid);
        factory.addParameter("tarchives_adid", tarchives_adid);
        Rows rows = dbConnect.runSqlQuery(factory.getSQL());
        return getSucReturnObject().setDataByPaging(rows).setFinalDo(DataPool.defaultdatalife, 1);
    }

    /**
     * 已浏览用户列表
     *
     * @return
     */
    public String havereaduserlist() {
        /**
         *排序条件设置
         */
        String[] sortfield = {"t2.tenterprise_userid"};
        String sort = getSort(sortfield, "t2.tenterprise_userid");
        String tarchives_adid = content.getString("tarchives_adid");

        SQLFactory factory = new SQLFactory(this, "分析_推广素材已浏览经销商", pageSize, pageNumber, sort);
        factory.addParameter("siteid", siteid);
        factory.addParameter("tarchives_adid", tarchives_adid);
        Rows rows = dbConnect.runSqlQuery(factory.getSQL());

        Rows downloaduserid = dbConnect.runSqlQuery("select t2.tenterprise_userid from tattachment t1 inner join tattachment_downlog t2 on t1.siteid=t2.siteid and t1.tattachmentid=t2.tattachmentid where  t1.siteid='" + siteid + "' and t1.ownertable='tarchives_ad' and t1.ownerid='" + tarchives_adid + "' ");
        ArrayList<String> userlist = downloaduserid.toArrayList("tenterprise_userid");
        for (Row row : rows) {
            row.put("fisdownloadfile", userlist.contains(row.getString("tenterprise_userid")));
        }
        return getSucReturnObject().setDataByPaging(rows).setFinalDo(DataPool.defaultdatalife, 1);
    }

    /**
     * 已浏览用户列表
     *
     * @return
     */
    public String havereaduserlist_saler() {
        /**
         *排序条件设置
         */
        String[] sortfield = {"t2.tenterprise_userid"};
        String sort = getSort(sortfield, "t2.tenterprise_userid");
        String tarchives_adid = content.getString("tarchives_adid");

        SQLFactory factory = new SQLFactory(this, "分析_推广素材已浏览业务员", pageSize, pageNumber, sort);
        factory.addParameter("siteid", siteid);
        factory.addParameter("tarchives_adid", tarchives_adid);
        Rows rows = dbConnect.runSqlQuery(factory.getSQL());

        Rows downloaduserid = dbConnect.runSqlQuery("select t2.tenterprise_userid from tattachment t1 inner join tattachment_downlog t2 on t1.siteid=t2.siteid and t1.tattachmentid=t2.tattachmentid where  t1.siteid='" + siteid + "' and t1.ownertable='tarchives_ad' and t1.ownerid='" + tarchives_adid + "' ");
        ArrayList<String> userlist = downloaduserid.toArrayList("tenterprise_userid");
        for (Row row : rows) {
            row.put("fisdownloadfile", userlist.contains(row.getString("tenterprise_userid")));
        }
        return getSucReturnObject().setDataByPaging(rows).setFinalDo(DataPool.defaultdatalife, 1);
    }

    /**
     * 未下载用户列表
     *
     * @return
     */
    public String havenodownloaduserlist() {
        /**
         *排序条件设置
         */
        String[] sortfield = {"t2.tenterprise_userid"};
        String sort = getSort(sortfield, "t2.tenterprise_userid");
        String tarchives_adid = content.getString("tarchives_adid");
        SQLFactory factory = new SQLFactory(this, "分析_推广素材未下载经销商", pageSize, pageNumber, sort);
        factory.addParameter("siteid", siteid);
        factory.addParameter("tarchives_adid", tarchives_adid);
        Rows rows = dbConnect.runSqlQuery(factory.getSQL());
        return getSucReturnObject().setDataByPaging(rows).setFinalDo(DataPool.defaultdatalife, 1);
    }

    /**
     * 未下载用户列表
     *
     * @return
     */
    public String havenodownloaduserlist_saler() {
        /**
         *排序条件设置
         */
        String[] sortfield = {"t2.tenterprise_userid"};
        String sort = getSort(sortfield, "t2.tenterprise_userid");
        String tarchives_adid = content.getString("tarchives_adid");
        SQLFactory factory = new SQLFactory(this, "分析_推广素材未下载业务员", pageSize, pageNumber, sort);
        factory.addParameter("siteid", siteid);
        factory.addParameter("tarchives_adid", tarchives_adid);
        Rows rows = dbConnect.runSqlQuery(factory.getSQL());
        return getSucReturnObject().setDataByPaging(rows).setFinalDo(DataPool.defaultdatalife, 1);
    }

    /**
     * 已下载用户列表
     *
     * @return
     */
    public String havedownloaduserlist() {
        /**
         *排序条件设置
         */
        String[] sortfield = {"t2.tenterprise_userid"};
        String sort = getSort(sortfield, "t2.tenterprise_userid");

        String tarchives_adid = content.getString("tarchives_adid");
        SQLFactory factory = new SQLFactory(this, "分析_推广素材已下载经销商", pageSize, pageNumber, sort);
        factory.addParameter("siteid", siteid);
        factory.addParameter("tarchives_adid", tarchives_adid);
        Rows rows = dbConnect.runSqlQuery(factory.getSQL());
        return getSucReturnObject().setDataByPaging(rows).setFinalDo(DataPool.defaultdatalife, 1);
    }

    /**
     * 已下载用户列表
     *
     * @return
     */
    public String havedownloaduserlist_saler() {
        /**
         *排序条件设置
         */
        String[] sortfield = {"t2.tenterprise_userid"};
        String sort = getSort(sortfield, "t2.tenterprise_userid");

        String tarchives_adid = content.getString("tarchives_adid");
        SQLFactory factory = new SQLFactory(this, "分析_推广素材已下载业务员", pageSize, pageNumber, sort);
        factory.addParameter("siteid", siteid);
        factory.addParameter("tarchives_adid", tarchives_adid);
        Rows rows = dbConnect.runSqlQuery(factory.getSQL());
        return getSucReturnObject().setDataByPaging(rows).setFinalDo(DataPool.defaultdatalife, 1);
    }

    /**
     * 分享统计
     * 分享人数、分享名单、分享次数等
     *
     * @return
     */
    public String shareStatistics() {
        String tarchives_adid = content.getString("tarchives_adid");
        /**
         *排序条件设置
         */
        String[] sortfield = {"t1.tarchives_adid"};
        String sort = getSort(sortfield, "t1.tarchives_adid");

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


    /**
     * 分享统计,拉新名单
     *
     * @return
     */
    public String shareStatistics_custlist() {
        String tarchives_adid = content.getString("tarchives_adid");
        String tenterprise_userid = content.getString("tenterprise_userid");
        /**
         *排序条件设置
         */
        String[] sortfield = {"t1.createdate desc"};
        String sort = getSort(sortfield, "t1.createdate desc");

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

    /**
     * 分享渠道统计
     *
     * @return
     */
    public String shareChannelStatistics() {
        String tarchives_adid = content.getString("tarchives_adid");
        SQLFactory factory = new SQLFactory(this, "推广素材分享渠道统计");
        factory.addParameter("siteid", siteid);
        factory.addParameter("tarchives_adid", tarchives_adid);
        Rows rows = dbConnect.runSqlQuery(factory.getSQL());
        return getSucReturnObject().setData(rows).saveToDataPool().toString();
    }

    /**
     * 分享拉新渠道统计
     *
     * @return
     */
    public String shareCustChannelStatistics() {
        String tarchives_adid = content.getString("tarchives_adid");
        SQLFactory factory = new SQLFactory(this, "推广素材拉新渠道统计");
        factory.addParameter("siteid", siteid);
        factory.addParameter("tarchives_adid", tarchives_adid);
        Rows rows = dbConnect.runSqlQuery(factory.getSQL());
        return getSucReturnObject().setData(rows).saveToDataPool().toString();
    }
}
