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 extends Controller {
    public archives(JSONObject content) {
        super(content);
    }

    /**
     * 营销物料列表查询
     *
     * @return
     */
    public String query_archivesList() {
        /**
         *排序条件设置
         */
        String[] sortfield = {"t1.checkdate", "t1.fvisitors"};
        String sort = getSort(sortfield, "t1.checkdate 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() {
        SQLFactory sqlFactory = new SQLFactory(this, "营销物料主界面查询");
        sqlFactory.addParameter("siteid", siteid);
        sqlFactory.addParameter("tarchivesid", content.getString("tarchivesid"));
        Rows rows = dbConnect.runSqlQuery(sqlFactory.getSQL());
        return getSucReturnObject().setData(rows).toString();
    }

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

        PaoSetRemote tarchivesSet = getP2ServerSystemPaoSet("tarchives", "siteid='" + siteid + "' and tarchivesid='" + tarchivesid + "'");
        PaoRemote tarchives = null;
        if (tarchivesid == 0 || tarchivesSet.isEmpty()) {
            tarchives = tarchivesSet.addAtEnd();
            tarchives.setValue("siteid", siteid, 11L);//企业ID
            tarchives.setValue("tenterprise_userid", userid, 11L);//用户ID
            tarchives.setValue("createby", username, 11L);//录入人
            tarchives.setValue("createdate", sysdate, 11L);//录入时间
            tarchives.setValue("fstatus", "新建", 11L);//营销物料状态
        } else {
            tarchives = tarchivesSet.getPao(0);
        }
        tarchives.setValue("fclass1", fclass1, 11L);
        tarchives.setValue("fclass2", fclass2, 11L);
        tarchives.setValue("ftitle", ftitle, 11L);
        tarchives.setValue("fnotes", fnotes, 11L);
        tarchives.setValue("fsalercanread", fsalercanread, 11L);
        tarchives.setValue("fagentcanread", fagentcanread, 11L);
        tarchives.setValue("fagentsalercanread", fagentsalercanread, 11L);

        tarchives.setValue("changeby", username);//修改人
        tarchives.setValue("changedate", sysdate);//修改时间

        content.put("tarchivesid", tarchives.getString("tarchivesid"));
        saveDataLog(tarchives);
        tarchivesSet.save();

        return query_archivesMain();
    }

    /**
     * 营销物料发布
     *
     * @return
     */
    public String archivesCheck() {
        long tarchivesid = content.getLongValue("tarchivesid");
        if (!dbConnect.runSqlQuery("select * from tarchives where siteid='" + siteid + "' and fstatus='发布' and tarchivesid=" + tarchivesid).isEmpty()) {
            return getErrReturnObject().setErrMsg("营销物料已发布，不可重复发布！").toString();
        }
        SQLFactory factory = new SQLFactory(this, "营销物料发布");
        factory.addParameter("siteid", siteid);
        factory.addParameter("tarchivesid", tarchivesid);
        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("tarchivesid", content.getString("tarchivesid"));
            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");
                msgfac.addParameter("objectid", tarchivesid);
                msgfac.addParameter("fmessage", "新发布了一条【" + fclass1 + "-" + fclass2 + "】类营销物料：《" + ftitle + "》");
                dbConnect.runSqlUpdate(msgfac.getSQL());
            }
            return getSucReturnObject().toString();
        } else {
            return getErrReturnObject().setErrMsg(status).toString();
        }
    }

    /**
     * 营销物料取消发布
     *
     * @return
     */
    public String archivesUnCheck() {
        long tarchivesid = content.getLongValue("tarchivesid");//营销物料ID，新增时默认传0
        if (dbConnect.runSqlQuery("select * from tarchives where siteid='" + siteid + "' and fstatus='发布' and tarchivesid=" + tarchivesid).isEmpty()) {
            return getErrReturnObject().setErrMsg("营销物料不在发布状态，不可取消发布！").toString();
        }
        SQLFactory factory = new SQLFactory(this, "营销物料取消发布");
        factory.addParameter("siteid", siteid);
        factory.addParameter("tarchivesid", tarchivesid);
        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 tarchivesid = content.getLongValue("tarchivesid");
        if (dbConnect.runSqlQuery("select * from tarchives where siteid='" + siteid + "' and fstatus='新建' and tarchivesid=" + tarchivesid).isEmpty()) {
            return getErrReturnObject().setErrMsg("当前状态不可删除！").toString();
        }
        SQLFactory sqlFactory = new SQLFactory(this, "营销物料删除");
        sqlFactory.addParameter("siteid", siteid);
        sqlFactory.addParameter("tarchivesid", tarchivesid);

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


    /**
     * 营销物料阅读分析
     *
     * @return
     */
    public String read_analysis() {
        long tarchivesid = content.getLongValue("tarchivesid");
        SQLFactory factory = new SQLFactory(this, "分析_营销物料阅读占比分析_经销商");
        factory.addParameter("siteid", siteid);
        factory.addParameter("tarchivesid", tarchivesid);
        Rows rows = dbConnect.runSqlQuery(factory.getSQL());
        return getSucReturnObject().setData(rows).saveToDataPool().toString();
    }

    /**
     * 营销物料阅读分析
     *
     * @return
     */
    public String read_analysis_saler() {
        long tarchivesid = content.getLongValue("tarchivesid");
        SQLFactory factory = new SQLFactory(this, "分析_营销物料阅读占比分析_业务员");
        factory.addParameter("siteid", siteid);
        factory.addParameter("tarchivesid", tarchivesid);
        Rows rows = dbConnect.runSqlQuery(factory.getSQL());
        return getSucReturnObject().setData(rows).saveToDataPool().toString();
    }

    /**
     * 营销物料下载分析
     *
     * @return
     */
    public String download_analysis() {
        long tarchivesid = content.getLongValue("tarchivesid");
        SQLFactory factory = new SQLFactory(this, "分析_营销物料下载占比分析_经销商");
        factory.addParameter("siteid", siteid);
        factory.addParameter("tarchivesid", tarchivesid);
        Rows rows = dbConnect.runSqlQuery(factory.getSQL());
        return getSucReturnObject().setData(rows).saveToDataPool().toString();
    }

    /**
     * 营销物料下载分析
     *
     * @return
     */
    public String download_analysis_saler() {
        long tarchivesid = content.getLongValue("tarchivesid");
        SQLFactory factory = new SQLFactory(this, "分析_营销物料下载占比分析_业务员");
        factory.addParameter("siteid", siteid);
        factory.addParameter("tarchivesid", tarchivesid);
        Rows rows = dbConnect.runSqlQuery(factory.getSQL());
        return getSucReturnObject().setData(rows).saveToDataPool().toString();
    }

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

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


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

        SQLFactory factory = new SQLFactory(this, "分析_营销物料已浏览经销商", pageSize, pageNumber, sort);
        factory.addParameter("siteid", siteid);
        factory.addParameter("tarchivesid", tarchivesid);
        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' and t1.ownerid='" + tarchivesid + "' ");
        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 = {"t1.tenterprise_userid"};
        String sort = getSort(sortfield, "t1.tenterprise_userid");
        long tarchivesid = content.getLongValue("tarchivesid");

        SQLFactory factory = new SQLFactory(this, "分析_营销物料已浏览业务员", pageSize, pageNumber, sort);
        factory.addParameter("siteid", siteid);
        factory.addParameter("tarchivesid", tarchivesid);
        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' and t1.ownerid='" + tarchivesid + "' ");
        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 = {"t1.tenterprise_userid"};
        String sort = getSort(sortfield, "t1.tenterprise_userid");
        long tarchivesid = content.getLongValue("tarchivesid");
        SQLFactory factory = new SQLFactory(this, "分析_营销物料未下载经销商", pageSize, pageNumber, sort);
        factory.addParameter("siteid", siteid);
        factory.addParameter("tarchivesid", tarchivesid);
        Rows rows = dbConnect.runSqlQuery(factory.getSQL());
        return getSucReturnObject().setDataByPaging(rows).setFinalDo(DataPool.defaultdatalife, 1);
    }

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

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

        long tarchivesid = content.getLongValue("tarchivesid");
        SQLFactory factory = new SQLFactory(this, "分析_营销物料已下载经销商", pageSize, pageNumber, sort);
        factory.addParameter("siteid", siteid);
        factory.addParameter("tarchivesid", tarchivesid);
        Rows rows = dbConnect.runSqlQuery(factory.getSQL());
        return getSucReturnObject().setDataByPaging(rows).setFinalDo(DataPool.defaultdatalife, 1);
    }

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

        long tarchivesid = content.getLongValue("tarchivesid");
        SQLFactory factory = new SQLFactory(this, "分析_营销物料已下载业务员", pageSize, pageNumber, sort);
        factory.addParameter("siteid", siteid);
        factory.addParameter("tarchivesid", tarchivesid);
        Rows rows = dbConnect.runSqlQuery(factory.getSQL());
        return getSucReturnObject().setDataByPaging(rows).setFinalDo(DataPool.defaultdatalife, 1);
    }
}
