package com.cnd3b.restcontroller.publicmethod.agentactivities;

import com.alibaba.fastjson.JSONObject;
import com.cnd3b.common.Controller;
import com.cnd3b.common.data.Row;
import com.cnd3b.common.data.Rows;
import com.cnd3b.common.data.SQLFactory;
import com.cnd3b.utility.wechatdock.WechatDock_gzh;
import com.cnd3b.utility.wechatdock.WechatDock_xcx;
import com.cnd3b.utility.wechatdock.WechatUser;
import p2.pao.PaoRemote;
import p2.pao.PaoSetRemote;
import p2.util.P2Exception;
import p2.application.tuseraccountdetails.tuseraccountdetails;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;

public class agentactivities extends Controller {

    /**
     * 构造函数
     *
     * @param content
     */
    public agentactivities(JSONObject content) {
        super(content);
    }

    public static HashMap<String, String> shareidmap = new HashMap<>();
    public static ArrayList<String> wechat_openidmap = new ArrayList<>();


    /**
     * 分享找客户信息查询,及推广流量记录
     *
     * @return
     */
    public String query_agentactivitiesforshare() throws P2Exception {
        String tagentactivities_shareid = content.getString("tagentactivities_shareid");
        String siteid = content.getString("siteid");
        boolean iswechatapp = false;
        if (content.containsKey("iswechatapp")) {
            iswechatapp = content.getString("iswechatapp").equals("1");
        }
        if (siteid == null || "".equals(siteid) || "null".equalsIgnoreCase(siteid) || tagentactivities_shareid == null || "".equals(tagentactivities_shareid) || "null".equalsIgnoreCase(tagentactivities_shareid)) {
            return getErrReturnObject().setErrMsg("无效的分享链接").toString();
        }

        SQLFactory sqlFactory = new SQLFactory(this, "找客户分享页信息查询");
        sqlFactory.addParameter("siteid", siteid);
        sqlFactory.addParameter("tagentactivities_shareid", tagentactivities_shareid);
        Rows rows = dbConnect.runSqlQuery(sqlFactory.getSQL());
        String tagentactivitiesid = "";
        for (Row row : rows) {
            tagentactivitiesid = row.getString("tagentactivitiesid");

            shareidmap.put(tagentactivities_shareid, tagentactivitiesid);

            SQLFactory coverfactory = new SQLFactory(this, "找客户分享页封面图查询");
            coverfactory.addParameter("siteid", siteid);
            coverfactory.addParameter("tagentactivitiesid", tagentactivitiesid);
            Rows coverrows = dbConnect.runSqlQuery(coverfactory.getSQL());
            if (!coverrows.isEmpty()) {
                row.put("cover", coverrows.get(0).getString("fobsurl"));
            } else {
                row.put("cover", "");
            }

            SQLFactory docfactory = new SQLFactory(this, "找客户分享页详情图查询");
            docfactory.addParameter("siteid", siteid);
            docfactory.addParameter("tagentactivitiesid", tagentactivitiesid);
            Rows docrows = dbConnect.runSqlQuery(docfactory.getSQL());
            row.put("docinfos", docrows);

            String fsalerid = row.getString("fsalerid");

            SQLFactory userheadfactory = new SQLFactory(this, "找客户分享页推广人头像查询");
            userheadfactory.addParameter("siteid", siteid);
            userheadfactory.addParameter("tenterprise_userid", fsalerid);
            Rows userheadrows = dbConnect.runSqlQuery(userheadfactory.getSQL());
            if (!userheadrows.isEmpty()) {
                row.put("headportrait", userheadrows.get(0).getString("fobsurl"));
            } else {
                row.put("headportrait", "");
            }
            getShareuserType(siteid, tagentactivitiesid, tagentactivities_shareid);

            String wechat_openid = "";
            if (content.containsKey("wechat_code") && !"".equals(content.getString("wechat_code"))) {
                String wechat_code = content.getString("wechat_code");
                String wechat_name = content.getString("wechat_name");

                wechat_openid = addagentactivitiesCust(siteid, tagentactivities_shareid, tagentactivitiesid, wechat_code, wechat_name, iswechatapp);
                wechat_openidmap.add(wechat_openid);
            }
            row.put("wechat_openid", wechat_openid);
        }
        return getSucReturnObject().setData(rows).toString();
    }

