package com.sifang.modules.supply.order.dao;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.q7link.entity.WuziOrder;
import com.sifang.modules.q7link.entity.WuziOrderDetail;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.supply.order.entity.CrmSupplyMaterialDeliverOrder;
import com.sifang.modules.supply.order.vo.OrderDetailListVo;
import com.sifang.modules.supply.order.vo.OrderDetailVo;
import com.sifang.modules.supply.order.vo.OrderTbQqVO;
import com.sifang.modules.supply.order.vo.OrderTbQqDetailsVO;
import com.sifang.modules.sys.common.persistence.BaseDao;
import com.sifang.modules.sys.common.utils.Arith;
import com.sifang.modules.sys.common.utils.IdGen;
import com.sifang.modules.sys.util.LayuiPage;
import com.sifang.modules.sys.util.SqlBuilder;
import org.hibernate.SQLQuery;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;


@Component
public class CrmSupplyMaterialDeliverOrderDao extends BaseDao<CrmSupplyMaterialDeliverOrder> {

    public String queryCrmSupplyMaterialDeliverOrderId(String name){
        SqlBuilder sqlBuilder=new SqlBuilder();
        sqlBuilder.line(" select id from crm_supply_supplier  where status ='0' and name =? ",name);
        List<Record> list= Db.find(sqlBuilder.build(),sqlBuilder.params());
        if(CollectionUtil.isNotEmpty(list)){
            return list.get(0).get("id");
        }
        return "";
    }


    public List<Record> queryQqList(LayuiPage page, Map<String, String> map) {
        SqlBuilder sql = new SqlBuilder();
        sql.line(" select a.id,a.number,a.status,(case a.type when '6' then '企企数据' else '' end) as type, (case a.pattern when '1' then '平台采购' when '2' then '供应商直发' else '' end) as pattern,a.deliver_name as gysName,c.name as ckName,c.person_in_charge as personInCharge,c.mobile,a.in_stock_time_qq  as createTime    ");
        sql.line(" ,CONCAT(CONCAT(CONCAT(c.province,c.city),c.city),c.address) as address ");
        sql.line(" from crm_supply_material_deliver_order as a ");
        sql.line(" left join crm_supply_supplier as b on a.supply_id=b.id ");
        sql.line(" left join crm_supply_warehouse as c on a.in_warehouse_id=c.id ");
        sql.line(" where a.type=6 and a.status=10 and a.pattern=1 and  c.type='1'  ");
        //订单编号
        if(map.get("number") !=null && StringUtil.isNotBlank(String.valueOf(map.get("number")))){
        sql.line(" and a.number like ?","%"+String.valueOf(map.get("number"))+"%");
        }
        //供应商名称
        if(map.get("traderId") != null && StringUtil.isNotBlank(String.valueOf(map.get("traderId")))){
            sql.line(" and a.deliver_name like ?","%"+map.get("traderId")+"%");
        }
        //订单备注
        if(map.get("applyOrderRemarks") != null && StringUtil.isNotBlank(String.valueOf(map.get("applyOrderRemarks")))){
            sql.line(" and  a.supply_id like ?","%"+String.valueOf(map.get("applyOrderRemarks"))+"%");

        }
        //发货仓库
        if(map.get("ckName") != null && StringUtil.isNotBlank(String.valueOf(map.get("ckName")))){
            sql.line(" and c.name like ?","%"+String.valueOf(map.get("ckName"))+"%");
        }
        //下单日期
        if(map.get("placeTimeMin") != null && StringUtil.isNotBlank(String.valueOf(map.get("placeTimeMin"))) && map.get("placeTimeMax") != null && StringUtil.isNotBlank(String.valueOf(map.get("placeTimeMax")))){
            sql.line(" and a.in_stock_time_qq > ? ",String.valueOf(map.get("placeTimeMin")))
                    .line("  and a.in_stock_time_qq < ? ",String.valueOf(map.get("placeTimeMax")));
        }
        sql.line( " order by  a.in_stock_time_qq desc ");
        if (StrKit.notNull(page)) {
            sql.limit(page.getPage(), page.getLimit());
        }
        return Db.find(sql.build(), sql.params());
    }

