<?php
// +------------------------------------------------------------------------------------------------
// | 【使用说明】请将本文件上传至NB系统网站服务器：/addons/bsht_tbk/inc/mobile/  目录下。
// +------------------------------------------------------------------------------------------------
// | [18淘客助手api文件(NB微信淘宝客专用)] Copyright (c) 2019 18.LA
// +------------------------------------------------------------------------------------------------
// | 最后修改：2019年7月8日
// +------------------------------------------------------------------------------------------------
// | 官网：http://niubei.18.la/
// +------------------------------------------------------------------------------------------------
defined('IN_IA') or exit('Access Denied');
global $_W, $_GPC, $return, $aouthkey;
$uniacid = $_W['uniacid'];
//默认返回值
$return = array('state' => 'ok', 'code' => 1, 'message' => '', 'version' => '6.8', 'system' => urlencode('NB微信淘宝客'), 'updatetime' => urlencode('2019年7月8日'));
//接收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}' ");
$dtpid = intval($setting['dtpid']);
$dtpid_locktime = intval($setting['dtpid_locktime']);
if ($dtpid_locktime == 0) {
    $dtpid_locktime = 300;
}
//判断密钥是否正确
if (empty($aouthkey) || $aouthkey != $setting['nbkey']) {
    returnExit($return, 0, "密钥错误");
    //code值设置为0，表示失败
}
//接口验证
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['商品数'],
					//'ddlist' => serialize($value[33]),
				);


                //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) {
                        $get_pids = pdo_fetch("SELECT * FROM " . tablename('bsht_tbk_pids') . " WHERE uniacid = '{$_W['uniacid']}' AND pid2 = '{$data['来源媒体ID']}' AND pid3 = '{$data['广告位ID']}' AND status = 2 AND uid > 0 AND iid = '{$data['商品ID']}'");
                        if (!empty($get_pids)) {
                            $ck_u_uid = $get_pids['uid'];
                            if ($ck_u_uid > 0) {
                                $cate_data['uid'] = $ck_u_uid;
                                //解除锁定
                                $del = array();
                                $del['status'] = 1;
                                $del['uid'] = 0;
                                $del['iid'] = '';
                                $del['vtime'] = '';
                                pdo_update('bsht_tbk_pids', $del, array('uniacid' => $uniacid, 'id' => $get_pids['id']));
                                //解除锁定
                            }
                        }
                    } else {
                        $shop = pdo_fetch("SELECT * FROM " . tablename('bsht_tbk_shop') . " WHERE uniacid = '{$_W['uniacid']}' AND pid2 = '{$data['来源媒体ID']}' AND pid3 = '{$data['广告位ID']}' ");
                    }
                }
                //rid
                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;
                    }
                }
                if (empty($data['渠道关系ID'])) {
                    if ($data['广告位ID'] == 0 || $data['广告位ID'] == '0' || empty($data['广告位ID'])) {
                        $cate_data['dlm_id'] = 0;
                        $cate_data['shopid'] = 0;
                    }
                }
                

				//查询订单表
                $thisoid = pdo_fetch('select * from ' . tablename('bsht_tbk_order') . " where uniacid = '{$_W['uniacid']}' AND orderid = '{$data['子订单编号']}' ");
                //判断订单是否存在
                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 ($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 {
                                $cate_data['fwfbili'] = 10;
                            }
                            if ($sp_bl_lv1 > 0) {
                                $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);
                                $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['结算时间'])) {
                        $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);
                    //写入数据库
                    //记录入库结果
                    if ($isbanddd == 1 && ($data['订单状态'] == '订单付款' || $data['订单状态'] == '订单结算')) {
                        $nb_zd = nb_zd($data['商品信息'], $data['订单状态'], $data['子订单编号'], $data['创建时间'], '123', $data['商品ID'], $isddview, $synctipplus, $ck_u_uid);
                    }
                    if (!empty($result)) {
                        $resultStr = resultState($resultStr, $data['订单编号'], "1");
                        //成功
                    } else {
                        $resultStr = resultState($resultStr, $data['订单编号'], "0");
                        //失败
                    }
                } else {
                    //etime
                    if ($data['订单状态'] == '订单结算' && !empty($data['结算时间'])) {
                        $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']);
                    }
                    if (!empty($thisoid['pid3'])) {
                        unset($cate_data['pid3']);
                    }
                    if ($thisoid['shopid'] > 0) {
                        unset($cate_data['shopid']);
                    }
                    if ($thisoid['uid'] > 0) {
                        unset($cate_data['uid']);
                    }
                    $result = pdo_update('bsht_tbk_order', $cate_data, array('id' => $thisoid['id'], 'orderid' => $thisoid['orderid']));
                    //更新数据库
                    //记录入库结果
                    if (($data['订单状态'] == '订单付款' || $data['订单状态'] == '订单结算') && $thisoid['orderstatus'] != $data['订单状态'] && $isbanddd == 1) {
                        $nb_zd = nb_zd($data['商品信息'], $data['订单状态'], $data['子订单编号'], $data['创建时间'], $thisoid['orderstatus'], $data['商品ID'], $isddview, $synctipplus, $ck_u_uid);
                    }
                    $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
        }
        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;
            $ckspid = pdo_fetch("SELECT id,status FROM " . tablename('bsht_tbk_shop') . " WHERE uniacid = '{$uniacid}' AND jd_pid = '{$pid}' AND status = 2 ");
            if (!empty($ckspid)) {
                $shopid = intval($ckspid['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);
                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 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);
                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 == '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)
{
	//将结构化订单数组拆分为子订单数组
	$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')
{
    //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);
                            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);
                            }
                            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);
                $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";
                //$resp = ihttp_post($wxAPIUrl, array('op' => 'add', 'orderid' => $orderid, 'openid' => $dd_user['openid'], 'plus' => 1, 'auto' => 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;
}
// +----------------------------------------
// | 其他函数
// +----------------------------------------
//返回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;
}