    public static HashMap<String, Integer> sharesalertype = new HashMap<>();//原链接分享是一级推广人还是二级推广人，1表示一级推广人，2表示二级推广人
    public static HashMap<String, String> sharesalerid = new HashMap<>();//原链接分享是推广人ID
    public static HashMap<String, Long> createuserid = new HashMap<>();//活动发起人账号id

    /**
     * 根据tagentactivities_shareid判断该分享是一级推广人分享的还会二级推广人分享的
     *
     * @param tagentactivities_shareid
     */
    private void getShareuserType(String siteid, String tagentactivitiesid, String tagentactivities_shareid) {
        if (!sharesalertype.containsKey(tagentactivities_shareid)) {
            Rows rows = dbConnect.runSqlQuery("select isnull(t1.fsaler1id,'')as fsaler1id, isnull(t1.fsaler2id,'') as fsaler2id,t2.tenterprise_userid from tagentactivities_share t1 inner join tagentactivities t2 on t1.siteid=t2.siteid and t1.tagentactivitiesid=t2.tagentactivitiesid where t1.siteid='" + siteid + "'and t1.tagentactivitiesid='" + tagentactivitiesid + "' and t1.tagentactivities_shareid=" + tagentactivities_shareid);
            if (!rows.isEmpty()) {
                String fsaler1id = rows.get(0).getString("fsaler1id");
                String fsaler2id = rows.get(0).getString("fsaler2id");
                long tenterprise_userid = rows.get(0).getLong("tenterprise_userid");
                if ("".equals(fsaler2id) || "0".equals(fsaler2id)) {
                    sharesalertype.put(tagentactivities_shareid, 1);
                    sharesalerid.put(tagentactivities_shareid, fsaler1id);
                } else {
                    sharesalertype.put(tagentactivities_shareid, 2);
                    sharesalerid.put(tagentactivities_shareid, fsaler2id);
                }
                createuserid.put(tagentactivities_shareid, tenterprise_userid);
            }
        }
    }