    /**
     *  根据id查询订单详情
     * @param id
     * @return
     */
    public OrderDetailVo queryOrderById(String id,String status){
        SqlBuilder builder=new SqlBuilder();
        builder.line(" select a.in_stock_remarks as inStockRemarks,a.in_stock_proof as inStockProof,a.id,a.number,a.status ,(case a.type when '6' then '企企数据'  else a.type end) as type,(case a.pattern when '1' then '平台采购' else a.pattern end) as pattern, ")
                .line(" a.deliver_name as gysName,c.name as ckName,c.person_in_charge as personInCharge,c.mobile, ")
                .line(" (select create_time from crm_qq_main_body where main_id=a.id limit 1)  as createTime       ,CONCAT(CONCAT(CONCAT(c.province,c.city),c.city),c.address) as address,a.in_stock_proof as inStockProof,a.in_stock_proof_url as inStockProofUrl,a.in_stock_attachment_name as inStockAttachmentName,a.in_stock_attachment_url as inStockAttachmentUrl ")
                .line(" from crm_supply_material_deliver_order as a ")
                .line(" left join crm_supply_supplier as b on a.supply_id=b.id ")
                .line(" left join crm_supply_warehouse as c on a.in_warehouse_id=c.id ")
                .line(" where a.type=6   ");
                if(StringUtil.isNotBlank(status) && "7".equals(status)){
                    builder.line(" and a.status=7 ");
                }
                if(StringUtil.isBlank(status)){
                    builder.line(" and a.status=10 ");
                }
        builder.line(" and a.pattern=1 and a.id=? ",id);
        StringBuilder queryChi=new StringBuilder();
        queryChi.append(" select a.id,a.material_type as materialType,a.material_spec as materialSpec,b.material_name as materialName,b.code,b.material_brand as materialBrand,b.unit_name as unitCode,a.out_amount as outAmount,a.in_amount as inAmount ")
                .append(" from crm_supply_material_deliver_order_detail as a  left join crm_supply_material as b on b.id=a.material_id  where a.main_id=? ");
        List<Record> records = Db.find(builder.build(), builder.params());
        OrderDetailVo vo=new OrderDetailVo();
        if(CollectionUtil.isNotEmpty(records)){
            for(Record rd:records){
                List<OrderDetailListVo> list=new ArrayList<>();
                vo.setId(rd.get("id"));
                vo.setNumber(rd.getStr("number"));
                vo.setStatus(rd.getStr("status"));
                vo.setType(rd.getStr("type"));
                vo.setPattern(rd.getStr("pattern"));
                vo.setGysName(rd.getStr("gysName"));
                vo.setCkName(rd.getStr("ckName"));
                vo.setPersonInCharge(rd.getStr("personInCharge"));
                vo.setMobile(rd.getStr("mobile"));
                vo.setCreateTime(rd.getStr("createTime"));
                vo.setAddress(rd.getStr("address"));
                vo.setInStockRemarks(rd.getStr("inStockRemarks"));
                vo.setInStockProof(rd.getStr("inStockProof"));
                vo.setInStockProofUrl(rd.getStr("inStockProofUrl"));
                String[] attachmentNames=rd.getStr("inStockAttachmentName").split(",");
                String[] attachmentUrls=rd.getStr("inStockAttachmentUrl").split(",");
                List<Map> listMap=new ArrayList<>();
                if(attachmentNames != null){
                    for(int k=0;k<attachmentNames.length;k++){
                        String arr=attachmentNames[k];
                        Map m=new HashMap();
                        m.put("attachmentName",arr);
                        m.put("attachmentUrl",attachmentUrls[k]);
                        listMap.add(m);
                    }
                }
                vo.setAttachmentMap(listMap);
                List<Record> records1 = Db.find(queryChi.toString(), vo.getId());
                for(Record r:records1){
                    OrderDetailListVo chiVo=new OrderDetailListVo();
                    chiVo.setId(r.getStr("id"));
                    chiVo.setMaterialType(r.getStr("materialType"));
                    chiVo.setMaterialSpec(r.getStr("materialSpec"));
                    chiVo.setMaterialName(r.getStr("materialName"));
                    chiVo.setCode(r.getStr("code"));
                    chiVo.setMaterialBrand(r.getStr("materialBrand"));
                    chiVo.setUnitCode(r.getStr("unitCode"));
                    BigDecimal a=r.get("outAmount");
                    chiVo.setOutAmount(String.valueOf(a));
                    BigDecimal b=r.get("inAmount");
                    chiVo.setInAmount(String.valueOf(b));
                    list.add(chiVo);
                }
                vo.setList(list);
            }
        }
    return vo;
    }

