package com.cnd3b.restcontroller.enterprise.agentclient.mainpage.action.orderinput;

import com.alibaba.fastjson.JSONArray;
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.SQLFactory;
import com.cnd3b.common.data.db.DataPool;
import p2.pao.PaoRemote;
import p2.pao.PaoSetRemote;
import p2.util.P2Exception;
import p2.application.tcustomer_reception.tcustomer_reception;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

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

    /**
     * 经销商销售记录列表查询
     *
     * @return
     */
    public String query_orderList() {
        /**
         *排序条件设置
         */
        String[] sortfield = {"t1.changedate"};
        String sort = getSort(sortfield, "t1.changedate 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.fname like'%").append(whereObject.getString("condition")).append("%' ");
                where.append("or t1.fcommunity like'%").append(whereObject.getString("condition")).append("%' ");
                where.append("or t1.fphonenumber like'%").append(whereObject.getString("condition")).append("%' ");
                where.append(")");
            }
            if (whereObject.containsKey("begdate") && !"".equals(whereObject.getString("begdate"))) {
                where.append(" and convert(varchar(10),t1.changedate,120)>=").append("'").append(whereObject.getString("begdate")).append("'");
            }
            if (whereObject.containsKey("enddate") && !"".equals(whereObject.getString("enddate"))) {
                where.append(" and convert(varchar(10),t1.changedate,120)<=").append("'").append(whereObject.getString("enddate")).append("'");
            }
            if (!fisadministrator) {
                where.append(" and (t1.tenterprise_userid is null or t1.tenterprise_userid='").append(userid).append("' or t1.tenterprise_userid in ( select fsubid from tenterprise_userdetail where siteid='").append(siteid).append("' and fparentid='").append(userid).append("' )) ");
            }
        }
        SQLFactory sqlFactory = new SQLFactory(this, "经销商销售记录列表查询", pageSize, pageNumber, sort);
        sqlFactory.addParameter("siteid", siteid);
        sqlFactory.addParameter("tagentsid", tagentsid);
        sqlFactory.addParameter_SQL("where", where);
        Rows rows = dbConnect.runSqlQuery(sqlFactory.getSQL());
        return getSucReturnObject().setDataByPaging(rows, sortfield).addAppHelpNotes(getAppHelpNotes("销售系统")).setFinalDo(DataPool.defaultdatalife, 1);
    }


    /**
     * 经销商销售记录主界面查询
     *
     * @return
     */
    public String query_orderMain() {
        SQLFactory sqlFactory = new SQLFactory(this, "经销商销售记录主界面查询");
        sqlFactory.addParameter("siteid", siteid);
        sqlFactory.addParameter("tagentsid", tagentsid);
        sqlFactory.addParameter("tcustomer_receptid", content.getString("tcustomer_receptid"));
        Rows rows = dbConnect.runSqlQuery(sqlFactory.getSQL());
        for (Row row : rows) {
            SQLFactory orderFactory = new SQLFactory(this, "订单明细查询");
            orderFactory.addParameter("siteid", siteid);
            orderFactory.addParameter("tagentsid", tagentsid);
            orderFactory.addParameter("tcustomerid", row.getString("tcustomerid"));
            orderFactory.addParameter("tcustomer_receptid", row.getString("tcustomer_receptid"));
            Rows orderRows = dbConnect.runSqlQuery(orderFactory.getSQL());
            row.put("orderlist", orderRows.toJsonArray());
            row.put("datalog", getDataLog("tcustomer_reception", row.getString("tcustomer_receptid")));
        }
        return getSucReturnObject().setData(rows).toString();
    }

    public String orderInsertOrModify() throws D3bException, P2Exception {
        long tcustomer_receptid = content.getLongValue("tcustomer_receptid");//接待记录ID，新增时默认传0
        String fname = content.getString("fname", "tcustomer.fname", "客户姓名");//顾客姓名
        String fphonenumber = content.getString("fphonenumber", "tcustomer.fphonenumber", "手机号码");//手机号
        String fchannel = content.getString("fchannel");//来源渠道
        String fcommunity = content.getString("fcommunity", "tcustomer.fcommunity", "小区名称");//小区名称
        String fnumber = content.getString("fnumber", "tcustomer.fnumber", "幢/单元/室");//幢/单元/室
        String frenovationplandate = content.getString("frenovationplandate");//计划装修时间
        Date fbirthdate = content.getDate("fbirthdate");//出生日期
        String fwechatno = content.getString("fwechatno", "tcustomer.fwechatno", "微信号");//微信号
        String fnotes = content.getString("fnotes", "tcustomer_reception.fnotes", "备注");//订单备注
        String tstoreid = content.getString("tstoreid");//门店ID
        Date fdate = content.getDate("fdate");//下单日期
        Date finstalldate = content.getDate("finstalldate");//安装时间
        String tsaleeventid = content.getString("tsaleeventid");//营销事件id

        double forderamount = content.getDoubleValue("forderamount");//订单金额
        double fdepositamount = content.getDoubleValue("fdepositamount");//定金
        double freceivedamount = content.getDoubleValue("freceivedamount");//已收尾款
        double freceivablesamount = content.getDoubleValue("freceivablesamount");//应收款

        PaoSetRemote tcustomerSet = getP2ServerSystemPaoSet("tcustomer", "siteid='" + siteid + "' and tagentsid='" + tagentsid + "' and fphonenumber='" + fphonenumber + "'");
        PaoRemote tcustomer = null;
        if (tcustomerSet.isEmpty()) {
            tcustomer = tcustomerSet.addAtEnd();
            tcustomer.setValue("siteid", siteid, 11L);//企业ID
            tcustomer.setValue("tagentsid", tagentsid, 11L);//经销商ID
            tcustomer.setValue("createby", username, 11L);//录入人
            tcustomer.setValue("createdate", sysdate, 11L);//录入时间
        } else {
            tcustomer = tcustomerSet.getPao(0);
        }
        tcustomer.setValue("fname", fname, 11L);
        tcustomer.setValue("fphonenumber", fphonenumber, 11L);//客户手机
        tcustomer.setValue("fchannel", fchannel, 11L);//来源渠道
        tcustomer.setValue("fcommunity", fcommunity, 11L);//小区名称
        tcustomer.setValue("fnumber", fnumber, 11L);//幢/单元/室
        tcustomer.setValue("frenovationplandate", frenovationplandate, 11L);//计划装修时间
        tcustomer.setValue("fbirthdate", fbirthdate, 11L);//出生日期
        tcustomer.setValue("fwechatno", fwechatno, 11L);//微信号
        tcustomer.setValue("tstoreid", tstoreid, 11L);//门店ID
        tcustomer.setValue("changeby", username, 11L);//修改人
        tcustomer.setValue("changedate", sysdate, 11L);//修改时间

        long tcustomerid = tcustomer.getUniqueIDValue();
        /**
         * 查询销售记录，如不存在，则新增此销售记录
         */
        PaoSetRemote tcustomer_receptionSet = tcustomer.getPaoSet("$tcustomer_reception", "tcustomer_reception", "siteid=:siteid and tagentsid=:tagentsid and tcustomer_receptid='" + tcustomer_receptid + "'");
        tcustomer_reception tcustomer_reception = null;
        if (tcustomer_receptid == 0 || tcustomer_receptionSet.isEmpty()) {
            tcustomer_reception = (tcustomer_reception) tcustomer_receptionSet.addAtEnd();
            tcustomer_reception.setValue("fwaiter", username, 11L);//接待员
            tcustomer_reception.setValue("tenterprise_userid", userid, 11L);//账号ID
            tcustomer_reception.setValue("siteid", siteid, 11L);//企业ID
            tcustomer_reception.setValue("tagentsid", tagentsid, 11L);//经销商ID
            tcustomer_reception.setValue("ftype", "销售", 11L);//记录类型
            tcustomer_reception.setValue("fcustaction", "成交", 11L);//顾客动作（坐下、设计）

            tcustomer_reception.setValue("fbillnum", tcustomer_reception.getAgentOrderBillNum(Long.parseLong(tagentsid)));
            tcustomer_reception.setValue("createby", username, 11L);//录入人
            tcustomer_reception.setValue("createdate", sysdate, 11L);//录入时间

            tcustomer.setValue("freceptiontimes", tcustomer.getInt("freceptiontimes") + 1, 11L);

            addActionScore(ActionScore.fsourcetype.销售录入, tcustomer_reception.getUniqueIDValue(), "销售录入");

        } else {
            tcustomer_reception = (tcustomer_reception) tcustomer_receptionSet.getPao(0);
        }
        tcustomer_reception.setValue("tcustomerid", tcustomerid, 11L);//客户档案ID
        tcustomer_reception.setValue("fname", fname, 11L);//顾客姓名
        tcustomer_reception.setValue("fphonenumber", fphonenumber, 11L);//客户手机
        tcustomer_reception.setValue("fchannel", fchannel, 11L);//来源渠道
        tcustomer_reception.setValue("fcommunity", fcommunity, 11L);//小区名称
        tcustomer_reception.setValue("fnumber", fnumber, 11L);//幢/单元/室
        tcustomer_reception.setValue("frenovationplandate", frenovationplandate, 11L);//计划装修时间
        tcustomer_reception.setValue("fbirthdate", fbirthdate, 11L);//出生日期
        tcustomer_reception.setValue("fwechatno", fwechatno, 11L);//微信号
        tcustomer_reception.setValue("fdate", fdate, 11L);//下单日期
        tcustomer_reception.setValue("finstalldate", finstalldate, 11L);//安装日期
        tcustomer_reception.setValue("fnotes", fnotes, 11L);//订单备注
        tcustomer_reception.setValue("tsaleeventid", tsaleeventid, 11L);//营销事件
        Rows tsaleeventrows = dbConnect.runSqlQuery("select fsaleevent from tsaleevent where tsaleeventid='" + tsaleeventid + "' and siteid='" + siteid + "' ");
        if (!tsaleeventrows.isEmpty()) {
            tcustomer_reception.setValue("fsaleevent", tsaleeventrows.get(0).getString("fsaleevent"), 11L);//营销事件
        }

        tcustomer_reception.setValue("forderamount", forderamount, 11L);//订单金额
        tcustomer_reception.setValue("fdepositamount", fdepositamount, 11L);//定金
        tcustomer_reception.setValue("freceivedamount", freceivedamount, 11L);//已收尾款
        tcustomer_reception.setValue("freceivablesamount", freceivablesamount, 11L);//应收款
        tcustomer_reception.setValue("fstatus", "正常", 11L);//订单状态

        tcustomer_reception.setValue("tstoreid", tstoreid, 11L);//门店ID

        tcustomer_reception.setValue("changeby", username, 11L);//修改人
        tcustomer_reception.setValue("changedate", sysdate, 11L);//修改时间

        if (tcustomer.getPaoSet("tcustomer_reception_firstorder").isEmpty()) {
            tcustomer.setValue("freceptiontimes_first", tcustomer.getInt("freceptiontimes"), 11L);
            tcustomer.setValue("ffirstorderid", tcustomer_reception.getUniqueIDValue(), 11L);
        }

        /**
         * 查询订单明细，如不存在，则新增订单明细
         */
        PaoSetRemote tcustomer_orderSet = tcustomer_reception.getPaoSet("$tcustomer_order", "tcustomer_order", "siteid=:siteid and tagentsid=:tagentsid and tcustomer_receptid=:tcustomer_receptid");
        HashMap<String, PaoRemote> paoMap = getPaoMap(tcustomer_orderSet, "tcustomer_orderid");

        /**
         * 用以判断是否需要将表体行删除
         */
        ArrayList<String> donotdeleteid = new ArrayList<>();
        JSONArray orderlist = content.getJSONArray("orderlist");
        for (Object orderobject : orderlist) {
            JSONObject order = (JSONObject) orderobject;
            String tcustomer_orderid = order.getString("tcustomer_orderid");
            String fprodname = order.getString("fprodname", "tcustomer_order.fprodname", "产品名");
            double fqty = order.getDoubleValue("fqty");
            double fprice = order.getDoubleValue("fprice");
            double famount = order.getDoubleValue("famount");

            PaoRemote orderpao = null;
            if ("0".equals(tcustomer_orderid) || !paoMap.containsKey(tcustomer_orderid)) {
                orderpao = tcustomer_orderSet.addAtEnd();
                orderpao.setValue("siteid", siteid, 11L);//企业ID
                orderpao.setValue("tagentsid", tagentsid, 11L);//经销商ID
                orderpao.setValue("tcustomer_receptid", tcustomer_reception.getUniqueIDValue(), 11L);//接待记录id

                orderpao.setValue("createby", username, 11L);//录入人
                orderpao.setValue("createdate", sysdate, 11L);//录入时间
            } else {
                donotdeleteid.add(tcustomer_orderid);
                orderpao = paoMap.get(tcustomer_orderid);
            }
            orderpao.setValue("tcustomerid", tcustomerid, 11L);//客户档案id
            orderpao.setValue("fprodname", fprodname, 11L);
            orderpao.setValue("fqty", fqty, 11L);
            orderpao.setValue("fprice", fprice, 11L);
            orderpao.setValue("famount", famount, 11L);

            orderpao.setValue("changeby", username, 11L);//修改人
            orderpao.setValue("changedate", sysdate, 11L);//修改时间
        }
        /**
         * 删除多余的行
         */
        for (String id : paoMap.keySet()) {
            if (!donotdeleteid.contains(id)) {
                if (!paoMap.get(id).isModified()) {
                    paoMap.get(id).delete();
                }
            }
        }
        content.put("tcustomer_receptid", tcustomer_reception.getString("tcustomer_receptid"));

        saveDataLog(tcustomer_reception);
        tcustomerSet.save();

        return query_orderMain();
    }

    /**
     * 经销商销售退单
     *
     * @return
     */
    public String orderClose() throws P2Exception {
        long tcustomer_receptid = content.getLongValue("tcustomer_receptid");//接待记录ID，新增时默认传0
        PaoSetRemote tcustomer_receptionSet = getP2ServerSystemPaoSet("tcustomer_reception", "siteid='" + siteid + "' and tagentsid='" + tagentsid + "' and tcustomer_receptid='" + tcustomer_receptid + "'");
        if (!tcustomer_receptionSet.isEmpty()) {
            PaoRemote tcustomer_reception = tcustomer_receptionSet.getPao(0);
            tcustomer_reception.setValue("fstatus", "退单", 11L);
            tcustomer_reception.setValue("closeby", username, 11L);
            tcustomer_reception.setValue("closedate", getDateTime(), 11L);
            tcustomer_reception.setValue("changeby", username, 11L);//修改人
            tcustomer_reception.setValue("changedate", getDateTime(), 11L);//修改时间
            saveDataLog(tcustomer_reception);
            tcustomer_receptionSet.save();
        }
        return query_orderMain();
    }


    /**
     * 经销商销售记录删除
     *
     * @return
     */
    public String orderDelete() {
        SQLFactory sqlFactory = new SQLFactory(this, "经销商销售记录删除");
        sqlFactory.addParameter("siteid", siteid);
        sqlFactory.addParameter("tagentsid", tagentsid);
        sqlFactory.addParameter("tcustomer_receptid", content.getString("tcustomer_receptid"));

        String result = dbConnect.runSqlUpdate(sqlFactory.getSQL());
        if ("true".equals(result)) {
            return getSucReturnObject().toString();
        } else {
            return getErrReturnObject().setErrMsg(result).toString();
        }
    }


    /**
     * 来源渠道选择
     *
     * @return
     */
    public String selectChannel() {
        SQLFactory sqlFactory = new SQLFactory(this, "来源渠道选择");
        sqlFactory.addParameter("siteid", siteid);
        Rows rows = dbConnect.runSqlQuery(sqlFactory.getSQL());
        String result = rows.toJsonArray("fchannel").toString();
        DataPool.put(content.toString(), result);
        return result;
    }


    /**
     * 接待门店选择
     *
     * @return
     */
    public String selectStore() {
        SQLFactory sqlFactory = new SQLFactory(this, "接待门店选择");
        sqlFactory.addParameter("siteid", siteid);
        sqlFactory.addParameter("tagentsid", tagentsid);
        Rows rows = dbConnect.runSqlQuery(sqlFactory.getSQL());
        return getSucReturnObject().setData(rows).saveToDataPool().toString();
    }


    /**
     * 营销事件选择
     *
     * @return
     */
    public String selectSaleevent() {
        SQLFactory sqlFactory = new SQLFactory(this, "营销事件选择");
        sqlFactory.addParameter("siteid", siteid);
        sqlFactory.addParameter("tagentsid", tagentsid);
        Rows rows = dbConnect.runSqlQuery(sqlFactory.getSQL());
        return getSucReturnObject().setData(rows).saveToDataPool().toString();
    }

    public String queryCustomerByPhoneNumber() {
        if (content.getString("fphonenumber").length() >= 7) {
            SQLFactory sqlFactory = new SQLFactory(this, "手机号查询客户档案");
            sqlFactory.addParameter("siteid", siteid);
            sqlFactory.addParameter("tagentsid", tagentsid);
            sqlFactory.addParameter("fphonenumber", content.getString("fphonenumber") + "%");
            Rows rows = dbConnect.runSqlQuery(sqlFactory.getSQL());
            return getSucReturnObject().setData(rows).saveToDataPool().toString();
        } else {
            return getSucReturnObject().setData(new Rows()).toString();
        }
    }
}
