package com.cnd3b.restcontroller.singleagent.webclient.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.fdate desc"};
        String sort = getSort(sortfield, "t1.fdate 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.fdate,120)>=").append("'").append(whereObject.getString("begdate")).append("'");
            }
            if (whereObject.containsKey("enddate") && !"".equals(whereObject.getString("enddate"))) {
                where.append(" and convert(varchar(10),t1.fdate,120)<=").append("'").append(whereObject.getString("enddate")).append("'");
            }
            /**
             * 生日
             */
            if (whereObject.containsKey("begbirthdate") && !"".equals(whereObject.getString("begbirthdate")) && whereObject.containsKey("endbirthdate") && !"".equals(whereObject.getString("endbirthdate"))) {
                String begbirthdate = whereObject.getString("begbirthdate");
                String endbirthdate = whereObject.getString("endbirthdate");
                where.append(" and (dateadd(year,datediff(year,t1.fbirthdate,'").append(begbirthdate).append("'),t1.fbirthdate) between '").append(begbirthdate).append("' and '").append(endbirthdate).append("'or dateadd(year,datediff(year,t1.fbirthdate,'").append(endbirthdate).append("'),fbirthdate) between '").append(begbirthdate).append("' and '").append(endbirthdate).append("') ");
            }
            //单据状态
            if (whereObject.containsKey("forderstatus") && !"".equals(whereObject.getString("forderstatus"))) {
                if ("已结清".equals(whereObject.getString("forderstatus"))) {
                    where.append(" and t1.fispayout =1 and t1.fstatus ='正常'");
                } else if ("未结清".equals(whereObject.getString("forderstatus"))) {
                    where.append(" and t1.fispayout =0 and t1.fstatus ='正常'");
                } else if ("已出库".equals(whereObject.getString("forderstatus"))) {
                    where.append(" and t1.fisstockout =1 ");
                } else if ("未出库".equals(whereObject.getString("forderstatus"))) {
                    where.append(" and t1.fisstockout =0 ");
                } else if ("已退单".equals(whereObject.getString("forderstatus"))) {
                    where.append(" and t1.fstatus ='退单' ");
                } else if ("正常".equals(whereObject.getString("forderstatus"))) {
                    where.append(" and t1.fstatus ='正常' ");
                }
            }
            //根据数据权限进行过滤
            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("previewurl", "https://www.baidu.com");//预览url
            row.put("datalog", getDataLog("tcustomer_reception", row.getString("tcustomer_receptid")));
        }
        return getSucReturnObject().setData(rows).toString();
    }

    /**
     * 经销商销售记录新增、修改
     *
     * @return
     */
    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 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", "备注");//订单备注
        Date fdate = content.getDate("fdate");//下单日期
        Date finstalldate = content.getDate("finstalldate");//安装时间
        double forderamount = content.getDoubleValue("forderamount");//成交金额
        double freceiveamount = content.getDoubleValue("freceiveamount");//本次收款

        JSONArray orderlist = content.getJSONArray("orderlist");
        for (Object orderobject : orderlist) {
            JSONObject order = (JSONObject) orderobject;
            order.checkStringLength("fprodname", "tcustomer_order.fprodname", "产品名");
        }

        PaoSetRemote tcustomerSet = getP2ServerSystemPaoSet("tcustomer", "siteid='" + siteid + "' and tagentsid='" + tagentsid + "' and fphonenumber='" + fphonenumber + "'", "tcustomerid desc");
        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);//录入时间
            tcustomer.setValue("fwaiter", username, 11L);//首次接待
        } else {
            tcustomer = tcustomerSet.getPao(0);
        }
        tcustomer.setValue("fname", fname, 11L);
        tcustomer.setValue("fphonenumber", fphonenumber, 11L);//客户手机
        tcustomer.setValue("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("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", "零售", 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("forderamount", forderamount, 11L);//成交金额
        tcustomer_reception.setValue("fstatus", "正常", 11L);//订单状态

        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<>();

        for (Object o : orderlist) {
            JSONObject order = (JSONObject) o;
            String tcustomer_orderid = order.getString("tcustomer_orderid");
            String fprodname = order.getString("fprodname");
            String tagents_productid = order.getString("tagents_productid");
            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("tagents_productid", tagents_productid, 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();
                }
            }
        }
        String id = tcustomer_reception.getString("tcustomer_receptid");
        content.put("tcustomer_receptid", id);

        saveDataLog(tcustomer_reception);
        tcustomerSet.save();
        //生成收款记录
        if (freceiveamount > 0) {
            content.put("tcustomerid", tcustomerid);
            content.put("tcustomer_receptid", id);
            content.put("famount", freceiveamount);
            content.put("ftype", "货款");
            content.put("fnotes", "首笔货款");
            createOrderBill();
        }

        return query_orderMain();
    }

    /**
     * 创建订单收款记录
     *
     * @return
     */
    public String createOrderBill() throws P2Exception {
        long tcustomerid = content.getLongValue("tcustomerid");//客户档案ID
        long tcustomer_receptid = content.getLongValue("tcustomer_receptid");//接待记录ID
        double famount = content.getDoubleValue("famount");//收款金额
        String ftype = content.getString("ftype");//收款类型
        String fnotes = content.getString("fnotes");//备注
        boolean fispayout = content.getBooleanValue("fispayout");//是否已结清
        double freceamount = ftype.equals("退款") ? -famount : famount;

        PaoSetRemote tcustomer_receptionSet = getP2ServerSystemPaoSet("tcustomer_reception", "siteid='" + siteid + "' and tagentsid='" + tagentsid + "' and tcustomerid='" + tcustomerid + "' and tcustomer_receptid='" + tcustomer_receptid + "'");
        if (tcustomer_receptionSet.isEmpty()) {
            return getErrReturnObject().setErrMsg("找不到对应的客户订单").toString();
        }
        PaoRemote tcustomer_reception = tcustomer_receptionSet.getPao(0);

        double forderamount = tcustomer_reception.getDouble("forderamount");//成交金额
        double freceivedamount = tcustomer_reception.getDouble("freceivedamount");//已收尾款
        freceivedamount = freceivedamount + freceamount;

        tcustomer_reception.setValue("fispayout", fispayout, 11L);//是否已结清
        tcustomer_reception.setValue("freceivedamount", freceivedamount, 11L);//已收尾款
        if (fispayout) {
            tcustomer_reception.setValue("freceivablesamount", 0, 11L);//应收款
        } else {
            tcustomer_reception.setValue("freceivablesamount", forderamount - freceivedamount, 11L);//应收款
        }
        if ("定金".equals(ftype)) {
            tcustomer_reception.setValue("fdepositamount", freceamount, 11L);//定金
        }
        tcustomer_reception.setValue("changeby", username, 11L);//修改人
        tcustomer_reception.setValue("changedate", sysdate, 11L);//修改时间

        PaoSetRemote tcustomer_orderbillSet = tcustomer_reception.getPaoSet("$tcustomer_orderbill", "tcustomer_orderbill");
        PaoRemote tcustomer_orderbill = tcustomer_orderbillSet.addAtEnd();
        tcustomer_orderbill.setValue("ftype", ftype, 11L);
        tcustomer_orderbill.setValue("fnotes", fnotes, 11L);
        tcustomer_orderbill.setValue("famount", freceamount, 11L);
        tcustomer_orderbill.setValue("tcustomer_receptid", tcustomer_receptid, 11L);
        tcustomer_orderbill.setValue("tcustomerid", tcustomerid, 11L);
        tcustomer_orderbill.setValue("fispayout", fispayout, 11L);//结清标志

        tcustomer_orderbill.setValue("siteid", siteid, 11L);
        tcustomer_orderbill.setValue("tagentsid", tagentsid, 11L);
        tcustomer_orderbill.setValue("createby", username, 11L);//收款人
        tcustomer_orderbill.setValue("createdate", sysdate, 11L);//收款时间
        tcustomer_orderbill.setValue("changeby", username, 11L);//修改人
        tcustomer_orderbill.setValue("changedate", sysdate, 11L);//修改时间
        tcustomer_receptionSet.save();

        return query_orderMain();
    }

    /**
     * 查询订单收款记录
     *
     * @return
     */
    public String queryOrderBill() {
        String tcustomerid = content.getString("tcustomerid");//客户档案ID
        String tcustomer_receptid = content.getString("tcustomer_receptid");//接待记录ID

        SQLFactory sqlFactory = new SQLFactory(this, "订单收款记录查询");
        sqlFactory.addParameter("siteid", siteid);
        sqlFactory.addParameter("tagentsid", tagentsid);
        sqlFactory.addParameter("tcustomerid", tcustomerid);
        sqlFactory.addParameter("tcustomer_receptid", tcustomer_receptid);

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

    /**
     * 经销商销售退单
     *
     * @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 queryCommunity() {
        if (content.getString("fcommunity").length() >= 2) {
            SQLFactory sqlFactory = new SQLFactory(this, "小区名称模糊查询");
            sqlFactory.addParameter("siteid", siteid);
            sqlFactory.addParameter("tagentsid", tagentsid);
            sqlFactory.addParameter("fcommunity", "%" + content.getString("fcommunity") + "%");
            Rows rows = dbConnect.runSqlQuery(sqlFactory.getSQL());
            return getSucReturnObject().setData(rows).saveToDataPool().toString();
        } else {
            return getSucReturnObject().setData(new Row()).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();
        }
    }
}
