package com.cnd3b.restcontroller.enterprise.agentclient.mainpage.tagentactivities;

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

    /**
     * 数据统计（首页简报）
     *
     * @return
     */
    public String query_analysis() {
        SQLFactory sqlFactory = new SQLFactory(this, "数据统计");
        sqlFactory.addParameter("tagentsid", tagentsid);
        sqlFactory.addParameter("tenterprise_userid", userid);
        sqlFactory.addParameter("siteid", siteid);
        Rows rows = dbConnect.runSqlQuery(sqlFactory.getSQL());
        return getSucReturnObject().setData(rows).saveToDataPool().toString();
    }

    /**
     * 经销商活动（找客户）列表查询
     *
     * @return
     */
    public String query_agentactivitiesList() {
        /**
         *排序条件设置
         */
        String[] sortfield = {"case when t1.fenddate>getdate() then 1 else 2 end ,t1.checkdate desc"};
        String sort = getSort(sortfield, "case when t1.fenddate>getdate() then 1 else 2 end ,t1.checkdate desc");
        SQLFactory activitiesSQl = new SQLFactory(this, "活动列表查询", pageSize, pageNumber, sort);
        activitiesSQl.addParameter("siteid", siteid);
        activitiesSQl.addParameter("tagentsid", tagentsid);
        Rows rows = dbConnect.runSqlQuery(activitiesSQl.getSQL());
        ArrayList<String> tagentactivitiesidlist = rows.toArrayList("tagentactivitiesid");

        SQLFactory coverfactory = new SQLFactory(this, "找客户分享页封面图查询");
        coverfactory.addParameter("siteid", siteid);
        coverfactory.addParameter_in("tagentactivitiesid", tagentactivitiesidlist);
        RowsMap coverrowsmap = dbConnect.runSqlQuery(coverfactory.getSQL()).toRowsMap("tagentactivitiesid");

        for (Row row : rows) {
            String tagentactivitiesid = row.getString("tagentactivitiesid");
            if (coverrowsmap.containsKey(tagentactivitiesid)) {
                row.put("cover", coverrowsmap.get(tagentactivitiesid).get(0).getString("fobsurl"));
            } else {
                row.put("cover", "");
            }
        }
        return getSucReturnObject().setDataByPaging(rows, sortfield).setFinalDo(DataPool.defaultdatalife, 1);
    }

    /**
     * 经销商活动（找客户）主界面查询
     *
     * @return
     */
    public String query_agentactivitiesMain() {
        String tagentactivitiesid = content.getString("tagentactivitiesid");//活动ID
        long tenterprise_userid = content.getLongValue("tenterprise_userid");//活动创建ID

        boolean isself = (userid == tenterprise_userid);//是否为自己的活动

        SQLFactory activitiesSQl = new SQLFactory(this, isself ? "活动详情页查询_个人" : "活动详情页查询_他人");
        activitiesSQl.addParameter("siteid", siteid);
        activitiesSQl.addParameter("tagentactivitiesid", tagentactivitiesid);
        activitiesSQl.addParameter("tenterprise_userid", userid);

        Rows rows = dbConnect.runSqlQuery(activitiesSQl.getSQL());
        return getSucReturnObject().setData(rows).toString();
    }

    /**
     * 经销商活动（找客户）主界面查询_拉新统计
     *
     * @return
     */
    public String query_agentactivitiesCustList() {
        long tagentactivitiesid = content.getLongValue("tagentactivitiesid");//活动ID
        long tenterprise_userid = content.getLongValue("tenterprise_userid");//活动创建ID

        boolean isself = (userid == tenterprise_userid);//是否为自己的活动

        SQLFactory activitiesSQl = new SQLFactory(this, isself ? "活动详情页拉新统计查询_个人" : "活动详情页拉新统计查询_他人", pageSize, pageNumber, "t1.createdate desc");
        activitiesSQl.addParameter("siteid", siteid);
        activitiesSQl.addParameter("tagentactivitiesid", tagentactivitiesid);
        activitiesSQl.addParameter("tenterprise_userid", userid);

        Rows rows = dbConnect.runSqlQuery(activitiesSQl.getSQL());
        return getSucReturnObject().setDataByPaging(rows).setFinalDo(DataPool.defaultdatalife, 1);
    }

    /**
     * 经销商活动（找客户）主界面查询_线索统计
     *
     * @return
     */
    public String query_agentactivitiesFormList() {
        long tagentactivitiesid = content.getLongValue("tagentactivitiesid");//活动ID
        long tenterprise_userid = content.getLongValue("tenterprise_userid");//活动创建ID

        boolean isself = (userid == tenterprise_userid);//是否为自己的活动

        SQLFactory activitiesSQl = new SQLFactory(this, isself ? "活动详情页线索数据查询_个人" : "活动详情页线索数据查询_他人", pageSize, pageNumber, "t1.createdate desc");
        activitiesSQl.addParameter("siteid", siteid);
        activitiesSQl.addParameter("tagentactivitiesid", tagentactivitiesid);
        activitiesSQl.addParameter("tenterprise_userid", userid);

        Rows rows = dbConnect.runSqlQuery(activitiesSQl.getSQL());
        return getSucReturnObject().setDataByPaging(rows).setFinalDo(DataPool.defaultdatalife, 1);
    }

    /**
     * 活动新增或修改
     *
     * @return
     */
    public String agentactivitiesInsertOrModify() throws D3bException, P2Exception {
        long tagentactivitiesid = content.getLongValue("tagentactivitiesid");//活动ID，新增时默认传0
        String ftitle = content.getString("ftitle", "tagentactivities.ftitle", "活动名称");//活动名称
        String fbegdate = content.getString("fbegdate");//开始时间
        String fenddate = content.getString("fenddate");//结束时间
        String fnotes = content.getString("fnotes", "tagentactivities.fnotes", "活动说明");//活动说明
        String fphonenumber = content.getString("fphonenumber", "tagentactivities.fphonenumber", "联系方式");//联系方式


        int fsaler1rewardamount1 = content.getIntValue("fsaler1rewardamount1");//一级推广人流量奖励(单位分)
        int fsaler1rewardamount2 = content.getIntValue("fsaler1rewardamount2");//一级推广人线索奖励(单位分)
        int fsaler2rewardamount1 = 0;
        if (content.containsKey("fsaler2rewardamount1")) {
            Object o = content.getObject("fsaler2rewardamount1", Integer.class);//二级推广人流量奖励(单位分)
            if (o != null) {
                fsaler2rewardamount1 = (int) o;
            }
        }
        int fsaler2rewardamount2 = 0;
        if (content.containsKey("fsaler2rewardamount2")) {
            Object o = content.getObject("fsaler2rewardamount2", Integer.class);//二级推广人线索奖励(单位分)
            if (o != null) {
                fsaler2rewardamount1 = (int) o;
            }
        }
        int fupperlimitamount = content.getIntValue("fupperlimitamount");//活动预算（单位分）
        int fnewfreezamount = fupperlimitamount;//新增冻结金额
        Rows checkrows = dbConnect.runSqlQuery("select * from tagentactivities where siteid='" + siteid + "' and tagentsid='" + tagentsid + "' and tagentactivitiesid='" + tagentactivitiesid + "'");
        if (!checkrows.isEmpty()) {
            int fusedamount = checkrows.get(0).getInteger("fusedamount");
            int foldupperlimitamount = checkrows.get(0).getInteger("fupperlimitamount");
            String fstatus = checkrows.get(0).getString("fstatus");
            if ("已结束".equals(fstatus)) {
                return getErrReturnObject().setErrMsg("活动已结束，不可修改！").toString();
            } else if (fupperlimitamount < fusedamount) {
                return getErrReturnObject().setErrMsg("活动预算不可小于已使用金额！").toString();
            }
            if (fupperlimitamount > foldupperlimitamount) {
                fnewfreezamount = fupperlimitamount - foldupperlimitamount;
            }
        }
        //如果是新增
        if (getUserCanUseAmount() < fnewfreezamount) {
            return getErrReturnObject().setErrMsg("账户可用余额不足！").toString();
        }

        PaoSetRemote tagentactivitiesSet = getP2ServerSystemPaoSet("tagentactivities", "siteid='" + siteid + "' and tagentsid='" + tagentsid + "' and tagentactivitiesid='" + tagentactivitiesid + "'");
        PaoRemote tagentactivities = null;
        if (tagentactivitiesid <= 0 || tagentactivitiesSet.isEmpty()) {
            tagentactivities = tagentactivitiesSet.addAtEnd();
            tagentactivities.setValue("siteid", siteid, 11L);//企业ID
            tagentactivities.setValue("tenterprise_userid", userid, 11L);//用户ID
            tagentactivities.setValue("createby", username, 11L);//录入人
            tagentactivities.setValue("createdate", sysdate, 11L);//录入时间
            tagentactivities.setValue("fstatus", "推广中", 11L);//推广素材状态
            tagentactivities.setValue("tagentsid", tagentsid, 11L);
            tagentactivities.setValue("fusedamount", 0, 11L);

            tagentactivitiesid = tagentactivities.getLong("tagentactivitiesid");
        } else {
            tagentactivities = tagentactivitiesSet.getPao(0);
        }
        tagentactivities.setValue("ftitle", ftitle, 11L);
        tagentactivities.setValue("fbegdate", fbegdate, 11L);
        tagentactivities.setValue("fenddate", fenddate, 11L);

        tagentactivities.setValue("fsaler1rewardamount1", fsaler1rewardamount1, 11L);
        tagentactivities.setValue("fsaler1rewardamount2", fsaler1rewardamount2, 11L);
        tagentactivities.setValue("fsaler2rewardamount1", fsaler2rewardamount1, 11L);
        tagentactivities.setValue("fsaler2rewardamount2", fsaler2rewardamount2, 11L);
        tagentactivities.setValue("fupperlimitamount", fupperlimitamount, 11L);

        tagentactivities.setValue("fnotes", fnotes, 11L);
        tagentactivities.setValue("fphonenumber", fphonenumber, 11L);

        tagentactivities.setValue("checkby", username, 11L);//录入人
        tagentactivities.setValue("checkdate", sysdate, 11L);//录入时间
        tagentactivities.setValue("changeby", username);//修改人
        tagentactivities.setValue("changedate", sysdate);//修改时间

        content.put("tagentactivitiesid", tagentactivitiesid);
        content.put("tenterprise_userid", userid);
        saveDataLog(tagentactivities);
        tagentactivitiesSet.save();

        return query_agentactivitiesMain();
    }

    /**
     * 经销商活动分享记录
     *
     * @return
     */
    public String agentactivitiesShare() throws P2Exception {
        long tagentactivitiesid = content.getLongValue("tagentactivitiesid");//活动ID

        PaoSetRemote tagentactivities_shareSet = getP2ServerSystemPaoSet("tagentactivities_share");
        PaoRemote tagentactivities_share = tagentactivities_shareSet.addAtEnd();
        tagentactivities_share.setValue("siteid", siteid, 11L);//企业ID
        tagentactivities_share.setValue("fsaler1id", userid, 11L);//一级推广人ID
        tagentactivities_share.setValue("fsaler1", username, 11L);//一级推广人姓名
        tagentactivities_share.setValue("tagentactivitiesid", tagentactivitiesid, 11L);
        tagentactivities_share.setValue("createdate", getDateTime(), 11L);//推广时间
        long tagentactivities_shareid = tagentactivities_share.getUniqueIDValue();
        tagentactivities_shareSet.save();

        JSONObject dataobject = new JSONObject();
        dataobject.put("tagentactivities_shareid", tagentactivities_shareid);
        return getSucReturnObject().setData(dataobject).toString();
    }

}
