package com.cnd3b.restcontroller.enterprise.salerclient.mainpage.submitedit;

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 java.util.ArrayList;

/**
 * 提报管理
 */
public class submitedit extends Controller {

    public submitedit(JSONObject content) {
        super(content);
    }

    /**
     * 业务员提报列表查询
     *
     * @return
     */
    public String query_submiteditmodelList() {
        /**
         *排序条件设置
         */
        String[] sortfield = {"t1.checkdate"};
        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(")");
            }
            if (whereObject.containsKey("fisnotlimittimes") && !"".equals(whereObject.getString("fisnotlimittimes"))) {
                where.append(" and(");
                where.append("t1.fisnotlimittimes ='").append(whereObject.getString("fisnotlimittimes")).append("' ");
                where.append(")");
            }
        }
        SQLFactory submitedithead = new SQLFactory(this, "提报列表查询", pageSize, pageNumber, sort);
        submitedithead.addParameter("siteid", siteid);
        submitedithead.addParameter("tenterprise_userid", userid);
        submitedithead.addParameter_SQL("where", where);
        Rows rows = dbConnect.runSqlQuery(submitedithead.getSQL());

        SQLFactory editstatuslist = new SQLFactory(this, "提报列表查询_提报状态查询");
        editstatuslist.addParameter("siteid", siteid);
        editstatuslist.addParameter("tenterprise_userid", userid);
        editstatuslist.addParameter_in("tsubmiteditmodelid", rows.toArray("tsubmiteditmodelid"));
        RowsMap editstatusrowsMap = dbConnect.runSqlQuery(editstatuslist).toRowsMap("tsubmiteditmodelid");

        SQLFactory editsubmitusercountlist = new SQLFactory(this, "提报列表查询_提报人数查询");
        editsubmitusercountlist.addParameter("siteid", siteid);
        editsubmitusercountlist.addParameter_in("tsubmiteditmodelid", rows.toArray("tsubmiteditmodelid"));
        RowsMap editsubmitusercountrowsMap = dbConnect.runSqlQuery(editsubmitusercountlist).toRowsMap("tsubmiteditmodelid");

        for (Row row : rows) {
            String tsubmiteditmodelid = row.getString("tsubmiteditmodelid");
            if (editstatusrowsMap.containsKey(tsubmiteditmodelid)) {
                row.put("fisread", editstatusrowsMap.get(tsubmiteditmodelid).get(0).getInteger("fisread") > 0 ? 1 : 0);
                row.put("fissubmit", editstatusrowsMap.get(tsubmiteditmodelid).get(0).getInteger("fissubmit") > 0 ? 1 : 0);
            } else {
                row.put("fisread", 0);
                row.put("fissubmit", 0);
            }

            if (editsubmitusercountrowsMap.containsKey(tsubmiteditmodelid)) {
                row.put("fsubmitqty", editsubmitusercountrowsMap.get(tsubmiteditmodelid).get(0).getInteger("fsubmitqty"));
            } else {
                row.put("fsubmitqty", 0);
            }
        }
        return getSucReturnObject().setDataByPaging(rows, sortfield).setFinalDo(DataPool.defaultdatalife, 1);
    }

    /**
     * 业务员提报主界面
     *
     * @return
     */
    public String query_submiteditmodelMain() {
        String tsubmiteditmodelid = content.getString("tsubmiteditmodelid");//提报模板ID
        SQLFactory submithead = new SQLFactory(this, "提报主界面查询");
        submithead.addParameter("siteid", siteid);
        submithead.addParameter("tsubmiteditmodelid", tsubmiteditmodelid);
        Rows headrows = dbConnect.runSqlQuery(submithead.getSQL());
        for (Row row : headrows) {
            SQLFactory submitlist = new SQLFactory(this, "提报主界面查询_提报明细");
            submitlist.addParameter("siteid", siteid);
            submitlist.addParameter("tenterprise_userid", userid);
            submitlist.addParameter("tsubmiteditmodelid", tsubmiteditmodelid);
            Rows listrows = dbConnect.runSqlQuery(submitlist.getSQL());

            String fstatus = listrows.getLastRow().getString("fstatus");
            row.put("fissubmit", "提交".equals(fstatus) ? 1 : 0);
            row.put("submiteditlist", listrows);
        }
        dbConnect.runSqlUpdate("update tsubmitedit set fisread=1 where siteid='" + siteid + "' and tsubmiteditmodelid='" + tsubmiteditmodelid + "' and tenterprise_userid='" + userid + "'");
        return getSucReturnObject().setData(headrows).toString();
    }

    /**
     * 业务员新建提报，针对一事多报的功能
     *
     * @return
     */
    public String newedit() throws D3bException {
        long tsubmiteditmodelid = content.getLongValue("tsubmiteditmodelid");//提报模板ID

        Rows check = dbConnect.runSqlQuery("select tsubmiteditid from tsubmitedit where siteid='" + siteid + "' and fstatus='新建' and tsubmiteditmodelid='" + tsubmiteditmodelid + "' and tenterprise_userid='" + userid + "'");
        if (!check.isEmpty()) {
            return getErrReturnObject().setErrMsg("已存在一个未提交的提报，不可进行新增操作").toString();
        }

        String fcontent = content.getString("fcontent", "tsubmitedit.fcontent", "提报内容");
        SQLFactory sqlFactory = new SQLFactory(this, "新增");
        sqlFactory.addParameter("siteid", siteid);
        sqlFactory.addParameter("createby", username);
        sqlFactory.addParameter("tsubmiteditmodelid", tsubmiteditmodelid);
        sqlFactory.addParameter("tenterprise_userid", userid);
        sqlFactory.addParameter("tagentsid", tagentsid);
        sqlFactory.addParameter("fcontent", fcontent);
        String status = dbConnect.runSqlUpdate(sqlFactory.getSQL());
        if ("true".equalsIgnoreCase(status)) {
            return query_submiteditmodelMain();
        } else {
            return getErrReturnObject().setErrMsg(status).toString();
        }
    }

    /**
     * 业务员提报保存
     *
     * @return
     */
    public String saveedit() throws D3bException {
        long tsubmiteditmodelid = content.getLong("tsubmiteditmodelid");//提报模板ID
        long tsubmiteditid = content.getLong("tsubmiteditid");//提报ID

        Rows check = dbConnect.runSqlQuery("select tsubmiteditid from tsubmitedit where siteid='" + siteid + "' and fstatus='提交' and tsubmiteditmodelid='" + tsubmiteditmodelid + "' and tsubmiteditid='" + tsubmiteditid + "' and tenterprise_userid='" + userid + "'");
        if (!check.isEmpty()) {
            return getErrReturnObject().setErrMsg("当前提报已提交，不可进行修改操作").toString();
        }

        String fcontent = content.getString("fcontent", "tsubmitedit.fcontent", "提报内容");
        SQLFactory sqlFactory = new SQLFactory(this, "保存");
        sqlFactory.addParameter("fcontent", fcontent);
        sqlFactory.addParameter("changeby", username);
        sqlFactory.addParameter("siteid", siteid);
        sqlFactory.addParameter("tsubmiteditmodelid", tsubmiteditmodelid);
        sqlFactory.addParameter("tsubmiteditid", tsubmiteditid);
        sqlFactory.addParameter("tenterprise_userid", userid);
        String status = dbConnect.runSqlUpdate(sqlFactory.getSQL());
        if ("true".equalsIgnoreCase(status)) {
            return query_submiteditmodelMain();
        } else {
            return getErrReturnObject().setErrMsg(status).toString();
        }
    }

    /**
     * 业务员提交
     *
     * @return
     */
    public String submitedit() throws D3bException {
        String tsubmiteditmodelid = content.getString("tsubmiteditmodelid");//提报模板ID
        String tsubmiteditid = content.getString("tsubmiteditid");//提报ID

        Rows check = dbConnect.runSqlQuery("select tsubmiteditid from tsubmitedit where siteid='" + siteid + "' and fstatus='提交' and tsubmiteditmodelid='" + tsubmiteditmodelid + "' and tsubmiteditid='" + tsubmiteditid + "' and tenterprise_userid='" + userid + "'");
        if (!check.isEmpty()) {
            return getErrReturnObject().setErrMsg("当前提报已提交，不可进行提交操作").toString();
        }

        String fcontent = content.getString("fcontent", "tsubmitedit.fcontent", "提报内容");

        SQLFactory sqlFactory = new SQLFactory(this, "提报");
        sqlFactory.addParameter("submitby", username);
        sqlFactory.addParameter("fcontent", fcontent);
        sqlFactory.addParameter("siteid", siteid);
        sqlFactory.addParameter("tsubmiteditmodelid", tsubmiteditmodelid);
        sqlFactory.addParameter("tsubmiteditid", tsubmiteditid);
        sqlFactory.addParameter("tenterprise_userid", userid);
        String status = dbConnect.runSqlUpdate(sqlFactory.getSQL());
        if ("true".equalsIgnoreCase(status)) {
            return query_submiteditmodelMain();
        } else {
            return getErrReturnObject().setErrMsg(status).toString();
        }
    }

    /**
     * 下级提报管理列表查询
     */
    public String query_subsubmiteditmodelList() {
        /**
         *排序条件设置
         */
        String[] sortfield = {"t1.checkdate"};
        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(")");
            }
            if (whereObject.containsKey("fisnotlimittimes") && !"".equals(whereObject.getString("fisnotlimittimes"))) {
                where.append(" and(");
                where.append("t1.fisnotlimittimes ='").append(whereObject.getString("fisnotlimittimes")).append("' ");
                where.append(")");
            }
        }

        SQLFactory costhead = new SQLFactory(this, "提报管理列表查询", pageSize, pageNumber, sort);
        costhead.addParameter("siteid", siteid);
        costhead.addParameter_in("tenterprise_userid", getSubUsers());
        costhead.addParameter_SQL("where", where);
        Rows rows = dbConnect.runSqlQuery(costhead.getSQL());
        return getSucReturnObject().setDataByPaging(rows, sortfield).setFinalDo(DataPool.defaultdatalife, 1);
    }

    /**
     * 下级提报管理主界面查询
     */
    public String query_subsubmiteditmodelMain() {
        String tsubmiteditmodelid = content.getString("tsubmiteditmodelid");

        SQLFactory costhead = new SQLFactory(this, "提报管理主界面查询");
        costhead.addParameter("siteid", siteid);
        costhead.addParameter("tsubmiteditmodelid", tsubmiteditmodelid);
        costhead.addParameter_in("fsaleruserid", getSubUsers());
        Rows rows = dbConnect.runSqlQuery(costhead.getSQL());
        ArrayList<String> fsaleruseridlist = rows.toArrayList("fsaleruserid");

        SQLFactory unsubmitagentmx = new SQLFactory(this, "提报管理主界面未提报经销商明细查询");
        unsubmitagentmx.addParameter("siteid", siteid);
        unsubmitagentmx.addParameter("tsubmiteditmodelid", tsubmiteditmodelid);
        unsubmitagentmx.addParameter_in("fsaleruserid", fsaleruseridlist);
        RowsMap unsubmitagentmap = dbConnect.runSqlQuery(unsubmitagentmx.getSQL()).toRowsMap("fsaleruserid");

        SQLFactory submitagentmx = new SQLFactory(this, "提报管理主界面已提报经销商明细查询");
        submitagentmx.addParameter("siteid", siteid);
        submitagentmx.addParameter("tsubmiteditmodelid", tsubmiteditmodelid);
        submitagentmx.addParameter_in("fsaleruserid", fsaleruseridlist);
        Rows submitagentRows_All = dbConnect.runSqlQuery(submitagentmx.getSQL());
        RowsMap submitagentRowsmap = submitagentRows_All.toRowsMap("fsaleruserid");

        SQLFactory submitagentsubmiteditmx = new SQLFactory(this, "提报管理主界面已提报经销商提报明细查询");
        submitagentsubmiteditmx.addParameter("siteid", siteid);
        submitagentsubmiteditmx.addParameter("tsubmiteditmodelid", tsubmiteditmodelid);
        submitagentsubmiteditmx.addParameter_in("tenterprise_userid", submitagentRows_All.toArray("tenterprise_userid"));
        Rows submitagentsubmiteditRows_All = dbConnect.runSqlQuery(submitagentsubmiteditmx.getSQL());
        RowsMap submitagentsubmiteditRowsmap = submitagentsubmiteditRows_All.toRowsMap("tenterprise_userid");

        /**
         * 附件查询
         */
        RowsMap attachmentRowsMap = getAttachmentUrl("tsubmitedit", submitagentRows_All.toArray("tsubmiteditid"));

        for (Row row : rows) {
            //未提报经销商列表
            row.put("unsubmitagentlist", unsubmitagentmap.get(row.getString("fsaleruserid")));

            //已提报经销商列表处理
            Rows submitagentRows = submitagentRowsmap.get(row.getString("fsaleruserid"));
            //遍历已提报经销商列表
            for (Row submitagentRow : submitagentRows) {
                //经销商提报明细
                Rows submitagentsubmiteditRows = submitagentsubmiteditRowsmap.get(submitagentRow.getString("tenterprise_userid"));
                //遍历经销商提报明细
                for (Row submitagentsubmiteditRow : submitagentsubmiteditRows) {
                    //根据提报ID获取提报附件
                    submitagentsubmiteditRow.put("docinfos", attachmentRowsMap.get(submitagentsubmiteditRow.getString("tsubmiteditid")));
                }
                //将经销商提报明细放至经销商下
                submitagentRow.put("submiteditlist", submitagentsubmiteditRows);
            }
            row.put("submitagentlist", submitagentRows);
        }
        return getSucReturnObject().setData(rows).saveToDataPool().toString();
    }
}