    public Long queryQqCount(Map<String, String> map) {
        SqlBuilder sql = new SqlBuilder();
        sql.line(" select count(1) ");
        sql.line(" from crm_supply_material_deliver_order as a ");
        sql.line(" left join crm_supply_supplier as b on a.supply_id=b.id ");
        sql.line(" left join crm_supply_warehouse as c on a.in_warehouse_id=c.id ");
        sql.line(" where a.type=6 and a.status=10 and a.pattern=1 and  c.type='1' ");
        //订单编号
        if(map.get("number") !=null && StringUtil.isNotBlank(String.valueOf(map.get("number")))){
            sql.line(" and a.number like ?","%"+String.valueOf(map.get("number"))+"%");
        }
        //代理商名称
        if(map.get("traderId") != null && StringUtil.isNotBlank(String.valueOf(map.get("traderId")))){
            sql.line(" and a.deliver_name like ?","%"+map.get("traderId")+"%");
        }
        //订单备注
        if(map.get("applyOrderRemarks") != null && StringUtil.isNotBlank(String.valueOf(map.get("applyOrderRemarks")))){
            sql.line(" and  a.supply_id like ?","%"+String.valueOf(map.get("applyOrderRemarks"))+"%");

        }
        //发货仓库
        if(map.get("ckName") != null && StringUtil.isNotBlank(String.valueOf(map.get("ckName")))){
            sql.line(" and c.name like ?","%"+String.valueOf(map.get("ckName"))+"%");
        }
        //下单日期
        if (StringUtil.checkParamsValid(map.get("placeTimeMin"))) {
            sql.line(" and a.in_stock_time_qq >= ? ",String.valueOf(map.get("placeTimeMin")));
        }
        if (StringUtil.checkParamsValid(map.get("placeTimeMax"))) {
            sql.line(" and a.in_stock_time_qq <= ? ",String.valueOf(map.get("placeTimeMax")));
        }
        return Db.queryLong(sql.build(), sql.params());
    }

    public boolean orderSubmit(Map map){
        Date now=new Date();
        StringBuilder builder=new StringBuilder();
        builder.append(" update crm_supply_material_deliver_order ");
        builder.append(" set in_stock_remarks=:inStockRemarks1 ,in_stock_proof=:inStockProof ,in_stock_proof_url=:inStockProofUrl1 ");
        builder.append(" ,receive_invoice=:inStockProofUrl2,receive_remark=:inStockRemarks2,receive_time=:p1 ");
        if(map.containsKey("submit") && "1".equals(map.get("submit"))){
            builder.append(" ,status='7' ");
        }
        builder.append(" where id=:id ");
        SQLQuery sqlQuery = getSession()
                .createSQLQuery(builder.toString());
        sqlQuery.setParameter("inStockRemarks1", map.get("inStockRemarks"));
        sqlQuery.setParameter("inStockProof", map.get("inStockProof"));
        sqlQuery.setParameter("inStockProofUrl1", map.get("inStockProofUrl"));
        sqlQuery.setParameter("inStockProofUrl2", map.get("inStockProofUrl"));
        sqlQuery.setParameter("inStockRemarks2", map.get("inStockRemarks"));
        sqlQuery.setParameter("id", map.get("id"));
        sqlQuery.setParameter("p1", now);
        return sqlQuery.executeUpdate() > 0;
//        SqlBuilder builder=new SqlBuilder();
//        builder.line(" update crm_supply_material_deliver_order " +
//                "set in_stock_remarks=? ,in_stock_proof=? ,in_stock_proof_url=?,receive_invoice=?,receive_remark=?  ",
//                map.get("inStockRemarks"),
//                map.get("inStockProof"),
//                map.get("inStockProofUrl"),
//                map.get("inStockProofUrl"),
//                map.get("inStockRemarks"));
//        if(map.containsKey("submit") && "1".equals(map.get("submit"))){
//            builder.line(" ,status='7' ");
//        }
//        builder.line(" where id=? ",map.get("id"));
//        return Db.update(builder.build(),builder.params());
    }





