<?php
// +------------------------------------------------------------------------------------------------
// | 【使用说明】请将本文件上传至NB系统网站服务器：/addons/bsht_tbk/inc/mobile/  目录下。
// +------------------------------------------------------------------------------------------------
// | [18淘客助手api文件(NB微信淘宝客专用)] Copyright (c) 2019 18.LA
// +------------------------------------------------------------------------------------------------
// | 最后修改：2019年12月21日
// +------------------------------------------------------------------------------------------------
// | 官网：http://niubei.18.la/
// +------------------------------------------------------------------------------------------------
defined('IN_IA') or exit('Access Denied');
global $_W, $_GPC, $return, $aouthkey;
include_once IA_ROOT . "/addons/bsht_tbk/dtfl.php";
$uniacid = $_W['uniacid'];
//默认返回值
$return = array('state' => 'ok', 'code' => 1, 'message' => '', 'version' => '7.6', 'system' => urlencode('NB微信淘宝客'), 'updatetime' => urlencode('2019年12月21日'));
//接收post参数
$api = trim($_GPC['api']);
//api名称
$aouthkey = trim($_GPC['key']);
//传入的密钥
$op = trim($_GPC['op']);
//如果未传入有效参数
if (empty($aouthkey) || empty($api)) {
    returnExit($return, 0, "API接口正常");
    //code值设置为0，表示失败
}
//读取相关参数
$setting = pdo_fetch("SELECT * FROM " . tablename('bsht_tbk_set') . " WHERE uniacid = '{$uniacid}' ");
$isrrqd = intval($setting['isrrqd']);
$isodfix = intval($setting['isodfix']);
$plus_set = pdo_fetch("SELECT * FROM " . tablename('bsht_tbk_plus') . " WHERE uniacid = '{$uniacid}' ");
$is_filter = intval($plus_set['is_filter']);
$is_wqplus = intval($plus_set['is_wqplus']);
$is_dtfl = intval($plus_set['is_dtfl']);
$is_dtfd = intval($plus_set['is_dtfd']);
$dtpid = intval($setting['dtpid']);
$dtpid_zdh = intval($setting['dtpid_zdh']);
$dtpid_locktime = intval($setting['dtpid_locktime']);
if ($dtpid_locktime == 0) {
    $dtpid_locktime = 300;
}
//判断密钥是否正确
if (empty($aouthkey) || $aouthkey != $setting['nbkey']) {
    returnExit($return, 0, "密钥错误");
    //code值设置为0，表示失败
}
//判断有无新版APP设置msg参数
$exists_app = pdo_tableexists('bsht_tbk_tkapp');
if ($exists_app) {
    $nbapp = pdo_fetch("SELECT * FROM " . tablename('bsht_tbk_tkapp') . " WHERE uniacid = '{$uniacid}' ");
    $isnbshare = intval($nbapp['isnbshare']);
    $jg_endat = trim($nbapp['jg_endat']);
    if (!empty($jg_endat) && $isnbshare == 1) {
        $appmsg = 1;
    } else {
        $jg_ak = trim($nbapp['jg_appkey']);
        $jg_as = trim($nbapp['jg_appsecret']);
        if (!empty($jg_ak) && !empty($jg_as)) {
            $appmsg = 1;
        } else {
            $appmsg = 0;
        }
    }
} else {
    $appmsg = 0;
}
//判断有无新版APP设置msg参数
//接口验证
if ($api == 'verify') {
    returnExit($return, 1, "验证成功");
    //code值设置为1，表示成功
} elseif ($api == 'nbtbapi') {
    //获取post过来的订单内容
    $content = htmlspecialchars_decode($_GPC['content']);
    $contentArr = @json_decode($content, true);
    if (!empty($contentArr)) {
        if (empty($contentArr['session'])) {
            returnExit($return, 0, "未传入有效的session数据");
        }
        $tbapidata['api_token'] = $contentArr['session'];
        if (!empty($contentArr['refresh_token'])) {
            $tbapidata['api_retoken'] = $contentArr['refresh_token'];
        }
        //更新数据库中的session
        $result = pdo_update('bsht_tbk_nice', $tbapidata, array('uniacid' => $_W['uniacid']));
        if (!empty($result)) {
            returnExit($return, 1, "更新session成功");
        } else {
            returnExit($return, 0, "更新session失败");
        }
    } else {
        //取ak、st
        include_once IA_ROOT . "/addons/bsht_tbk/tbsdk/TbkSdk.php";
        $nbapi = new NbtbkApi();
        $eninfo = $nbapi->enapicode();
        $return['tbapi']['appkey'] = urlencode($eninfo['ak']);
        $return['tbapi']['appsecret'] = urlencode($eninfo['st']);
        //取session
        $nice = pdo_fetch("SELECT id,api_token FROM " . tablename('bsht_tbk_nice') . " WHERE uniacid = '{$uniacid}' ");
        $return['tbapi']['session'] = urlencode(trim($nice['api_token']));
        returnExit($return, 1, "nbapi ver 1.0.1");
    }
} elseif ($api == 'postorder') {
    //获取post过来的订单内容
    $content = htmlspecialchars_decode($_GPC['content']);
    $contentArr = @json_decode($content, true);
    //json解码
    //判断传入订单数据是否为空
    if (!empty($contentArr)) {
        //获取相关参数
        $synctipplus = intval($setting['synctipplus']);
        $tbpid = trim($setting['tb_pid']);
        if (!empty($tbpid)) {
            $pidarr = explode("_", $tbpid);
            $pid1 = $pidarr[1];
        }
        $ddbili = intval($setting['ddbili']);
        $fwfbili = intval($setting['lmcbbl']);
        $lmcbbl = intval($setting['lmcbbl']);
        if ($fwfbili > 0 && $fwfbili < 100) {
            $fwfbili = 100 - $fwfbili;
            $lmcbbl = 100 - $fwfbili;
        }
        $ddjiangli1 = intval($setting['ddjiangli1']);
        $ddjiangli2 = intval($setting['ddjiangli2']);
        $ddjiangli3 = intval($setting['ddjiangli3']);
        $sp_bl_lv1 = intval($setting['sp_bl_lv1']);
        $sp_bl_lv1_lv2 = intval($setting['sp_bl_lv1_lv2']);
        $sp_bl_lv1_lv3 = intval($setting['sp_bl_lv1_lv3']);
        $nice = pdo_fetch("SELECT * FROM " . tablename('bsht_tbk_nice') . " WHERE uniacid = '{$_W['uniacid']}' ");
        $isddview = intval($nice['isddview']);
        $ddisstatus = $setting['ddisstatus'];
        $isbanddd = intval($setting['isbanddd']);
        $isbandddsms = $setting['isbandddsms'];
        //格式化订单数据
        $newdata = orderFormat($contentArr);
        if (!empty($newdata)) {
            $data_values = array_filter($newdata);
            $newArr_nb = array_values($data_values);
            //定义记录订单入库结果的变量
            $resultStr = "";
            //遍历订单数据
            foreach ($newArr_nb as $k => $data) {
                //将数据分配到对应字段
                $cate_data = array('uniacid' => $_W['uniacid'], 'type' => 0, 'itemtitle' => $data['商品信息'], 'itemid' => $data['商品ID'], 'ctime' => $data['创建时间'], 'dtime' => $data['点击时间'], 'orderid' => $data['子订单编号'], 'orderid_p' => $data['订单编号'], 'etime' => $data['结算时间'], 'orderfee' => $data['付款金额'], 'shouru_bili' => $data['收入比率'], 'shouru_yongjin' => $data['效果预估'], 'pid2' => $data['来源媒体ID'], 'pid3' => $data['广告位ID'], 'orderstatus' => $data['订单状态'], 'count' => $data['商品数']);
                //增加订单类型字段匹配
                if (!empty($data['订单类型'])) {
                    if (pdo_fieldexists('bsht_tbk_order', 'order_type')) {
                        $cate_data['order_type'] = $data['订单类型'];
                    }
                }
                //增加订单类型字段匹配
                //rid
                if (!empty($data['渠道关系ID'])) {
                    $shop = pdo_fetch("SELECT * FROM " . tablename('bsht_tbk_shop') . " WHERE uniacid = '{$_W['uniacid']}' AND rid = '{$data['渠道关系ID']}' AND rid!='0' AND rid !='' ");
                    $cate_data['rid'] = trim($data['渠道关系ID']);
                    unset($cate_data['pid2']);
                    unset($cate_data['pid3']);
                    //if (empty($shop)) {
                    $ck_u_rid = pdo_fetch("SELECT * FROM " . tablename('bsht_tbk_user') . " WHERE uniacid = '{$_W['uniacid']}' AND rid = '{$data['渠道关系ID']}' AND rid!='0' AND rid !='' ");
                    //}
                } else {
                    if (!empty($pid1) && !empty($data['来源媒体ID']) && !empty($data['广告位ID'])) {
                        $pid2 = $data['来源媒体ID'];
                        $pid3 = $data['广告位ID'];
                        $pid = "mm_" . $pid1 . "_" . $pid2 . "_" . $pid3;
                    }
                    if ($dtpid == 1) {
                        //清理过期pid
                        $delpids = pdo_fetchall("SELECT * FROM " . tablename('bsht_tbk_pids') . " WHERE uniacid = '{$uniacid} ' AND status = 2");
                        if (!empty($delpids)) {
                            foreach ($delpids as $k => $v) {
                                $this_id = $v['id'];
                                $this_vtime = $v['vtime'];
                                $now_time = time();
                                $pplus = $now_time - $this_vtime;
                                if ($pplus > $dtpid_locktime) {
                                    $del = array();
                                    $del['status'] = 1;
                                    $del['uid'] = 0;
                                    $del['iid'] = '';
                                    $del['vtime'] = '';
                                    pdo_update('bsht_tbk_pids', $del, array('uniacid' => $uniacid, 'id' => $this_id));
                                    //清理过期pid-2
                                    pdo_delete('bsht_tbk_pids_iid', array('uniacid' => $uniacid, 'uid' => $v['uid']));
                                    //清理过期pid-2
                                }
                            }
                        }
                        //清理过期pid
                        //获取动态pid
                        $get_pids = pdo_fetch("SELECT * FROM " . tablename('bsht_tbk_pids_iid') . " WHERE uniacid = '{$_W['uniacid']}' AND pid2 = '{$data['来源媒体ID']}' AND pid3 = '{$data['广告位ID']}' AND uid > 0 AND iid = '{$data['商品ID']}'");
                        //获取动态pid
                        if (!empty($get_pids)) {
                            $ck_u_uid = $get_pids['uid'];
                            if ($ck_u_uid > 0) {
                                $cate_data['uid'] = $ck_u_uid;
                                //删除对应记录
                                pdo_delete('bsht_tbk_pids_iid', array('uniacid' => $uniacid, 'id' => $get_pids['id']));
                                //删除对应记录
                                //处理一单多物跟踪
                                pdo_update('bsht_tbk_order', array('uid' => $ck_u_uid), array('uniacid' => $uniacid, 'orderid_p' => $data['订单编号']));
                                //处理一单多物跟踪
                                //验证是否还有同pid记录
                                $this_pid = $get_pids['tb_pid'];
                                $ckall_pids_iid = pdo_fetchall("SELECT * FROM " . tablename('bsht_tbk_pids_iid') . " WHERE uniacid = '{$uniacid} ' AND tb_pid = '{$this_pid}'");
                                $ckall_pids_iid_num = count($ckall_pids_iid);
                                //验证是否还有同pid记录
                                //解除锁定
                                if ($ckall_pids_iid_num == 0) {
                                    $del = array();
                                    $del['status'] = 1;
                                    $del['uid'] = 0;
                                    $del['iid'] = '';
                                    $del['vtime'] = '';
                                    pdo_update('bsht_tbk_pids', $del, array('uniacid' => $uniacid, 'tb_pid' => $get_pids['tb_pid']));
                                }
                                //解除锁定
                                //追单号
                                if ($dtpid_zdh == 1) {
                                    $orderid = $data['子订单编号'];
                                    $orderidsmall = substr($orderid, -6);
                                    if (!empty($orderidsmall)) {
                                        pdo_update('bsht_tbk_user', array('orderidsmall' => ''), array('uniacid' => $uniacid, 'orderidsmall' => $orderidsmall));
                                        pdo_update('bsht_tbk_user', array('orderidsmall' => $orderidsmall), array('uniacid' => $uniacid, 'uid' => $ck_u_uid));
                                    }
                                }
                                //追单号
                            }
                        } else {
                            //处理一单多物跟踪
                            $thisoid_p = pdo_fetch('select * from ' . tablename('bsht_tbk_order') . " where uniacid = '{$uniacid}' AND orderid_p = '{$data['订单编号']}' ");
                            if (!empty($thisoid_p)) {
                                $ck_u_uid = intval($thisoid_p['uid']);
                                $cate_data['uid'] = $ck_u_uid;
                                //追单号
                                if ($dtpid_zdh == 1) {
                                    $orderid = $data['子订单编号'];
                                    $orderidsmall = substr($orderid, -6);
                                    if (!empty($orderidsmall) && $ck_u_uid > 0) {
                                        pdo_update('bsht_tbk_user', array('orderidsmall' => ''), array('uniacid' => $uniacid, 'orderidsmall' => $orderidsmall));
                                        pdo_update('bsht_tbk_user', array('orderidsmall' => $orderidsmall), array('uniacid' => $uniacid, 'uid' => $ck_u_uid));
                                    }
                                }
                                //追单号
                            }
                            //处理一单多物跟踪
                        }
                    } else {
                        $shop = pdo_fetch("SELECT * FROM " . tablename('bsht_tbk_shop') . " WHERE uniacid = '{$_W['uniacid']}' AND pid2 = '{$data['来源媒体ID']}' AND pid3 = '{$data['广告位ID']}' AND pid2 != '' AND pid3 != '' ");
                    }
                }
                //rid
                //is_filter
                if ($is_filter == 1) {
                    if ($ck_u_uid > 0) {
                        $ck_filter = pdo_fetch('select * from ' . tablename('bsht_tbk_filter') . " where uniacid = '{$uniacid}' AND uid = '{$ck_u_uid}'");
                        if (!empty($ck_filter)) {
                            $orderid = $data['子订单编号'];
                            $orderidsmall = substr($orderid, -6);
                            if (!empty($orderidsmall)) {
                                pdo_update('bsht_tbk_user', array('orderidsmall' => ''), array('uniacid' => $uniacid, 'orderidsmall' => $orderidsmall, 'uid' => $ck_u_uid));
                            }
                            $ck_u_uid = 0;
                            $cate_data['uid'] = 0;
                        }
                    }
                }
                //is_filter
                if (!empty($shop)) {
                    $cate_data['shopid'] = $shop['id'];
                    $isdiybl = intval($shop['isdiybl']);
                    if ($isdiybl == 2) {
                        $sp_bl_lv1 = intval($shop['sp_bl_lv1']);
                        $sp_bl_lv1_lv2 = intval($shop['sp_bl_lv1_lv2']);
                        $sp_bl_lv1_lv3 = intval($shop['sp_bl_lv1_lv3']);
                    }
                    $dlm_id = intval($shop['dlm_id']);
                    if ($dlm_id > 0) {
                        $cate_data['dlm_id'] = $dlm_id;
                    }
                }
                if (!empty($ck_u_rid) && $dtpid == 0) {
                    $dlm_id = intval($ck_u_rid['dlm_id']);
                    $ck_u_uid = intval($ck_u_rid['uid']);
                    if ($ck_u_uid > 0) {
                        $cate_data['uid'] = $ck_u_uid;
                    }
                    if ($dlm_id > 0) {
                        $cate_data['dlm_id'] = $dlm_id;
                    }
                }
                //dtfl动态返利
                if ($is_dtfl == 1 && $cate_data['shouru_yongjin'] > 0) {
                    $yjfee = $cate_data['shouru_yongjin'];
                    $dtfl = get_dtfl($uniacid, $ck_u_uid, $yjfee);
                    $dtfl = intval($dtfl);
                    if ($dtfl > 0) {
                        $ddbili = $dtfl;
                    }
                }
                //dtfl动态返利
                //dtfl动态返利
                if ($shop['id'] > 0 && $is_dtfd == 1 && $cate_data['shouru_yongjin'] > 0) {
                    $yjfee = $cate_data['shouru_yongjin'];
                    $dtfd = get_dtfd($uniacid, $shop['id'], $yjfee);
                    $dtfd = intval($dtfd);
                    if ($dtfd >= 0) {
                        $ddbili = $dtfd;
                    }
                }
                //dtfl动态返利
                if (empty($data['渠道关系ID'])) {
                    if ($data['广告位ID'] == 0 || $data['广告位ID'] == '0' || empty($data['广告位ID'])) {
                        $cate_data['dlm_id'] = 0;
                        $cate_data['shopid'] = 0;
                    }
                }
                $wq_status = 0;
                if (!empty($data['维权标签']) && $is_wqplus == 1) {
                    if ($data['维权标签'] == '维权单') {
                        $wq_status = 1;
                        $cate_data['wq_status'] = 1;
                        $cate_data['noup'] = 1;
                        $cate_data['orderstatus'] = '订单失效';
                    }
                }
                //-----历史遗留的一单多物订单处理---------
                $tradeParentID = $cate_data['orderid_p'];
                //父订单编号
                $tradeID = $cate_data['orderid'];
                //子订单编号
                //如果父订单编号和子订单编号不一样，判定为一单多物订单
                if ($tradeParentID != $tradeID) {
                    //根据父订单号查询订单是否存在
                    $thisoid_ck = pdo_fetch('select * from ' . tablename('bsht_tbk_order') . " where uniacid = '{$_W['uniacid']}' AND orderid = '{$tradeParentID}' ");
                    //查询订单表
                    if (!empty($thisoid_ck)) {
                        $his_fix = array('status' => $thisoid_ck['status'], 'noup' => $thisoid_ck['noup'], 'isjs' => $thisoid_ck['isjs'], 'jsrq' => $thisoid_ck['jsrq'], 'uid' => $thisoid_ck['uid'], 'shopid' => $thisoid_ck['shopid'], 'issh' => $thisoid_ck['issh']);
                        //如果存在，说明是以前遗留的合并的一单多物订单，删除该订单，并执行返利和免单的相关处理
                        //pdo_delete('bsht_tbk_order', array('orderid' => $tradeParentID, 'uniacid' => $_W['uniacid']));
                        //pdo_delete('bsht_tbk_orderus', array('orderid' => $tradeParentID, 'uniacid' => $_W['uniacid']));
                    } else {
                        $his_fix = '';
                    }
                }
                //-----历史遗留的一单多物订单处理---------
                //查询订单表
                $thisoid = pdo_fetch('select * from ' . tablename('bsht_tbk_order') . " where uniacid = '{$_W['uniacid']}' AND orderid = '{$data['子订单编号']}' ");
                //fixqdxls
                if ($data['订单编号'] != $data['子订单编号']) {
                    pdo_delete('bsht_tbk_order', array('uniacid' => $uniacid, 'orderid' => $data['订单编号']));
                }
                //fixqdxls
                //判断订单是否存在
                if (empty($thisoid)) {
                    //新增数据
                    $cate_data['status'] = $data['订单状态'] == '订单失效' ? 0 : 1;
                    //信息状态 0失效 1有效
                    if ($ddbili > 0) {
                        $cate_data['ddbili'] = $ddbili;
                    }
                    if (pdo_fieldexists('bsht_tbk_order', 'jiangli1')) {
                        if ($setting['isgdbl'] > 1) {
                            /*
                                                        if (!empty($pid1) && !empty($data['来源媒体ID']) && !empty($data['广告位ID'])) {
                                                            $cate_data['tb_pid'] = $pid;
                                                        }
                            */
                            //查询有无多等级
                            if ($ck_u_uid > 0) {
                                $thisu = pdo_fetch("SELECT id,uid,lv_id FROM " . tablename('bsht_tbk_user') . " WHERE uid = '{$ck_u_uid}' AND uniacid = '{$_W['uniacid']}' ");
                                if (!empty($thisu) && $thisu['lv_id'] > 0) {
                                    $lv_id = intval($thisu['lv_id']);
                                    $lv_info = pdo_fetch("SELECT * FROM " . tablename('bsht_tbk_lv') . " WHERE id = '{$lv_id}' AND uniacid = '{$_W['uniacid']}' ");
                                    if (!empty($lv_info) && $lv_info['status'] == 1) {
                                        $ddjiangli1 = intval($lv_info['lv1']);
                                        $ddjiangli2 = intval($lv_info['lv2']);
                                        $ddjiangli3 = intval($lv_info['lv3']);
                                    }
                                }
                            }
                            //查询有无多等级
                            if ($ddjiangli1 > 0) {
                                $cate_data['jiangli1'] = $ddjiangli1;
                            }
                            if ($ddjiangli2 > 0) {
                                $cate_data['jiangli2'] = $ddjiangli2;
                            }
                            if ($ddjiangli3 > 0) {
                                $cate_data['jiangli3'] = $ddjiangli3;
                            }
                            if ($sp_bl_lv1 > 0) {
                                $cate_data['sp_bl_lv1'] = $sp_bl_lv1;
                            }
                            if ($sp_bl_lv1_lv2 > 0) {
                                $cate_data['sp_bl_lv1_lv2'] = $sp_bl_lv1_lv2;
                            }
                            if ($sp_bl_lv1_lv3 > 0) {
                                $cate_data['sp_bl_lv1_lv3'] = $sp_bl_lv1_lv3;
                            }

                            if ($fwfbili > 0 && $fwfbili > 10 && $fwfbili < 100) {
                                $cate_data['fwfbili'] = $fwfbili;
                            } else {
                                if ($fwfbili == 100) {
                                    $cate_data['fwfbili'] = 0;
                                } else {
                                    $cate_data['fwfbili'] = 10;
                                }
                            }
                            if ($sp_bl_lv1 > 0) {
                                //$lmcbbl = $fwfbili;
                                $feebl = (100 - $ddbili) / 100 * $lmcbbl / 100;
                                $fee1 = round($data['效果预估'] * $feebl * $sp_bl_lv1 / 100, 2);
                                $fee2 = round($data['效果预估'] * $feebl * $sp_bl_lv1_lv2 / 100, 2);
                                $fee3 = round($data['效果预估'] * $feebl * $sp_bl_lv1_lv3 / 100, 2);
                                //固定比例fix
                                $helpshopid = intval($shop['helpshopid']);
                                if ($helpshopid == 0) {
                                    $fee2 = 0;
                                    $fee3 = 0;
                                } else {
                                    $shop2 = pdo_fetch("SELECT * FROM " . tablename('bsht_tbk_shop') . " WHERE id = '{$helpshopid}' AND uniacid = '{$_W['uniacid']}' ");
                                    if (!empty($shop2)) {
                                        $helpshopid2 = intval($shop2['helpshopid']);
                                    } else {
                                        $fee2 = 0;
                                        $helpshopid2 = 0;
                                    }
                                    if ($helpshopid2 == 0) {
                                        $fee3 = 0;
                                    }
                                }
                                //固定比例fix
                                $feeall = round($fee1 + $fee2 + $fee3, 2);
                                if ($fee1 == 0) {
                                    $fee1 = '0.00';
                                }
                                if ($fee2 == 0) {
                                    $fee2 = '0.00';
                                }
                                if ($fee3 == 0) {
                                    $fee3 = '0.00';
                                }
                                if ($feeall == 0) {
                                    $feeall = '0.00';
                                }
                                $cate_data['fee1'] = $fee1;
                                $cate_data['fee2'] = $fee2;
                                $cate_data['fee3'] = $fee3;
                                $cate_data['feeall'] = $feeall;
                            }
                        } else {
                            $cate_data['fwfbili'] = $fwfbili;
                        }
                    }
                    //etime
                    if ($data['订单状态'] == '订单结算' && !empty($data['结算时间']) && $wq_status != 1) {
                        $etm = array();
                        $etm['etime'] = strtotime($data['结算时间']);
                        $etm['orderstatus'] = '订单结算';
                        $etm['shouru_yongjin'] = $data['效果预估'];
                        $etm['orderid_p'] = $data['订单编号'];
                        pdo_update('bsht_tbk_orderus', $etm, array('orderid' => $data['子订单编号'], 'uniacid' => $_W['uniacid']));
                    }
                    if ($data['订单状态'] == '订单失效') {
                        $etm = array();
                        $etm['etime'] = '';
                        $etm['orderstatus'] = '';
                        $etm['shouru_yongjin'] = $data['效果预估'];
                        $etm['orderid_p'] = $data['订单编号'];
                        pdo_update('bsht_tbk_orderus', $etm, array('orderid' => $data['子订单编号'], 'uniacid' => $_W['uniacid']));
                    }
                    //etime
                    $result = pdo_insert('bsht_tbk_order', $cate_data);
                    //app推送tb
                    $is_fdpush = intval($plus_set['is_fdpush']);
                    if ($appmsg == 1 && $is_fdpush == 1 && !empty($shop) && !empty($shop['glopenid']) && $result) {
                        $this_user = pdo_fetch("SELECT id,uid FROM " . tablename('bsht_tbk_user') . " WHERE uniacid = '{$uniacid}' AND openid = '{$shop['glopenid']}' ORDER BY id DESC");
                        $sp_uid = intval($this_user['uid']);
                        $sp_id = intval($shop['id']);
                        $jg_user = pdo_fetch("SELECT * FROM " . tablename('bsht_tbk_app_user') . " WHERE uniacid = '{$uniacid}' AND uid = '{$sp_uid}' ORDER BY id DESC");
                        if (!empty($jg_user) && $sp_uid > 0 && $sp_id > 0) {
                            $app_url = $_W['siteroot'] . "app/index.php?i=" . $uniacid . "&c=entry&op=m&shopid=" . $sp_id . "&do=uc_shop_order_all&m=bsht_tbkdl&tp=tb&fm=xcx&to=nbapp&orderid=" . $data['订单编号'];
                            $push = array();
                            $push['registrationId'] = trim($jg_user['registrationId']);
                            $push['push_tit'] = '〖分店〗订单：TB-' . $data['订单编号'];
                            $push['push_txt'] = '订单状态：' . $data['订单状态'] . '【查看详情】';
                            $push['push_url'] = $app_url . "|web|分店用户下单|h5|#FFFFFF|#FFFFFF";
                            $push['push_type'] = trim($jg_user['type']);
                            $push['dd_uid'] = $sp_uid;
                            $push['op'] = 'send';
                            $push_url = $_W['siteroot'] . "app/index.php?i=" . $uniacid . "&c=entry&do=jiguang&m=bsht_tkapp&op=send";
                            $jg_res = curl_request_app($push_url, $push);
                        }
                    }
                    //app推送tb
                    //历史订单修正
                    if (!empty($his_fix)) {
                        //$fix_his = pdo_update('bsht_tbk_order', $his_fix, array('orderid' => $tradeID, 'uniacid' => $_W['uniacid']));
                    }
                    //历史订单修正
                    //写入数据库
                    //记录入库结果
                    if ($isbanddd == 1 && ($data['订单状态'] == '订单付款' || $data['订单状态'] == '订单结算') && $wq_status != 1) {
                        $nb_zd = nb_zd($data['商品信息'], $data['订单状态'], $data['子订单编号'], $data['创建时间'], '123', $data['商品ID'], $isddview, $synctipplus, $ck_u_uid, '', $cate_data['order_type']);
                    }
                    if (!empty($result)) {
                        $resultStr = resultState($resultStr, $data['订单编号'], "1");
                        //成功
                    } else {
                        $resultStr = resultState($resultStr, $data['订单编号'], "0");
                        //失败
                    }
                } else {
                    //etime
                    if ($data['订单状态'] == '订单结算' && !empty($data['结算时间']) && $wq_status != 1) {
                        $etm = array();
                        $etm['etime'] = strtotime($data['结算时间']);
                        $etm['orderstatus'] = '订单结算';
                        $etm['shouru_yongjin'] = $data['效果预估'];
                        $etm['orderid_p'] = $data['订单编号'];
                        pdo_update('bsht_tbk_orderus', $etm, array('orderid' => $data['子订单编号'], 'uniacid' => $_W['uniacid']));
                    }
                    if ($data['订单状态'] == '订单失效') {
                        $etm = array();
                        $etm['etime'] = '';
                        $etm['orderstatus'] = '';
                        $etm['shouru_yongjin'] = $data['效果预估'];
                        $etm['orderid_p'] = $data['订单编号'];
                        pdo_update('bsht_tbk_orderus', $etm, array('orderid' => $data['子订单编号'], 'uniacid' => $_W['uniacid']));
                    }
                    //etime
                    //更新数据
                    $cate_data['status'] = $data['订单状态'] == '订单失效' ? 0 : $thisoid['status'];
                    //信息状态 0失效 1有效
                    $noup = intval($thisoid['noup']);
                    if ($noup == 1) {
                        unset($cate_data['shouru_yongjin']);
                        unset($cate_data['itemtitle']);
                    }
                    if ($thisoid['orderstatus'] == '订单失效') {
                        unset($cate_data['orderstatus']);
                    }
                    if (!empty($thisoid['rid'])) {
                        unset($cate_data['pid2']);
                        unset($cate_data['pid3']);
                        $cate_data['pid2'] = '';
                        $cate_data['pid3'] = '';
                    }
                    if (!empty($thisoid['pid3'])) {
                        unset($cate_data['pid3']);
                    }
                    if ($thisoid['shopid'] > 0 && empty($cate_data['rid']) && !empty($cate_data['shopid']) && $cate_data['shopid'] > 0) {
                        unset($cate_data['shopid']);
                    }
                    if ($thisoid['uid'] > 0) {
                        unset($cate_data['uid']);
                    }
                    if ($thisoid['ddbili'] > 0) {
                        unset($cate_data['ddbili']);
                    }
                    if ($thisoid['jiangli1'] > 0) {
                        unset($cate_data['jiangli1']);
                    }
                    if ($thisoid['jiangli2'] > 0) {
                        unset($cate_data['jiangli2']);
                    }
                    if ($thisoid['jiangli3'] > 0) {
                        unset($cate_data['jiangli3']);
                    }
                    if ($thisoid['sp_bl_lv1'] > 0) {
                        unset($cate_data['sp_bl_lv1']);
                    }
                    if ($thisoid['sp_bl_lv1_lv2'] > 0) {
                        unset($cate_data['sp_bl_lv1_lv2']);
                    }
                    if ($thisoid['sp_bl_lv1_lv3'] > 0) {
                        unset($cate_data['sp_bl_lv1_lv3']);
                    }
                    if ($thisoid['shopid'] > 0) {
                        unset($cate_data['shopid']);
                    }
					//fix
					if ($thisoid['fee1'] > 0) {
                        unset($cate_data['fee1']);
                    }
					if ($thisoid['fee2'] > 0) {
                        unset($cate_data['fee2']);
                    }
					if ($thisoid['fee3'] > 0) {
                        unset($cate_data['fee3']);
                    }
					if ($thisoid['feeall'] > 0) {
                        unset($cate_data['feeall']);
                    }
					//fix
                    if ($noup != 2) {
                        $result = pdo_update('bsht_tbk_order', $cate_data, array('id' => $thisoid['id'], 'orderid' => $thisoid['orderid']));
                    }
                    if ($isodfix == 1) {
                        //清理重复
                        $allsame = pdo_fetchall("select id from " . tablename('bsht_tbk_order') . " where uniacid = '{$uniacid}' AND orderid = '{$thisoid['orderid']}' ");
                        if (!empty($allsame)) {
                            $allnum = count($allsame);
                            if ($allnum > 1) {
                                foreach ($allsame as $k => $v) {
                                    if ($k > 0) {
                                        $del = pdo_delete('bsht_tbk_order', array('id' => $allsame[$k]['id'], 'uniacid' => $uniacid));
                                    }
                                }
                            }
                        }
                        //清理重复
                    }
                    //历史订单修正
                    if (!empty($his_fix) && $noup != 2) {
                        $fix_his = pdo_update('bsht_tbk_order', $his_fix, array('orderid' => $tradeID, 'uniacid' => $_W['uniacid']));
                    }
                    //历史订单修正
                    //更新数据库
                    //记录入库结果
                    if (($data['订单状态'] == '订单付款' || $data['订单状态'] == '订单结算') && $thisoid['orderstatus'] != $data['订单状态'] && $isbanddd == 1 && $wq_status != 1) {
                        $nb_zd = nb_zd($data['商品信息'], $data['订单状态'], $data['子订单编号'], $data['创建时间'], $thisoid['orderstatus'], $data['商品ID'], $isddview, $synctipplus, $ck_u_uid, '', $cate_data['order_type']);
                    }
                    $resultStr = resultState($resultStr, $data['订单编号'], "1");
                    //成功
                }
            }
        }
        if ($dtpid == 1) {
            //清理过期pid
            $delpids = pdo_fetchall("SELECT * FROM " . tablename('bsht_tbk_pids') . " WHERE uniacid = '{$uniacid} ' AND status = 2");
            if (!empty($delpids)) {
                foreach ($delpids as $k => $v) {
                    $this_id = $v['id'];
                    $this_vtime = $v['vtime'];
                    $now_time = time();
                    $pplus = $now_time - $this_vtime;
                    if ($pplus > $dtpid_locktime) {
                        $del = array();
                        $del['status'] = 1;
                        $del['uid'] = 0;
                        $del['iid'] = '';
                        $del['vtime'] = '';
                        pdo_update('bsht_tbk_pids', $del, array('uniacid' => $uniacid, 'id' => $this_id));
                        //清理过期pid-2
                        pdo_delete('bsht_tbk_pids_iid', array('uniacid' => $uniacid, 'uid' => $v['uid']));
                        //清理过期pid-2
                    }
                }
            }
            //清理过期pid
        }
        returnExit($return, 1, "result:" . $resultStr);
        //code值设置为1，表示成功
    } else {
        returnExit($return, 0, "传入订单数据不正确");
        //code值设置为0，表示失败
    }
} elseif ($api == 'postgoods') {
    //获取post过来的商品内容
    $content = htmlspecialchars_decode($_GPC['content']);
    //json解码
    $contentArr = @json_decode($content, true);
    //如果数组不为空
    if (!empty($contentArr['cat']) && !empty($contentArr['goods'])) {
        //商品分类
        $cat = goodsCat(tablename($this->modulename . "_all_cate"), $contentArr['cat']);
        if (empty($cat)) {
            returnExit($return, 0, "分类绑定不正确");
            //code值设置为0，表示失败
        }
        //商品数据
        $goodsDbTable = $this->modulename . "_all_item";
        //商品数据库表名
        $field = tableField(tablename($goodsDbTable));
        //获取商品表的所有字段
        $resultStr = "";
        //记录订单入库结果字符串
        foreach ($contentArr['goods'] as $data) {
            $itemid = $data['商品ID'];
            //格式化商品数据
            $newdata = goodsFormat($cat, $data, $field);
            //print_r($newdata);
            //查询是否存在
            $goodsid = pdo_fetch('select itemid from ' . tablename($goodsDbTable) . " where uniacid='{$_W['uniacid']}'  and itemid='{$itemid}'");
            if (empty($goodsid)) {
                //$newdata['status']=1;//1有效，0下架 ,入库时候设置为1，更新时不处理
                //如果不存在，新增
                $result = pdo_insert($goodsDbTable, $newdata);
            } else {
                //如果已存在，更新
                $result = pdo_update($goodsDbTable, $newdata, array('itemid' => $itemid, 'uniacid' => $_W['uniacid']));
            }
            //记录入库结果
            if (!empty($result)) {
                //添加成功
                $resultStr = resultState($resultStr, $itemid, "1");
            } else {
                //添加失败
                $resultStr = resultState($resultStr, $itemid, "0");
            }
        }
        returnExit($return, 1, "result:" . $resultStr);
        //code值设置为1，表示成功
    } else {
        returnExit($return, 0, "传入商品数据不正确");
        //code值设置为0，表示失败
    }
    returnExit($return, 0, '暂不支持');
} elseif ($api == 'delgoods') {
    //获取post过来的订单内容
    $content = htmlspecialchars_decode($_GPC['content']);
    //json解码
    $contentArr = @json_decode($content, true);
    //订单数据库表名
    $goodsDbTable = $this->modulename . "_all_item";
    //如果where数组不为空
    if (!empty($contentArr['where'])) {
        $whereArr = $contentArr['where'];
        //print_r($whereArr);
        //构造sql语句
        if (!empty($whereArr['销量小于'])) {
            if (!empty($where)) {
                $where .= " or ";
            }
            $where .= " itemmsell<'{$whereArr['销量小于']}' ";
        }
        if (!empty($whereArr['价格小于'])) {
            if (!empty($where)) {
                $where .= " or ";
            }
            $where .= " itemfee2<'{$whereArr['价格小于']}' ";
        }
        if (!empty($whereArr['价格大于'])) {
            if (!empty($where)) {
                $where .= " or ";
            }
            $where .= " itemfee2>'{$whereArr['价格大于']}' ";
        }
        if (!empty($whereArr['佣金小于'])) {
            if (!empty($where)) {
                $where .= " or ";
            }
            $where .= " shouru_yongjin<'{$whereArr['佣金小于']}' ";
        }
        if (!empty($whereArr['佣金比例'])) {
            if (!empty($where)) {
                $where .= " or ";
            }
            $where .= " shouru_bili<'{$whereArr['佣金比例']}' ";
        }
        if (!empty($whereArr['非天猫'])) {
            if (!empty($where)) {
                $where .= " or ";
            }
            $where .= " istmall!=1 ";
        }
        if (!empty($whereArr['非视频单'])) {
            if (!empty($where)) {
                $where .= " or ";
            }
            $where .= " isvideo=0 ";
        }
        if (!empty($whereArr['优惠券过期'])) {
            if (!empty($where)) {
                $where .= " or ";
            }
            $where .= "(itemyhj_etime<>'' and  itemyhj_etime<='" . date('Y-m-d H:i:s') . "') ";
        }
        if (!empty($whereArr['无优惠券'])) {
            if (!empty($where)) {
                $where .= " or ";
            }
            $where .= " (quan_id='' or quan_id is null) ";
        }
        //echo $where;
        if (!empty($where)) {
            //执行删除语句
            $result = pdo_query("DELETE  FROM " . tablename($goodsDbTable) . " WHERE uniacid = '{$_W['uniacid']}' and " . $where);
            if (!empty($result)) {
                returnExit($return, 1, '成功删除' . $result . '件商品');
                //code值设置为1，表示成功
            } else {
                returnExit($return, 1, '暂无符合条件商品');
                //code值设置为1，表示成功
            }
        } else {
            returnExit($return, 0, '传入条件数据不正确');
            //code值设置为1，表示成功
        }
    } elseif (!empty($contentArr['goodsid'])) {
        $count = 0;
        //遍历订单ID数组
        foreach ($contentArr['goodsid'] as $goodsid) {
            //查询是否存在
            $itemid = pdo_fetch('select itemid from ' . tablename($goodsDbTable) . " where uniacid='{$_W['uniacid']}'  and itemid='{$goodsid}'");
            if (!empty($itemid)) {
                //如果已存在，删除
                $result = pdo_delete($goodsDbTable, array('itemid' => $itemid, 'uniacid' => $_W['uniacid']));
                if (!empty($result)) {
                    $count += $result;
                }
            }
        }
        if ($count > 0) {
            returnExit($return, 1, '成功删除' . $count . '件商品');
            //code值设置为1，表示成功
        } else {
            returnExit($return, 1, '暂无符合条件商品');
            //code值设置为1，表示成功
        }
    } elseif (!empty($contentArr['all'])) {
        $result = pdo_delete($goodsDbTable, array('uniacid' => $_W['uniacid']));
        if (!empty($result)) {
            returnExit($return, 1, '成功删除' . $result . '件商品');
            //code值设置为1，表示成功
        } else {
            returnExit($return, 1, '暂无商品');
            //code值设置为1，表示成功
        }
        //无有效参数
    } else {
        returnExit($return, 0, '传入条件数据不正确');
        //code值设置为1，表示成功
    }
} elseif ($api == 'agentadmin') {
    returnExit($return, 18, 'NB淘宝客系统自身已经支持自动审核代理功能，所以无需在程序内使用此功能');
} elseif ($api == 'postjdpid') {
    //订单数据库表名
    $jdpidDbTable = "bsht_jd_pid";
    //获取post过来的订单内容
    $content = htmlspecialchars_decode($_GPC['content']);
    $contentArr = @json_decode($content, true);
    if (empty($contentArr['name']) || empty($contentArr['adzoneid']) || empty($contentArr['pid'])) {
        returnExit($return, 0, '传入数据不正确');
        //code值设置为1，表示成功
    }
    $pid = $contentArr['pid'];
    //pid：完整三段式，adzoneid：推广位ID
    $name = $contentArr['name'];
    //查询是否存在
    $id = pdo_fetch('select id from ' . tablename($jdpidDbTable) . " where uniacid='{$_W['uniacid']}'  and pid='{$pid}'");
    if (empty($id)) {
        //设置入库数据
        $data = array(
            'uniacid' => $_W['uniacid'],
            //公众号ID
            'name' => $name,
            //推广位名称
            'pid' => $pid,
            //推广位ID
            'ctime' => time(),
        );
        //如果不存在，新增
        $result = pdo_insert($jdpidDbTable, $data);
        //记录入库结果
        if (!empty($result)) {
            //添加成功
            returnExit($return, 1, '入库成功');
        } else {
            //添加失败
            returnExit($return, 0, '入库失败');
        }
    } else {
        returnExit($return, 0, 'PID已经存在');
    }
} elseif ($api == 'postjdgoods') {
    $uniacid = 0;
    //公众号ID(为0的情况下是共用商品库) 分库的情况使用：$uniacid=$_W['uniacid'];
    //获取post过来的商品内容
    $content = htmlspecialchars_decode($_GPC['content']);
    //json解码
    $contentArr = @json_decode($content, true);
    //如果数组不为空
    if (!empty($contentArr['cat']) && !empty($contentArr['goods'])) {
        //商品分类
        $cat = goodsCatJD(tablename("bsht_jd_cat"), $contentArr['cat']);
        if (empty($cat)) {
            returnExit($return, 0, "分类绑定不正确");
            //code值设置为0，表示失败
        }
        //商品数据
        $goodsDbTable = "bsht_jd_item";
        //商品数据库表名
        $field = tableField(tablename($goodsDbTable));
        //获取商品表的所有字段
        $resultStr = "";
        //记录订单入库结果字符串
        foreach ($contentArr['goods'] as $data) {
            $itemid = $data['商品ID'];
            //格式化商品数据
            $newdata = goodsFormatJD($cat, $data, $field);
            //print_r($newdata);
            //查询是否存在
            $goodsid = pdo_fetch('select goods_id from ' . tablename($goodsDbTable) . " where uniacid='{$uniacid}'  and goods_id='{$itemid}'");
            if (empty($goodsid)) {
                //$newdata['status']=1;//1有效，0下架 ,入库时候设置为1，更新时不处理
                //如果不存在，新增
                $result = pdo_insert($goodsDbTable, $newdata);
            } else {
                //如果已存在，更新
                $result = pdo_update($goodsDbTable, $newdata, array('goods_id' => $itemid, 'uniacid' => $uniacid));
            }
            //记录入库结果
            if (!empty($result)) {
                //添加成功
                $resultStr = resultState($resultStr, $itemid, "1");
            } else {
                //添加失败
                $resultStr = resultState($resultStr, $itemid, "0");
            }
        }
        returnExit($return, 1, "result:" . $resultStr);
        //code值设置为1，表示成功
    } else {
        returnExit($return, 0, "传入商品数据不正确");
        //code值设置为0，表示失败
    }
    returnExit($return, 0, '暂不支持');
} elseif ($api == 'deljdgoods') {
    $uniacid = 0;
    //公众号ID(为0的情况下是共用商品库) 分库的情况使用：$uniacid=$_W['uniacid'];
    //获取post过来的订单内容
    $content = htmlspecialchars_decode($_GPC['content']);
    //json解码
    $contentArr = @json_decode($content, true);
    //订单数据库表名
    $goodsDbTable = "bsht_jd_item";
    //如果where数组不为空
    if (!empty($contentArr['where'])) {
        $whereArr = $contentArr['where'];
        //print_r($whereArr);
        //构造sql语句
        if (!empty($whereArr['价格小于'])) {
            if (!empty($where)) {
                $where .= " or ";
            }
            $where .= " coupon_price<'{$whereArr['价格小于']}' ";
        }
        if (!empty($whereArr['价格大于'])) {
            if (!empty($where)) {
                $where .= " or ";
            }
            $where .= " coupon_price>'{$whereArr['价格大于']}' ";
        }
        if (!empty($whereArr['佣金小于'])) {
            if (!empty($where)) {
                $where .= " or ";
            }
            $where .= " yongjin<'{$whereArr['佣金小于']}' ";
        }
        if (!empty($whereArr['佣金比例'])) {
            if (!empty($where)) {
                $where .= " or ";
            }
            $where .= " commission<'{$whereArr['佣金比例']}' ";
        }
        if (!empty($whereArr['非京东配送'])) {
            if (!empty($where)) {
                $where .= " or ";
            }
            $where .= " shop_type!=1 ";
        }
        if (!empty($whereArr['非精选好货'])) {
            if (!empty($where)) {
                $where .= " or ";
            }
            $where .= " goods_level!=20 ";
        }
        if (!empty($whereArr['优惠券过期'])) {
            if (!empty($where)) {
                $where .= " or ";
            }
            $where .= "(discount_end<>'' and  discount_end<='" . time() . "') ";
        }
        if (!empty($whereArr['无优惠券'])) {
            if (!empty($where)) {
                $where .= " or ";
            }
            $where .= " (discount_link='' or discount_link is null) ";
        }
        //echo $where;
        if (!empty($where)) {
            //执行删除语句
            $result = pdo_query("DELETE  FROM " . tablename($goodsDbTable) . " WHERE uniacid = '{$uniacid}' and " . $where);
            if (!empty($result)) {
                returnExit($return, 1, '成功删除' . $result . '件商品');
                //code值设置为1，表示成功
            } else {
                returnExit($return, 1, '暂无符合条件商品');
                //code值设置为1，表示成功
            }
        } else {
            returnExit($return, 0, '传入条件数据不正确');
            //code值设置为1，表示成功
        }
    } elseif (!empty($contentArr['goodsid'])) {
        $count = 0;
        //遍历订单ID数组
        foreach ($contentArr['goodsid'] as $goodsid) {
            //查询是否存在
            $itemid = pdo_fetch('select goods_id from ' . tablename($goodsDbTable) . " where uniacid='{$uniacid}'  and goods_id='{$goodsid}'");
            if (!empty($itemid)) {
                //如果已存在，删除
                $result = pdo_delete($goodsDbTable, array('goods_id' => $itemid, 'uniacid' => $uniacid));
                if (!empty($result)) {
                    $count += $result;
                }
            }
        }
        if ($count > 0) {
            returnExit($return, 1, '成功删除' . $count . '件商品');
            //code值设置为1，表示成功
        } else {
            returnExit($return, 1, '暂无符合条件商品');
            //code值设置为1，表示成功
        }
    } elseif (!empty($contentArr['all'])) {
        $result = pdo_delete($goodsDbTable, array('uniacid' => $uniacid));
        if (!empty($result)) {
            returnExit($return, 1, '成功删除' . $result . '件商品');
            //code值设置为1，表示成功
        } else {
            returnExit($return, 1, '暂无商品');
            //code值设置为1，表示成功
        }
        //无有效参数
    } else {
        returnExit($return, 0, '传入条件数据不正确');
        //code值设置为1，表示成功
    }
} elseif ($api == 'postjdorder') {
    //获取post过来的订单内容
    $content = htmlspecialchars_decode($_GPC['content']);
    $contentArr = @json_decode($content, true);
    $ddbili = intval($setting['ddbili']);
    //json解码
    //判断传入订单数据是否为空
    if (!empty($contentArr)) {
        //定义记录订单入库结果的变量
        $resultStr = "";
        //遍历订单数据
        foreach ($contentArr as $orderid => $v) {
            //读取常用参数
            $ctime = strtotime($v[0]['orderTime']);
            //下单时间
            $otime = $v[0]['finishTime'];
            //订单完成时间
            $otime = $otime == 0 || $otime == "0" ? "" : strtotime($otime);
            $etime = $v[0]['payMonth'];
            //结算时间
            $etime = $etime == 0 || $etime == "0" ? "" : strtotime($etime);
            $pid = $v[0]['positionId'];
            //pid取推广位id
            //查询shopid
            $shopid = 0;
            $shop = pdo_fetch("SELECT id,status,glopenid FROM " . tablename('bsht_tbk_shop') . " WHERE uniacid = '{$uniacid}' AND jd_pid = '{$pid}' AND status = 2 ");
            if (!empty($shop)) {
                $shopid = intval($shop['id']);
            }
            $list = array();
            $vnum = count($v);
            if ($vnum == 1) {
                //格式化数据
                $list['orderid'] = $orderid;
                $list['shopid'] = $shopid;
                $list['itempic'] = '';
                $list['count'] = $v[0]['skuNum'];
                $list['pid'] = $pid;
                $list['ctime'] = substr($ctime, 0, 10);
                $list['otime'] = substr($otime, 0, 10);
                $list['etime'] = substr($etime, 0, 10);
                $list['orderstatus'] = $v[0]['validCode'];
                $list['itemtitle'] = $v[0]['skuName'];
                $list['itemid'] = $v[0]['skuId'];
                $list['orderfee'] = $v[0]['estimateCosPrice'];
                $list['shouru_bili'] = $v[0]['commissionRate'] * $v[0]['finalRate'] / 100;
                $list['shouru_yongjin'] = $v[0]['estimateFee'];
                //$list['lmbl'] = $v[0]['finalRate'];
            }
            if ($vnum > 1) {
                //同一订单号存在多个商品的情况
                //排序
                $sort = array('direction' => 'SORT_DESC', 'field' => 'estimateFee');
                $arrSort = array();
                foreach ($v as $uniqid => $row) {
                    if (empty($row['estimateFee'])) {
                        $row['estimateFee'] = 0;
                    }
                    foreach ($row as $key => $value) {
                        $arrSort[$key][$uniqid] = $value;
                    }
                }
                if ($sort['direction']) {
                    array_multisort($arrSort[$sort['field']], constant($sort['direction']), $v);
                }
                //格式化数据
                $list['orderid'] = $orderid;
                $list['shopid'] = $shopid;
                $list['itempic'] = '';
                $list['pid'] = $pid;
                $list['ctime'] = substr($ctime, 0, 10);
                $list['otime'] = substr($otime, 0, 10);
                $list['etime'] = substr($etime, 0, 10);
                $list['orderstatus'] = $v[0]['validCode'];
                $list['itemtitle'] = $v[0]['skuName'];
                $list['itemid'] = $v[0]['skuId'];
                $list['shouru_bili'] = $v[0]['commissionRate'] * $v[0]['finalRate'] / 100;
                foreach ($v as $k => $vv) {
                    //合并相关数据
                    $list['count'] += $v[$k]['skuNum'];
                    $list['orderfee'] += $v[$k]['estimateCosPrice'];
                    $list['shouru_yongjin'] += $v[$k]['estimateFee'];
                }
            }
            $ck = pdo_fetch("SELECT * FROM " . tablename('bsht_jd_order') . " WHERE uniacid = '{$uniacid}' AND orderid='{$orderid}' ");
            $noup = intval($ck['noup']);
            if (!empty($ck)) {
                //更新数据
                if ($noup == 1) {
                    unset($list['shouru_yongjin']);
                    unset($list['itemtitle']);
                }
                $result = pdo_update('bsht_jd_order', $list, array('id' => $ck['id']));
                $resultStr = resultState($resultStr, $orderid, "1");
                //$list['ddbili'] = $ck['ddbili'];
                //$list['status'] = $ck['status'];
                //$list['uniacid'] = $ck['uniacid'];
                //$list['sta'] = 'upd';
            } else {
                //新增数据
                if ($ddbili > 0) {
                    $list['ddbili'] = $ddbili;
                }
                $list['status'] = 1;
                $list['uniacid'] = $uniacid;
                $result = pdo_insert('bsht_jd_order', $list);
                //app推送jd
                $is_fdpush = intval($plus_set['is_fdpush']);
                if ($appmsg == 1 && $is_fdpush == 1 && !empty($shop) && !empty($shop['glopenid']) && $result) {
                    $this_user = pdo_fetch("SELECT id,uid FROM " . tablename('bsht_tbk_user') . " WHERE uniacid = '{$uniacid}' AND openid = '{$shop['glopenid']}' ORDER BY id DESC");
                    $sp_uid = intval($this_user['uid']);
                    $sp_id = intval($shop['id']);
                    $jg_user = pdo_fetch("SELECT * FROM " . tablename('bsht_tbk_app_user') . " WHERE uniacid = '{$uniacid}' AND uid = '{$sp_uid}' ORDER BY id DESC");
                    if (!empty($jg_user) && $sp_uid > 0 && $sp_id > 0) {
                        $app_url = $_W['siteroot'] . "app/index.php?i=" . $uniacid . "&c=entry&op=m&shopid=" . $sp_id . "&do=uc_shop_order_all&m=bsht_tbkdl&tp=jd&fm=xcx&to=nbapp&orderid=" . $list['orderid'];
                        $push = array();
                        $push['registrationId'] = trim($jg_user['registrationId']);
                        $push['push_tit'] = '〖分店〗订单：JD-' . $list['orderid'];
                        $push['push_txt'] = '订单状态：' . $list['orderstatus'] . '【查看详情】';
                        $push['push_url'] = $app_url . "|web|分店用户下单|h5|#FFFFFF|#FFFFFF";
                        $push['push_type'] = trim($jg_user['type']);
                        $push['dd_uid'] = $sp_uid;
                        $push['op'] = 'send';
                        $push_url = $_W['siteroot'] . "app/index.php?i=" . $uniacid . "&c=entry&do=jiguang&m=bsht_tkapp&op=send";
                        $jg_res = curl_request_app($push_url, $push);
                    }
                }
                //app推送jd
                if (!empty($result)) {
                    $resultStr = resultState($resultStr, $orderid, "1");
                    //成功
                } else {
                    $resultStr = resultState($resultStr, $orderid, "0");
                    //失败
                }
                //$list['sta'] = 'ins';
            }
        }
        returnExit($return, 1, "result:" . $resultStr);
        //code值设置为1，表示成功
    } else {
        returnExit($return, 0, "传入订单数据不正确");
        //code值设置为0，表示失败
    }
} elseif ($api == 'postpddorder') {
    //拼多多订单入库
    //获取post过来的订单内容
    $content = htmlspecialchars_decode($_GPC['content']);
    $contentArr = @json_decode($content, true);
    //json解码
    //判断传入订单数据是否为空
    if (!empty($contentArr)) {
        //定义记录订单入库结果的变量
        $resultStr = "";
        //遍历订单数据
        foreach ($contentArr as $orderid => $orderdata) {
            //格式化订单数据
            $newdata = orderFormatPdd($orderdata);
            //获取shopid
            $pid = $orderdata['pid'];
            $shop = pdo_fetch("SELECT id,status,glopenid FROM " . tablename('bsht_tbk_shop') . " WHERE uniacid = '{$uniacid}' AND pdd_pid = '{$pid}'");
            $newdata['shopid'] = !empty($shop) ? intval($shop['id']) : 0;
            //查询订单是否存在
            $thisoid = pdo_fetch('select * from ' . tablename('bsht_pdd_order') . " where uniacid = '{$uniacid}' AND orderid = '{$orderid}' ");
            $noup = intval($thisoid['noup']);
            if (empty($thisoid)) {
                $newdata['status'] = 1;
                //如果不存在，新增数据
                $result = pdo_insert('bsht_pdd_order', $newdata);
                //app推送pdd
                $is_fdpush = intval($plus_set['is_fdpush']);
                if ($appmsg == 1 && $is_fdpush == 1 && !empty($shop) && !empty($shop['glopenid']) && $result) {
                    $this_user = pdo_fetch("SELECT id,uid FROM " . tablename('bsht_tbk_user') . " WHERE uniacid = '{$uniacid}' AND openid = '{$shop['glopenid']}' ORDER BY id DESC");
                    $sp_uid = intval($this_user['uid']);
                    $sp_id = intval($shop['id']);
                    $jg_user = pdo_fetch("SELECT * FROM " . tablename('bsht_tbk_app_user') . " WHERE uniacid = '{$uniacid}' AND uid = '{$sp_uid}' ORDER BY id DESC");
                    if (!empty($jg_user) && $sp_uid > 0 && $sp_id > 0) {
                        $app_url = $_W['siteroot'] . "app/index.php?i=" . $uniacid . "&c=entry&op=m&shopid=" . $sp_id . "&do=uc_shop_order_all&m=bsht_tbkdl&tp=pdd&fm=xcx&to=nbapp&orderid=" . $newdata['orderid'];
                        $push = array();
                        $push['registrationId'] = trim($jg_user['registrationId']);
                        $push['push_tit'] = '〖分店〗订单：PDD-' . $newdata['orderid'];
                        $push['push_txt'] = '订单状态：' . $newdata['orderstatus'] . '【查看详情】';
                        $push['push_url'] = $app_url . "|web|分店用户下单|h5|#FFFFFF|#FFFFFF";
                        $push['push_type'] = trim($jg_user['type']);
                        $push['dd_uid'] = $sp_uid;
                        $push['op'] = 'send';
                        $push_url = $_W['siteroot'] . "app/index.php?i=" . $uniacid . "&c=entry&do=jiguang&m=bsht_tkapp&op=send";
                        $jg_res = curl_request_app($push_url, $push);
                    }
                }
                //app推送pdd
                if (!empty($result)) {
                    $resultStr = resultState($resultStr, $orderid, "1");
                    //成功
                } else {
                    $resultStr = resultState($resultStr, $orderid, "0");
                    //失败
                }
            } else {
                if ($noup == 1) {
                    unset($newdata['shouru_yongjin']);
                    unset($newdata['itemtitle']);
                }
                $newdata['status'] = $thisoid['status'];
                //如果存在，更新数据
                $result = pdo_update('bsht_pdd_order', $newdata, array('id' => $thisoid['id'], 'orderid' => $thisoid['orderid']));
                $resultStr = resultState($resultStr, $orderid, "1");
                //成功
            }
        }
        returnExit($return, 1, "result:" . $resultStr);
        //code值设置为1，表示成功
    } else {
        returnExit($return, 0, "传入订单数据不正确");
        //code值设置为0，表示失败
    }
} elseif ($api == 'postviporder') {
    //唯品会订单入库
    //获取post过来的订单内容
    $content = htmlspecialchars_decode($_GPC['content']);
    $contentArr = @json_decode($content, true);
    //json解码
    //判断传入订单数据是否为空
    if (!empty($contentArr)) {
        //定义记录订单入库结果的变量
        $resultStr = "";
        //遍历订单数据
        foreach ($contentArr as $orderid => $orderdata) {
            //格式化订单数据
            $newdata = orderFormatVip($orderdata);
            //查询订单是否存在
            //file_put_contents(IA_ROOT."/addons/bsht_tbk/vip.txt","\n mc:".json_encode($newdata)."-",FILE_APPEND);
            $thisoid = pdo_fetch('select * from ' . tablename('bsht_vip_order') . " where uniacid = '{$uniacid}' AND ordermd5 = '{$newdata['ordermd5']}' ");
            if (empty($thisoid)) {
                $newdata['status'] = 1;
                //如果不存在，新增数据
                $result = pdo_insert('bsht_vip_order', $newdata);
                //app推送唯品会，你来填充下
                //app推送唯品会，你来填充下
                if (!empty($result)) {
                    $resultStr = resultState($resultStr, $orderid, "1");
                    //成功
                } else {
                    $resultStr = resultState($resultStr, $orderid, "0");
                    //失败
                }
            } else {
                if ($newdata['orderstatus'] == 8) {
                    $etm = array();
                    $etm['etime'] = '';
                    $etm['orderstatus'] = '';
                    pdo_update('bsht_tbk_orderus', $etm, array('id' => $thisoid['id'], 'ordermd5' => $thisoid['ordermd5']));
                }
                $newdata['status'] = $thisoid['status'];
                //如果存在，更新数据
                $noup = intval($thisoid['noup']);
                if ($noup == 1) {
                    unset($newdata['shouru_yongjin']);
                    unset($newdata['itemtitle']);
                }
                $result = pdo_update('bsht_vip_order', $newdata, array('id' => $thisoid['id'], 'ordermd5' => $thisoid['ordermd5']));
                $resultStr = resultState($resultStr, $orderid, "1");
                //成功
            }
        }
        returnExit($return, 1, "result:" . $resultStr);
        //code值设置为1，表示成功
    } else {
        returnExit($return, 0, "传入订单数据不正确");
        //code值设置为0，表示失败
    }
} elseif ($api == 'timetask') {
    if (!empty($op)) {
        $filename = IA_ROOT . "/addons/bsht_tbk/inc/mobile/timetask_" . $op . ".inc.php";
        if (file_exists($filename) !== false) {
            include IA_ROOT . "/addons/bsht_tbk/inc/mobile/timetask_" . $op . ".inc.php";
            returnExit($return, 0, '任务执行超时(或者任务任务文件未正常返回信息)');
        }
    }
    //【不带返回参数测试】
    if ($op == "pinduoduo") {
        //1、执行拼多多订单同步函数
        //2、返回结果
        returnExit($return, 1, '拼多多订单同步成功');
        //【带传入参数、带回传参数测试】
    } elseif ($op == 'jingdong') {
        //0、【接收参数】
        $day = empty($_GPC['day']) ? 1 : $_GPC['day'];
        //接收要同步的天数参数(post参数，即软件定时任务里面设置的任务参数)
        $page = empty($_GPC['page']) ? 1 : $_GPC['page'];
        //接收页码参数(回传参数)
        //1、【执行京东订单同步函数】
        $message = '同步京东近' . $day . '天订单,第' . $page . '页成功';
        //返回信息
        //2、【构造回传参数】
        //判断是否执行到最后一页（我这里假设最多只有10页，具体情况根据业务代码判断是否最后一页）
        if ($page >= 10) {
            //执行到最后1页，不回传参数即可
        } else {
            $page++;
            //页码加1
            //追加回传参数 param 为下次要回传的参数字段，支持任意参数构造(命名注意不要和系统已有的post参数冲突)；  sleep 是控制访问下一页的间隔时间参数，单位为秒
            $return['timetaskdata'] = array('param' => 'test1=111&test2=222&page=' . $page, 'sleep' => 1);
            //(test1=111&test2=222 为其他测试参数，可以删除)
        }
        //3、【返回结果】
        returnExit($return, 1, $message);
    } else {
        returnExit($return, 0, '任务标识不正确');
    }
} else {
    returnExit($return, 0, '未传入有效API参数');
}
// +----------------------------------------
// | 商品采集相关函数
// +----------------------------------------
//格式化商品数据
function goodsFormat($cat, $data, $field)
{
    global $_W;
    //处理商品类目
    if (empty($cat[$data['商品类目']])) {
        $data['商品类目'] = 0;
    } else {
        $data['商品类目'] = $cat[$data['商品类目']];
    }
    //处理店铺类型
    if ($data['店铺类型'] == 'B') {
        $data['店铺类型'] = 1;
    } else {
        $data['店铺类型'] = 0;
    }
    //处理佣金计划
    if ($data['佣金计划'] == '通用计划') {
        $data['佣金计划'] = 0;
    } elseif ($data['佣金计划'] == '鹊桥活动') {
        $data['佣金计划'] = 1;
    } elseif ($data['佣金计划'] == '定向计划') {
        $data['佣金计划'] = 2;
    } else {
        $data['佣金计划'] = 2;
    }
    //处理优惠券数量
    if (empty($data['优惠券总数量'])) {
        $data['优惠券总数量'] = rand(10000, 50000);
    }
    //生成随机的优惠券总数
    if (empty($data['优惠券领取量'])) {
        $data['优惠券领取量'] = intval($data['优惠券总数量'] * (rand(60, 98) / 100));
    }
    //生成随机的优惠券领取量
    $data['优惠券剩余量'] = $data['优惠券总数量'] - $data['优惠券领取量'];
    //计算优惠券剩余量
    if (empty($data['卖家昵称'])) {
        $data['卖家昵称'] = $data['商品文案'];
    }
    //处理采集来源
    /*
    if($data['采集来源']=='大淘客'){
    	$data['采集来源']='dtk';
    }elseif($data['采集来源']=='好单库'){
    	$data['采集来源']='hdk';
    }elseif($data['采集来源']=='轻淘客'){
    	$data['采集来源']='qtk';
    }elseif($data['采集来源']=='一手单'){
    	$data['采集来源']='ysd';
    }
    */
    $newData = array(
        'uniacid' => $_W['uniacid'],
        //'displayorder'=>0,//排序，不处理
        'itemid' => $data['商品ID'],
        //商品ID、、带$this->nbde的需要编码位base64，我来解码
        'title' => trimExcessChar($data['商品标题']),
        //商品标题
        'd_title' => trimExcessChar($data['商品短标题']),
        //商品短标题
        'itempic' => $data['商品图片'],
        //商品图片
        'shoptitle' => $data['卖家昵称'],
        //店铺标题
        'wenan' => trimExcessChar($data['商品文案']),
        //文案
        'itemfee' => $data['商品原价'],
        //售价
        'itemfee2' => $data['商品券后价'],
        //券后价
        'itemmsell' => $data['商品销量'],
        //销量
        'itemyhj_zl' => $data['优惠券总数量'],
        //优惠券总量
        'itemyhj_yl' => $data['优惠券剩余量'],
        //优惠券余量
        'itemyhj_stime' => date('Y-m-d H:i:s', $data['优惠券开始时间']),
        //优惠券开始时间
        'itemyhj_etime' => date('Y-m-d H:i:s', $data['优惠券结束时间']),
        //优惠券结束时间
        'cate_id' => $data['商品类目'],
        //需要入库的分类ID
        'atime' => TIMESTAMP,
        'fm' => 'dtk',
        //采集来源
        'shouru_bili' => $data['佣金比例'],
        //佣金比
        'shouru_yongjin' => $data['预计佣金'],
        //预计收入
        'quan_id' => $data['优惠券ID'],
        //优惠券ID
        'maijia_id' => $data['卖家ID'],
        //商家ID
        'istmall' => $data['店铺类型'],
        //1天猫，0淘宝
        'tktype' => $data['佣金计划'],
        //申请计划后的状态，0通用，1，2鹊桥
        'itemsurl' => $data['优惠券链接'],
        //商品短链接
        'itemurl' => $data['优惠券链接'],
        //商品链接
        'itemyhj_url' => $data['优惠券链接'],
        //优惠券链接
        'quan_link' => $data['优惠券链接'],
        //WAP优惠券地址
        'itemyhj_tit' => $data['优惠券使用条件'],
    );
    //处理咚咚抢商品
    if ($data['采集来源'] == '咚咚抢') {
        $newData['ddqatime'] = time();
        //咚咚抢添加时间
        $newData['ddqstime'] = date('H', $data['活动开始时间']);
        //咚咚抢排期时间
        $newData['isms'] = 1;
        //秒杀设置为1
    }
    //处理视频单
    if (!empty($data['商品视频ID'])) {
        $newData['isvideo'] = 1;
        //是否视频单
        $newData['videourl'] = 'http://cloud.video.taobao.com/play/u/1/p/1/e/6/t/1/' . $data['商品视频ID'] . '.mp4';
    }
    //处理活动类型
    if ($data['活动类型'] == '聚划算') {
        $newData['isjhs'] = 1;
        //是否聚划算
    } elseif ($data['活动类型'] == '淘抢购') {
        $newData['istqg'] = 1;
        //是否淘抢购
    }
    //过滤数据库不支持的字段(因为各个版本的数据库字段有差异，所以要处理下)
    foreach ($newData as $key => $value) {
        if (isset($field[$key])) {
            $saveData[$key] = $value;
        }
    }
    return $saveData;
}
//处理商品分类
function goodsCat($table, $softCat)
{
    global $_W;
    //查询数据库的分类名和对应ID
    $allCat = pdo_fetchall('select name,id from ' . $table . " where uniacid='{$_W['uniacid']}'");
    //print_r($allCat);
    foreach ($allCat as $cat) {
        $cat['name'] = str_replace("其他", "其它", $cat['name']);
        //兼容分类名字为“其他”时的情况
        $dbCat[$cat['name']] = $cat['id'];
    }
    //将程序商品分类关系转化成对应的id
    foreach ($softCat as $key => $value) {
        $value = str_replace("其他", "其它", $value);
        //兼容分类名字为“其他”时的情况
        if (isset($dbCat[$value])) {
            $newCat[$key] = $dbCat[$value];
        }
    }
    //print_r($softCat);
    return $newCat;
}
// +----------------------------------------
// | 订单入库相关函数
// +----------------------------------------
//格式化订单数据
function orderFormat($contentArr)
{
    global $_W;
    //将结构化订单数组拆分为子订单数组
    $orderData = array();
    foreach ($contentArr as $tradeParentData) {
        //遍历子订单数据
        foreach ($tradeParentData as $data) {
            //初步处理数据
            $data['创建时间'] = str_replace("/", "-", $data['创建时间']);
            $data['点击时间'] = str_replace("/", "-", $data['点击时间']);
            $data['结算时间'] = str_replace("/", "-", $data['结算时间']);
            if ($data['渠道关系ID'] == 'null' || $data['渠道关系ID'] == null) {
                $data['渠道关系ID'] = '';
            }
            if (!empty($data['结算金额']) && $data['结算金额'] > 0 && $data['结算金额'] != $data['付款金额']) {
                $data['付款金额'] = $data['结算金额'];
            }
            if (!empty($data['预估收入']) && $data['预估收入'] > 0 && $data['预估收入'] != $data['效果预估']) {
                $data['效果预估'] = $data['预估收入'];
            }
            //处理维权订单
            if (strpos($data['维权状态'], "维权创建") !== false || strpos($data['维权状态'], "等待处理") !== false) {
                $data['订单状态'] = '订单付款';
                $data['效果预估'] = $data['效果预估'] - $data['维权应返还金额'];
                //强制将订单状态设置为：订单付款
            } elseif (strpos($data['维权状态'], "维权成功") !== false) {
                $data['效果预估'] = $data['效果预估'] - $data['维权应返还金额'];
                if ($data['效果预估'] <= 0) {
                    $data['效果预估'] = 0;
                    $data['订单状态'] = '订单失效';
                }
                //强制将订单状态设置为：订单失效
            } elseif (strpos($str, "维权失败") !== false) {
                //$data['订单状态']='订单结算';//强制将订单状态设置为：订单结算(因为订单也有可能本身是其他状态，所以此处不做处理即可)
            }
            //记录到新数组
            $orderData[$data['子订单编号']] = $data;
        }
    }
    return $orderData;
}
function nb_zd($itemtitle, $orderstatus, $orderid, $citme, $orderstatus_old = '123', $itemid = '', $isddview = 0, $synctipplus, $uid = '0', $orderid_p = '', $order_type = '')
{
    //file_put_contents(IA_ROOT."/addons/bsht_tbk/oid.txt","\n OID:".$orderid."-",FILE_APPEND);
    global $_W;
    $uniacid = $_W['uniacid'];
    load()->func('communication');
    $noapi = 0;
    $moreiid = 0;
    $uid = intval($uid);
    //etime
    if ($orderstatus == '订单结算' && !empty($etime)) {
        $etm = array();
        $etm['orderstatus'] = '订单结算';
        $etm['etime'] = strtotime($etime);
        pdo_update('bsht_tbk_orderus', $etm, array('orderid' => $orderid, 'uniacid' => $_W['uniacid']));
    }
    //etime
    if (($orderstatus == '订单付款' || $orderstatus == '订单结算' || $orderstatus != '订单失效') && $orderstatus != $orderstatus_old) {
        if ($uid > 0 && $isddview == 1) {
            $dd_user = pdo_fetch('SELECT * FROM ' . tablename('bsht_tbk_user') . ' WHERE uniacid = :uniacid AND uid = :uid AND status = 1', array(':uniacid' => $_W['uniacid'], ':uid' => $uid));
            if (!empty($dd_user)) {
                $noapi = 0;
                $moreiid = 0;
            }
        } else {
            $dd_user = pdo_fetch('SELECT * FROM ' . tablename('bsht_tbk_orderus') . ' WHERE uniacid = :uniacid AND orderid = :orderid AND status = 1', array(':uniacid' => $_W['uniacid'], ':orderid' => $orderid));
            $exists_lastiid = pdo_tableexists('bsht_lastiid');
            if (empty($dd_user) && $orderstatus != '订单失效' && $isddview == 1 && $exists_lastiid) {
                $now = time();
                $beginToday = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
                $endToday = mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')) - 1;
                $dd_user_all = pdo_fetchall("SELECT * FROM " . tablename('bsht_lastiid') . " WHERE uniacid = '{$_W['uniacid']}' AND lastiid = '{$itemid}' AND ctime < {$endToday} AND ctime > {$beginToday} ORDER BY id DESC ");
                $cknum = count($dd_user_all);
                if (!empty($dd_user_all) && $cknum == 1) {
                    $dd_ctime = strtotime($citme);
                    $plustime = $dd_ctime - $dd_user_all[0]['ctime'];
                    if ($plustime < 300) {
                        $dd_user = $dd_user_all[0];
                        $moreiid = 0;
                    } else {
                        if ($synctipplus == 1) {
                            $ordermsg = "【商品】" . $itemtitle . "\n【状态】" . $orderstatus . "\n\n如您已购买此宝贝，请在下方聊天窗口发送订单号绑定";
                            $fixsend = sendtxt18($dd_user_all[0]['openid'], $ordermsg, $uniacid);
                        }
                    }
                }
                if (!empty($dd_user_all) && $cknum > 1) {
                    $dd_ctime = strtotime($citme);
                    foreach ($dd_user_all as $k => $v) {
                        $plustime = $dd_ctime - $dd_user_all[$k]['ctime'];
                        if ($plustime < 300) {
                            $orderidsmall = substr($orderid, -6);
                            $ordermsg = "【商品】" . $itemtitle . "\n【状态】" . $orderstatus . "\n\n此订单多人购买，请在下方聊天窗口发送订单号绑定";
                            $fixsend = sendtxt18($dd_user_all[$k]['openid'], $ordermsg, $uniacid);
                            if ($order_type != '饿了么' && !empty($orderidsmall)) {
                                pdo_update('bsht_tbk_user', array('orderidsmall' => ''), array('openid' => $dd_user_all[$k]['openid']));
                            }
                        } else {
                            if ($synctipplus == 1) {
                                $ordermsg = "【商品】" . $itemtitle . "\n【状态】" . $orderstatus . "\n\n如您已购买此宝贝，请在下方聊天窗口发送订单号绑定";
                                $fixsend = sendtxt18($dd_user_all[$k]['openid'], $ordermsg, $uniacid);
                            }
                            if ($order_type != '饿了么' && !empty($orderidsmall)) {
                                pdo_update('bsht_tbk_user', array('orderidsmall' => ''), array('openid' => $dd_user_all[$k]['openid']));
                            }
                        }
                    }
                    pdo_delete('bsht_lastiid', array('uniacid' => $_W['uniacid'], 'lastiid' => $itemid));
                    $dd_user = "";
                    $moreiid = 1;
                }
            }
            if (empty($dd_user) && $orderstatus != '订单失效' && $moreiid != 1) {
                ///file_put_contents(IA_ROOT."/addons/bsht_tbk/log.txt","\n rec:666-",FILE_APPEND);
                $orderidsmall = substr($orderid, -6);
                if (!empty($orderidsmall)) {
                    $dd_user_all = pdo_fetchall('SELECT * FROM ' . tablename('bsht_tbk_user') . ' WHERE uniacid = :uniacid AND orderidsmall = :orderidsmall', array(':uniacid' => $_W['uniacid'], ':orderidsmall' => $orderidsmall));
                    if (!empty($dd_user_all)) {
                        $dd_user_num = count($dd_user_all);
                        if ($dd_user_num == 1) {
                            $dd_user = $dd_user_all[0];
                        } else {
                            foreach ($dd_user_all as $k => $v) {
                                $ordermsg = "【商品】" . $itemtitle . "\n【状态】" . $orderstatus . "\n此订单多人购买，请在下方聊天窗口发送订单号绑定";
                                $osend = sendtxt18($v['openid'], $ordermsg, $uniacid);
                                //del oid
                                $data_del = array();
                                $data_del['orderidsmall'] = '';
                                pdo_update('bsht_tbk_user', $data_del, array('id' => $v['id']));
                                //del oid
                            }
                            $noapi = 1;
                        }
                    }
                }
            }
        }
        if (!empty($dd_user) && $noapi != 1 && $moreiid != 1) {
            load()->func('communication');
            $ckok = 0;
            //验证
            if ($orderstatus == '订单结算') {
                $ckodus = pdo_fetch("SELECT * FROM " . tablename('bsht_tbk_orderus') . " WHERE uniacid = '{$_W['uniacid']}' AND orderid = '{$orderid}' AND status = 1 AND openid = '{$dd_user['openid']}'");
                if (!empty($ckodus)) {
                    $ckok = 1;
                }
            } else {
                $ckok = 1;
            }
            //验证
            if ($ckok == 1) {
                $wxAPIUrl = $_W['siteroot'] . "app/index.php?c=entry&i=" . $_W['uniacid'] . "&m=bsht_tbk&do=uc_dd&op=add&plus=1&auto=1&orderid=" . $orderid . "&uid=" . $uid . "&openid=" . $dd_user['openid'];
                $resp = curl_rest($wxAPIUrl);
            } else {
                if ($uid > 0) {
                    $wxAPIUrl = $_W['siteroot'] . "app/index.php?c=entry&i=" . $_W['uniacid'] . "&m=bsht_tbk&do=uc_dd&op=add&plus=1&auto=1&orderid=" . $orderid . "&uid=" . $uid . "&openid=";
                    $resp = curl_rest($wxAPIUrl);
                }
            }
            if (!empty($dd_user) && !empty($itemid)) {
                pdo_update('bsht_tbk_user', array('lastiid' => ''), array('openid' => $dd_user['openid'], 'lastiid' => $itemid, 'uniacid' => $_W['uniacid']));
                if ($exists_lastiid) {
                    pdo_delete('bsht_lastiid', array('uniacid' => $_W['uniacid'], 'lastiid' => $itemid));
                }
            }
            return 1;
        } else {
            if ($uid > 0) {
                $wxAPIUrl = $_W['siteroot'] . "app/index.php?c=entry&i=" . $_W['uniacid'] . "&m=bsht_tbk&do=uc_dd&op=add&plus=1&auto=1&orderid=" . $orderid . "&uid=" . $uid . "&openid=";
                $resp = curl_rest($wxAPIUrl);
            }
        }
    }
    return 0;
}
function curl_rest($url, $post = '', $cookie = '', $returnCookie = 0)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1;  Trident/6.0)');
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
    curl_setopt($curl, CURLOPT_REFERER, "http://XXX");
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    if ($post) {
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post));
    }
    if ($cookie) {
        curl_setopt($curl, CURLOPT_COOKIE, $cookie);
    }
    curl_setopt($curl, CURLOPT_HEADER, $returnCookie);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $data = curl_exec($curl);
    if (curl_errno($curl)) {
        return curl_error($curl);
    }
    curl_close($curl);
    if ($returnCookie) {
        list($header, $body) = explode("\r\n\r\n", $data, 2);
        preg_match_all('/Set\\-Cookie:([^;]*);/', $header, $matches);
        $info['cookie'] = substr($matches[1][0], 1);
        $info['content'] = $body;
        return $info;
    } else {
        return $data;
    }
}
function nb_get($data_values, $orderid)
{
    $newArr = array();
    $re = array();
    $re['orderfee'] = 0;
    $re['shouru_yongjin'] = 0;
    $re['orderfee2'] = 0;
    $re['shouru_yongjin2'] = 0;
    $bnum = 1;
    //取出一单中多个相同
    foreach ($data_values as $k => $v) {
        if ($data_values[$k][25] == $orderid) {
            $newArr[$k] = $v;
        }
    }
    if (!empty($newArr)) {
        sort($newArr);
        //排序
        $sort = array('direction' => 'SORT_DESC', 'field' => 14);
        $arrSort = array();
        foreach ($newArr as $uniqid => $row) {
            if (empty($row[14])) {
                $row[14] = 0;
            }
            foreach ($row as $key => $value) {
                $arrSort[$key][$uniqid] = $value;
            }
        }
        if ($sort['direction']) {
            array_multisort($arrSort[$sort['field']], constant($sort['direction']), $newArr);
        }
        //排序
        //41
        foreach ($newArr as $k => $v) {
            if (!empty($v[15]) && $v[15] > $v[13]) {
                $newArr[$k][13] = $v[15];
            }
            if (!empty($v[16]) && $v[16] > $v[14]) {
                $newArr[$k][14] = $v[16];
            }
        }
        //41
        //统计
        foreach ($newArr as $k => $v) {
            $re['orderfee'] += $newArr[$k][13];
            $re['shouru_yongjin'] += $newArr[$k][14];
            $re['orderfee2'] += $newArr[$k][15];
            $re['shouru_yongjin2'] += $newArr[$k][16];
        }
        //统计
    }
    $num = count($newArr);
    $re['num'] = $num;
    $re['dat'] = $newArr;
    return $re;
}
// +----------------------------------------
// | 京东商品采集相关函数
// +----------------------------------------
//格式化商品数据
function goodsFormatJD($cat, $data, $field)
{
    global $_W;
    //处理商品类目
    if (empty($cat[$data['商品类目']])) {
        $data['商品类目'] = 0;
    } else {
        $data['商品类目'] = $cat[$data['商品类目']];
    }
    $newData = array(
        //'uniacid' => $_W['uniacid'],//公众号ID，默认为0，就是使用共用商品库
        'goods_id' => $data['商品ID'],
        //商品ID
        'goods_name' => trimExcessChar($data['商品标题']),
        //商品标题
        'goods_link' => $data['商品链接'],
        //商品链接
        'goods_img' => $data['商品图片'],
        //商品图片
        'goods_price' => $data['商品原价'],
        //商品原价
        'coupon_price' => $data['商品券后价'],
        //券后价
        'discount_start' => $data['优惠券开始时间'],
        //优惠券开始时间
        'discount_end' => $data['优惠券到期时间'],
        //优惠券结束时间
        'discount_price' => $data['优惠券金额'],
        //优惠券金额
        'discount_link' => $data['优惠券链接'],
        //优惠券链接
        'goods_content' => trimExcessChar($data['商品文案']),
        //文案
        'goods_type' => $data['商品类目'],
        //	商品类目
        'commission' => $data['佣金比例'],
        //	商品佣金比例
        'yongjin' => $data['预计佣金'],
        //		商品佣金金额
        'goods_level' => $data['商品等级'],
        //		商品等级(20=精选好货)
        'shop_type' => $data['店铺类型'],
        //	店铺类型(0=普通产品1=京东配送)
        //'status'=>1,//状态，不处理
        //'displayorder'=>0,//排序，不处理
        'ctime' => TIMESTAMP,
    );
    //过滤数据库不支持的字段(因为各个版本的数据库字段有差异，所以要处理下)
    foreach ($newData as $key => $value) {
        if (isset($field[$key])) {
            $saveData[$key] = $value;
        }
    }
    return $saveData;
}
//处理商品分类
function goodsCatJD($table, $softCat)
{
    global $_W;
    //查询数据库的分类名和对应ID
    $allCat = pdo_fetchall('select name,id from ' . $table . " where uniacid=0 ");
    //print_r($allCat);
    foreach ($allCat as $cat) {
        $cat['name'] = str_replace("其他", "其它", $cat['name']);
        //兼容分类名字为“其他”时的情况
        $dbCat[$cat['name']] = $cat['id'];
    }
    //将程序商品分类关系转化成对应的id
    foreach ($softCat as $key => $value) {
        $value = str_replace("其他", "其它", $value);
        //兼容分类名字为“其他”时的情况
        if (isset($dbCat[$value])) {
            $newCat[$key] = $dbCat[$value];
        }
    }
    //print_r($softCat);
    return $newCat;
}
// +----------------------------------------
// | 【拼多多】相关函数
// +----------------------------------------
//格式化拼多多订单数据
function orderFormatPdd($data)
{
    global $_W;
    //确保uid值不小于0
    if ($data['customParameters'] < 0) {
        $data['customParameters'] = 0;
    }
    //去除佣金比例中的百分号
    $data['佣金比例'] = str_replace("%", "", $data['佣金比例']);
    $newData = array('uniacid' => $_W['uniacid'], 'uid' => $data['customParameters'], 'orderid' => $data['订单编号'], 'channel' => $data['matchChannel'], 'itemtitle' => trimExcessChar($data['商品信息']), 'itemid' => $data['商品ID'], 'ctime' => strtotime($data['支付时间']), 'otime' => strtotime($data['收货时间']), 'etime' => strtotime($data['审核时间']), 'orderfee' => $data['订单金额'], 'shouru_bili' => $data['佣金比例'], 'shouru_yongjin' => $data['预估佣金收入'], 'pid' => $data['pid'], 'orderstatus' => $data['订单状态ID'], 'itempic' => $data['商品图片']);
    return $newData;
}
//格式化唯品会订单数据
function orderFormatVip($data)
{
    global $_W, $return;
    //判断orderOnly字段是否包含下划线，如果不包含，则说明助手版本太老（老版本助手使用“-”做为连接符，会和牛贝不兼容），直接返回提示消息
    //if (strpos($data['orderOnly'], '-') !== false) {
    //$data['orderOnly'] = str_replace("-", "_", $data['orderOnly']);
    //$data['orderKey'] = md5($data['orderOnly']);
    //}
    if (strpos($data['orderOnly'], '_') == false) {
        returnExit($return, 0, '当前使用的18助手版本不是最新，请重启助手，自动升级到最新版再使用');
    }
    //从自定义参数中提取shopid和uid
    $channeltag = !empty($data['channelTag']) ? $data['channelTag'] : $data['pid'];
    //pid的值和channelTag值一致
    $channeltag_arr = explode('_', $channeltag);
    //分割成数组
    //$shopid = intval($channeltag_arr[0]);
    //$uid = intval($channeltag_arr[1]);
    $uid = intval($channeltag_arr[0]);
    $shopid = intval($channeltag_arr[1]);
    //处理订单状态
    $orderSubStatusName = $data['orderSubStatusName'];
    $orderstatus = 0;
    switch ($orderSubStatusName) {
        case "已下单":
            $orderstatus = 0;
            break;
        case "已付款":
            $orderstatus = 1;
            break;
        case "已签收":
            $orderstatus = 2;
            break;
        case "待结算":
            $orderstatus = 5;
            break;
        case "已结算":
            $orderstatus = 3;
            break;
        case "已失效":
            $orderstatus = 8;
            break;
        default:
    }
    //标准化数据
    $newData = array('uniacid' => $_W['uniacid'], 'ordermd5' => $data['orderKey'], 'orderkey' => $data['orderOnly'], 'shopid' => $shopid, 'uid' => $uid, 'orderid' => $data['orderSn'], 'channel' => $data['matchChannel'], 'itemtitle' => trimExcessChar($data['goodsName']), 'itemid' => $data['goodsId'], 'ctime' => strtotime($data['orderTime']), 'otime' => strtotime($data['signTime']), 'etime' => strtotime($data['settledTime']), 'orderfee' => $data['commissionTotalCost'], 'shouru_bili' => $data['commissionRate'], 'shouru_yongjin' => $data['commission'], 'count' => $data['goodsCount'], 'pid' => $data['pid'], 'orderstatus' => $orderstatus, 'itempic' => $data['goodsThumb']);
    if ($orderstatus == 8) {
        $newData['shouru_yongjin'] = 0;
    }
    return $newData;
}
// +----------------------------------------
// | 其他函数
// +----------------------------------------
//返回json信息并退出
function returnExit($return, $code, $message)
{
    $return['code'] = $code;
    $return['message'] = urlencode($message);
    exit(urldecode(json_encode($return)));
}
//构造返回状态结果字符串
function resultState($result, $id, $v)
{
    if (!empty($result)) {
        $result .= '|';
    }
    $result .= $id . ':' . $v;
    return $result;
}
//获取数据库表的所有字段
function tableField($table)
{
    $sqlColumns = pdo_fetchall('SHOW COLUMNS FROM ' . $table);
    //查询表的所有字段
    //处理查询结果
    foreach ($sqlColumns as $value) {
        if (isset($value['Field']) && isset($value['Type'])) {
            $sqlField[$value['Field']] = $value['Type'];
        }
    }
    return $sqlField;
}
//去除多余的字符
function trimExcessChar($str)
{
    $str = trim($str);
    $str = str_replace("；", "", $str);
    $str = str_replace('"', "", $str);
    $str = str_replace('&quot', "", $str);
    $str = str_replace('&quot;', "", $str);
    $str = str_replace(PHP_EOL, '', $str);
    return $str;
}
function sendtxt18($openid, $content, $uniacid)
{
    global $_GPC, $_W;
    $send = array();
    $send['touser'] = trim($openid);
    $send['msgtype'] = 'text';
    $send['text'] = array('content' => urlencode($content));
    load()->classs('account');
    $acid = $_W['account']['acid'];
    if (!$acid) {
        $acid = pdo_fetchcolumn("SELECT acid FROM " . tablename('account') . " WHERE uniacid=:uniacid ", array(':uniacid' => $uniacid));
        $acid = $acid['acid'];
    }
    if (empty($acid)) {
        $acid = $uniacid;
    }
    $acc = WeAccount::create($acid);
    $data = $acc->sendCustomNotice($send);
    return $data;
}
function curl_request_app($url, $post = '', $cookie = '', $returnCookie = 0)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1;  Trident/6.0)');
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
    curl_setopt($curl, CURLOPT_REFERER, "http://XXX");
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    if ($post) {
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post));
    }
    if ($cookie) {
        curl_setopt($curl, CURLOPT_COOKIE, $cookie);
    }
    curl_setopt($curl, CURLOPT_HEADER, $returnCookie);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $data = curl_exec($curl);
    if (curl_errno($curl)) {
        return curl_error($curl);
    }
    curl_close($curl);
    if ($returnCookie) {
        list($header, $body) = explode("\r\n\r\n", $data, 2);
        preg_match_all('/Set\\-Cookie:([^;]*);/', $header, $matches);
        $info['cookie'] = substr($matches[1][0], 1);
        $info['content'] = $body;
        return $info;
    } else {
        return $data;
    }
}