    /**
     * 客户拉新记录
     *
     * @return
     */
    private String addagentactivitiesCust(String siteid, String tagentactivities_shareid, String tagentactivitiesid, String wechat_code, String wechat_name, boolean iswechatapp) throws P2Exception {
        String wechat_openid = "";
        if (iswechatapp) {
            WechatDock_xcx wechatDock_xcx = new WechatDock_xcx();
            wechat_openid = wechatDock_xcx.getOpenId(wechat_code);
        } else {
            WechatDock_gzh wechatDock_gzh = new WechatDock_gzh();
            WechatUser wechatUser = wechatDock_gzh.getCustMsg(wechat_code);
            wechat_openid = wechatUser.getOpenid();
            wechat_name = wechatUser.getNickname();
        }
        if (!"".equals(wechat_openid)) {
            PaoSetRemote tagentactivities_custSet = getP2ServerSystemPaoSet("tagentactivities_cust", "siteid='" + siteid + "' and tagentactivities_shareid='" + tagentactivities_shareid + "' and tagentactivitiesid='" + tagentactivitiesid + "' and wechat_openid='" + wechat_openid + "'");
            long tagentactivities_custid = 0L;
            PaoRemote tagentactivities_cust = null;
            if (tagentactivities_custSet.isEmpty()) {
                tagentactivities_cust = tagentactivities_custSet.addAtEnd();
                tagentactivities_cust.setValue("siteid", siteid, 11L);//企业ID
                tagentactivities_cust.setValue("tagentactivitiesid", tagentactivitiesid, 11L);//活动ID
                tagentactivities_cust.setValue("tagentactivities_shareid", tagentactivities_shareid, 11L);//分享ID
                tagentactivities_cust.setValue("fwechatname", wechat_name, 11L);//微信名
                tagentactivities_cust.setValue("createdate", getDateTime(), 11L);//分享时间
                tagentactivities_cust.setValue("fvisitors", 1, 11L);
                tagentactivities_cust.setValue("wechat_openid", wechat_openid, 11L);
                tagentactivities_cust.setValue("changedate", getDateTime(), 11L);
                tagentactivities_cust.setValue("fvisitors", 1, 11L);
                if (sharesalertype.containsKey(tagentactivities_shareid) && sharesalerid.containsKey(tagentactivities_shareid)) {
                    int usertype = sharesalertype.get(tagentactivities_shareid);//推广人级别
                    int famount = 0;
                    Rows rows = dbConnect.runSqlQuery("select (isnull(fupperlimitamount,0)-isnull(fusedamount,0)) as fcanuseamount,fsaler1rewardamount1,fsaler2rewardamount1 from tagentactivities where fstatus='推广中' and fbegdate<GETDATE() and fenddate>GETDATE() and siteid='" + siteid + "' and tagentactivitiesid='" + tagentactivitiesid + "'");
                    if (!rows.isEmpty()) {
                        int fcanuseamount = rows.get(0).getInteger("fcanuseamount");
                        int fsaler1rewardamount1 = rows.get(0).getInteger("fsaler1rewardamount1");
                        int fsaler2rewardamount1 = rows.get(0).getInteger("fsaler2rewardamount1");

                        if (usertype == 1 && fcanuseamount > fsaler1rewardamount1) {
                            famount = fsaler1rewardamount1;
                        } else if (usertype == 2 && fcanuseamount > fsaler2rewardamount1) {
                            famount = fsaler2rewardamount1;
                        }
                        /**
                         * 活动已使用金额通过触发器进行计算
                         */
                        if (tagentactivities_cust.toBeAdded()) {
                            /**
                             * 创建支出明细
                             */
                            PaoSetRemote tuseraccountdetailsSet = tagentactivities_cust.getPaoSet("$tuseraccountdetails" + Calendar.getInstance().getTime(), "tuseraccountdetails");
                            if (createuserid.get(tagentactivities_shareid) != Long.parseLong(sharesalerid.get(tagentactivities_shareid))) {
                                createUseraccountdetails(tuseraccountdetailsSet, "支出", "拉新", tagentactivities_cust, famount, "拉新：" + wechat_name, createuserid.get(tagentactivities_shareid));
                                createUseraccountdetails(tuseraccountdetailsSet, "收入", "拉新", tagentactivities_cust, famount, "拉新：" + wechat_name, Long.parseLong(sharesalerid.get(tagentactivities_shareid)));
                            }
                        }
                    }
                    tagentactivities_cust.setValue("famount", famount, 11L);
                }
                tagentactivities_custid = tagentactivities_cust.getUniqueIDValue();
            } else {
                tagentactivities_cust = tagentactivities_custSet.getPao(0);

                tagentactivities_cust.setValue("changedate", getDateTime(), 11L);
                tagentactivities_cust.setValue("fvisitors", tagentactivities_cust.getInt("fvisitors") + 1, 11L);
            }
            tagentactivities_custSet.save();

            if (tagentactivities_custid > 0) {
                SQLFactory messgae = new SQLFactory(this, "拉新用户消息提醒");
                messgae.addParameter("siteid", siteid);
                messgae.addParameter("tagentactivitiesid", tagentactivitiesid);
                messgae.addParameter("tagentactivities_shareid", tagentactivities_shareid);
                messgae.addParameter("tagentactivities_custid", tagentactivities_custid);
                dbConnect.runSqlUpdate(messgae.getSQL());
            }
        }
        return wechat_openid;
    }