    public List<Record> queryInStockList(LayuiPage page, Map<String, String> map) {
        SqlBuilder sql = new SqlBuilder();
        sql.line(" select a.id,a.number,a.status,(case a.type when '6' then '企企数据'  else a.type end) as type,(case a.pattern when '1' then '平台采购' else a.pattern end) as pattern,a.deliver_name as  gysName,c.name as ckName,c.person_in_charge as personInCharge,c.mobile,a.receive_time  as receiveTime    ");
        sql.line(" ,CONCAT(CONCAT(CONCAT(c.province,c.city),c.city),c.address) as address,a.in_stock_time_qq as inStockTimeQq,a.in_stock_remarks as inStockRemarks ");
        sql.line(" from crm_supply_material_deliver_order as a ");
        sql.line(" left join crm_supply_supplier as b on a.supply_id=b.id ");
        sql.line(" left join crm_supply_warehouse as c on a.in_warehouse_id=c.id ");
        sql.line(" where a.type=6 and a.status=7 and a.pattern=1  and  c.type='1' ");
        //订单编号
        if(map.get("number") !=null && StringUtil.isNotBlank(String.valueOf(map.get("number")))){
            sql.line(" and a.number like ?","%"+String.valueOf(map.get("number"))+"%");
        }
        //代理商名称
        if(map.get("traderId") != null && StringUtil.isNotBlank(String.valueOf(map.get("traderId")))){
            sql.line(" and a.deliver_name like ?","%"+map.get("traderId")+"%");
        }
        //订单备注
        if(map.get("applyOrderRemarks") != null && StringUtil.isNotBlank(String.valueOf(map.get("applyOrderRemarks")))){
            sql.line(" and  a.supply_id like ?","%"+String.valueOf(map.get("applyOrderRemarks"))+"%");

        }
        //发货仓库
        if(map.get("ckName") != null && StringUtil.isNotBlank(String.valueOf(map.get("ckName")))){
            sql.line(" and c.name like ?","%"+String.valueOf(map.get("ckName"))+"%");
        }
        //下单日期
        if (StringUtil.checkParamsValid(map.get("placeTimeMin"))) {
            sql.line(" and a.in_stock_time_qq >= ? ",String.valueOf(map.get("placeTimeMin")));
        }
        if (StringUtil.checkParamsValid(map.get("placeTimeMax"))) {
            sql.line(" and a.in_stock_time_qq <= ? ",String.valueOf(map.get("placeTimeMax")));
        }
        sql.line(" order by a.receive_time desc ");
        if (StrKit.notNull(page)) {
            sql.limit(page.getPage(), page.getLimit());
        }
        return Db.find(sql.build(), sql.params());
    }

