package com.cnd3b.restcontroller.enterprise.webclient.tenterprise;

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.Rows;
import com.cnd3b.common.data.RowsMap;
import com.cnd3b.common.data.SQLFactory;
import com.cnd3b.common.data.db.DataPool;
import com.cnd3b.common.parameter.parameter;
import com.cnd3b.common.data.Row;
import p2.pao.PaoRemote;
import p2.pao.PaoSetRemote;
import p2.util.P2Exception;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

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

    /**
     * 企业档案主界面查询
     *
     * @return
     */
    public String query_enterpriseMain() {
        SQLFactory sql = new SQLFactory(this, "企业档案主界面查询");
        sql.addParameter("siteid", siteid);
        Rows rows = dbConnect.runSqlQuery(sql.getSQL());
        for (Row row : rows) {
            row.put("datalog", getDataLog("tenterprise", row.getString("tenterpriseid")));
        }
        return getSucReturnObject().setData(rows).saveToDataPool().toString();
    }

    /**
     * 企业档案主界面修改
     *
     * @return
     */
    public String update_enterpriseMain() throws D3bException, P2Exception {
        String fcontact = content.getString("fcontact", "tenterprise.fcontact", "联系人");
        String faddress = content.getString("faddress", "tenterprise.faddress", "详细地址");
        String fphonenumber = content.getString("fphonenumber", "tenterprise.fphonenumber", "联系方式");
        String fwebsite = content.getString("fwebsite", "tenterprise.fwebsite", "官网首页");
        String fbrand = content.getString("fbrand", "tenterprise.fbrand", "品牌名称");

        PaoSetRemote tenterpriseSet = getP2ServerSystemPaoSet("tenterprise", "siteid='" + siteid + "'");
        PaoRemote tenterprise = tenterpriseSet.getPao(0);
        tenterprise.setValue("fbrand", fbrand, 11L);
        tenterprise.setValue("fcontact", fcontact, 11L);
        tenterprise.setValue("faddress", faddress, 11L);
        tenterprise.setValue("fphonenumber", fphonenumber, 11L);
        tenterprise.setValue("fwebsite", fwebsite, 11L);
        tenterprise.setValue("changeby", username, 11L);//修改人
        tenterprise.setValue("changedate", getDateTime(), 11L);//修改时间
        /**
         * 保存修改日志
         */
        saveDataLog(tenterprise);
        tenterpriseSet.save();

        return query_enterpriseMain();
    }


    /**
     * 企业档案企业参数查询
     *
     * @return
     */
    public String query_enterpriseVars() {
        SQLFactory sql = new SQLFactory(this, "企业参数查询");
        sql.addParameter("siteid", siteid);
        Rows rows = dbConnect.runSqlQuery(sql.getSQL());
        return getSucReturnObject().setData(rows).saveToDataPool().toString();
    }

    /**
     * 数据统计
     *
     * @return
     */
    public String query_analysis() {
        SQLFactory sqlFactory = new SQLFactory(this, "企业账号激活统计");
        sqlFactory.addParameter("siteid", siteid);
        Rows rows = dbConnect.runSqlQuery(sqlFactory.getSQL());
        RowsMap map = rows.toRowsMap("faccountstatus");

        JSONArray array = new JSONArray();
        for (String faccountstatus : map.keySet()) {
            JSONObject object = new JSONObject();
            object.put("faccountstatus", faccountstatus);
            object.put("fcount", map.get(faccountstatus).size());

            array.add(object);
        }
        return getSucReturnObject().setData(array).saveToDataPool().toString();
    }


    /**
     * 企业档案企业账号信息查询
     *
     * @return
     */
    public String query_enterpriseUsers() {
        StringBuffer where = new StringBuffer(" 1=1 ");
        if (content.containsKey("where")) {
            JSONObject whereObject = content.getJSONObject("where");
            if (whereObject.containsKey("fisadministrator") && !"".equals(whereObject.getString("fisadministrator"))) {
                where.append(" and(");
                where.append("t1.fisadministrator ='").append(whereObject.getString("fisadministrator")).append("' ");
                where.append(")");
            }
            if (whereObject.containsKey("condition") && !"".equals(whereObject.getString("condition"))) {
                where.append(" and(");
                where.append("t1.fphonenumber like'%").append(whereObject.getString("condition")).append("%' ");
                where.append("or t1.fname like'%").append(whereObject.getString("condition")).append("%' ");
                where.append("or t1.frole like'%").append(whereObject.getString("condition")).append("%' ");
                where.append(")");
            }
        }
        /**
         *排序条件设置
         */
        String[] sortfield = {"t1.tenterprise_userid"};
        String sort = getSort(sortfield, "t1.tenterprise_userid");


        SQLFactory sql = new SQLFactory(this, "企业账号查询", pageSize, pageNumber, sort);
        sql.addParameter("siteid", siteid);
        sql.addParameter_SQL("where", where);
        Rows rows = dbConnect.runSqlQuery(sql.getSQL());
        return getSucReturnObject().setDataByPaging(rows, sortfield).setFinalDo(0, 1);
        //return getSucObject().setPagingData(rows,sortfield).setFinalDo(DataPool.defaultdatalife,1);
    }

    /**
     * 企业档案企业账号信息查询
     *
     * @return
     */
    public String query_enterpriseUser() {
        String tenterprise_userid = content.getString("tenterprise_userid");

        SQLFactory sql = new SQLFactory(this, "企业账号主界面查询");
        sql.addParameter("siteid", siteid);
        sql.addParameter("tenterprise_userid", tenterprise_userid);

        Rows rows = dbConnect.runSqlQuery(sql.getSQL());

        SQLFactory subusersql = new SQLFactory(this, "企业账号下级账号查询");
        subusersql.addParameter("siteid", siteid);
        subusersql.addParameter_in("fparentid", rows.toArrayList("tenterprise_userid"));

        RowsMap map = dbConnect.runSqlQuery(subusersql.getSQL()).toRowsMap("fparentid");
        for (Row row : rows) {
            row.put("subusers", map.get(row.getString("tenterprise_userid")));
        }
        return getSucReturnObject().setData(rows).toString();
    }

    /**
     * 企业档案企业管理员账号信息查询
     *
     * @return
     */
    public String query_enterpriseAdministratorUsers() {
        /**
         *排序条件设置
         */
        String[] sortfield = {"tenterprise_userid"};
        String sort = getSort(sortfield, "tenterprise_userid");


        SQLFactory sql = new SQLFactory(this, "企业管理员账号查询", pageSize, pageNumber, sort);
        sql.addParameter("siteid", siteid);
        Rows rows = dbConnect.runSqlQuery(sql.getSQL());
        return getSucReturnObject().setDataByPaging(rows, sortfield).setFinalDo(DataPool.defaultdatalife, 1);
    }

    /**
     * 企业账号信息查询
     *
     * @return
     */
    public String query_allusers() {
        /**
         * 过滤条件设置
         */
        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.fname like'%").append(whereObject.getString("condition")).append("%' ");
                where.append(" or t1.fphonenumber like'%").append(whereObject.getString("condition")).append("%' ");
                where.append(" or t3.fname like'%").append(whereObject.getString("condition")).append("%' ");
                where.append(" or t1.fusertype like'%").append(whereObject.getString("condition")).append("%' ");
                where.append(" or t2.fagentname like'%").append(whereObject.getString("condition")).append("%' ");
                where.append(" or t4.fname like'%").append(whereObject.getString("condition")).append("%' ");
                where.append(" or t5.fname like'%").append(whereObject.getString("condition")).append("%' ");
                where.append(" or t6.fname like'%").append(whereObject.getString("condition")).append("%' ");
                where.append(")");
            }
            if (whereObject.containsKey("fusertype") && !"".equals(whereObject.getString("fusertype"))) {
                where.append(" and(");
                where.append("t1.fusertype ='").append(whereObject.getString("fusertype")).append("' ");
                where.append(")");
            }
            if (whereObject.containsKey("fisadministrator") && !"".equals(whereObject.getString("fisadministrator"))) {
                where.append(" and(");
                where.append("t1.fisadministrator ='").append(whereObject.getString("fisadministrator")).append("' ");
                where.append(")");
            }
            if (whereObject.containsKey("fsaler") && !"".equals(whereObject.getString("fsaler"))) {
                where.append(" and(");
                where.append("t3.fname ='").append(whereObject.getString("fsaler")).append("' ");
                where.append(")");
            }
            if (whereObject.containsKey("fsaleruserid") && !"".equals(whereObject.getString("fsaleruserid"))) {
                where.append(" and(");
                where.append("t2.fsaleruserid ='").append(whereObject.getString("fsaleruserid")).append("' ");
                where.append(")");
            }
            if (whereObject.containsKey("fagenttype") && !"".equals(whereObject.getString("fagenttype"))) {
                where.append(" and(");
                where.append("t2.ftype ='").append(whereObject.getString("fagenttype")).append("' ");
                where.append(")");
            }
        }
        /**
         *排序条件设置
         */
        String[] sortfield = {"t1.tenterprise_userid"};
        String sort = getSort(sortfield, "t1.tenterprise_userid");
        SQLFactory sql = new SQLFactory(this, "所有账号查询", pageSize, pageNumber, sort);
        sql.addParameter("siteid", siteid);
        sql.addParameter_SQL("where", where);
        Rows rows = dbConnect.runSqlQuery(sql.getSQL());
        return getSucReturnObject().setDataByPaging(rows, sortfield).setFinalDo(DataPool.defaultdatalife, 1);
    }


    /**
     * 经销商账号信息查询
     *
     * @return
     */
    public String query_agentusers() {
        /**
         * 过滤条件设置
         */
        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.fname like'%").append(whereObject.getString("condition")).append("%' ");
                where.append(" or t1.fphonenumber like'%").append(whereObject.getString("condition")).append("%' ");
                where.append(" or t4.fagentname like'%").append(whereObject.getString("condition")).append("%' ");
                where.append(" or t4.fagentnum like'%").append(whereObject.getString("condition")).append("%' ");
                where.append(")");
            }
            if (whereObject.containsKey("fisadministrator") && !"".equals(whereObject.getString("fisadministrator"))) {
                where.append(" and(");
                where.append("t1.fisadministrator ='").append(whereObject.getString("fisadministrator")).append("' ");
                where.append(")");
            }
        }
        /**
         *排序条件设置
         */
        String[] sortfield = {"t1.tenterprise_userid"};
        String sort = getSort(sortfield, "t1.tenterprise_userid");
        SQLFactory sql = new SQLFactory(this, "经销商账号查询", pageSize, pageNumber, sort);
        sql.addParameter("siteid", siteid);
        sql.addParameter_SQL("where", where);
        Rows rows = dbConnect.runSqlQuery(sql.getSQL());
        return getSucReturnObject().setDataByPaging(rows, sortfield).setFinalDo(DataPool.defaultdatalife, 1);
    }

    /**
     * 密码重置
     *
     * @return
     */
    public String setDefaultPassword() {
        String tenterprise_userid = content.getString("tenterprise_userid");
        String status = dbConnect.runSqlUpdate(
                "update tenterprise_users set fpassword=t1.fdefaultpassword from tenterprise t1 where t1.siteid=tenterprise_users.siteid and tenterprise_users.siteid='" + siteid + "' and tenterprise_users.tenterprise_userid='" + tenterprise_userid + "'");
        if ("true".equals(status)) {
            return getSucReturnObject().toString();
        } else {
            return getErrReturnObject().setErrMsg("重置失败！").toString();
        }
    }

    /**
     * 企业档案企业账号信息修改
     *
     * @return
     */
    public String update_enterpriseUsers() throws P2Exception {
        String tenterprise_userid = content.getString("tenterprise_userid");
        String fname = content.getString("fname");
        String fphonenumber = content.getString("fphonenumber");
        String frole = content.getString("frole");
        String fsex = content.getString("fsex");
        String fbirthdate = nullToStr(content.getString("fbirthdate"));

        String femail = content.getString("femail");
        String fwechatno = content.getString("fwechatno");
        String fdatamodify = content.getString("fdatamodify");
        String fcanreadagentanalysis = content.getString("fcanreadagentanalysis");

        JSONArray subusersArray = content.getJSONArray("subusers");


        SQLFactory upuserfactory = new SQLFactory(this, "上级业务员账号列表获取");
        upuserfactory.addParameter("siteid", siteid);
        upuserfactory.addParameter("userid", tenterprise_userid);
        Rows upuserrows = dbConnect.runSqlQuery(upuserfactory.getSQL());

        {
            SQLFactory subuserfactory = new SQLFactory(this, "下属业务员账号列表获取");
            subuserfactory.addParameter("siteid", siteid);
            subuserfactory.addParameter("userid", tenterprise_userid);
            Rows subuserrows = dbConnect.runSqlQuery(subuserfactory.getSQL());
            RowsMap subuserrowsmap = subuserrows.toRowsMap("tenterprise_userid");

            for (Row upuserrow : upuserrows) {
                String upuserid = upuserrow.getString("tenterprise_userid");
                if (subuserrowsmap.containsKey(upuserid)) {
                    return getErrReturnObject().setErrMsg("账号上下级关系嵌套，请检查！").toString();
                }
            }
        }
        {
            for (Object o : subusersArray) {
                JSONObject subuser = (JSONObject) o;
                String fsubid = subuser.getString("fsubid");

                for (Row upuserrow : upuserrows) {
                    String upuserid = upuserrow.getString("tenterprise_userid");

                    if (tenterprise_userid.equals(fsubid)) {
                        return getErrReturnObject().setErrMsg("无法将当前账号作为下级！").toString();
                    }
                    if (upuserid.equals(fsubid)) {
                        return getErrReturnObject().setErrMsg(getUser(fsubid).getString("fname") + "已作为当前账号的上级账号！").toString();
                    }
                    if (!upuserid.equals(tenterprise_userid)) {
                        SQLFactory subuserfactory = new SQLFactory(this, "下属业务员账号列表获取");
                        subuserfactory.addParameter("siteid", siteid);
                        subuserfactory.addParameter("userid", fsubid);
                        Rows subuserrows = dbConnect.runSqlQuery(subuserfactory.getSQL());
                        RowsMap subuserrowsmap = subuserrows.toRowsMap("tenterprise_userid");
                        if (subuserrowsmap.containsKey(upuserid)) {
                            return getErrReturnObject().setErrMsg("下级" + subuserrowsmap.get(upuserid).get(0).getString("fname") + "已作为当前账号的上级账号！").toString();
                        }
                    }
                }
            }
        }

        PaoSetRemote tenterprise_usersSet = getP2ServerSystemPaoSet("tenterprise_users", "siteid='" + siteid + "' and fusertype='企业' and tenterprise_userid=" + tenterprise_userid);
        PaoRemote tenterprise_users = tenterprise_usersSet.getPao(0);
        tenterprise_users.setValue("fname", fname, 11L);
        tenterprise_users.setValue("fphonenumber", fphonenumber, 11L);
        tenterprise_users.setValue("frole", frole, 11L);
        tenterprise_users.setValue("fsex", fsex, 11L);
        tenterprise_users.setValue("fbirthdate", fbirthdate, 11L);
        tenterprise_users.setValue("femail", femail, 11L);
        tenterprise_users.setValue("fwechatno", fwechatno, 11L);
        tenterprise_users.setValue("fdatamodify", fdatamodify.equals("1"), 11L);
        tenterprise_users.setValue("fcanreadagentanalysis", fcanreadagentanalysis.equals("1"), 11L);
        tenterprise_users.setValue("changeby", username, 11L);//修改人
        tenterprise_users.setValue("changedate", getDateTime(), 11L);//修改时间

        /**
         * 查询下级账号，如不存在，则新增下级账号
         */
        PaoSetRemote tenterprise_userdetailSet = tenterprise_users.getPaoSet("$tenterprise_userdetail", "tenterprise_userdetail", "siteid=:siteid and fparentid=:tenterprise_userid");
        HashMap<String, PaoRemote> paoMap = getPaoMap(tenterprise_userdetailSet, "fsubid");

        /**
         * 用以判断是否需要将表体行删除
         */
        ArrayList<String> donotdeleteid = new ArrayList<>();

        Iterator<Object> subuserlistit = subusersArray.iterator();
        ArrayList<String> distinctid = new ArrayList<>();
        while (subuserlistit.hasNext()) {
            JSONObject subuser = (JSONObject) subuserlistit.next();
            String fsubid = subuser.getString("fsubid");
            if (distinctid.contains(fsubid)) {
                continue;
            } else {
                distinctid.add(fsubid);
            }
            PaoRemote subuserpao = null;
            if (!paoMap.containsKey(fsubid)) {
                subuserpao = tenterprise_userdetailSet.addAtEnd();
                subuserpao.setValue("siteid", siteid, 11L);//企业ID
                subuserpao.setValue("fparentid", tenterprise_userid, 11L);//账号ID
                subuserpao.setValue("fsubid", fsubid, 11L);//下级账号ID
                subuserpao.setValue("createby", username, 11L);//录入人
                subuserpao.setValue("createdate", getDateTime(), 11L);//录入时间
            } else {
                donotdeleteid.add(fsubid);
                subuserpao = paoMap.get(fsubid);
            }
            subuserpao.setValue("changeby", username, 11L);//修改人
            subuserpao.setValue("changedate", getDateTime(), 11L);//修改时间
        }
        /**
         * 删除多余的行
         */
        for (String fsubid : paoMap.keySet()) {
            if (!donotdeleteid.contains(fsubid)) {
                if (!paoMap.get(fsubid).isModified()) {
                    paoMap.get(fsubid).delete();
                }
            }
        }

        /**
         * 保存修改日志
         */
        saveDataLog(tenterprise_users);
        tenterprise_usersSet.save();

        return query_enterpriseUser();
    }


    public String LoginUsers() {
        JSONArray jsonArray = new JSONArray();
        Set<Long> useridSet = parameter.userIdList.keySet();
        for (long userid : useridSet) {
            Row row = parameter.userIdList.get(userid);
            String token = row.getString("token");
            JSONObject object = row.toJsonObject();
            object.put("lastrequesttime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(parameter.requesttime.get(token)));
            jsonArray.add(object);
        }
        return getSucReturnObject().setData(jsonArray).toString();
    }
}