    /**
     * 分享找客户 客户表单提交
     *
     * @return
     */
    public String submitcustform() throws P2Exception {
        String wechat_openid = content.getString("wechat_openid");
        if (!wechat_openidmap.contains(wechat_openid)) {
            return getErrReturnObject().setErrMsg("提交参数错误").toString();
        }
        String tagentactivities_shareid = content.getString("tagentactivities_shareid");
        String siteid = content.getString("siteid");
        String fname = content.getString("fname");
        String fphonenumber = content.getString("fphonenumber");
        String faddress = content.getString("faddress");

        String tagentactivitiesid = shareidmap.get(tagentactivities_shareid);

        boolean issaler = false;//是否为一级二级推广人

        long tagentactivities_formid = 0L;
        PaoSetRemote tagentactivities_formSet = getP2ServerSystemPaoSet("tagentactivities_form");
        if (issaler) {
            tagentactivities_formSet.setWhere("siteid='" + siteid + "' and tagentactivitiesid='" + tagentactivitiesid + "' and tagentactivities_shareid='" + tagentactivities_shareid + "' and wechat_openid='" + wechat_openid + "' and fphonenumber='" + fphonenumber + "'");
        } else {
            tagentactivities_formSet.setWhere("siteid='" + siteid + "' and tagentactivitiesid='" + tagentactivitiesid + "' and tagentactivities_shareid='" + tagentactivities_shareid + "' and wechat_openid='" + wechat_openid + "'");
        }
        tagentactivities_formSet.reset();
        PaoRemote tagentactivities_form = null;
        if (tagentactivities_formSet.isEmpty()) {
            tagentactivities_form = tagentactivities_formSet.addAtEnd();
            tagentactivities_form.setValue("createdate", getDateTime(), 11L);
            tagentactivities_form.setValue("siteid", siteid, 11L);
            tagentactivities_form.setValue("wechat_openid", wechat_openid, 11L);
            tagentactivities_form.setValue("tagentactivities_shareid", tagentactivities_shareid, 11L);
            tagentactivities_form.setValue("tagentactivitiesid", tagentactivitiesid, 11L);
        } else {
            tagentactivities_form = tagentactivities_formSet.getPao(0);
        }
        tagentactivities_form.setValue("fname", fname, 11L);
        tagentactivities_form.setValue("fphonenumber", fphonenumber, 11L);
        tagentactivities_form.setValue("faddress", faddress, 11L);

        if (sharesalertype.containsKey(tagentactivities_shareid) && sharesalerid.containsKey(tagentactivities_shareid)) {
            int usertype = sharesalertype.get(tagentactivities_shareid);//推广人级别
            int famount = 0;
            Rows rows = dbConnect.runSqlQuery("select (isnull(fupperlimitamount,0)-isnull(fusedamount,0)) as fcanuseamount,fsaler1rewardamount2,fsaler2rewardamount2 from tagentactivities where fstatus='推广中' and fbegdate<GETDATE() and fenddate>GETDATE() and siteid='" + siteid + "' and tagentactivitiesid='" + tagentactivitiesid + "'");
            if (!rows.isEmpty()) {
                int fcanuseamount = rows.get(0).getInteger("fcanuseamount");
                int fsaler1rewardamount2 = rows.get(0).getInteger("fsaler1rewardamount2");
                int fsaler2rewardamount2 = rows.get(0).getInteger("fsaler2rewardamount2");

                if (usertype == 1 && fcanuseamount > fsaler1rewardamount2) {
                    famount = fsaler1rewardamount2;
                } else if (usertype == 2 && fcanuseamount > fsaler2rewardamount2) {
                    famount = fsaler2rewardamount2;
                }
                /**
                 * 活动已使用金额通过触发器进行计算
                 */
                if (tagentactivities_form.toBeAdded()) {
                    /**
                     * 创建支出明细
                     */
                    PaoSetRemote tuseraccountdetailsSet = tagentactivities_form.getPaoSet("$tuseraccountdetails" + Calendar.getInstance().getTime(), "tuseraccountdetails");

                    if (createuserid.get(tagentactivities_shareid) != Long.parseLong(sharesalerid.get(tagentactivities_shareid))) {
                        createUseraccountdetails(tuseraccountdetailsSet, "支出", "线索", tagentactivities_form, famount, "线索：" + fname, createuserid.get(tagentactivities_shareid));
                        createUseraccountdetails(tuseraccountdetailsSet, "收入", "线索", tagentactivities_form, famount, "线索：" + fname, Long.parseLong(sharesalerid.get(tagentactivities_shareid)));
                    }
                }
            }
            tagentactivities_form.setValue("famount", famount, 11L);
        }

        tagentactivities_formid = tagentactivities_form.getUniqueIDValue();
        tagentactivities_formSet.save();

        if (tagentactivities_formid > 0) {
            SQLFactory messgae = new SQLFactory(this, "线索用户消息提醒");
            messgae.addParameter("siteid", siteid);
            messgae.addParameter("tagentactivitiesid", tagentactivities_formid);
            messgae.addParameter("tagentactivities_shareid", tagentactivities_shareid);
            messgae.addParameter("tagentactivities_formid", tagentactivities_formid);
            dbConnect.runSqlUpdate(messgae.getSQL());
        }
        return getSucReturnObject().toString();
    }

    /**
     * 创建拉新支出明细
     */
    public void createUseraccountdetails(PaoSetRemote tuseraccountdetailsSet, String ftype, String ftypemx, PaoRemote pao, int famount, String fnotes, long tenterprise_userid) throws P2Exception {
        if (famount != 0) {
            if (tuseraccountdetailsSet.isEmpty()) {
                tuseraccountdetails tuseraccountdetails = (tuseraccountdetails) tuseraccountdetailsSet.addAtEnd();
                String siteid = pao.getString("siteid");
                tuseraccountdetails.setValues(ftype, ftypemx, famount, fnotes, "系统", siteid, tenterprise_userid);
                /**
                 * 账户余额通过tuseraccountdetails触发器实现
                 */
            }
        }
    }
}