    public Long queryInStockCount(Map<String, String> map) {
        SqlBuilder sql = new SqlBuilder();
        sql.line(" select count(1) ");
        sql.line(" from crm_supply_material_deliver_order as a ");
        sql.line(" left join crm_supply_supplier as b on a.supply_id=b.id ");
        sql.line(" left join crm_supply_warehouse as c on a.in_warehouse_id=c.id ");
        sql.line(" where a.type=6 and a.status=7 and a.pattern=1 and  c.type='1' ");
        //订单编号
        if(map.get("number") !=null && StringUtil.isNotBlank(String.valueOf(map.get("number")))){
            sql.line(" and a.number like ?","%"+String.valueOf(map.get("number"))+"%");
        }
        //代理商名称
        if(map.get("traderId") != null && StringUtil.isNotBlank(String.valueOf(map.get("traderId")))){
            sql.line(" and a.deliver_name like ?","%"+map.get("traderId")+"%");
        }
        //订单备注
        if(map.get("applyOrderRemarks") != null && StringUtil.isNotBlank(String.valueOf(map.get("applyOrderRemarks")))){
            sql.line(" and  a.supply_id like ?","%"+String.valueOf(map.get("applyOrderRemarks"))+"%");

        }
        //发货仓库
        if(map.get("ckName") != null && StringUtil.isNotBlank(String.valueOf(map.get("ckName")))){
            sql.line(" and c.name like ?","%"+String.valueOf(map.get("ckName"))+"%");
        }
        //下单日期
        if (StringUtil.checkParamsValid(map.get("placeTimeMin"))) {
            sql.line(" and a.in_stock_time_qq >= ? ",String.valueOf(map.get("placeTimeMin")));
        }
        if (StringUtil.checkParamsValid(map.get("placeTimeMax"))) {
            sql.line(" and a.in_stock_time_qq <= ? ",String.valueOf(map.get("placeTimeMax")));
        }
        return Db.queryLong(sql.build(), sql.params());
    }


    public OrderTbQqVO tbDate(String orderId){
        StringBuilder querySql=new StringBuilder();
        querySql.append(" select a.id, a.type, a.trader_id AS traderId, b.qq_company_code as companyCode,a.qq_project_code as projectCode,")
                .append("  c.name AS projectName,a.city, a.area, w.`qq_code` AS warehouseCode ")
                .append(" FROM crm_supply_material_deliver_order a ")
                .append(" LEFT JOIN crm_trader b ON b.id = a.trader_id ")
                .append(" LEFT JOIN crm_supply_material_project AS c ON c.code = a.qq_project_code ")
                .append(" LEFT JOIN crm_supply_warehouse w ON w.id=a.out_warehouse_id ")
                .append(" where a.id=? ");
        Record rd = Db.findFirst(querySql.toString(), orderId);

        OrderTbQqVO obj=new OrderTbQqVO();
        obj.setId(rd.getStr("id"));
        obj.setType(rd.getStr("type"));
        obj.setTraderId(rd.getStr("traderId"));
        obj.setCompanyCode(rd.getStr("companyCode"));
        obj.setProjectCode(rd.getStr("projectCode"));
        obj.setProjectName(rd.getStr("projectName"));
        if (StringUtil.isNotBlank(rd.getStr("city")) &&
                rd.getStr("city").contains("省直辖县级行政单位")) {
            obj.setCity(rd.getStr("area"));
        }
        else {
            obj.setCity(rd.getStr("city"));
        }
        obj.setWarehouseCode(rd.getStr("warehouseCode"));

        StringBuilder queryDetails=new StringBuilder();
        queryDetails.append(" SELECT d.id, CAST(d.purchase_price AS CHAR) AS purchasePrice,d.out_amount AS outAmount," )
                    .append("  m.material_name AS materialName, m.qq_code AS qqCode, c.price as hsPrice, ")
                    .append("  c.cs_jia_ge_han_shui AS csJiaGeHanShui,c.cs_shui_lv AS shuiLv, m.unit_name AS unitName ")
                    .append(" FROM `crm_supply_material_deliver_order_detail` d ")
                    .append(" LEFT JOIN `crm_supply_material` m ON d.material_id=m.id ")
                    .append(" LEFT JOIN crm_supply_material_project_price AS c ")
                    .append(" ON c.`status` = '0' AND c.qq_material_code = m.qq_code AND c.qq_project_code= ?")
                    .append(" WHERE d.main_id=? AND d.status='0' ");
        List<Record> record = Db.find(queryDetails.toString(), obj.getProjectCode(), obj.getId());
        List<OrderTbQqDetailsVO> l=new ArrayList<>();
        for(Record r:record){
            OrderTbQqDetailsVO details=new OrderTbQqDetailsVO();
            details.setId(r.getStr("id"));
            details.setPurchasePrice(r.getStr("purchasePrice"));

            BigDecimal outAmount = r.getBigDecimal("outAmount");
            details.setOutAmount(outAmount.toString()); // 提交数量

            details.setMaterialName(r.getStr("materialName"));
            details.setQqCode(r.getStr("qqCode"));

            BigDecimal hsPrice = r.getBigDecimal("hsPrice");
            details.setHsPrice(hsPrice.toString());//含税单价

            details.setUnitName(r.getStr("unitName"));

            BigDecimal shuiLv = r.getBigDecimal("shuiLv");
            details.setShuiLv(shuiLv.toString());// 税率

            details.setCsJiaGeHanShui(r.getStr("csJiaGeHanShui"));// 价格含税:是否 具体值： false/true

            // 计算 含税金额 公式：确认单价*确认数量
            BigDecimal hsSum = Arith.mul(hsPrice, outAmount, 2);
            details.setHsSum(hsSum.toString()); // 含税金额

            // 计算 税额 公式：金额/（1+税率）*税率，四舍五入后保留2位小数
            BigDecimal shuiLvSum = Arith.div(hsSum,Arith.add(BigDecimal.ONE,shuiLv)); // 金额/（1+税率）
            shuiLvSum = Arith.mul(shuiLvSum, shuiLv, 2); // * 税率
            details.setShuiLvSum(shuiLvSum.toString()); // 税额

            // 计算 无税金额 公式：金额-税额，四舍五入后保留2位小数
            BigDecimal bhsSum = Arith.sub(hsSum, shuiLvSum);
            details.setBhsSum(bhsSum.setScale(2, RoundingMode.HALF_UP).toString());

            // 计算 无税单价 公式：无税金额/确认数量，四舍五入后保留2位小数
            BigDecimal bhsPrice = Arith.div2P(bhsSum, outAmount);
            details.setBhsPrice(bhsPrice.toString());

            l.add(details);
        }
        obj.setList(l);
        return obj;
    }

