package com.cnd3b.restcontroller.enterprise.agentwebclient.mainpage.notice;

import com.alibaba.fastjson.JSONObject;
import com.cnd3b.common.Controller;
import com.cnd3b.common.D3bException;
import com.cnd3b.common.actionscore.ActionScore;
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;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;

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

    /**
     * 公告列表查询
     *
     * @return
     */
    public String query_noticeList() throws D3bException {
        /**
         *排序条件设置
         */
        String[] sortfield = {"t1.fisontop desc,t1.checkdate desc"};
        String sort = getSort(sortfield, "t1.fisontop desc,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.ftype like'%").append(whereObject.getString("condition")).append("%' ");
                where.append("or t1.fsummary like'%").append(whereObject.getString("condition")).append("%' ");
                where.append(")");
            }
        }
        SQLFactory noticehead = new SQLFactory(this, "公告列表查询", pageSize, pageNumber, sort);
        noticehead.addParameter("siteid", siteid);
        noticehead.addParameter("tenterprise_userid", userid);
        noticehead.addParameter_SQL("where", where);
        Rows rows = dbConnect.runSqlQuery(noticehead.getSQL());
        ArrayList<String> tnoticeidlist = rows.toArrayList("tnoticeid");

        SQLFactory noticeisread = new SQLFactory(this, "公告列表是否已读查询");
        noticeisread.addParameter("siteid", siteid);
        noticeisread.addParameter("tenterprise_userid", userid);
        noticeisread.addParameter_in("tnoticeid", tnoticeidlist);
        List tnoticeids = Arrays.asList(dbConnect.runSqlQuery(noticeisread.getSQL()).toArray("tnoticeid"));


        SQLFactory noticereadcount = new SQLFactory(this, "公告阅读量查询");
        noticereadcount.addParameter("siteid", siteid);
        noticereadcount.addParameter_in("tnoticeid", tnoticeidlist);
        RowsMap noticereadcountMap = dbConnect.runSqlQuery(noticereadcount.getSQL()).toRowsMap("tnoticeid");

        SQLFactory tattachmentcount = new SQLFactory(this, "附件数量查询");
        tattachmentcount.addParameter("siteid", siteid);
        tattachmentcount.addParameter_in("tnoticeid", tnoticeidlist);
        RowsMap tattachmentcountcountMap = dbConnect.runSqlQuery(tattachmentcount.getSQL()).toRowsMap("tnoticeid");


        SQLFactory docfactory = new SQLFactory(this, "公告列表封面查询");
        docfactory.addParameter("siteid", siteid);
        docfactory.addParameter_in("ownerid", tnoticeidlist);
        RowsMap map = dbConnect.runSqlQuery(docfactory.getSQL()).toRowsMap("tnoticeid");


        for (Row row : rows) {
            String tnoticeid = row.getString("tnoticeid");
            /**
             * 是否已读
             */
            if (tnoticeids.contains(tnoticeid)) {
                row.put("fisread", 1);
            } else {
                row.put("fisread", 0);
            }
            /**
             * 阅读量查询
             */
            if (noticereadcountMap.containsKey(tnoticeid)) {
                row.put("freadcount", noticereadcountMap.get(tnoticeid).getRow(0).getInteger("freadcount"));
            } else {
                row.put("freadcount", 0);
            }
            /**
             * 附件数量查询
             */
            if (tattachmentcountcountMap.containsKey(tnoticeid)) {
                row.put("fattachmentcount", tattachmentcountcountMap.get(tnoticeid).getRow(0).getInteger("fattachmentcount"));
            } else {
                row.put("fattachmentcount", 0);
            }

            row.put("docinfos", map.get(tnoticeid));
        }
        return getSucReturnObject().setDataByPaging(rows, sortfield).setFinalDo(DataPool.defaultdatalife, 1);
    }

    /**
     * 公告主界面查询(公告阅读)
     *
     * @return
     */
    public String query_noticeMain() throws P2Exception {
        long tnoticeid = content.getLongValue("tnoticeid");
        SQLFactory noticehead = new SQLFactory(this, "公告主界面查询");
        noticehead.addParameter("siteid", siteid);
        noticehead.addParameter("tnoticeid", tnoticeid);
        Rows rows = dbConnect.runSqlQuery(noticehead.getSQL());

        SQLFactory noticereadcount = new SQLFactory(this, "公告阅读量查询");
        noticereadcount.addParameter("siteid", siteid);
        noticereadcount.addParameter_in("tnoticeid", String.valueOf(tnoticeid));
        Rows noticereadcountRows = dbConnect.runSqlQuery(noticereadcount.getSQL());

        SQLFactory noticeleavemessage = new SQLFactory(this, "公告评分及留言查询");
        noticeleavemessage.addParameter("siteid", siteid);
        noticeleavemessage.addParameter("tnoticeid", tnoticeid);
        noticeleavemessage.addParameter("tenterprise_userid", userid);
        Rows noticeleavemessageRows = dbConnect.runSqlQuery(noticeleavemessage.getSQL());

        if (!rows.isEmpty()) {
            /**
             * 公告阅读量
             */
            if (!noticereadcountRows.isEmpty()) {
                rows.get(0).put("freadcount", noticereadcountRows.get(0).getInteger("freadcount") + 1);
            } else {
                rows.get(0).put("freadcount", 1);
            }
            /**
             * 评分及留言
             */
            if (!noticeleavemessageRows.isEmpty()) {
                rows.get(0).put("fleavemessage", noticeleavemessageRows.get(0).getString("fleavemessage"));
                rows.get(0).put("fscore", noticeleavemessageRows.get(0).getInteger("fscore"));
            } else {
                rows.get(0).put("fleavemessage", "");
                rows.get(0).put("fscore", 0);
            }
            Rows evaluationsRows = dbConnect.runSqlQuery("select count(0)evaluations from tnotice_users where siteid='" + siteid + "' and tnoticeid='" + tnoticeid + "' and fscore>0");
            rows.get(0).put("evaluations", evaluationsRows.get(0).getInteger("evaluations"));
        }
        PaoSetRemote tnotice_userdataSet = getP2ServerSystemPaoSet("tnotice_userdata");
        PaoRemote tnotice_userdata = tnotice_userdataSet.addAtEnd();
        tnotice_userdata.setValue("siteid", siteid, 11L);
        tnotice_userdata.setValue("tnoticeid", tnoticeid, 11L);
        tnotice_userdata.setValue("tenterprise_userid", userid, 11L);
        tnotice_userdata.setValue("createby", username, 11L);
        Calendar calendar = Calendar.getInstance();
        tnotice_userdata.setValue("createdate", calendar.getTime(), 11L);
        calendar.add(Calendar.MINUTE, 5);
        tnotice_userdata.setValue("closedate", calendar.getTime(), 11L);
        tnotice_userdataSet.save();

        dbConnect.runSqlUpdate("update tnotice_users set flastreadtime=getdate() where siteid='" + siteid + "' and tnoticeid='" + tnoticeid + "' and tenterprise_userid='" + userid + "'");
        addActionScore(ActionScore.fsourcetype.阅读通告, tnoticeid, "阅读通告");

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

    public String noticeexit() {
        long tnoticeid = content.getLongValue("tnoticeid");
        dbConnect.runSqlUpdate("update top(1) tnotice_userdata set closedate=getdate() where siteid='" + siteid + "' and tnoticeid='" + tnoticeid + "' and tenterprise_userid='" + userid + "'");
        return getSucReturnObject().toString();
    }

    /**
     * 公告评分及留言
     *
     * @return
     */
    public String notice_returnMessage() throws D3bException, P2Exception {
        long tnoticeid = content.getLongValue("tnoticeid");
        String fleavemessage = content.getString("fleavemessage", "tnotice_users.fleavemessage", "建议与反馈");
        int fscore = content.getIntValue("fscore");
        /**
         * 评分留言
         */
        PaoSetRemote tnotice_usersSet = getP2ServerSystemPaoSet("tnotice_users", "siteid='" + siteid + "' and tnoticeid=" + tnoticeid + " and tenterprise_userid='" + userid + "'");
        if (!tnotice_usersSet.isEmpty()) {
            PaoRemote tnotice_users = tnotice_usersSet.getPao(0);
            tnotice_users.setValue("fleavemessage", fleavemessage, 11L);
            tnotice_users.setValue("fscore", fscore, 11L);
            tnotice_users.setValue("changeby", username, 11L);
            tnotice_users.setValue("changedate", getDateTime(), 11L);
        } else {
            PaoRemote tnotice_users = tnotice_usersSet.addAtEnd();
            tnotice_users = tnotice_usersSet.getPao(0);
            tnotice_users.setValue("siteid", siteid);
            tnotice_users.setValue("tenterprise_userid", userid);
            tnotice_users.setValue("tnoticeid", tnoticeid);
            tnotice_users.setValue("fleavemessage", fleavemessage, 11L);
            tnotice_users.setValue("fscore", fscore, 11L);
            tnotice_users.setValue("changeby", username, 11L);
            tnotice_users.setValue("changedate", getDateTime(), 11L);
        }
        tnotice_usersSet.save();
        addActionScore(ActionScore.fsourcetype.通告评分, tnoticeid, "通告评分");
        return getSucReturnObject().toString();
    }
}