    /**
     * 企企小e销售单存储到本系统
     * @param orderId
     * @param qqCode
     * @param qqId
     * @return
     */
    public int saveEntity(String orderId,String qqCode,String qqId){
        StringBuilder insertSql=new StringBuilder();
        insertSql.append(" INSERT INTO crm_supply_material_deliver_order_qq(id,order_id,qq_code,qq_id,status,create_time) VALUES (?,?,?,?,'0',?)");
        int result=Db.update(insertSql.toString(), IdGen.uuid(),orderId,qqCode,qqId,DateUtil.now());
        return result;
    }

    /**
     * 保存领用出库单id
     */
    public boolean savePickingIssue(String qqOrderId,String pickingIssueId,String pickingIssueCode) {
        StringBuilder insertSql=new StringBuilder();
        insertSql.append("UPDATE crm_qq_wuzi_order a SET a.`picking_issue_id` = ?, a.`picking_issue_code` = ? WHERE a.`id` = ?");
        int result=Db.update(insertSql.toString(), pickingIssueId, pickingIssueCode, qqOrderId);
        return result>0;
    }

    public boolean saveWuziInfo(WuziOrder order) {
        // 先删除历史记录，再生成企企记录
        StringBuilder delWuziSql=new StringBuilder();
        delWuziSql.append(" DELETE FROM crm_qq_wuzi_order WHERE id = ?");
        Db.update(delWuziSql.toString(), order.getId());

        StringBuilder delWuziDetailSql=new StringBuilder();
        delWuziDetailSql.append(" DELETE FROM crm_qq_wuzi_order_detail WHERE order_id = ?");
        Db.update(delWuziDetailSql.toString(), order.getId());

        int num = saveWuziOrder(order.getId(), order.getCode(), order.getCsLingChuCangKuCode(), order.getBillStatus(),
                order.getBillTypeId(), order.getBusinessDate(), order.getDeliverOrderId());
        if (num <= 0) {
            return false;
        }

        for (WuziOrderDetail detail : order.getDetails()) {
            int updateFlag = saveWuziOrderDetail(detail.getId(), detail.getOrderId(), detail.getOrdinal(), detail.getCsShuiL(),
                    detail.getCsCunHuoCode(), detail.getCsShiJiShuLiang(), detail.getCsTiJiaoShuLiang(), detail.getDeliverDetailId());
            if (updateFlag <= 0) {
                return false;
            }
        }
        return true;
    }

    /**
     * 保存企企的物资需求单记录
     */
    public int saveWuziOrder(String id,String code,String csLingChuCangKuCode, String billStatus, String billTypeId,
                             Date businessDate, String deliverOrderId){
        StringBuilder insertSql=new StringBuilder();
        insertSql.append(" INSERT INTO `crm_qq_wuzi_order` (`id`,`code`,`cs_ling_chu_cang_ku_code`,`bill_status`");
        insertSql.append("  ,`bill_type_id`,`business_date`,`deliver_order_id`,`create_time`)");
        insertSql.append(" VALUES(?,?,?,?,?,?,?,NOW())");
        int result=Db.update(insertSql.toString(), id,code,csLingChuCangKuCode,billStatus,billTypeId,
                businessDate, deliverOrderId);
        return result;
    }

    /**
     * 保存企企的物资需求单明细记录
     */
    public int saveWuziOrderDetail(String id,String orderId, Long ordinal, BigDecimal csShuiL, String csCunHuoCode,
                             BigDecimal csShiJiShuLiang, BigDecimal csTiJiaoShuLiang, String deliverDetailId){
        StringBuilder insertSql=new StringBuilder();
        insertSql.append(" INSERT INTO `crm_qq_wuzi_order_detail` (`id`,`order_id`,`ordinal`,`cs_shui_l`,");
        insertSql.append("  `cs_cun_huo_code`,`cs_shi_ji_shu_liang`,`cs_ti_jiao_shu_liang`,`deliver_detail_id`)");
        insertSql.append(" VALUES (?,?,?,?,?,?,?,?)");
        int result=Db.update(insertSql.toString(), id,orderId,ordinal,csShuiL,csCunHuoCode,
                csShiJiShuLiang, csTiJiaoShuLiang, deliverDetailId);
        return result;
    }

    /**
     * 获取 已同步的企企物资需求单记录
     */
    public WuziOrder getWuziOrder(String qqOrderId){
        if (StringUtil.isBlank(qqOrderId)) {
            return null;
        }
        WuziOrder order = new WuziOrder();
        StringBuilder orderSql=new StringBuilder();
        orderSql.append(" SELECT a.* FROM crm_qq_wuzi_order a WHERE a.id = ?");
        Record or = Db.findFirst(orderSql.toString(), qqOrderId);
        if (or == null) {
            return null;
        }
        order.setId(or.getStr("id"));
        order.setCode(or.getStr("code"));
        order.setCsLingChuCangKuCode(or.getStr("csLingChuCangKuCode"));
        order.setDeliverOrderId(or.getStr("deliverOrderId"));

        // 获取明细记录
        StringBuilder detailSql=new StringBuilder();
        detailSql.append(" SELECT a.* FROM crm_qq_wuzi_order_detail a WHERE a.order_id = ? ORDER BY a.`ordinal`");
        List<Record> records = Db.find(detailSql.toString(), qqOrderId);
        List<WuziOrderDetail> details = new ArrayList<>();
        for (Record r : records) {
            WuziOrderDetail detail = new WuziOrderDetail();
            detail.setId(r.getStr("id"));
            detail.setOrderId(r.getStr("order_id"));
            detail.setDeliverDetailId(r.getStr("deliver_detail_id"));
            detail.setCsCunHuoCode(r.getStr("cs_cun_huo_code"));
            detail.setCsShuiL(r.getBigDecimal("cs_shui_l"));
            details.add(detail);
        }
        order.setDetails(details);
        return order;
    }


}
