0) { return $_SESSION['admin_id']; } else { return false; } } /** * 获取用户信息 * @param $user_id_or_name 用户id 邮箱 手机 第三方id * @param int $type 类型 0 user_id查找 1 邮箱查找 2 手机查找 3 第三方唯一标识查找 * @param int $stoid * @param string $oauth 第三方来源 * @return mixed */ function get_user_info($user_id_or_name, $type = 0, $stoid, $oauth = '') { $map = array(); if ($type == 0) $map['user_id'] = $user_id_or_name; if ($type == 1) $map['email'] = $user_id_or_name; if ($type == 2) $map['mobile'] = $user_id_or_name; if ($type == 3) { $map['openid'] = $user_id_or_name; // $map['oauth'] = $oauth; } if ($type == 4) { $map['unionid'] = $user_id_or_name; $map['oauth'] = $oauth; } $user = null; //$user0 = M('users')->alias('a')->join('store b', ' a.store_id=b.store_id')->where('a.store_id', $stoid)->where($map)->field('a.*,b.ERPId')->select(); $user0 = M('users')->where('store_id', $stoid)->where($map)->select(); if ($user0) { if (count($user0) > 1) { foreach ($user0 as $kj => $vj) { if (!empty($vj['mobile'])) { $user = $user0[$kj]; } } if ($type == 3) { $wh['openid'] = $user_id_or_name; M('users')->where('store_id', $stoid)->where($wh)->where("mobile='' or mobile is null")->delete(); } } else { $user = $user0[0]; } $user['ERPId'] = tpCache('shop_info.ERPId', $stoid); } return $user; } /** * 更新会员等级,折扣,消费总额 * @param $user_id 用户ID * @return boolean */ function update_user_level($user_id) { //实时查询 // $m_db = Db::connect('mian_db'); $level_info = M('user_level')->order('level_id')->select(); $total_amount = M('order')->where("user_id=:user_id AND pay_status=1 and order_status not in (3,5)")->bind(['user_id' => $user_id])->sum('order_amount'); /* $total_amount2 = M('giftuser_order')->where("user_id=:user_id AND pay_status=1 and order_status not in (3,5)")->bind(['user_id' => $user_id])->sum('order_amount');*/ $total_amount = $total_amount;//+$total_amount2; if ($level_info) { foreach ($level_info as $k => $v) { if ($total_amount >= $v['amount']) { $level = $level_info[$k]['level_id']; $discount = $level_info[$k]['discount'] / 100; } } $user = session('user'); $updata['total_amount'] = $total_amount;//更新累计修复额度 //累计额度达到新等级,更新会员折扣 if (isset($level) && $level > $user['level']) { $updata['level'] = $level; $updata['discount'] = $discount; } M('users')->where("user_id", $user_id)->save($updata); } } /** * 商品缩略图 给于标签调用 拿出商品表的 original_img 原始图来裁切出来的 * @param type $goods_id 商品id * @param type $width 生成缩略图的宽度 * @param type $height 生成缩略图的高度 */ function goods_thum_images($goods_id, $width, $height, $sid = '') { if (empty($goods_id)) return NOIMG; if (empty($sid)) $sid = getMobileStoId(); //判断缩略图是否存在 $path = "public/upload/goods/thumb/$goods_id/"; $goods_thumb_name = "goods_thumb_{$goods_id}_{$width}_{$height}"; // 这个商品 已经生成过这个比例的图片就直接返回了 if (file_exists($path . $goods_thumb_name . '.jpg')) return '/' . $path . $goods_thumb_name . '.jpg'; if (file_exists($path . $goods_thumb_name . '.jpeg')) return '/' . $path . $goods_thumb_name . '.jpeg'; if (file_exists($path . $goods_thumb_name . '.gif')) return '/' . $path . $goods_thumb_name . '.gif'; if (file_exists($path . $goods_thumb_name . '.png')) return '/' . $path . $goods_thumb_name . '.png'; $original_img = M('Goods')->where("goods_id", $goods_id)->getField('original_img'); if (empty($original_img)) return NOIMG;; $original_img = '.' . $original_img; // 相对路径 if (!file_exists($original_img)) return NOIMG; //$image = new \think\Image(); $image = \think\Image::open($original_img); mlog($original_img, "Ueditor"); $goods_thumb_name = $goods_thumb_name . '.' . $image->type(); //生成缩略图 if (!is_dir($path)) mkdir($path, 0777, true); //参考文章 http://www.mb5u.com/biancheng/php/php_84533.html 改动参考 http://www.thinkphp.cn/topic/13542.html $image->thumb($width, $height, 2)->save($path . $goods_thumb_name, NULL, 100); //按照原图的比例生成一个最大为$width*$height的缩略图并保存 //图片水印处理 // $water = tpCache('water', $sid); // if ($water['is_mark'] == 1) { // $imgresource = './' . $path . $goods_thumb_name; // if ($width > $water['mark_width'] && $height > $water['mark_height']) { // if ($water['mark_type'] == 'img') { // try { // $image->open($imgresource)->water("." . $water['mark_img'], $water['mark_position'], $water['mark_degree'])->save($imgresource); // } catch (Exception $e) { // return NOIMG; // } // } else { // //检查字体文件是否存在 // if (file_exists('./zhjt.ttf')) { // // mlog("是否存在","water"); // $image->open($imgresource)->text($water['mark_txt'], './zhjt.ttf', 20, '#000000', $water['mark_position'])->save($imgresource); // } // } // } // } return '/' . $path . $goods_thumb_name; } /** * 商品相册缩略图 */ function get_sub_images($sub_img, $goods_id, $width, $height) { //判断缩略图是否存在 $path = "public/upload/goods/thumb/$goods_id/"; $goods_thumb_name = "goods_sub_thumb_{$sub_img['img_id']}_{$width}_{$height}"; //这个缩略图 已经生成过这个比例的图片就直接返回了 if (file_exists($path . $goods_thumb_name . '.jpg')) return '/' . $path . $goods_thumb_name . '.jpg'; if (file_exists($path . $goods_thumb_name . '.jpeg')) return '/' . $path . $goods_thumb_name . '.jpeg'; if (file_exists($path . $goods_thumb_name . '.gif')) return '/' . $path . $goods_thumb_name . '.gif'; if (file_exists($path . $goods_thumb_name . '.png')) return '/' . $path . $goods_thumb_name . '.png'; $original_img = '.' . $sub_img['image_url']; //相对路径 if (!file_exists($original_img)) return ''; //$image = new \think\Image(); //$image->open($original_img); $image = \think\Image::open($original_img); $goods_thumb_name = $goods_thumb_name . '.' . $image->type(); // 生成缩略图 if (!is_dir($path)) mkdir($path, 777, true); $image->thumb($width, $height, 2)->save($path . $goods_thumb_name, NULL, 100); //按照原图的比例生成一个最大为$width*$height的缩略图并保存 return '/' . $path . $goods_thumb_name; } /** * 刷新商品库存, 如果商品有设置规格库存, 则商品总库存 等于 所有规格库存相加 * @param type $goods_id 商品id */ function refresh_stock($goods_id) { $count = M("SpecGoodsPrice")->where("goods_id", $goods_id)->count(); if ($count == 0) return false; // 没有使用规格方式 没必要更改总库存 $store_count = M("SpecGoodsPrice")->where("goods_id", $goods_id)->sum('store_count'); M("Goods")->where("goods_id", $goods_id)->save(array('store_count' => $store_count)); // 更新商品的总库存 } /** * 根据 order_goods 表扣除商品库存 * @param type $order_id 订单id */ function minus_stock($order_id, $type = 0, $qh = 0) { $orderGoodsArr = null; $pk = null; if ($type == 1) { /*--在活动的条件下,以及总部销售的条件下要减线上库存--*/ $orderGoodsArr = M('giftuser_order_goods')->where("order_id", $order_id)->select(); //门店id $pk = M('giftuser_order')->where("order_id", $order_id)->field('pickup_id,user_id')->find(); } else { /*--在活动的条件下,以及总部销售的条件下要减线上库存--*/ $orderGoodsArr = M('OrderGoods')->where("order_id", $order_id)->select(); //门店id $pk = M('order')->where("order_id", $order_id)->field('pickup_id,user_id')->find(); } //销售规则 $sales_rules = tpCache('basic.sales_rules', $orderGoodsArr[0]['store_id']); $stoid = $orderGoodsArr[0]['store_id']; //$redis = new \Redis(); //$redis->connect(redisip, 6379); $redis = get_redis_handle(); foreach ($orderGoodsArr as $key => $val) { /**---- * if (!empty($val['spec_key'])) { // 先到规格表里面扣除数量 再重新刷新一个 这件商品的总数量 * M('SpecGoodsPrice')->where("goods_id = :goods_id and `key` = :key")->bind(['goods_id' => $val['goods_id'], 'key' => $val['spec_key']])->setDec('store_count', $val['goods_num']); * refresh_stock($val['goods_id']); * } else { * M('Goods')->where("goods_id", $val['goods_id'])->setDec('store_count', $val['goods_num']); // 直接扣除商品总数量 * }---**/ M('Goods')->where("goods_id", $val['goods_id'])->setInc('sales_sum', $val['goods_num']); // 增加商品销售量 //更新活动商品购买量 if ($val['prom_type'] == 1 || $val['prom_type'] == 2 || $val['prom_type'] == 4 || $val['prom_type'] == 6) { $prom = get_goods_promotion($val['goods_id']); if ($prom['is_end'] == 0 || $prom['is_end'] == 2) { switch ($val['prom_type']) { case "1": $tb = 'flash_sale'; break; case "2": $tb = 'group_buy'; break; case "4": $tb = 'integral_buy'; break; case "6": $tb = 'teamlist'; break; } M($tb)->where("id", $val['prom_id'])->setInc('buy_num', $val['goods_num']); M($tb)->where("id", $val['prom_id'])->setInc('order_num'); M('Goods')->where("goods_id", $val['goods_id'])->setDec('store_count', $val['goods_num']); } else { if ($sales_rules == 1) { M('Goods')->where("goods_id", $val['goods_id'])->setDec('store_count', $val['goods_num']); } else { $d = [ 'order_sn' => $val['order_sn'], 'store_id' => $val['store_id'], 'goods_id' => $val['goods_id'], 'pickup_id' => $pk['pickup_id'], 'out_qty' => $val['goods_num'], 'updatetime' => time(), ]; M('erp_yqty')->save($d); } } } else { if ($sales_rules == 1 && $val['goods_price'] > 0) { M('Goods')->where("goods_id", $val['goods_id'])->setDec('store_count', $val['goods_num']); } if ($sales_rules == 2 && $val['goods_price'] > 0) { $d = [ 'order_sn' => $val['order_sn'], 'store_id' => $val['store_id'], 'goods_id' => $val['goods_id'], 'pickup_id' => $pk['pickup_id'], 'out_qty' => $val['goods_num'], 'updatetime' => time(), ]; M('erp_yqty')->save($d); } /*---在买的时候减--- if ($val['goods_price']==0){//去除赠品库存 M('Gift')->where(['goods_id'=>$val['goods_id'],'is_end'=>0])->setDec('goods_num', $val['goods_num']); }---*/ } } } /** * 邮件发送 * @param $to 接收人 * @param string $subject 邮件标题 * @param string $content 邮件内容(html模板渲染后的内容) * @throws Exception * @throws phpmailerException */ function send_email($to, $subject = '', $content = '') { vendor('phpmailer.PHPMailerAutoload'); ////require_once vendor/phpmailer/PHPMailerAutoload.php'; $mail = new PHPMailer; $config = tpCache('smtp'); $mail->CharSet = 'UTF-8'; //设定邮件编码,默认ISO-8859-1,如果发中文此项必须设置,否则乱码 $mail->isSMTP(); //Enable SMTP debugging // 0 = off (for production use) // 1 = client messages // 2 = client and server messages $mail->SMTPDebug = 0; //调试输出格式 //$mail->Debugoutput = 'html'; //smtp服务器 $mail->Host = $config['smtp_server']; //端口 - likely to be 25, 465 or 587 $mail->Port = $config['smtp_port']; if ($mail->Port === 465) $mail->SMTPSecure = 'ssl';// 使用安全协议 //Whether to use SMTP authentication $mail->SMTPAuth = true; //用户名 $mail->Username = $config['smtp_user']; //密码 $mail->Password = $config['smtp_pwd']; //Set who the message is to be sent from $mail->setFrom($config['smtp_user']); //回复地址 //$mail->addReplyTo('replyto@example.com', 'First Last'); //接收邮件方 if (is_array($to)) { foreach ($to as $v) { $mail->addAddress($v); } } else { $mail->addAddress($to); } $mail->isHTML(true);// send as HTML //标题 $mail->Subject = $subject; //HTML内容转换 $mail->msgHTML($content); //Replace the plain text body with one created manually //$mail->AltBody = 'This is a plain-text message body'; //添加附件 //$mail->addAttachment('images/phpmailer_mini.png'); //send the message, check for errors return $mail->send(); } /** * 发送短信 * @param $mobile 手机号码 * @param $content 内容 * @return bool function sendSMS($mobile,$content) * { * $config = F('sms','',TEMP_PATH); * $http = $config['sms_url']; //短信接口 * $uid = $config['sms_user']; //用户账号 * $pwd = $config['sms_pwd']; //密码 * $mobileids = $mobile; //号码发送状态接收唯一编号 * $data = array * ( * 'uid'=>$uid, //用户账号 * 'pwd'=>md5($pwd.$uid), //MD5位32密码,密码和用户名拼接字符 * 'mobile'=>$mobile, //号码,以英文逗号隔开 * 'content'=>$content, //内容 * 'mobileids'=>$mobileids, * ); * //即时发送 * $res = httpRequest($http,'POST',$data);//POST方式提交 * $stat = strpos($res,'stat=100'); * if($stat){ * return true; * }else{ * return false; * } * } */ /** * 获取短信配置信息 * @param unknown $key * @return string */ function smsConfigValueScene($scene, $stoid = '') { if (empty($stoid)) { $stoid = getMobileStoId(); } $keys = array( 'sms_product' => 'sms_product', //产品名称 1 => 'regis_sms_enable', //1 : 用户注册 2 => 'forget_pwd_sms_enable', //2 : 用户找回密码 3 => 'order_add_sms_enable', //3. 客户下单 4 => 'order_pay_sms_enable', //4.客户支付 5 => 'order_shipping_sms_enable', //5.商家发货 6 => 'bind_mobile_sms_enable' //6.修改手机号码 ); $key = $keys[$scene]; $config = tpCache('sms', $stoid); $value = $config[$key]; return $value; } /** * 检测是否能够发送短信 * @param unknown $scene * @return multitype:number string */ function checkEnableSendSms($scene) { // $smsEnable = smsConfigValueScene($scene); // $sendScenes = C('SEND_SCENE'); // $sceneName = $sendScenes[$scene][0]; // // if(!$smsEnable){ // return array("status"=>-1,"msg"=>"['$sceneName']短信模板已经关闭'"); // } //判断是否添加"注册模板" $size = M('sms_template')->where("send_scene=$scene")->count('tpl_id'); if (!$size) { return array("status" => -1, "msg" => "请先添加短信模板"); } return array("status" => 1, "msg" => "可以发送短信"); } /** * 发送短信逻辑 * @param unknown $scene */ function sendSms($scene, $sender, $params) { // $smsTemp = M('sms_template')->where("send_scene= :send_scene")->bind(['send_scene' => $scene])->find(); //用户注册. // $code = !empty($params['code']) ? $params['code'] : false; // $consignee = !empty($params['consignee']) ? $params['consignee'] : false; // $user_name = !empty($params['user_name']) ? $params['user_name'] : false; // $order_sn = $params['order_sn']; // // $product = smsConfigValueScene('sms_product'); // // $smsParams = array( // 1 => "{\"code\":\"$code\",\"product\":\"$product\"}", //1. 用户注册 // 2 => "{\"code\":\"$code\"}", //2. 用户找回密码 // 3 => "{\"consignee\":\"$consignee\",\"phone\":\"$sender\"}", //3. 客户下单 // 4 => "{\"order_sn\":\"$order_sn\"}", //4. 客户支付 // 5 => "{\"user_name\":\"$user_name\",\"order_sn\":\"$order_sn\",\"consignee\":\"$consignee\"}", //5.商家发货 // 6 => "{\"user_name\":\"$user_name\",\"code\":\"$code\"}" //6. 修改手机号码 // ); // // $smsParam = $smsParams[$scene]; // // $resp = realSendSMS($sender, $smsTemp['sms_sign'], $smsParam, $smsTemp['sms_tpl_code']); // // if ($resp['status'] == 1) { // $session_id = session_id(); // // 从数据库中查询是否有验证码 // $data = M('sms_log')->where(array('store_id' => getMobileStoId(), 'mobile' => $sender, 'status' => 0, 'session_id' => $session_id))->order('add_time desc')->find(); // if (empty($data)) { // // 没有就插入验证码,供验证用 // $data = array('store_id' => getMobileStoId(), 'mobile' => $sender, 'add_time' => time(), 'status' => 1, 'session_id' => $session_id); // if ($code) { // $data['code'] = $code; // } // M('sms_log')->add($data); // } else { // //修改发送状态为成功 // M('sms_log')->where(array('id' => $data['id']))->save(array('status' => 1)); // } // } // return $resp; } // /** // * 为照顾新手开发者 方便调试, 此方法每一行加以注释说明 // * 发送短信 // * @param $mobile 手机号码 // * @param $smsSign 短信签名 必须 // * @param smsParam 短信模板 必须 // * @param $templateCode 短信模板ID,传入的模板必须是在阿里大鱼“管理中心-短信模板管理”中的可用模板。 // * @return bool 短信发送成功返回true失败返回false // */ function realSendSMS($mobile, $smsSign, $smsParam, $templateCode) { //时区设置:亚洲/上海 date_default_timezone_set('Asia/Shanghai'); //这个是你下面实例化的类 vendor('Alidayu.TopClient'); //这个是topClient 里面需要实例化一个类所以我们也要加载 不然会报错 vendor('Alidayu.ResultSet'); //这个是成功后返回的信息文件 vendor('Alidayu.RequestCheckUtil'); //这个是错误信息返回的一个php文件 vendor('Alidayu.TopLogger'); //这个也是你下面示例的类 vendor('Alidayu.AlibabaAliqinFcSmsNumSendRequest'); $c = new \TopClient; $config = tpCache('sms'); //App Key的值 这个在开发者控制台的应用管理点击你添加过的应用就有了 $c->appkey = $config['sms_appkey']; //App Secret的值也是在哪里一起的 你点击查看就有了 $c->secretKey = $config['sms_secretKey']; //这个是用户名记录那个用户操作 $req = new \AlibabaAliqinFcSmsNumSendRequest; //代理人编号 可选 $req->setExtend("123456"); //短信类型 此处默认 不用修改 $req->setSmsType("normal"); //短信签名 必须 $req->setSmsFreeSignName($smsSign); //短信模板 必须 $req->setSmsParam($smsParam); //短信接收号码 支持单个或多个手机号码,传入号码为11位手机号码,不能加0或+86。群发短信需传入多个号码,以英文逗号分隔, $req->setRecNum("$mobile"); //短信模板ID,传入的模板必须是在阿里大鱼“管理中心-短信模板管理”中的可用模板。 $req->setSmsTemplateCode($templateCode); // templateCode $c->format = 'json'; //发送短信 $resp = $c->execute($req); //短信发送成功返回True,失败返回false //if (!$resp) if ($resp && $resp->result) { return array('status' => 1, 'msg' => $resp->sub_msg); } else { return array('status' => -1, 'msg' => $resp->sub_msg . ' ,msg :' . $resp->msg . ' subcode:' . $resp->sub_code); } } /** * 查询快递 * @param $postcom 快递公司编码 * @param $getNu 快递单号 * @return array 物流跟踪信息数组 */ function queryExpress($postcom, $getNu) { /* $url = "http://wap.kuaidi100.com/wap_result.jsp?rand=".time()."&id={$postcom}&fromWeb=null&postid={$getNu}"; //$resp = httpRequest($url,'GET'); $resp = file_get_contents($url); if (empty($resp)) { return array('status'=>0, 'message'=>'物流公司网络异常,请稍后查询'); } preg_match_all('/\\
·(.*)\\<\\/p\\>/U', $resp, $arr);
        if (!isset($arr[1])) {
            return array( 'status'=>0, 'message'=>'查询失败,参数有误' );
        }else{
            foreach ($arr[1] as $key => $value) {
                $a = array();
                $a = explode('
 ', $value);
                $data[$key]['time'] = $a[0];
                $data[$key]['context'] = $a[1];
            }
            return array( 'status'=>1, 'message'=>'1','data'=> array_reverse($data));
        }*/
    $url = "https://m.kuaidi100.com/query?type=" . $postcom . "&postid=" . $getNu . "&id=1&valicode=&temp=0.49738534969422676";
    $resp = httpRequest($url, "GET");
    return json_decode($resp, true);
}
/**
 * 获取某个商品分类的 儿子 孙子  重子重孙 的 id
 * @param type $cat_id
 */
function getCatGrandson($cat_id)
{
    $GLOBALS["ary"] = array();
    getCatGrandson2($cat_id);
    return $GLOBALS["ary"];
}
/**
 * 获取某个文章分类的 儿子 孙子  重子重孙 的 id
 * @param type $cat_id
 */
function getArticleCatGrandson($cat_id)
{
    $GLOBALS['ArticleCatGrandson'] = array();
    $GLOBALS['cat_id_arr'] = array();
    // 先把自己的id 保存起来
    $GLOBALS['ArticleCatGrandson'][] = $cat_id;
    // 把整张表找出来
    $GLOBALS['cat_id_arr'] = M('ArticleCat')->getField('cat_id,parent_id');
    // 先把所有儿子找出来
    $son_id_arr = M('ArticleCat')->where("parent_id", $cat_id)->getField('cat_id', true);
    foreach ($son_id_arr as $k => $v) {
        getArticleCatGrandson2($v);
    }
    return $GLOBALS['ArticleCatGrandson'];
}
/**
 * 递归调用找到 重子重孙
 * @param type $cat_id
 */
function getCatGrandson2($cat_id)
{
    $GLOBALS["ary"][] = $cat_id;
    $r = M("goods_category")->where("parent_id", $cat_id)->field('id')->select();
    if (empty($r)) return;
    foreach ($r as $key => $val) {
        getCatGrandson2($val['id']);
    }
}
/**
 * 递归调用找到 重子重孙
 * @param type $cat_id
 */
function getArticleCatGrandson2($cat_id)
{
    $GLOBALS['ArticleCatGrandson'][] = $cat_id;
    foreach ($GLOBALS['cat_id_arr'] as $k => $v) {
        // 找到孙子
        if ($v == $cat_id) {
            getArticleCatGrandson2($k); // 继续找孙子
        }
    }
}
/**
 * 查看某个用户购物车中商品的数量
 * @param type $user_id
 * @param type $session_id
 * @return type 购买数量
 */
function cart_goods_num($user_id = 0, $session_id = '')
{
    $where = " session_id = :session_id ";
    $bind['session_id'] = $session_id;
    if ($user_id) {
        $where .= " or user_id = :user_id ";
        $bind['user_id'] = $user_id;
    }
    $where .= ' and state=0';
    // 查找购物车数量
    $cart_count = M('Cart')->where($where)->bind($bind)->sum('goods_num');
    $cart_count = $cart_count ? $cart_count : 0;
    return $cart_count;
}
/**
 * 获取商品库存
 * @param type $goods_id 商品id
 * @param type $key 库存 key
 */
function getGoodNum($goods_id, $key)
{
    if (!empty($key))
        return M("SpecGoodsPrice")->where(['goods_id' => $goods_id, 'key' => $key])->getField('store_count');
    else
        return M("Goods")->where("goods_id", $goods_id)->getField('store_count');
}
/**
 * 获取缓存或者更新缓存
 * @param string $config_key 缓存文件名称
 * @param array $data 缓存数据  array('k1'=>'v1','k2'=>'v3')
 * @return array or string or bool
 */
function tpCache_old($config_key, $data = array())
{
    $param = explode('.', $config_key);
    if (empty($data)) {
        //如$config_key=shop_info则获取网站信息数组
        //如$config_key=shop_info.logo则获取网站logo字符串
        $config = F($param[0], '', TEMP_PATH);//直接获取缓存文件
        if (empty($config)) {
            //缓存文件不存在就读取数据库
            $res = D('config')->where("inc_type", $param[0])->select();
            if ($res) {
                foreach ($res as $k => $val) {
                    $config[$val['name']] = $val['value'];
                }
                F($param[0], $config, TEMP_PATH);
            }
        }
        if (count($param) > 1) {
            return $config[$param[1]];
        } else {
            return $config;
        }
    } else {
        //更新缓存
        $result = D('config')->where("inc_type", $param[0])->select();
        if ($result) {
            foreach ($result as $val) {
                $temp[$val['name']] = $val['value'];
            }
            foreach ($data as $k => $v) {
                $newArr = array('name' => $k, 'value' => trim($v), 'inc_type' => $param[0]);
                if (!isset($temp[$k])) {
                    M('config')->add($newArr);//新key数据插入数据库
                } else {
                    if ($v != $temp[$k])
                        M('config')->where("name", $k)->save($newArr);//缓存key存在且值有变更新此项
                }
            }
            //更新后的数据库记录
            $newRes = D('config')->where("inc_type", $param[0])->select();
            foreach ($newRes as $rs) {
                $newData[$rs['name']] = $rs['value'];
            }
        } else {
            foreach ($data as $k => $v) {
                $newArr[] = array('name' => $k, 'value' => trim($v), 'inc_type' => $param[0]);
            }
            M('config')->insertAll($newArr);
            $newData = $data;
        }
        return F($param[0], $newData, TEMP_PATH);
    }
}
/********
 * 获取缓存或者更新缓存
 * @param string $config_key 缓存文件名称
 * @param string $stoid 门店id
 * @param array $data 缓存数据  array('k1'=>'v1','k2'=>'v3')
 * @return array or string or bool
 *******/
function tpCache($config_key, $stoid, $data = array())
{
    $param = explode('.', $config_key);
    if (empty($data)) {
        //如$config_key=shop_info则获取网站信息数组
        //如$config_key=shop_info.logo则获取网站logo字符串
        $config = F($param[0] . "_" . $stoid, '', TEMP_PATH);//直接获取缓存文件
        if (empty($config)) {
            //缓存文件不存在就读取数据库
            $table = null;
            switch ($param[0]) {
                case "shop_info":
                    $table = "store";
                    break;
                case "basic":
                case "sms":
                case "shopping":
                case "water":
                case "cardsetup":
                    $table = "store_config";
                    break;
                case "distribut":
                    $table = "store_distribut";
                    break;
            }
            if ($table == null) return null;
            $res = D($table)->where("store_id", (int)$stoid)->find();
            if ($res) {
                foreach ($res as $k => $val) {
                    $config[$k] = $val;
                    //邀请
                    if ($k == "invitation_rate") {
                        $invitation_rate = json_decode($val, true);
                        $config['inv_jf'] = $invitation_rate['inv_jf'];
                        $config['inv_coupon'] = $invitation_rate['inv_coupon'];
                        $config['inv_cz'] = $invitation_rate['inv_cz'];
                    }
                    //注册默认
                    if ($k == "reg_default") {
                        $reg_default = json_decode($val, true);
                        $config['reg_def_ty'] = $reg_default['reg_def_ty'];
                        $config['jf'] = $reg_default['jf'];
                        $config['coupon'] = $reg_default['coupon'];
                        $config['reg_cz'] = $reg_default['reg_cz'];
                    }
                    //注册自定义
                    if ($k == "reg_info") {
                        $reg_info = json_decode($val, true);
                        $config['name'] = $reg_info['name'];
                        $config['name_state'] = $reg_info['name_state'];
                        $config['name_val_type'] = $reg_info['name_val_type'];
                        $config['birthday'] = $reg_info['birthday'];
                        $config['birthday_state'] = $reg_info['birthday_state'];
                        $config['birthday_type'] = $reg_info['birthday_type'];
                        $config['idcard'] = $reg_info['idcard'];
                        $config['idcard_state'] = $reg_info['idcard_state'];
                        $config['idcard_type'] = $reg_info['idcard_type'];
                        $config['address'] = $reg_info['address'];
                        $config['address_state'] = $reg_info['address_state'];
                        $config['address_type'] = $reg_info['address_type'];
                        $config['pick'] = $reg_info['pick'];
                        $config['pick_state'] = $reg_info['pick_state'];
                        $config['pick_type'] = $reg_info['pick_type'];
                        $config['sex'] = $reg_info['sex'];
                        $config['sex_state'] = $reg_info['sex_state'];
                        $config['sex_state_type'] = $reg_info['sex_state_type'];
                        $config['introducer'] = $reg_info['introducer'];
                        $config['introducer_state'] = $reg_info['introducer_state'];
                        $config['introducer_type'] = $reg_info['introducer_type'];
                        $config['reginfo_coupon'] = $reg_info['reginfo_coupon'];
                    }
                    //可选显示
                    if ($k == "switch_list") {
                        $switch_list = json_decode($val, true);
                        $config['jfcz_switch'] = $switch_list['jfcz_switch'];
                        $config['dhwz_switch'] = $switch_list['dhwz_switch'];
                        $config['yckcz_switch'] = $switch_list['yckcz_switch'];
                        $config['rank_switch'] = $switch_list['rank_switch'];
                        $config['isyaoqingma'] = $switch_list['isyaoqingma'];
                        $config['ispt_goods'] = $switch_list['ispt_goods'];
                        $config['is_tx_wx'] = $switch_list['is_tx_wx'];
                        $config['is_brithday'] = $switch_list['is_brithday'];
                        $config['is_flash_return'] = $switch_list['is_flash_return'];
                        $config['is_fast_reg'] = $switch_list['is_fast_reg'];
                        $config['is_close_quan'] = $switch_list['is_close_quan'];
                        $config['is_newchoosestore'] = $switch_list['is_newchoosestore'];
                        $config['is_closecoupon'] = $switch_list['is_closecoupon'];
                        $config['is_regstores'] = $switch_list['is_regstores'];
                        $config['is_newsgoodstype'] = $switch_list['is_newsgoodstype'];
                        if ($switch_list['usertool']) {
                            $config['usertool'] = json_decode($switch_list['usertool']);
                        }
                        $config['is_staffno'] = $switch_list['is_staffno'];
                        $config['is_closetxbank'] = $switch_list['is_closetxbank'];
                        $config['is_newsales_rules'] = $switch_list['is_newsales_rules'];
                        $config['user_label_set'] = $switch_list['user_label_set'];
                        $config['user_label_val'] =$switch_list['user_label_val'];
                        $config['user_label_type'] =$switch_list['user_label_type'];
                    }
                    //短信设置
                    if ($k == 'sms_send_type') {
                        $sms_send_type = json_decode($val, true);
                        $config['type'] = $sms_send_type['type'];
                        $config['time_out'] = $sms_send_type['time_out'];
                        $config['is_verifycode'] = $sms_send_type['is_verifycode'];
                    }
                    //美妆价格
                    if ($k == 'mzprice_list') {
                        $mz = json_decode($val, true);
                        $config['is_beauty'] = $mz['is_beauty'];
                        $config['mz_con'] = $mz['mz_con'];
                        $config['mz_tran'] = $mz['mz_tran'];
                        $config['mz_money'] = $mz['mz_money'];
                        $config['mz_goods_id'] = $mz['mz_goods_id'];
                        $config['mz_goods_name'] = $mz['mz_goods_name'];
                        $config['mz_time'] = $mz['mz_time'];
                    }
                    //自动评价
                    if ($k == 'autopj_list') {
                        $autopj = json_decode($val, true);
                        $config['is_autopj'] = $autopj['is_autopj'];
                        $config['auto_pjday'] = $autopj['auto_pjday'];
                        $config['auto_pjremark'] = $autopj['auto_pjremark'];
                    }
                }
                F($param[0] . "_" . $stoid, $config, TEMP_PATH);
            }
        }
        if (count($param) > 1) {
            return $config[$param[1]];
        } else {
            return $config;
        }
        //编辑
    } else {
        $tb = null;
        $newData = null;
        switch ($param[0]) {
            case "shop_info":
                $tb = "store";
                break;
            case "basic":
            case "shopping":
            case "cardsetup":
                $tb = "store_config";
                break;
            case "sms":
                $data["order_add_sms"] = (bool)$data["order_add_sms"];
            case "water":
                $data["is_mark"] = (bool)$data["is_mark"];
                $tb = "store_config";
                break;
            case "distribut":
                $data["switch"] = (bool)$data["switch"];
                //$data["pattern"] = 0;
                $tb = "store_distribut";
                break;
        }
        if ($tb == null) return null;
        $vv = validate($tb);
        $rs = null;
        if ($param[0] != "cardsetup") {
            if ($param[0] == "basic" || $param[0] == "sms" || $param[0] == "shopping" || $param[0] == "water")
                $rs = $vv->scene($param[0])->check($data);
            else
                $rs = $vv->check($data);
            if (!$rs) {
                $arr1["code"] = false;
                $arr1["str"] = $vv->getError();
                return $arr1;
            }
        }
        //查询是否有改商家记录
        $result = D($tb)->where("store_id", $stoid)->find();
        if ($result) {
            $result = D($tb)->where('store_id', $stoid)->save($data);
            //更新后的数据库记录
            $newData = D($tb)->where("store_id", $stoid)->find();
        } else {
            foreach ($data as $k => $v) {
                $newArr[$k] = trim($v);
            }
            $newArr['store_id'] = (int)$stoid;
            $result = D($tb)->insert($newArr);
            $newData = D($tb)->where("store_id", $stoid)->find();
        }
        //将json格式的数据拆分保存到缓存
        if ($newData['invitation_rate'] != "" || $newData['invitation_rate'] != null) {
            $invitation_rate = json_decode($newData['invitation_rate'], true);
            $newData['inv_jf'] = $invitation_rate['inv_jf'];
            $newData['inv_coupon'] = $invitation_rate['inv_coupon'];
            $newData['inv_cz'] = $invitation_rate['inv_cz'];
        }
        if ($newData['reg_default'] != "" || $newData['reg_default'] != null) {
            $default = json_decode($newData['reg_default'], true);
            $newData['reg_def_ty'] = $default['reg_def_ty'];
            $newData['jf'] = $default['jf'];
            $newData['coupon'] = $default['coupon'];
            $newData['reg_cz'] = $default['reg_cz'];
        }
        if ($newData['reg_info'] != "" || $newData['reg_info'] != null) {
            $info = json_decode($newData['reg_info'], true);
            $newData['name'] = $info['name'];
            $newData['name_state'] = $info['name_state'];
            $newData['name_val_type'] = $info['name_val_type'];
            $newData['birthday'] = $info['birthday'];
            $newData['birthday_state'] = $info['birthday_state'];
            $newData['birthday_type'] = $info['birthday_type'];
            $newData['idcard'] = $info['idcard'];
            $newData['idcard_state'] = $info['idcard_state'];
            $newData['idcard_type'] = $info['idcard_type'];
            $newData['address'] = $info['address'];
            $newData['address_state'] = $info['address_state'];
            $newData['address_type'] = $info['address_type'];
            $newData['pick'] = $info['pick'];
            $newData['pick_state'] = $info['pick_state'];
            $newData['pick_type'] = $info['pick_type'];
            $newData['sex'] = $info['sex'];
            $newData['sex_state'] = $info['sex_state'];
            $newData['sex_state_type'] = $info['sex_state_type'];
            $newData['introducer'] = $info['introducer'];
            $newData['introducer_state'] = $info['introducer_state'];
            $newData['introducer_type'] = $info['introducer_type'];
        }
        if ($newData['switch_list'] != "" || $newData['switch_list'] != null) {
            $switch_list = json_decode($newData['switch_list'], true);
            $newData['jfcz_switch'] = $switch_list['jfcz_switch'];
            $newData['dhwz_switch'] = $switch_list['dhwz_switch'];
            $newData['yckcz_switch'] = $switch_list['yckcz_switch'];
            $newData['rank_switch'] = $switch_list['rank_switch'];
            $newData['isyaoqingma'] = $switch_list['isyaoqingma'];
            $newData['ispt_goods'] = $switch_list['ispt_goods'];
            $newData['is_tx_wx'] = $switch_list['is_tx_wx'];
            $newData['is_brithday'] = $switch_list['is_brithday'];
            $newData['is_flash_return'] = $switch_list['is_flash_return'];
            $newData['is_fast_reg'] = $switch_list['is_fast_reg'];
            $newData['is_close_quan'] = $switch_list['is_close_quan'];
            $newData['is_newchoosestore'] = $switch_list['is_newchoosestore'];
            $newData['is_closecoupon'] = $switch_list['is_closecoupon'];
            $newData['is_regstores'] = $switch_list['is_regstores'];
            $newData['is_newsgoodstype'] = $switch_list['is_newsgoodstype'];
            if ($switch_list['usertool']) {
                $newData['usertool'] = json_decode($switch_list['usertool']);
            }
            $newData['is_staffno'] = $switch_list['is_staffno'];
            $newData['is_closetxbank'] = $switch_list['is_closetxbank'];
            $newData['is_newsales_rules'] = $switch_list['is_newsales_rules'];
            $newData['user_label_set'] = $switch_list['user_label_set'];
            $newData['user_label_val'] =$switch_list['user_label_val'];
            $newData['user_label_type'] =$switch_list['user_label_type'];
        }
        //短信设置
        if ($newData['sms_send_type'] != "" || $newData['sms_send_type'] != null) {
            $sst = json_decode($newData['sms_send_type'], true);
            $newData['type'] = $sst['type'];
            $newData['time_out'] = $sst['time_out'];
            $newData['is_verifycode'] = $sst['is_verifycode'];
        }
        //美妆价格
        if ($newData['mzprice_list'] != "" || $newData['mzprice_list'] != null) {
            $sst = json_decode($newData['mzprice_list'], true);
            $newData['is_beauty'] = $sst['is_beauty'];
            $newData['mz_con'] = $sst['mz_con'];
            $newData['mz_tran'] = $sst['mz_tran'];
            $newData['mz_money'] = $sst['mz_money'];
            $newData['mz_goods_id'] = $sst['mz_goods_id'];
            $newData['mz_goods_name'] = $sst['mz_goods_name'];
            $newData['mz_time'] = $sst['mz_time'];
        }
        return F($param[0] . "_" . $stoid, $newData, TEMP_PATH);
    }
}
/**
 * 记录帐户变动
 * @param   int $user_id 用户id
 * @param   float $user_money 可用余额变动
 * @param   int $pay_points 消费积分变动
 * @param   string $desc 变动说明
 * @param   float   distribut_money 分佣金额
 * @param   float $user_pay_pints 当前用户积分
 * @param   string $orderno 单号
 * @param   int $type 类型
 * @return  bool
 */
function accountLog($user_id, $user_money = 0, $pay_points = 0, $desc = '', $distribut_money = 0,
                    $stoid = 0, $user_pay_points = null, $orderno = '', $type = 0)
{
    if ($orderno != "" || $type == 1) {
        $rs = M('account_log')
            ->where("store_id", $stoid)
            ->where("order_sn", $orderno)//订单号带入
            ->where("user_id", $user_id)
            ->where("type", 1)->find();    //1为分销
        if ($rs) {
            return false;
        }
    }
    /* 插入帐户变动记录 */
    $account_log = array(
        'user_id' => $user_id,
        'user_money' => $user_money,
        'pay_points' => $pay_points,
        'change_time' => time(),
        'desc' => $desc,
        'store_id' => $stoid,
        'type' => $type,
    );
    if ($orderno != "") $account_log['order_sn'] = $orderno;
    if ($user_pay_points) {
        $account_log['end_pay_points'] = $user_pay_points - $pay_points;
    }
    //启动事务
    Db::startTrans();
    try {
        //先插入日志
        $rs = M('account_log')->add($account_log);
        if (!$rs) throw new Exception("add_err");
        /* 更新用户信息 */
        $sql = "UPDATE __PREFIX__users SET user_money = user_money + $user_money," .
            " pay_points = pay_points + $pay_points, distribut_money = distribut_money + $distribut_money WHERE user_id = $user_id";
        if (!DB::execute($sql)) {
            throw new Exception("update_err");
        }
        Db::commit();
        return true;
    } catch (\Exception $e) {
        // 回滚事务
        Db::rollback();
        return false;
    }
}
//流动金额
function add_withdrawals($userid = 0, $money = 0, $remark, $stoid, $order_sn = "", $type = 0, $other = array())
{
    $odata['user_id'] = $userid;
    $odata['create_time'] = time();
    $odata['money'] = $money;
    $odata['remark'] = $remark;
    $odata['store_id'] = $stoid;
    $odata['order_sn'] = $order_sn;
    $odata['status'] = 1;
    $odata['type'] = $type;
    /* 更新用户信息 */
    $sql = "UPDATE __PREFIX__users SET user_money = user_money + $money WHERE user_id = $userid";
    if (DB::execute($sql)) {
        M('withdrawals')->save($odata);
    }
}
//线上优惠处理
// @param   $adddata 提交信息
// @param   $userinfo 用户信息
// @param   $stoid 商户id
//@param   $is_add 是否添加到我的优惠表
function add_coupon($adddata, $userinfo, $stoid, $is_add = 1)
{
    if (empty($adddata)) {
        return json_encode(array('code' => -1, 'msg' => '非法参数'));
    }
    mlog(json_encode($adddata), "add_coupon/" . $stoid);
    $is_ok = 1;
    if ($is_add) {
        $res = M('coupon_list')->add($adddata);
        mlog("返回值 :" . json_encode($res), "add_coupon/" . $stoid);
        if (empty($res)) {
            $is_ok = 0;
        }
    }
    if ($is_ok) {
        $colorlist = urlencode("#FF0000|#173177|#173177|#173177|#173177|#173177|#FF0000|#ca003a");
        $pd['typeid'] = "1006";
        $pd['backurl'] = curHostURL() . '/index.php/Mobile/User/coupon/stoid/' . getMobileStoId();
        $pd['colorlist'] = $colorlist;
        $gettemplate_type = 1;
        $reswx = M('wx_sendlist')->where(array('store_id' => $stoid, 'typeid' => '1006'))->find();
        if ($reswx) {
            $gettemplate_type = $reswx['template_type'];
        }
        $getnickname = $userinfo['vipname'];
        if (empty($getnickname)) {
            $getnickname = $userinfo['nickname'];
        }
        switch ($gettemplate_type) {
            case 1:
                $pd['title'] = "您好,恭喜您成功领取" . $adddata["sum"] . "元优惠券";
                $pd['key1'] = $getnickname;
                $pd['key2'] = $adddata["sum"] . "元优惠券";
                $pd['key3'] = date("Y-m-d");
                $pd['remark'] = "点击详情查看优惠券详情信息";
                break;
            case 2:
                $pd['title'] = "您好,恭喜您成功领取" . $adddata["sum"] . "元优惠券";
                $pd['key1'] = $getnickname;
                $pd['key2'] = $userinfo['mobile'];
                $pd['key3'] = $adddata['remark'] . '优惠券';
                $pd['key4'] = $adddata["sum"] . "元优惠券";
                $pd['key5'] = date("Y-m-d");
                $pd['remark'] = "点击详情查看优惠券详情信息";
                break;
            default:
                break;
        }
        $Event = \think\Loader::controller('home/Api');
        $Event->web_poswxcode($pd, getMobileStoId(), $userinfo);
        return json_encode(array('code' => 1, 'msg' => 'ok'));
    } else {
        return json_encode(array('code' => -1, 'msg' => '提交失败'));
    }
}
//核销券
// @param   $coupon 券号
// @param   $userinfo 用户信息
// @param   $stoid 商户id
function update_coupon($quanno, $userinfo, $stoid, $store_erpid = "")
{
    $erpid = $store_erpid;
    if (empty($erpid)) $erpid = tpCache('shop_info.ERPId', $stoid);
    //查一下是否有包邮券
    $by_q = M('user_feemail')->where('no', $quanno)
        ->where('user_id', $userinfo['user_id'])
        ->field('id')->find();
    if ($by_q) {
        $rs = M("user_feemail")->where('no', $quanno)
            ->where('user_id', $userinfo['user_id'])
            ->where('isuse', 0)
            ->save(['isuse' => 1, 'use_time' => time()]);
        if ($rs)
            M("frozen_quan")->where('CashRepNo', $quanno)
                ->where('user_id', $userinfo['user_id'])->delete();
    } else {
        if ($erpid && empty($by_q)) {
            $sto = tpCache("shop_info", $stoid);
            $data = array('CashRepNo' => $quanno, 'VIPId' => $userinfo['erpvipid']);
            $s = getApiData('wxderp.cashreplace.edit', $sto['api_token'], array($data,));
            mlog("优惠券的" . $quanno . "-" . $userinfo['erpvipid'] . '-' . $s, "quan/" . $stoid);
            if ($s) {
                mlog($userinfo["user_id"] . $s, "quan/" . $stoid);
                //解冻优惠券
                M("frozen_quan")->where('CashRepNo', $quanno)->where('user_id', $userinfo['user_id'])->delete();
            } else {
                mlog($userinfo["user_id"] . "核销券失败", "quan/" . $stoid);
            }
        } else {
            $rs = M("coupon_list")->where('code', $quanno)
                ->where('uid', $userinfo['user_id'])
                ->where('is_user', 0)
                ->save(['is_user' => 1]);
            if ($rs)
                M("frozen_quan")->where('CashRepNo', $quanno)
                    ->where('user_id', $userinfo['user_id'])->delete();
        }
    }
}
//获取用户积分
// @param   $userid
function get_userpoints($userd, $stoid, $erpid)
{
    $integ = 0;
    if ($erpid) {
        if (empty($userd['erpvipid'])) {
            return $integ;
        }
        $where['VIPId'] = urlencode($userd['erpvipid']);
        $d = getApiData_java_p("/api/erp/vip/info/page", $erpid, $where, 1, 1);
        if (empty($d))
        {
            return $integ;
        }
        $d = json_decode($d, true);
        if ($d['data']['pageData'] && $d['data']['pageData'][0]) {
            $integ = $d['data']['pageData'][0]['Integral'];
            return $integ;
        }
        return $integ;
    } else {
        $newinfo = M('users')->where(array('store_id' => $stoid, 'user_id' => $userd['user_id']))->field('pay_points')->find();
        if ($newinfo) {
            $integ = $newinfo['pay_points'];
        }
        return $integ;
    }
}
/**
 * 订单操作日志
 * 参数示例
 * @param type $order_id 订单id
 * @param type $action_note 操作备注
 * @param type $status_desc 操作状态  提交订单, 付款成功, 取消, 等待收货, 完成
 * @param type $user_id 用户id 默认为管理员
 * @return boolean
 */
function logOrder($order_id, $action_note, $status_desc, $user_id = 0, $logtime = 0, $type = 0)
{
    //实时读取
    //$m_db = Db::connect('mian_db');
    $getlogtime = time();
    if ($logtime) {
        $getlogtime = $logtime;
    }
    $status_desc_arr = array('提交订单', '付款成功', '取消', '等待收货', '完成', '退货');
    // if(!in_array($status_desc, $status_desc_arr))
    // return false;
    $order = null;
    switch ($type) {
        case 0:
            $order = M('order')->where("order_id", $order_id)->find();
            break;
        case 1:
            $order = M('giftuser_order')->where("order_id", $order_id)->find();
            break;
    }
    if (empty($order)) {
        $order['order_status'] = 1;
        $order['shipping_status'] = 0;
        $order['pay_status'] = 1;
        $order['store_id'] = 1;
    }
    $action_info = array(
        'order_id' => $order_id,
        'action_user' => $user_id,
        'order_status' => $order['order_status'],
        'shipping_status' => $order['shipping_status'],
        'pay_status' => $order['pay_status'],
        'action_note' => $action_note,
        'status_desc' => $status_desc, //''
        'log_time' => $getlogtime,
        'store_id' => $order['store_id'],
        'type' => $type
    );
    return M('order_action')->add($action_info);
}
/*
 * 获取地区列表
 */
function get_region_list()
{
    //获取地址列表 缓存读取
    if (!S('region_list')) {
        $region_list = M('region')->select();
        $region_list = convert_arr_key($region_list, 'id');
        S('region_list', $region_list);
    }
    return $region_list ? $region_list : S('region_list');
}
/*
 * 获取用户地址列表
 */
function get_user_address_list($user_id)
{
    $lists = M('user_address')->where(array('user_id' => $user_id))->select();
    return $lists;
}
/*
 * 获取指定地址信息
 */
function get_user_address_info($user_id, $address_id)
{
    $data = M('user_address')->where(array('user_id' => $user_id, 'address_id' => $address_id))->find();
    return $data;
}
/*
 * 获取用户默认收货地址
 */
function get_user_default_address($user_id)
{
    $data = M('user_address')->where(array('user_id' => $user_id, 'is_default' => 1))->find();
    return $data;
}
/**
 * 获取订单状态的 中文描述名称
 * @param type $order_id 订单id
 * @param type $order 订单数组
 * @return string
 */
function orderStatusDesc($order_id = 0, $order = array())
{
    if (empty($order))
        $order = M('Order')->where("order_id", $order_id)->find();
    // 货到付款
    if ($order['pay_code'] == 'cod') {
        if (in_array($order['order_status'], array(0, 1)) && $order['shipping_status'] == 0)
            return 'WAITSEND'; //'待发货',
    } else // 非货到付款
    {
        if ($order['pay_status'] == 0 && $order['order_status'] == 0)
            return 'WAITPAY'; //'待支付',
        if ($order['pay_status'] == 1 && ($order['shipping_status'] == 1 || $order['shipping_status'] == 2) && ($order['order_status'] == 1))
            return 'WAITRECEIVE'; //'待收货',
        if ($order['pay_status'] == 1 && in_array($order['order_status'], array(0, 1)) && $order['shipping_status'] != 1)
            return 'WAITSEND'; //'待发货',
    }
    if ($order['pay_status'] == 1 && ($order['shipping_status'] == 1 || $order['shipping_status'] == 2) && ($order['order_status'] == 1))
        return 'WAITRECEIVE'; //'待收货',
    if ($order['order_status'] == 2)
        return 'WAITCCOMMENT'; //'待评价',
    if ($order['order_status'] == 3)
        return 'CANCEL'; //'已取消',
    if ($order['order_status'] == 4)
        return 'FINISH'; //'已完成',
    if ($order['order_status'] == 5)
        return 'CANCELLED'; //'已作废',
    if ($order['order_status'] == 6)
        return 'RETURNED'; //'已退货换货',
    return 'OTHER';
}
/**
 * 获取订单状态的 显示按钮
 * @param type $order_id 订单id
 * @param type $order 订单数组
 * @return array()
 */
function orderBtn($order_id = 0, $order = array())
{
    if (empty($order))
        $order = M('Order')->where("order_id", $order_id)->find();
    /**
     *  订单用户端显示按钮
     * 去支付     AND pay_status=0 AND order_status=0 AND pay_code ! ="cod"
     * 取消按钮  AND pay_status=0 AND shipping_status=0 AND order_status=0
     * 确认收货  AND shipping_status=1 AND order_status=0
     * 评价      AND order_status=1
     * 查看物流  if(!empty(物流单号))
     */
    $btn_arr = array(
        'pay_btn' => 0, // 去支付按钮
        'cancel_btn' => 0, // 取消按钮
        'receive_btn' => 0, // 确认收货
        'comment_btn' => 0, // 评价按钮
        'shipping_btn' => 0, // 查看物流
        'return_btn' => 0, // 退货按钮 (联系客服)
    );
    // 货到付款
    if ($order['pay_code'] == 'cod') {
        if (($order['order_status'] == 0 || $order['order_status'] == 1) && $order['shipping_status'] == 0) // 待发货
        {
            $btn_arr['cancel_btn'] = 1; // 取消按钮 (联系客服)
        }
        if ($order['shipping_status'] == 1 && $order['order_status'] == 1) //待收货
        {
            $btn_arr['receive_btn'] = 1;  // 确认收货
            $btn_arr['return_btn'] = 1; // 退货按钮 (联系客服)
        }
    } // 非货到付款
    else {
        if ($order['pay_status'] == 0 && $order['order_status'] == 0) // 待支付
        {
            $btn_arr['pay_btn'] = 1; // 去支付按钮
            $btn_arr['cancel_btn'] = 1; // 取消按钮
        }
        if ($order['pay_status'] == 1 && in_array($order['order_status'], array(0, 1)) && $order['shipping_status'] == 0) // 待发货
        {
            $btn_arr['return_btn'] = 1; // 退货按钮 (联系客服)
        }
        if ($order['pay_status'] == 1 && $order['order_status'] == 1 && ($order['shipping_status'] == 1 || $order['shipping_status'] == 2)) //待收货
        {
            $btn_arr['receive_btn'] = 1;  // 确认收货
            $btn_arr['return_btn'] = 1; // 退货按钮 (联系客服)
        }
    }
    if ($order['order_status'] == 2) {
        $btn_arr['comment_btn'] = 1;  // 评价按钮
        $btn_arr['return_btn'] = 1; // 退货按钮 (联系客服)
    }
    if ($order['shipping_status'] != 0) {
        $btn_arr['shipping_btn'] = 1; // 查看物流
    }
    if ($order['shipping_status'] == 2 && $order['order_status'] == 1) // 部分发货
    {
        $btn_arr['return_btn'] = 1; // 退货按钮 (联系客服)
    }
    return $btn_arr;
}
/**
 * 给订单数组添加属性  包括按钮显示属性 和 订单状态显示属性
 * @param type $order
 */
function set_btn_order_status($order)
{
    $order_status_arr = C('ORDER_STATUS_DESC');
    $order['order_status_code'] = $order_status_code = orderStatusDesc(0, $order); // 订单状态显示给用户看的
    $order['order_status_desc'] = $order_status_arr[$order_status_code];
    $orderBtnArr = orderBtn(0, $order);
    return array_merge($order, $orderBtnArr); // 订单该显示的按钮
}
/**
 * 支付完成修改订单
 * @param $order_sn 订单号
 * @param array $ext 额外参数
 * @param transaction_id 交易流水号
 * @return bool|void
 */
function update_pay_status($order_sn, $ext = array(), $transaction_id)
{
    if (stripos($order_sn, 'recharge') !== false) {
        //用户在线充值
        $count = M('recharge')->where("order_sn = :order_sn and pay_status = 0")->bind(['order_sn' => $order_sn])->count();   // 看看有没已经处理过这笔订单  支付宝返回不重复处理操作
        if ($count == 0) return false;
        $order = M('recharge')->where("order_sn", $order_sn)->find();
        M('recharge')->where("order_sn", $order_sn)->save(array('pay_status' => 1, 'pay_time' => time()));
        accountLog($order['user_id'], $order['account'], 0, '会员在线充值', 0, $order['store_id']);
    } else {
        // 如果这笔订单的支付状态为0
        //$count = M('order')->where("parent_sn = :order_sn and pay_status = 0")->bind(['order_sn' => $order_sn])
        //  ->count();   // 看看有没已经处理过这笔订单  支付宝返回不重复处理操作
        // 找出对应的订单
        $orderall = M('order')->where("parent_sn", $order_sn)
          //  ->field('order_id,order_sn,user_id,user_money,integral,coupon_price,discount_amount,order_prom_amount,goods_price,coupon_no,store_id,is_zsorder,pt_listno,pt_prom_id,is_pt_tz,pt_status,pay_status')
            ->select();
        if (count($orderall) <= 0) return false;
        $ord = $orderall[0];
        $r = 0;
        mlog('2-' . json_encode($orderall), "update_pay_status/" . $ord['store_id']);
        //处理拼单的订单
        if ($ord['is_zsorder'] < 2) {
            // 修改支付状态  已支付
            $r = M('order')->where("parent_sn", $order_sn)
                ->where("pay_status", 0)
                ->save(array('order_status' => 1, 'pay_status' => 1, 'pay_time' => time(), 'pay_sn' => $transaction_id));
        } else {
            // 修改支付状态  已支付
            $r = M('order')->where("order_sn", $order_sn)
                ->where("pt_status", 0)
                ->save(array('pt_status' => 1, 'pt_pay_sn' => $transaction_id, 'pt_pay_time' => time(), 'order_status' => 1,
                    'pay_time' => time(), 'pay_sn' => $transaction_id));
        }
        if (empty($r)) {
            mlog("支付失败-" . $order_sn, "update_pay_status/" . $ord['store_id']);
            return false;
        }
        //--如果是拼团的订单,从事务中拿出来--
        if ($ord['pt_prom_id'])
            check_team($ord['order_id'], $ord['pt_listno']);
        //--查找会员--
        $user = M('users')->where('user_id', $ord['user_id'])->find();
        //如果会员没有默认的门店,要反写订单的门店为默认门店
        if(empty($user['pickup_id'])  && empty($user['def_pickup_id']) && $ord['pickup_id'] ){
            M('users')->where('user_id', $ord['user_id'])->save(['def_pickup_id'=>$ord['pickup_id']]);
        }
        foreach ($orderall as $k => $v) {
            disoucponpt($v);
            if ($v['pt_prom_id'] == 0) {
                //如果是秒杀的redis有退回
                $hh = M('order_goods')->where('order_id', $v['order_id'])
                    ->where('prom_type', 1)->where('store_id', $v['store_id'])
                    ->field('order_id,goods_num,prom_id,rec_id,store_id')->select();
                if ($hh) {
                    //$redis = new \Redis();
                    //$redis->connect(redisip, 6379);
                    $redis = get_redis_handle();
                    //增加队列
                    foreach ($hh as $kk => $vv) {
                        //$name0 = 'ms' . $vv['prom_id'] . '-' . $vv['store_id'];
                        $name0 = get_redis_name($vv['prom_id'], 1, $vv['store_id']);
                        //如果redis有退订单
                        if (doublefind($redis, $name0, $vv['rec_id'])) {
                            for ($i = 0; $i < $vv['goods_num']; $i++) {
                                $redis->lPop($name0);
                            }
                            $jsda['num'] = -$vv['goods_num'];
                            $jsda['order_sn'] = $vv['order_sn'];
                            $jsda['type'] = 0;
                            mlog(json_encode($jsda), 'flash_log/' . $vv['store_id'] . '/' . $vv['prom_id']);
                        }
                    }
                }
                //如果是秒杀的redis有退回
                $hh = M('order_goods')->where('order_id', $v['order_id'])
                    ->where('prom_type', 2)->where('store_id', $v['store_id'])
                    ->field('order_id,goods_num,prom_id,rec_id,store_id')->select();
                if ($hh) {
                    //$redis = new \Redis();
                    //$redis->connect(redisip, 6379);
                    $redis = get_redis_handle();
                    //增加队列
                    foreach ($hh as $kk => $vv) {
                        //$name0 = 'grb' . $vv['prom_id'] . '-' . $vv['store_id'];
                        $name0 = get_redis_name($vv['prom_id'], 2, $vv['store_id']);
                        //如果redis有退订单
                        if (doublefind($redis, $name0, "2" . $vv['rec_id'])) {
                            for ($i = 0; $i < $vv['goods_num']; $i++) {
                                $redis->lPop($name0);
                            }
                            $jsda['num'] = -$vv['goods_num'];
                            $jsda['order_sn'] = $vv['order_sn'];
                            $jsda['type'] = 0;
                            mlog(json_encode($jsda), 'group_buy_log/' . $vv['store_id'] . '/' . $vv['prom_id']);
                        }
                    }
                }
            }
            if ($v['pt_prom_id'] > 0) {
                //如果是拼单的redis有退回
                $hh = M('order_goods')->where('order_id', $v['order_id'])
                    ->where('prom_type', 6)->where('store_id', $v['store_id'])
                    ->field('order_id,goods_num,prom_id,rec_id,store_id')->select();
                if ($hh) {
                    //$redis = new \Redis();
                    //$redis->connect(redisip, 6379);
                    $redis = get_redis_handle();
                    //增加队列
                    foreach ($hh as $kk => $vv) {
                        //$name0 = 'pind' . $vv['prom_id'] . '-' . $vv['store_id'];
                        $name0 = get_redis_name($vv['prom_id'], 6, $vv['store_id']);
                        //如果redis有退订单
                        if (doublefind($redis, $name0, $vv['rec_id'])) {
                            for ($i = 0; $i < $vv['goods_num']; $i++) {
                                $redis->lPop($name0);
                            }
                            $jsda['num'] = -$vv['goods_num'];
                            $jsda['order_sn'] = $vv['order_sn'];
                            $jsda['type'] = 0;
                            mlog(json_encode($jsda), 'pt_log/' . $vv['store_id'] . '/' . $vv['prom_id']);
                        }
                        //$name2 = 'pind' . $vv['prom_id'] . '-' . $ord['pt_listno'] . $vv['store_id'];
                        $name2 = $name0 . ":" . $ord['pt_listno'];
                        $len = $redis->lLen($name2);
                        if (doublefind($redis, $name2, $ord['order_id'])) {
                            $redis->lPop($name2, $ord['order_id'] . '_0');
                        } else {
                            //if($len==0){错的地方
                            if ($len == 0 && $ord['is_zsorder'] == 3 && $ord['is_pt_tz'] == 1) {
                                $teamnum = M('teamlist')->field('ct_num')->where('id', $vv['prom_id'])->find();
                                $th = $teamnum['ct_num'] - 1;
                                for ($o = 0; $o < $th; $o++) {
                                    $redis->lPush($name2, $v['order_id'] . '_' . $o);
                                }
                            }
                        }
                        //---如果这个单是这个人开的团,要还原团的状态---
                        if ($ord['is_pt_tz'] == 1) {
                            $da['state'] = 2;
                            $map['team_id'] = $vv['prom_id'];
                            $map['listno'] = $ord['pt_listno'];
                            $map['store_id'] = $vv['store_id'];
                            $ru = M('teamgroup')->where($map)->save($da);
                        }
                    }
                }
            }
        }
        //foreach ($orderall as $k => $v) {}
        mlog($order_sn . "交易流水" . $transaction_id, "update_pay_status/" . $ord['store_id']);
        // 成为分销商条件
        $distribut_condition = tpCache('distribut.condition', $ord['store_id']);
        $distribut_switch = tpCache('distribut.switch', $ord['store_id']);
        $distribut_money = tpCache('distribut.condition_money', $ord['store_id']);
        $distribut_goods_id = tpCache('distribut.condition_goods_id', $ord['store_id']);
        //判断分销可以注册的人数
        $isok = 1;
        $ty = M('store_distribut')->where('store_id', $ord['store_id'])->field('distribut_num')->find();
        $count1 = M("users")->where('store_id', $ord['store_id'])->where('is_distribut', 1)->count();
        //是否有购买
        $is_out = M("store_module_endtime")
            ->where('store_id', $ord['store_id'])
            ->where('type', 2)->find();
        if ($is_out) {
            if (empty($ty['distribut_num'])) {
                $isok = 0;
            }
            if ($ty['distribut_num'] <= $count1) {
                $isok = 0;
            }
        } else {
            //看体验人数是否到了
            $yy = M('distri_price')->where('type', 0)->where('money', 0)->find();
            $allnum = $yy['user_num'];
            if ($allnum <= $count1) {
                $isok = 0;
            }
        }
        /*--循环对单进行处理--*/
        foreach ($orderall as $k => $v) {
            $order = $v;
            mlog("支付:" . $order['user_id'], "order");
            // 减少对应商品的库存
            minus_stock($order['order_id']);
            // 给他升级, 根据order表查看消费记录 给他会员等级升级 修改他的折扣 和 总金额
            update_user_level($order['user_id']);
            if ($ext != 1) {
                // 记录订单操作日志
                if (array_key_exists('admin_id', $ext)) {
                    logOrder($order['order_id'], $ext['note'], '付款成功', $ext['admin_id']);
                } else {
                    logOrder($order['order_id'], '订单付款成功', '付款成功', $order['user_id']);
                }
            } else {
                logOrder($order['order_id'], '订单付款成功', '付款成功', $order['user_id']);
            }
            //分销设置
            $rrss = M('rebate_log')->where("order_id", $order['order_id'])->find();
            if ($rrss) {
                M('rebate_log')->where("order_id", $order['order_id'])->save(array('status' => 1));
            }
            mlog('isok:' . $isok, "order/" . $orderall[0]['store_id']);
            mlog('distribut_switch:' . $distribut_switch, "order/" . $orderall[0]['store_id']);
            mlog('is_dis:' . $user['is_distribut'], "order/" . $orderall[0]['store_id']);
            mlog('$distribut_condition:' . $distribut_condition, "order/" . $orderall[0]['store_id']);
            if ($isok == 1 && $distribut_switch == 1 && $user['is_distribut'] == 0) {
                switch ($distribut_condition) {
                    case 1:
                        $aprice = 0;
                        $odrgds = M("order_goods")->where('order_id', $order['order_id'])->select();
                        foreach ($odrgds as $k => $v) {
                            $aprice += $v['member_goods_price'] * $v['goods_num'];
                        }
                        mlog('aprice:' . $aprice, "order/" . $orderall[0]['store_id']);
                        mlog('distribut_money:' . $distribut_money, "order/" . $orderall[0]['store_id']);
                        if ($aprice >= $distribut_money) {
                            $str = "购买满" . $distribut_money . "元成为分销商";
                            M('users')->where("user_id", $order['user_id'])
                                ->save(array('is_distribut' => 1, 'be_distribut_time' => time(), 'be_dis_condition' => $str));
                            M('order')->where("order_id", $order['order_id'])->save(['is_bedistri' => 1]);
                            setcookie('is_distribut', 1, null, '/');
                        }
                        break;
                    case 2:
                        $odrgds = M("order_goods")->where('order_id', $order['order_id'])
                            ->where('goods_id', $distribut_goods_id)->select();
                        if ($odrgds) {
                            $gg = M('goods')->where('goods_id', $distribut_goods_id)->field('goods_name')->find();
                            $str = "购买" . $gg['goods_name'] . "成为分销商";
                            M('users')->where("user_id", $order['user_id'])
                                ->save(array('is_distribut' => 1, 'be_distribut_time' => time(), 'be_dis_condition' => $str));
                            M('order')->where("order_id", $order['order_id'])->save(['is_bedistri' => 1]);
                            setcookie('is_distribut', 1, null, '/');
                        }
                        break;
                    case 3:
                        $aprice = 0;
                        $odrgds = M("order_goods")->where('order_id', $order['order_id'])->select();
                        $ishasgoodsid = 0;
                        $str = "";
                        foreach ($odrgds as $k => $v) {
                            $aprice += $v['member_goods_price'] * $v['goods_num'];
                            if ($v['goods_id'] == $distribut_goods_id) {
                                $ishasgoodsid = 1;
                                $gg = M('goods')->where('goods_id', $distribut_goods_id)->field('goods_name')->find();
                                $str = "购买" . $gg['goods_name'] . "成为分销商";
                            }
                        }
                        if ($aprice >= $distribut_money || $ishasgoodsid == 1) {
                            if (empty($str))
                                $str = "购买满" . $distribut_money . "元成为分销商";
                            M('users')->where("user_id", $order['user_id'])
                                ->save(array('is_distribut' => 1, 'be_distribut_time' => time(), 'be_dis_condition' => $str));
                            M('order')->where("order_id", $order['order_id'])->save(['is_bedistri' => 1]);
                            setcookie('is_distribut', 1, null, '/');
                        }
                        break;
                }
            }
            //用户支付, 发送短信给商家
            //$res = checkEnableSendSms("4");
            //if (!$res || $res['status'] != 1) return;
            //if (!$res || $res['status'] != 1) return;
            //$sender = tpCache("shop_info.mobile");
            //if (empty($sender)) return;
            //$params = array('order_sn' => $order_sn);
            //sendSms("4", $sender, $params)
            if ($order['user_money'] > 0) {
                //扣除余额
                M('Users')->where("user_id", $order['user_id'])->setDec('user_money', $order['user_money']);
                //解冻余额
                $rs = M('Users')->where("user_id", $order['user_id'])
                    ->where('frozen_money>=' . $order['user_money'])->find();
                if ($rs)
                    M('Users')->where("user_id", $order['user_id'])->setDec('frozen_money', $order['user_money']);
                //记录log 日志
                $data4['user_id'] = $order['user_id'];
                $data4['user_money'] = -$order['user_money'];
                $data4['pay_points'] = -$order['user_money'];
                $data4['change_time'] = time();
                $data4['desc'] = '下单消费';
                $data4['order_sn'] = $order['order_sn'];
                $data4['order_id'] = $order['order_id'];
                // 如果使用了积分或者余额才记录
                ($data4['user_money'] || $data4['pay_points']) && M("AccountLog")->add($data4);
                $odata['user_id'] = $order['user_id'];
                //$odata['user_id']=null;
                $odata['create_time'] = time();
                $odata['money'] = $order['user_money'];
                $odata['remark'] = "购买使用余额";
                $odata['store_id'] = $order['store_id'];
                $odata['order_sn'] = $order['order_sn'];
                $odata['status'] = 1;
                $odata['type'] = 2;
                M('withdrawals')->save($odata);
            }
            $store_erpid = tpCache('shop_info.ERPId', $order['store_id']);//season
            /*---优惠券核销---*/
            $quanno = $order['coupon_no'];
            if (!empty($quanno)) {
                update_coupon($quanno, $user, $order['store_id'], $store_erpid);
            }
            /*---积分购,要减积分---*/
            if ($order['integral']) {
                //读取token
                if ($store_erpid) {
                    $user['api_token'] = tpCache('shop_info.api_token', $order['store_id']);
                    /*---
                    $vipid = $user['erpvipid'];
                    $data = ['Id' => $vipid,
                        'Integral' => -$order['integral'],
                        'Remark' => "积分购买商品",
                    ];
                    $re1 = getApiData("wxd.vip.addreduce", $user['api_token'], array($data));
                    mlog($user["user_id"] . $re1 . "积分购买", "Integral");--*/
                    cut_inte_order($user,$order,$store_erpid);
                } else {
                    accountLog($user["user_id"], 0, -$order['integral'], "积分购买商品", 0, $user['store_id'], $user["pay_points"]);//线上表
                }
            }
        }
    }
}
/**
 * 支付完成修改订单
 * @param $order_sn 订单号
 * @param array $ext 额外参数
 * @return bool|void
 */
function update_pay_status2($order_sn, $ext = array())
{
    // 如果这笔订单的支付状态为0
    //$count = M('order')->where("order_sn = :order_sn and pay_status = 0")->bind(['order_sn' => $order_sn])->count();      // 看看有没已经处理过这笔订单  支付宝返回不重复处理操作
    // 找出对应的订单
    $orderall = M('order')->where("order_sn", $order_sn)
       // ->field('order_id,order_sn,user_id,user_money,integral,coupon_price,discount_amount,order_prom_amount,goods_price,coupon_no,store_id,is_zsorder,pt_listno,pt_prom_id,order_amount')
        ->select();
    if (count($orderall) <= 0) return false;
    $user_id = $orderall[0]["user_id"];
    $ord = $orderall[0];
    $r = 0;
    if ($ord['is_zsorder'] < 2) {
        // 修改支付状态  已支付
        $r = M('order')->where("order_sn", $order_sn)
            ->where('pay_status', 0)->save(array('order_status' => 1, 'pay_status' => 1, 'pay_time' => time(), 'pay_sn' => 0));
    } else {
        // 修改支付状态  已支付
        $r = M('order')->where("order_sn", $order_sn)
            ->where('pt_status', 0)
            ->save(array('order_status' => 1, 'pt_status' => 1, 'pt_pay_sn' => 0, 'pt_pay_time' => time(), 'pay_time' => time()));
    }
    if (empty($r)) {
        mlog("支付失败0", "order/" . $orderall[0]['store_id']);
        return false;
    }
    foreach ($orderall as $k => $v) {
        if ($v['pt_prom_id'] > 0) {
            check_team($v['order_id'], $v['pt_listno']);
        }
        disoucponpt($v);
    }
    //查找会员
    $user = M('users')->where('user_id', $ord['user_id'])->find();
    //如果会员没有默认的门店,要反写订单的门店为默认门店
    if(empty($user['pickup_id'])  && empty($user['def_pickup_id']) && $ord['pickup_id'] ){
        M('users')->where('user_id', $ord['user_id'])->save(['def_pickup_id'=>$ord['pickup_id']]);
    }
    // 成为分销商条件
    $distribut_condition = tpCache('distribut.condition', $ord['store_id']);
    $distribut_switch = tpCache('distribut.switch', $ord['store_id']);
    $distribut_money = tpCache('distribut.condition_money', $ord['store_id']);
    $distribut_goods_id = tpCache('distribut.condition_goods_id', $ord['store_id']);
    //判断分销可以注册的人数
    $isok = 1;
    $ty = M('store_distribut')->where('store_id', $ord['store_id'])->field('distribut_num')->find();
    $count1 = M("users")->where('store_id', $ord['store_id'])->where('is_distribut', 1)->count();
    //是否有购买
    $is_out = M("store_module_endtime")
        ->where('store_id', $ord['store_id'])
        ->where('type', 2)->find();
    if ($is_out) {
        if (empty($ty['distribut_num'])) {
            $isok = 0;
        }
        if ($ty['distribut_num'] <= $count1) {
            $isok = 0;
        }
    } else {
        //看体验人数是否到了
        $yy = M('distri_price')->where('type', 0)->where('money', 0)->find();
        $allnum = $yy['user_num'];
        if ($allnum <= $count1) {
            $isok = 0;
        }
    }
    /*--循环对单进行处理--*/
    foreach ($orderall as $k => $v) {
        $order = $v;
        mlog("支付:" . $order['user_id'], "order");
        // 减少对应商品的库存
        minus_stock($order['order_id'], 0, $order['pt_listno']);
        // 给他升级, 根据order表查看消费记录 给他会员等级升级 修改他的折扣 和 总金额
        update_user_level($order['user_id']);
        if ($ext != 1) {
            // 记录订单操作日志
            if (array_key_exists('admin_id', $ext)) {
                logOrder($order['order_id'], $ext['note'], '付款成功', $ext['admin_id']);
            } else {
                logOrder($order['order_id'], '订单付款成功', '付款成功', $order['user_id']);
            }
        } else {
            logOrder($order['order_id'], '订单付款成功', '付款成功', $order['user_id']);
        }
        //分销设置
        M('rebate_log')->where("order_id", $order['order_id'])->save(array('status' => 1));
        //$str11=M('rebate_log')->where("order_id", $order['order_id'])->fetchSql(true)->save(array('status' => 1));
        //mlog($str11,'rebate_log/'.$order['store_id']);
        mlog('isok:' . $isok, "order/" . $orderall[0]['store_id']);
        mlog('distribut_switch:' . $distribut_switch, "order/" . $orderall[0]['store_id']);
        mlog('is_dis:' . $user['is_distribut'], "order/" . $orderall[0]['store_id']);
        mlog('distribut_condition:' . $distribut_condition, "order/" . $orderall[0]['store_id']);
        if ($isok == 1 && $distribut_switch == 1 && $user['is_distribut'] == 0) {
            switch ($distribut_condition) {
                case 1:
                    $aprice = 0;
                    $odrgds = M("order_goods")->where('order_id', $order['order_id'])->select();
                    foreach ($odrgds as $k => $v) {
                        $aprice += $v['member_goods_price'] * $v['goods_num'];
                    }
                    mlog('aprice:' . $aprice, "order/" . $orderall[0]['store_id']);
                    mlog('distribut_money:' . $distribut_money, "order/" . $orderall[0]['store_id']);
                    if ($aprice >= $distribut_money) {
                        $str = "购买满" . $distribut_money . "元成为分销商";
                        M('users')->where("user_id", $order['user_id'])
                            ->save(array('is_distribut' => 1, 'be_distribut_time' => time(), 'be_dis_condition' => $str));
                        M('order')->where("order_id", $order['order_id'])->save(['is_bedistri' => 1]);
                        setcookie('is_distribut', 1, null, '/');
                    }
                    break;
                case 2:
                    $odrgds = M("order_goods")->where('order_id', $order['order_id'])
                        ->where('goods_id', $distribut_goods_id)->select();
                    if ($odrgds) {
                        $gg = M('goods')->where('goods_id', $distribut_goods_id)->field('goods_name')->find();
                        $str = "购买" . $gg['goods_name'] . "成为分销商";
                        M('users')->where("user_id", $order['user_id'])
                            ->save(array('is_distribut' => 1, 'be_distribut_time' => time(), 'be_dis_condition' => $str));
                        M('order')->where("order_id", $order['order_id'])->save(['is_bedistri' => 1]);
                        setcookie('is_distribut', 1, null, '/');
                    }
                    break;
                case 3:
                    $aprice = 0;
                    $odrgds = M("order_goods")->where('order_id', $order['order_id'])->select();
                    $ishasgoodsid = 0;
                    $str = "";
                    foreach ($odrgds as $k => $v) {
                        $aprice += $v['member_goods_price'] * $v['goods_num'];
                        if ($v['goods_id'] == $distribut_goods_id) {
                            $ishasgoodsid = 1;
                            $gg = M('goods')->where('goods_id', $distribut_goods_id)->field('goods_name')->find();
                            $str = "购买" . $gg['goods_name'] . "成为分销商";
                        }
                    }
                    if ($aprice >= $distribut_money || $ishasgoodsid == 1) {
                        if (empty($str))
                            $str = "购买满" . $distribut_money . "元成为分销商";
                        M('users')->where("user_id", $order['user_id'])
                            ->save(array('is_distribut' => 1, 'be_distribut_time' => time(), 'be_dis_condition' => $str));
                        M('order')->where("order_id", $order['order_id'])->save(['is_bedistri' => 1]);
                        setcookie('is_distribut', 1, null, '/');
                    }
                    break;
            }
        }
        //用户支付, 发送短信给商家
        //$res = checkEnableSendSms("4");
        //if (!$res || $res['status'] != 1) return;
        //if (!$res || $res['status'] != 1) return;
        //$sender = tpCache("shop_info.mobile");
        //if (empty($sender)) return;
        //$params = array('order_sn' => $order_sn);
        //sendSms("4", $sender, $params);
        if ($order['user_money'] > 0) {
            //扣除余额
            M('Users')->where("user_id", $user_id)->setDec('user_money', $order['user_money']);
            //解冻余额
            $rs = M('Users')->where("user_id", $order['user_id'])
                ->where('frozen_money>=' . $order['user_money'])->find();
            if ($rs)
                M('Users')->where("user_id", $order['user_id'])->setDec('frozen_money', $order['user_money']);
            //记录log 日志
            $data4['user_id'] = $user_id;
            $data4['user_money'] = -$order['user_money'];
            $data4['pay_points'] = -$order['user_money'];
            $data4['change_time'] = time();
            $data4['desc'] = '下单消费';
            $data4['order_sn'] = $order['order_sn'];
            $data4['order_id'] = $order['order_id'];
            // 如果使用了积分或者余额才记录
            ($data4['user_money'] || $data4['pay_points']) && M("AccountLog")->add($data4);
            $odata['user_id'] = $order['user_id'];
            $odata['create_time'] = time();
            $odata['money'] = $order['user_money'];
            $odata['remark'] = "购买使用余额";
            $odata['store_id'] = $order['store_id'];
            $odata['order_sn'] = $order['order_sn'];
            $odata['status'] = 1;
            $odata['type'] = 2;
            M('withdrawals')->save($odata);
        }
        $store_erpid = tpCache('shop_info.ERPId', $order['store_id']);//season
        if ($order['integral'] > 0) {
            if ($store_erpid) {
                $user['api_token'] = tpCache('shop_info.api_token', $order['store_id']);
                /*---
                $data = ['Id' => $user['erpvipid'],
                    'Integral' => '-' . $order['integral'],
                    'Remark' => '积分购扣积分',
                ];
                //$re1 = getApiData("wxd.vip.addreduce", $user['api_token'], array($data));
                //$re_data = json_decode($re1, true);
                //mlog("购扣积分".$order['order_sn'].":".$re1, "Integral/" . $order['store_id']);--*/
                cut_inte_order($user,$order,$store_erpid);
            } else {
                accountLog($user["user_id"], 0, -$order['integral'], "积分购扣积分", 0, $user['store_id'], $user["pay_points"]);//线上表
            }
        }
        /*---优惠券核销---*/
        $quanno = $order['coupon_no'];
        if (!empty($quanno)) {
            update_coupon($quanno, $user, $order['store_id'], $store_erpid);
        }
    }
}
/**
 * 支付完成修改订单
 * @param $order_sn 订单号
 * @param array $ext 额外参数
 * @param transaction_id 交易流水号
 * @return bool|void
 */
function update_pay_status_gift($order_sn, $ext = array(), $transaction_id)
{
    // 如果这笔订单的支付状态为0
    $count = M('giftuser_order')->where("parent_sn = :order_sn and pay_status = 0")->bind(['order_sn' => $order_sn])->count();   // 看看有没已经处理过这笔订单  支付宝返回不重复处理操作
    if ($count == 0) return false;
    Db::startTrans();
    try {
        // 找出对应的订单
        $orderall = M('giftuser_order')->where("parent_sn", $order_sn)->select();
        // 修改支付状态  已支付
        $r = M('giftuser_order')->where("parent_sn", $order_sn)->save(array('order_status' => 1, 'pay_status' => 1, 'pay_time' => time(), 'pay_sn' => $transaction_id));
        if (empty($r)) {
            mlog("支付失败", "order");
        }
        mlog("交易流水" . $transaction_id, "order");
        $ord = $orderall[0];
        //查找会员
        $user = M('users')->where('user_id', $ord['user_id'])->find();
        // 成为分销商条件
        $distribut_condition = tpCache('distribut.condition', $ord['store_id']);
        $distribut_switch = tpCache('distribut.switch', $ord['store_id']);
        $distribut_money = tpCache('distribut.condition_money', $ord['store_id']);
        $distribut_goods_id = tpCache('distribut.condition_goods_id', $ord['store_id']);
        //判断分销可以注册的人数
        $isok = 1;
        $ty = M('store_distribut')->where('store_id', $ord['store_id'])->field('distribut_num')->find();
        $count1 = M("users")->where('store_id', $ord['store_id'])->where('is_distribut', 1)->count();
        //是否有购买
        $is_out = M("store_module_endtime")
            ->where('store_id', $ord['store_id'])
            ->where('type', 2)->find();
        if ($is_out) {
            if (empty($ty['distribut_num'])) {
                $isok = 0;
            }
            if ($ty['distribut_num'] <= $count1) {
                $isok = 0;
            }
        } else {
            //看体验人数是否到了
            $yy = M('distri_price')->where('type', 0)->where('money', 0)->find();
            $allnum = $yy['user_num'];
            if ($allnum <= $count1) {
                $isok = 0;
            }
        }
        /*--循环对单进行处理--*/
        foreach ($orderall as $k => $v) {
            $order = $v;
            /*---针对秒杀特殊处理---*/
            $ordid = $v['order_id'];
            $gdlist = M('giftuser_order_goods')->where('order_id', $ordid)->select();
            foreach ($gdlist as $kko => $vvo) {
                if ($vvo['prom_type'] == 1) {
                }
            }
            mlog("支付:" . $order['user_id'], "order");
            // 减少对应商品的库存
            minus_stock($order['order_id'], 1);
            // 给他升级, 根据order表查看消费记录 给他会员等级升级 修改他的折扣 和 总金额
            update_user_level($order['user_id']);
            if ($ext != 1) {
                // 记录订单操作日志
                if (array_key_exists('admin_id', $ext)) {
                    logOrder($order['order_id'], $ext['note'], '付款成功', $ext['admin_id'], 1);
                } else {
                    logOrder($order['order_id'], '订单付款成功', '付款成功', $order['user_id'], 1);
                }
            } else {
                logOrder($order['order_id'], '订单付款成功', '付款成功', $order['user_id'], 1);
            }
            //分销设置
            $rrss = M('rebate_log')->where("order_id", $order['order_id'])->find();
            if ($rrss) {
                M('rebate_log')->where("order_id", $order['order_id'])->save(array('status' => 1));
            }
            if ($isok == 1 && $distribut_switch == 1 && $user['is_distribut'] == 0) {
                switch ($distribut_condition) {
                    case 1:
                        $aprice = 0;
                        $odrgds = M("giftuser_order_goods")->where('order_id', $order['order_id'])->select();
                        foreach ($odrgds as $k => $v) {
                            $aprice += $v['member_goods_price'] * $v['goods_num'];
                        }
                        if ($aprice >= $distribut_money) {
                            $str = "购买满" . $distribut_money . "元成为分销商";
                            M('users')->where("user_id", $order['user_id'])
                                ->save(array('is_distribut' => 1, 'be_distribut_time' => time(), 'be_dis_condition' => $str));
                            M('order')->where("order_id", $order['order_id'])->save(['is_bedistri' => 1]);
                            setcookie('is_distribut', 1, null, '/');
                        }
                        break;
                    case 2:
                        $odrgds = M("giftuser_order_goods")->where('order_id', $order['order_id'])
                            ->where('goods_id', $distribut_goods_id)->select();
                        if ($odrgds) {
                            $gg = M('goods')->where('goods_id', $distribut_goods_id)->field('goods_name')->find();
                            $str = "购买" . $gg['goods_name'] . "成为分销商";
                            M('users')->where("user_id", $order['user_id'])
                                ->save(array('is_distribut' => 1, 'be_distribut_time' => time(), 'be_dis_condition' => $str));
                            M('order')->where("order_id", $order['order_id'])->save(['is_bedistri' => 1]);
                            setcookie('is_distribut', 1, null, '/');
                        }
                        break;
                    case 3:
                        $aprice = 0;
                        $odrgds = M("giftuser_order_goods")->where('order_id', $order['order_id'])->select();
                        $ishasgoodsid = 0;
                        $str = "";
                        foreach ($odrgds as $k => $v) {
                            $aprice += $v['member_goods_price'] * $v['goods_num'];
                            if ($v['goods_id'] == $distribut_goods_id) {
                                $ishasgoodsid = 1;
                                $gg = M('goods')->where('goods_id', $distribut_goods_id)->field('goods_name')->find();
                                $str = "购买" . $gg['goods_name'] . "成为分销商";
                            }
                        }
                        if ($aprice >= $distribut_money || $ishasgoodsid == 1) {
                            if (empty($str))
                                $str = "购买满" . $distribut_money . "元成为分销商";
                            M('users')->where("user_id", $order['user_id'])
                                ->save(array('is_distribut' => 1, 'be_distribut_time' => time(), 'be_dis_condition' => $str));
                            M('order')->where("order_id", $order['order_id'])->save(['is_bedistri' => 1]);
                            setcookie('is_distribut', 1, null, '/');
                        }
                        break;
                }
            }
            //用户支付, 发送短信给商家
            //$res = checkEnableSendSms("4");
            //if (!$res || $res['status'] != 1) return;
            //if (!$res || $res['status'] != 1) return;
            //$sender = tpCache("shop_info.mobile");
            //if (empty($sender)) return;
            //$params = array('order_sn' => $order_sn);
            //sendSms("4", $sender, $params)
            if ($order['user_money'] > 0) {
                //扣除余额
                M('Users')->where("user_id", $order['user_id'])->setDec('user_money', $order['user_money']);
                //解冻余额
                //解冻余额
                $rs = M('Users')->where("user_id", $order['user_id'])
                    ->where('frozen_money>=' . $order['user_money'])->find();
                if ($rs)
                    M('Users')->where("user_id", $order['user_id'])->setDec('frozen_money', $order['user_money']);
                //记录log 日志
                $data4['user_id'] = $order['user_id'];
                $data4['user_money'] = -$order['user_money'];
                $data4['pay_points'] = -$order['user_money'];
                $data4['change_time'] = time();
                $data4['desc'] = '下单消费';
                $data4['order_sn'] = $order['order_sn'];
                $data4['order_id'] = $order['order_id'];
                // 如果使用了积分或者余额才记录
                ($data4['user_money'] || $data4['pay_points']) && M("AccountLog")->add($data4);
                //$odata['user_id'] = $order['user_id'];
                $odata['user_id'] = null;
                $odata['create_time'] = time();
                $odata['money'] = $order['user_money'];
                $odata['remark'] = "购买使用余额";
                $odata['store_id'] = $order['store_id'];
                $odata['order_sn'] = $order['order_sn'];
                $odata['status'] = 1;
                $odata['type'] = 2;
                M('withdrawals')->save($odata);
            }
            $store_erpid = tpCache('shop_info.ERPId', $order['store_id']);//season
            /*---优惠券核销---*/
            $quanno = $order['coupon_no'];
            if (!empty($quanno)) {
                update_coupon($quanno, $user, $order['store_id'], $store_erpid);
            }
            /*---积分购,要减积分---*/
            if ($order['integral']) {
                //读取token
                if ($store_erpid) {
                    /*--
                    $user['api_token'] = tpCache('shop_info.api_token', $order['store_id']);
                    $vipid = $user['erpvipid'];
                    $data = ['Id' => $vipid,
                        'Integral' => -$order['integral'],
                        'Remark' => "积分购买商品",
                    ];
                    $re1 = getApiData("wxd.vip.addreduce", $user['api_token'], array($data));
                    mlog($user["user_id"] . $re1 . "积分购买", "Integral");--*/
                    cut_inte_order($user,$order,$store_erpid);
                } else {
                    accountLog($user["user_id"], 0, -$order['integral'], "积分购买商品", 0, $user['store_id'], $user["pay_points"]);//线上表
                }
            }
        }
        Db::commit();
        return true;
    } catch (\Exception $e) {
        Db::rollback();
        return false;
    }
}
/**
 * 支付完成修改订单
 * @param $order_sn 订单号
 * @param array $ext 额外参数
 * @return bool|void
 */
function update_pay_status_gift2($order_sn, $ext = array())
{
    // 如果这笔订单的支付状态为0
    $count = M('giftuser_order')->where("order_sn = :order_sn and pay_status = 0")->bind(['order_sn' => $order_sn])->count();   // 看看有没已经处理过这笔订单  支付宝返回不重复处理操作
    if ($count == 0) return false;
    // 找出对应的订单
    $orderall = M('giftuser_order')->where("order_sn", $order_sn)
        ->field('order_id,order_sn,user_id,user_money,integral,coupon_no,store_id,is_zsorder,pt_listno')
        ->select();
    $user_id = $orderall[0]["user_id"];
    // 修改支付状态  已支付
    $r = M('giftuser_order')->where("order_sn", $order_sn)->save(array('order_status' => 1, 'pay_status' => 1, 'pay_time' => time()));
    if (empty($r)) {
        mlog("支付失败", "order");
    }
    $ord = $orderall[0];
    //查找会员
    $user = M('users')->where('user_id', $ord['user_id'])->find();
    // 成为分销商条件
    $distribut_condition = tpCache('distribut.condition', $ord['store_id']);
    $distribut_switch = tpCache('distribut.switch', $ord['store_id']);
    $distribut_money = tpCache('distribut.condition_money', $ord['store_id']);
    $distribut_goods_id = tpCache('distribut.condition_goods_id', $ord['store_id']);
    //判断分销可以注册的人数
    $isok = 1;
    $ty = M('store_distribut')->where('store_id', $ord['store_id'])->field('distribut_num')->find();
    $count1 = M("users")->where('store_id', $ord['store_id'])->where('is_distribut', 1)->count();
    //是否有购买
    $is_out = M("store_module_endtime")
        ->where('store_id', $ord['store_id'])
        ->where('type', 2)->find();
    if ($is_out) {
        if (empty($ty['distribut_num'])) {
            $isok = 0;
        }
        if ($ty['distribut_num'] <= $count1) {
            $isok = 0;
        }
    } else {
        //看体验人数是否到了
        $yy = M('distri_price')->where('type', 0)->where('money', 0)->find();
        $allnum = $yy['user_num'];
        if ($allnum <= $count1) {
            $isok = 0;
        }
    }
    /*--循环对单进行处理--*/
    foreach ($orderall as $k => $v) {
        $order = $v;
        mlog("支付:" . $order['user_id'], "order");
        // 减少对应商品的库存
        minus_stock($order['order_id'], 1);
        // 给他升级, 根据order表查看消费记录 给他会员等级升级 修改他的折扣 和 总金额
        update_user_level($order['user_id']);
        if ($ext != 1) {
            // 记录订单操作日志
            if (array_key_exists('admin_id', $ext)) {
                logOrder($order['order_id'], $ext['note'], '付款成功', $ext['admin_id'], 1);
            } else {
                logOrder($order['order_id'], '订单付款成功', '付款成功', $order['user_id'], 1);
            }
        } else {
            logOrder($order['order_id'], '订单付款成功', '付款成功', $order['user_id'], 1);
        }
        //分销设置
        M('rebate_log')->where("order_id", $order['order_id'])->save(array('status' => 1));
        if ($isok == 1 && $distribut_switch == 1 && $user['is_distribut'] == 0) {
            switch ($distribut_condition) {
                case 1:
                    $aprice = 0;
                    $odrgds = M("giftuser_order_goods")->where('order_id', $order['order_id'])->select();
                    foreach ($odrgds as $k => $v) {
                        $aprice += $v['member_goods_price'] * $v['goods_num'];
                    }
                    if ($aprice >= $distribut_money) {
                        $str = "购买满" . $distribut_money . "元成为分销商";
                        M('users')->where("user_id", $order['user_id'])
                            ->save(array('is_distribut' => 1, 'be_distribut_time' => time(), 'be_dis_condition' => $str));
                        M('order')->where("order_id", $order['order_id'])->save(['is_bedistri' => 1]);
                        setcookie('is_distribut', 1, null, '/');
                    }
                    break;
                case 2:
                    $odrgds = M("giftuser_order_goods")->where('order_id', $order['order_id'])
                        ->where('goods_id', $distribut_goods_id)->select();
                    if ($odrgds) {
                        $gg = M('goods')->where('goods_id', $distribut_goods_id)->field('goods_name')->find();
                        $str = "购买" . $gg['goods_name'] . "成为分销商";
                        M('users')->where("user_id", $order['user_id'])
                            ->save(array('is_distribut' => 1, 'be_distribut_time' => time(), 'be_dis_condition' => $str));
                        M('order')->where("order_id", $order['order_id'])->save(['is_bedistri' => 1]);
                        setcookie('is_distribut', 1, null, '/');
                    }
                    break;
                case 3:
                    $aprice = 0;
                    $odrgds = M("giftuser_order_goods")->where('order_id', $order['order_id'])->select();
                    $ishasgoodsid = 0;
                    $str = "";
                    foreach ($odrgds as $k => $v) {
                        $aprice += $v['member_goods_price'] * $v['goods_num'];
                        if ($v['goods_id'] == $distribut_goods_id) {
                            $ishasgoodsid = 1;
                            $gg = M('goods')->where('goods_id', $distribut_goods_id)->field('goods_name')->find();
                            $str = "购买" . $gg['goods_name'] . "成为分销商";
                        }
                    }
                    if ($aprice >= $distribut_money || $ishasgoodsid == 1) {
                        if (empty($str))
                            $str = "购买满" . $distribut_money . "元成为分销商";
                        M('users')->where("user_id", $order['user_id'])
                            ->save(array('is_distribut' => 1, 'be_distribut_time' => time(), 'be_dis_condition' => $str));
                        M('order')->where("order_id", $order['order_id'])->save(['is_bedistri' => 1]);
                        setcookie('is_distribut', 1, null, '/');
                    }
                    break;
            }
        }
        //用户支付, 发送短信给商家
        //$res = checkEnableSendSms("4");
        //if (!$res || $res['status'] != 1) return;
        //if (!$res || $res['status'] != 1) return;
        //$sender = tpCache("shop_info.mobile");
        //if (empty($sender)) return;
        //$params = array('order_sn' => $order_sn);
        //sendSms("4", $sender, $params);
        if ($order['user_money'] > 0) {
            //扣除余额
            M('Users')->where("user_id", $user_id)->setDec('user_money', $order['user_money']);
            //解冻余额
            //解冻余额
            $rs = M('Users')->where("user_id", $order['user_id'])
                ->where('frozen_money>=' . $order['user_money'])->find();
            if ($rs)
                M('Users')->where("user_id", $order['user_id'])->setDec('frozen_money', $order['user_money']);
            //记录log 日志
            $data4['user_id'] = $user_id;
            $data4['user_money'] = -$order['user_money'];
            $data4['pay_points'] = -$order['user_money'];
            $data4['change_time'] = time();
            $data4['desc'] = '下单消费';
            $data4['order_sn'] = $order['order_sn'];
            $data4['order_id'] = $order['order_id'];
            // 如果使用了积分或者余额才记录
            ($data4['user_money'] || $data4['pay_points']) && M("AccountLog")->add($data4);
            $odata['user_id'] = $order['user_id'];
            $odata['create_time'] = time();
            $odata['money'] = $order['user_money'];
            $odata['remark'] = "购买使用余额";
            $odata['store_id'] = $order['store_id'];
            $odata['order_sn'] = $order['order_sn'];
            $odata['status'] = 1;
            $odata['type'] = 2;
            M('withdrawals')->save($odata);
        }
        $store_erpid = tpCache('shop_info.ERPId', $order['store_id']);//season
        if ($order['integral'] > 0) {
            if ($store_erpid) {
                cut_inte_order($user,$order,$store_erpid);
            } else {
                accountLog($user["user_id"], 0, -$order['integral'], "积分购扣积分", 0, $user['store_id'], $user["pay_points"]);//线上表
            }
        }
        /*---优惠券核销---*/
        $quanno = $order['coupon_no'];
        if (!empty($quanno)) {
            update_coupon($quanno, $user, $order['store_id'], $store_erpid);
        }
    }
}
/**
 * 订单确认收货,要实现倍增
 * @param $id   订单id
 */
function confirm_order($id, $user_id = 0, $confirm_time = 0)
{
    $getconfirm_time = time();
    if ($confirm_time) {
        $getconfirm_time = $confirm_time;
    }
    $where = "order_id = :id";
    $bind['id'] = $id;
    $user_id && $where .= " and user_id = $user_id ";
    $order = M('order')->where($where)->bind($bind)->find();
    if ($order['order_status'] != 1)
        return array('status' => -1, 'msg' => '该订单不能收货确认');
    if ($order['order_status'] > 1)
        return array('status' => -1, 'msg' => '该订单不能收货确认');
    if ($order['order_status'] == 2)
        return array('status' => -1, 'msg' => '该订单已收货确认');
    $data['order_status'] = 2; // 已收货
    $data['pay_status'] = 1; // 已付款
    $data['confirm_time'] = $getconfirm_time; // 收货确认时间
    $row = M('order')->where(array('order_id' => $id))->save($data);
    if (!$row)
        return array('status' => -3, 'msg' => '操作失败');
    //order_give($order);// 调用送礼物方法, 给下单这个人赠送相应的礼物
    if (!empty($order['give_integral']) || !empty($order['give_coupon_id']) || !empty($order['give_lb_id']))
        give_discount($user_id, $order['give_integral'], $order['give_coupon_id'], $order['store_id'], $order);//优惠促销赠送积分、优惠券
    mz_condition($order, $user_id);//美妆会员条件
    //分销设置
    M('rebate_log')->where("order_id", $id)->save(array('status' => 2, 'confirm' => $getconfirm_time));
    logOrder($id, $user_id . '您已经确认收货', '确认收货', $user_id, $getconfirm_time);
    //确认收货,那么会员团要返利
    tz_fl($order);
    return array('status' => 1, 'msg' => '操作成功', 'order' => $order);
}
/**
 * 给订单送券送积分 送东西
 */
function order_give($order)
{
    $order_goods = M('order_goods')->where("order_id", $order['order_id'])
        ->cache("order_goods_" . getMobileStoId())->select();
    //查找购买商品送优惠券活动
    foreach ($order_goods as $val) {
        if ($val['prom_type'] == 3) {
            $prom = M('prom_goods')->where('type=3 and id=:id')->bind(['id' => $val['prom_id']])->find();
            if ($prom) {
                $coupon = M('coupon')->where("id", $prom['expression'])->find();//查找优惠券模板
                if ($coupon && $coupon['createnum'] > 0) {
                    $remain = $coupon['createnum'] - $coupon['send_num'];//剩余派发量
                    if ($remain > 0) {
                        $data = array('cid' => $coupon['id'], 'type' => $coupon['type'], 'uid' => $order['user_id'], 'send_time' => time());
                        M('coupon_list')->add($data);
                        M('Coupon')->where("id", $coupon['id'])->setInc('send_num'); // 优惠券领取数量加一
                    }
                }
            }
        }
    }
    //查找订单满额送优惠券活动
    $pay_time = $order['pay_time'];
    $prom = M('prom_order')
        ->where("type>1 and end_time>:pay_time1 and start_time<:pay_time2 and money<=:money")
        ->bind(['pay_time1' => $pay_time, 'pay_time2' => $pay_time, 'money' => $order['order_amount']])
        ->order('money desc')
        ->find();
    if ($prom) {
        if ($prom['type'] == 3) {
            $coupon = M('coupon')->where("id", $prom['expression'])->find();//查找优惠券模板
            if ($coupon) {
                if ($coupon['createnum'] > 0) {
                    $remain = $coupon['createnum'] - $coupon['send_num'];//剩余派发量
                    if ($remain > 0) {
                        $data = array('cid' => $coupon['id'], 'type' => $coupon['type'], 'uid' => $order['user_id'], 'send_time' => time());
                        M('coupon_list')->add($data);
                        M('Coupon')->where("id", $coupon['id'])->setInc('send_num'); // 优惠券领取数量加一
                    }
                }
            }
        } else if ($prom['type'] == 2) {
            accountLog($order['user_id'], 0, $prom['expression'], "订单活动赠送积分");
        }
    }
    $points = M('order_goods')->where("order_id", $order['order_id'])->sum("give_integral * goods_num");
    $points && accountLog($order['user_id'], 0, $points, "下单赠送积分");
}
/**
 * 查看商品活动情况
 * @param goods_id 商品ID
 */
function get_goods_promotion($goods_id, $user_id = 0, $goods_num = 0)
{
    $now = time();
    $goods = M('goods')->where("goods_id", $goods_id)->find();
    $where = [
        'end_time' => ['gt', $now],
        'start_time' => ['lt', $now],
        'id' => $goods['prom_id'],
        'is_end' => 0,
    ];
    $prom['price'] = $goods['shop_price'];
    $prom['prom_type'] = $goods['prom_type'];
    $prom['prom_id'] = $goods['prom_id'];
    $prom['is_end'] = 0;
    $prom['store_count'] = $goods['store_count'];
    if ($goods['prom_type'] == 1) {//抢购
        $prominfo = M('flash_sale')->where($where)->find();
        if (!empty($prominfo)) {
            $prom['start'] = $prominfo["start_time"];
            $prom['end'] = $prominfo["end_time"];
            $prom['goods_num'] = $prominfo['goods_num'];
            $prom['buy_num'] = $prominfo['buy_num'];
            $prom['onlybuy'] = $prominfo['goods_num'] - $prominfo['buy_num'];
            if ($prominfo['goods_num'] <= $prominfo['buy_num']) {
                $prom['is_end'] = 2;//已售馨
                //$prom['price'] = $prominfo['price'];
            } else {
                $prom['price'] = $prominfo['price'];
                if ($prominfo['buy_limit'] == 0) {
                    $prom['buy_limit'] = 100000;
                } else {
                    //核查用户购买数量
                    $where = "user_id = :user_id and order_status in(1,2,4) and (order_status =0 or pay_status=1) and  add_time>" . $prominfo['start_time'] . " and add_time<" . $prominfo['end_time'];
                    $order_id_arr = M('order')->where($where)->bind(['user_id' => $user_id])->getField('order_id', true);
                    if ($order_id_arr) {
                        $goods_num = M('order_goods')->where("prom_id={$goods['prom_id']} and prom_type={$goods['prom_type']} and order_id in (" . implode(',', $order_id_arr) . ")")->sum('goods_num');
                        if ($goods_num == null) $goods_num = 0;
                        if ($goods_num < $prominfo['buy_limit']) {
                            $prom['buy_limit'] = $prominfo['buy_limit'] - $goods_num;
                        } else {
                            $prom['is_end'] = 3;//已经超出限购数量
                            $prom['buy_limit'] = 0;
                        }
                    } else {
                        $prom['buy_limit'] = $prominfo['buy_limit'];
                    }
                }
            }
        } else {
            $prom['is_end'] = 4;//未找到活动
        }
    }
    if ($goods['prom_type'] == 2) {//团购
        $prominfo = M('group_buy')->where($where)->find();
        if (!empty($prominfo)) {
            $prom['start'] = $prominfo["start_time"];
            $prom['end'] = $prominfo["end_time"];
            $prom['goods_num'] = $prominfo['goods_num'];
            $prom['buy_num'] = $prominfo['buy_num'];
            $prom['onlybuy'] = $prominfo['goods_num'] - $prominfo['buy_num'];
            if ($prominfo['goods_num'] <= $prominfo['buy_num']) {
                $prom['is_end'] = 2;//已售馨
            } else {
                $prom['price'] = $prominfo['price'];
                if ($prominfo['buy_limit'] == 0) {
                    $prom['buy_limit'] = 100000;
                } else {
                    //核查用户购买数量
                    $where = "user_id = :user_id and  order_status in(1,2,4) and (order_status =0 or pay_status=1) and  add_time>" . $prominfo['start_time'] . " and add_time<" . $prominfo['end_time'];
                    $order_id_arr = M('order')->where($where)->bind(['user_id' => $user_id])->getField('order_id', true);
                    if ($order_id_arr) {
                        $goods_num = M('order_goods')->where("prom_id={$goods['prom_id']} and prom_type={$goods['prom_type']} and order_id in (" . implode(',', $order_id_arr) . ")")->sum('goods_num');
                        if ($goods_num == null) $goods_num = 0;
                        if ($goods_num < $prominfo['buy_limit']) {
                            $prom['buy_limit'] = $prominfo['buy_limit'] - $goods_num;
                        } else {
                            if ($prominfo['buy_limit'] > 0) {
                                $prom['is_end'] = 3;//已经超出限购数量
                                $prom['buy_limit'] = 0;
                            }
                        }
                    } else {
                        $prom['buy_limit'] = $prominfo['buy_limit'];
                    }
                }
            }
        } else {
            $prom['is_end'] = 4;//未找到活动
        }
    }
    if ($goods['prom_type'] == 3) {//优惠促销
        $prominfo = M('prom_goods')->where($where)->field('id')->find();
        if (!empty($prominfo) && $goods_num > 0) {
            $prom = discount($goods['shop_price'] * $goods_num, $prominfo['id'], $goods_num, $user_id);
            $prom['store_count'] = $goods['store_count'];
        }
    }
    if ($goods['prom_type'] == 4) {
        $prominfo = M('integral_buy')->where('is_show', 1)->where($where)->find();
        if (!empty($prominfo)) {
            $prom['start'] = $prominfo["start_time"];
            $prom['end'] = $prominfo["end_time"];
            $prom['goods_num'] = $prominfo['limitqty'];
            $prom['buy_num'] = $prominfo['buy_num'];
            $prom['buy_limit'] = $prominfo['limitvipqty'];
            $prom['showlimit'] = $prominfo['limitvipqty'];
            $prom['integral'] = 0;
            $prom['addmoney'] = 0;
            $prom['onlybuy'] = $prominfo['limitqty'] - $prominfo['buy_num'];
            if ($prominfo['limitqty'] <= $prominfo['buy_num']) {
                $prom['is_end'] = 2;//已售馨
                $prom['integral'] = $prominfo['integral'];
                $prom['addmoney'] = $prominfo['addmoney'];
            } else {
                $prom['integral'] = $prominfo['integral'];
                $prom['addmoney'] = $prominfo['addmoney'];
                $prom['name'] = $prominfo['name'];
                $prom['price'] = $prominfo['addmoney'];
                if ($prominfo['limitvipqty'] == 0) {
                    $prom['buy_limit'] = 100000;
                } else {
                    //核查用户购买数量
                    $where = "user_id = :user_id and order_status in(1,2,4) and (order_status =0 or pay_status=1) and  add_time>" . $prominfo['start_time'] . " and add_time<" . $prominfo['end_time'];
                    $order_id_arr = M('order')->where($where)->bind(['user_id' => $user_id])->getField('order_id', true);
                    if ($order_id_arr) {
                        $wh = "prom_id={$goods['prom_id']} and prom_type={$goods['prom_type']} and order_id in (" . implode(',', $order_id_arr) . ")";
                        $goods_num = M('order_goods')->where($wh)->sum('goods_num');
                        if ($goods_num == null) $goods_num = 0;
                        if ($goods_num < $prominfo['limitvipqty']) {
                            $prom['buy_limit'] = $prominfo['limitvipqty'] - $goods_num;
                        } else {
                            $prom['buy_limit'] = 0;
                            $prom['is_end'] = 3;//已经超出限购数量
                        }
                    } else {
                        $prom['buy_limit'] = $prominfo['limitvipqty'];
                    }
                }
            }
        } else {
            $prom['is_end'] = 4;//未找到活动
        }
    }
    if ($goods['prom_type'] == 5) {
        $prominfo = M('collocation')->where($where)->find();
    }
    //拼团活动
    if ($goods['prom_type'] == 6) {
        $prominfo = M('teamlist')->where($where)->where('is_show', 1)->find();
        if (!empty($prominfo)) {
            $prom['start'] = $prominfo["start_time"];
            $prom['end'] = $prominfo["end_time"];
            $prom['goods_num'] = $prominfo['goods_num'];
            $prom['buy_num'] = $prominfo['buy_num'];
            $prom['onlybuy'] = $prominfo['goods_num'] - $prominfo['buy_num'];
            if ($prominfo['goods_num'] <= $prominfo['buy_num']) {
                $prom['is_end'] = 2;//已售馨
                //$prom['price'] = $prominfo['price'];
            } else {
                $prom['price'] = $prominfo['price'];
                //单是阶梯团的时候,应该是付定金
                if ($prominfo['kttype'] == 3) {
                    $prom['price'] = $prominfo['yf_price'];
                }
                if ($prominfo['buy_limit'] == 0) {
                    $prom['buy_limit'] = 100000;
                } else {
                    //核查用户购买数量
                    $where = "user_id = :user_id and order_status in(0,1,2,4,6) and pt_status<>3 and pt_status<>0  and pt_prom_id>0 and add_time>" . $prominfo['start_time'] . " and add_time<" . $prominfo['end_time'];
                    $order_id_arr = M('order')->where($where)->bind(['user_id' => $user_id])->getField('order_id', true);
                    if ($order_id_arr) {
                        $goods_num = M('order_goods')->where("prom_id={$goods['prom_id']} and prom_type={$goods['prom_type']} and order_id in (" . implode(',', $order_id_arr) . ")")->sum('goods_num');
                        if ($goods_num == null) $goods_num = 0;
                        if ($goods_num < $prominfo['buy_limit']) {
                            $prom['buy_limit0'] = $prominfo['buy_limit'];
                            $prom['buy_limit'] = $prominfo['buy_limit'] - $goods_num;
                        } else {
                            if ($prominfo['buy_limit'] > 0) {
                                $prom['is_end'] = 3;//已经超出限购数量
                                $prom['buy_limit'] = 0;
                            }
                        }
                    } else {
                        $prom['buy_limit'] = $prominfo['buy_limit'];
                    }
                }
            }
        } else {
            $prom['is_end'] = 4;//未找到活动
        }
    }
    if (!empty($prominfo)) {
        $prom['start_time'] = $prominfo['start_time'];
        $prom['end_time'] = $prominfo['end_time'];
    } else {
        $prom['prom_type'] = $prom['prom_id'] = 0;//活动已过期
        $prom['is_end'] = 1;//已结束
    }
    if ($prom['prom_id'] == 0) {
        //M('goods')->where("goods_id", $goods_id)->save($prom);
    }
    return $prom;
}
/**
 * 查看商品活动情况
 * @param goods_id 商品ID,带入商品,带入活动
 */
function get_goods_promotion1($goods, $prom1 = null, $user_id = 0, $goods_num = 0, $goods_list = '')
{
    $now = time();
    $where = [
        'end_time' => ['gt', $now],
        'start_time' => ['lt', $now],
        'id' => $goods['prom_id'],
        'is_end' => 0,
    ];
    $prom['price'] = $goods['shop_price'];
    $prom['prom_type'] = $goods['prom_type'];
    $prom['prom_id'] = $goods['prom_id'];
    $prom['is_end'] = 0;
    $prom['store_count'] = $goods['store_count'];
    if ($goods['prom_type'] == 1) {//抢购
        $prominfo = $prom1;
        if ($prominfo == null)
            $prominfo = M('flash_sale')->where($where)->find();
        if (!empty($prominfo)) {
            $prom['start'] = $prominfo["start_time"];
            $prom['end'] = $prominfo["end_time"];
            $prom['goods_num'] = $prominfo['goods_num'];
            $prom['buy_num'] = $prominfo['buy_num'];
            $prom['onlybuy'] = $prominfo['goods_num'] - $prominfo['buy_num'];
            if ($prominfo['goods_num'] <= $prominfo['buy_num']) {
                $prom['is_end'] = 2;//已售馨
                //$prom['price'] = $prominfo['price'];
            } else {
                $prom['price'] = $prominfo['price'];
                if ($prominfo['buy_limit'] == 0) {
                    $prom['buy_limit'] = 100000;
                } else {
                    //核查用户购买数量
                    $where = "user_id = :user_id and order_status in(1,2,4) and (order_status =0 or pay_status=1) and  add_time>" . $prominfo['start_time'] . " and add_time<" . $prominfo['end_time'];
                    $order_id_arr = M('order')->where($where)->bind(['user_id' => $user_id])->getField('order_id', true);
                    if ($order_id_arr) {
                        $goods_num = M('order_goods')->where("prom_id={$goods['prom_id']} and prom_type={$goods['prom_type']} and order_id in (" . implode(',', $order_id_arr) . ")")->sum('goods_num');
                        if ($goods_num == null) $goods_num = 0;
                        if ($goods_num < $prominfo['buy_limit']) {
                            $prom['buy_limit'] = $prominfo['buy_limit'] - $goods_num;
                        } else {
                            $prom['is_end'] = 3;//已经超出限购数量
                            $prom['buy_limit'] = 0;
                        }
                    } else {
                        $prom['buy_limit'] = $prominfo['buy_limit'];
                    }
                }
            }
        } else {
            $prom['is_end'] = 4;//未找到活动
        }
    }
    if ($goods['prom_type'] == 2) {//团购
        $prominfo = $prom1;
        if ($prominfo == null)
            $prominfo = M('group_buy')->where($where)->find();
        if (!empty($prominfo)) {
            $prom['start'] = $prominfo["start_time"];
            $prom['end'] = $prominfo["end_time"];
            $prom['goods_num'] = $prominfo['goods_num'];
            $prom['buy_num'] = $prominfo['buy_num'];
            $prom['onlybuy'] = $prominfo['goods_num'] - $prominfo['buy_num'];
            if ($prominfo['goods_num'] <= $prominfo['buy_num']) {
                $prom['is_end'] = 2;//已售馨
            } else {
                $prom['price'] = $prominfo['price'];
                if ($prominfo['buy_limit'] == 0) {
                    $prom['buy_limit'] = 100000;
                } else {
                    //核查用户购买数量
                    $where = "user_id = :user_id and order_status in(1,2,4) and (order_status =0 or pay_status=1) and  add_time>" . $prominfo['start_time'] . " and add_time<" . $prominfo['end_time'];
                    $order_id_arr = M('order')->where($where)->bind(['user_id' => $user_id])->getField('order_id', true);
                    if ($order_id_arr) {
                        $goods_num = M('order_goods')->where("prom_id={$goods['prom_id']} and prom_type={$goods['prom_type']} and order_id in (" . implode(',', $order_id_arr) . ")")->sum('goods_num');
                        if ($goods_num == null) $goods_num = 0;
                        if ($goods_num < $prominfo['buy_limit']) {
                            $prom['buy_limit'] = $prominfo['buy_limit'] - $goods_num;
                        } else {
                            $prom['is_end'] = 3;//已经超出限购数量
                            $prom['buy_limit'] = 0;
                        }
                    } else {
                        $prom['buy_limit'] = $prominfo['buy_limit'];
                    }
                }
            }
        } else {
            $prom['is_end'] = 4;//未找到活动
        }
    }
    if ($goods['prom_type'] == 3) {//优惠促销
        $prominfo = M('prom_goods')->where($where)->field('id')->find();
        mlog(json_encode($prominfo), "get_goods_promotion1/" . $goods['store_id']);
        if (!empty($prominfo) && $goods_num > 0) {
            mlog(json_encode($prominfo) . "12121", "get_goods_promotion1/" . $goods['store_id']);
            $prom = discount($goods['shop_price'] * $goods_num, $prominfo['id'], $goods_num, $user_id);
            $prom['store_count'] = $goods['store_count'];
        }
    }
    if ($goods['prom_type'] == 4) {
        $prominfo = $prom1;
        if ($prominfo == null)
            $prominfo = M('integral_buy')->where('is_show', 1)->where($where)->find();
        if (!empty($prominfo)) {
            $prom['start'] = $prominfo["start_time"];
            $prom['end'] = $prominfo["end_time"];
            $prom['goods_num'] = $prominfo['limitqty'];
            $prom['buy_num'] = $prominfo['buy_num'];
            $prom['buy_limit'] = $prominfo['limitvipqty'];
            $prom['showlimit'] = $prominfo['limitvipqty'];
            $prom['integral'] = 0;
            $prom['addmoney'] = 0;
            $prom['onlybuy'] = $prominfo['limitqty'] - $prominfo['buy_num'];
            if ($prominfo['limitqty'] <= $prominfo['buy_num']) {
                $prom['is_end'] = 2;//已售馨
                $prom['integral'] = $prominfo['integral'];
                $prom['addmoney'] = $prominfo['addmoney'];
            } else {
                $prom['integral'] = $prominfo['integral'];
                $prom['addmoney'] = $prominfo['addmoney'];
                $prom['name'] = $prominfo['name'];
                $prom['price'] = $prominfo['addmoney'];
                if ($prominfo['limitvipqty'] == 0) {
                    $prom['buy_limit'] = 100000;
                } else {
                    //核查用户购买数量
                    $where = "user_id = :user_id and order_status in(1,2,4) and (order_status =0 or pay_status=1) and  add_time>" . $prominfo['start_time'] . " and add_time<" . $prominfo['end_time'];
                    $order_id_arr = M('order')->where($where)->bind(['user_id' => $user_id])->getField('order_id', true);
                    if ($order_id_arr) {
                        $wh = "prom_id={$goods['prom_id']} and prom_type={$goods['prom_type']} and order_id in (" . implode(',', $order_id_arr) . ")";
                        $goods_num = M('order_goods')->where($wh)->sum('goods_num');
                        if ($goods_num == null) $goods_num = 0;
                        if ($goods_num < $prominfo['limitvipqty']) {
                            $prom['buy_limit'] = $prominfo['limitvipqty'] - $goods_num;
                        } else {
                            $prom['buy_limit'] = 0;
                            $prom['is_end'] = 3;//已经超出限购数量
                        }
                    } else {
                        $prom['buy_limit'] = $prominfo['limitvipqty'];
                    }
                }
            }
        } else {
            $prom['is_end'] = 4;//未找到活动
        }
    }
    if ($goods['prom_type'] == 5) {
        $prominfo = M('collocation')->where($where)->find();
        if (!empty($prominfo)) {
            $prom['goods'] = M('collocation_list')->where(['prom_id' => $goods['prom_id'], 'goods_id' => ['in', $goods_list]])->select();
        }
    }
    //拼团活动
    if ($goods['prom_type'] == 6) {
        $prominfo = $prom1;
        if ($prominfo == null)
            $prominfo = M('teamlist')->where($where)->where('is_show', 1)->find();
        if (!empty($prominfo)) {
            $prom['start'] = $prominfo["start_time"];
            $prom['end'] = $prominfo["end_time"];
            $prom['goods_num'] = $prominfo['goods_num'];
            $prom['buy_num'] = $prominfo['buy_num'];
            $prom['onlybuy'] = $prominfo['goods_num'] - $prominfo['buy_num'];
            if ($prominfo['goods_num'] <= $prominfo['buy_num']) {
                $prom['is_end'] = 2;//已售馨
                //$prom['price'] = $prominfo['price'];
            } else {
                $prom['price'] = $prominfo['price'];
                //单是阶梯团的时候,应该是付定金
                if ($prominfo['kttype'] == 3) {
                    $prom['price'] = $prominfo['yf_price'];
                }
                if ($prominfo['buy_limit'] == 0) {
                    $prom['buy_limit'] = 100000;
                } else {
                    //核查用户购买数量
                    $where = "user_id = :user_id and order_status in(0,1,2,4,6) and pt_status<>3 and pt_status<>0  and pt_prom_id>0 and add_time>" . $prominfo['start_time'] . " and add_time<" . $prominfo['end_time'];
                    $order_id_arr = M('order')->where($where)->bind(['user_id' => $user_id])->getField('order_id', true);
                    if ($order_id_arr) {
                        $goods_num = M('order_goods')->where("prom_id={$goods['prom_id']} and prom_type={$goods['prom_type']} and order_id in (" . implode(',', $order_id_arr) . ")")->sum('goods_num');
                        if ($goods_num == null) $goods_num = 0;
                        if ($goods_num < $prominfo['buy_limit']) {
                            $prom['buy_limit'] = $prominfo['buy_limit'] - $goods_num;
                        } else {
                            if ($prominfo['buy_limit'] > 0) {
                                $prom['is_end'] = 3;//已经超出限购数量
                                $prom['buy_limit'] = 0;
                            }
                        }
                    } else {
                        $prom['buy_limit'] = $prominfo['buy_limit'];
                    }
                }
            }
        } else {
            $prom['is_end'] = 4;//未找到活动
        }
    }
    if (!empty($prominfo)) {
        $prom['start_time'] = $prominfo['start_time'];
        $prom['end_time'] = $prominfo['end_time'];
    } else {
         if ($goods['prom_type'] != 3) {
             $prom['prom_type'] = $prom['prom_id'] = 0;//活动已过期
             $prom['is_end'] = 1;//已结束
         }
    }
    if ($prom['prom_id'] == 0) {
        //M('goods')->where("goods_id", $goods_id)->save($prom);
    }
    return $prom;
}
/**
 * 查看商品活动情况
 * @param goods_id 商品ID,带入商品,带入活动
 */
function get_goods_promotion2($goods, $prom1 = null, $user_id = 0, $goods_num = 0, $goods_list = '')
{
    $now = time();
    $where = [
        'end_time' => ['gt', $now],
        'start_time' => ['lt', $now],
        'id' => $goods['prom_id'],
        'is_end' => 0,
    ];
    $prom['price'] = $goods['shop_price'];
    $prom['prom_type'] = $goods['prom_type'];
    $prom['prom_id'] = $goods['prom_id'];
    $prom['is_end'] = 0;
    $prom['store_count'] = $goods['store_count'];
    if ($goods['prom_type'] == 1) {//抢购
        $prominfo = $prom1;
        if ($prominfo == null)
            $prominfo = M('flash_sale')->where($where)->find();
        if (!empty($prominfo)) {
            $prom['start'] = $prominfo["start_time"];
            $prom['end'] = $prominfo["end_time"];
            $prom['goods_num'] = $prominfo['goods_num'];
            $prom['buy_num'] = $prominfo['buy_num'];
            $prom['onlybuy'] = $prominfo['goods_num'] - $prominfo['buy_num'];
            if ($prominfo['goods_num'] <= $prominfo['buy_num']) {
                $prom['is_end'] = 2;//已售馨
                //$prom['price'] = $prominfo['price'];
            } else {
                $prom['price'] = $prominfo['price'];
                if ($prominfo['buy_limit'] == 0) {
                    $prom['buy_limit'] = 100000;
                } else {
                    //核查用户购买数量
                    $where = "user_id = :user_id and order_status in(1,2,4) and (order_status =0 or pay_status=1) and  add_time>" . $prominfo['start_time'] . " and add_time<" . $prominfo['end_time'];
                    $order_id_arr = M('order')->where($where)->bind(['user_id' => $user_id])->getField('order_id', true);
                    if ($order_id_arr) {
                        $goods_num = M('order_goods')->where("prom_id={$goods['prom_id']} and prom_type={$goods['prom_type']} and order_id in (" . implode(',', $order_id_arr) . ")")->sum('goods_num');
                        if ($goods_num == null) $goods_num = 0;
                        if ($goods_num < $prominfo['buy_limit']) {
                            $prom['buy_limit'] = $prominfo['buy_limit'] - $goods_num;
                        } else {
                            $prom['is_end'] = 3;//已经超出限购数量
                            $prom['buy_limit'] = 0;
                        }
                    } else {
                        $prom['buy_limit'] = $prominfo['buy_limit'];
                    }
                }
            }
        } else {
            $prom['is_end'] = 4;//未找到活动
        }
    }
    if ($goods['prom_type'] == 2) {//团购
        $prominfo = $prom1;
        if ($prominfo == null)
            $prominfo = M('group_buy')->where($where)->find();
        if (!empty($prominfo)) {
            $prom['start'] = $prominfo["start_time"];
            $prom['end'] = $prominfo["end_time"];
            $prom['goods_num'] = $prominfo['goods_num'];
            $prom['buy_num'] = $prominfo['buy_num'];
            $prom['onlybuy'] = $prominfo['goods_num'] - $prominfo['buy_num'];
            if ($prominfo['goods_num'] <= $prominfo['buy_num']) {
                $prom['is_end'] = 2;//已售馨
            } else {
                $prom['price'] = $prominfo['price'];
                if ($prominfo['buy_limit'] == 0) {
                    $prom['buy_limit'] = 100000;
                } else {
                    //核查用户购买数量
                    $where = "user_id = :user_id and order_status in(1,2,4) and (order_status =0 or pay_status=1) and  add_time>" . $prominfo['start_time'] . " and add_time<" . $prominfo['end_time'];
                    $order_id_arr = M('order')->where($where)->bind(['user_id' => $user_id])->getField('order_id', true);
                    if ($order_id_arr) {
                        $goods_num = M('order_goods')->where("prom_id={$goods['prom_id']} and prom_type={$goods['prom_type']} and order_id in (" . implode(',', $order_id_arr) . ")")->sum('goods_num');
                        if ($goods_num == null) $goods_num = 0;
                        if ($goods_num < $prominfo['buy_limit']) {
                            $prom['buy_limit'] = $prominfo['buy_limit'] - $goods_num;
                        } else {
                            $prom['is_end'] = 3;//已经超出限购数量
                            $prom['buy_limit'] = 0;
                        }
                    } else {
                        $prom['buy_limit'] = $prominfo['buy_limit'];
                    }
                }
            }
        } else {
            $prom['is_end'] = 4;//未找到活动
        }
    }
    if ($goods['prom_type'] == 3) {//优惠促销
        $prominfo = M('prom_goods')->where($where)->field('id')->find();
        if (!empty($prominfo) && $goods_num > 0) {
            $prom = discount($goods['shop_price'] * $goods_num, $prominfo['id'], $goods_num, $user_id);
            $prom['store_count'] = $goods['store_count'];
        }
    }
    if ($goods['prom_type'] == 4) {
        $prominfo = $prom1;
        if ($prominfo == null)
            $prominfo = M('integral_buy')->where('is_show', 1)->where($where)->find();
        if (!empty($prominfo)) {
            $prom['start'] = $prominfo["start_time"];
            $prom['end'] = $prominfo["end_time"];
            $prom['goods_num'] = $prominfo['limitqty'];
            $prom['buy_num'] = $prominfo['buy_num'];
            $prom['buy_limit'] = $prominfo['limitvipqty'];
            $prom['showlimit'] = $prominfo['limitvipqty'];
            $prom['integral'] = 0;
            $prom['addmoney'] = 0;
            $prom['onlybuy'] = $prominfo['limitqty'] - $prominfo['buy_num'];
            if ($prominfo['limitqty'] <= $prominfo['buy_num']) {
                $prom['is_end'] = 2;//已售馨
                $prom['integral'] = $prominfo['integral'];
                $prom['addmoney'] = $prominfo['addmoney'];
            } else {
                $prom['integral'] = $prominfo['integral'];
                $prom['addmoney'] = $prominfo['addmoney'];
                $prom['name'] = $prominfo['name'];
                $prom['price'] = $prominfo['addmoney'];
                if ($prominfo['limitvipqty'] == 0) {
                    $prom['buy_limit'] = 100000;
                } else {
                    //核查用户购买数量
                    $where = "user_id = :user_id and order_status in(1,2,4) and (order_status =0 or pay_status=1) and  add_time>" . $prominfo['start_time'] . " and add_time<" . $prominfo['end_time'];
                    $order_id_arr = M('order')->where($where)->bind(['user_id' => $user_id])->getField('order_id', true);
                    if ($order_id_arr) {
                        $wh = "prom_id={$goods['prom_id']} and prom_type={$goods['prom_type']} and order_id in (" . implode(',', $order_id_arr) . ")";
                        $goods_num = M('order_goods')->where($wh)->sum('goods_num');
                        if ($goods_num == null) $goods_num = 0;
                        if ($goods_num < $prominfo['limitvipqty']) {
                            $prom['buy_limit'] = $prominfo['limitvipqty'] - $goods_num;
                        } else {
                            $prom['buy_limit'] = 0;
                            $prom['is_end'] = 3;//已经超出限购数量
                        }
                    } else {
                        $prom['buy_limit'] = $prominfo['limitvipqty'];
                    }
                }
            }
        } else {
            $prom['is_end'] = 4;//未找到活动
        }
    }
    if ($goods['prom_type'] == 5) {
        $prominfo = M('collocation')->where($where)->find();
        if (!empty($prominfo)) {
            $prom['goods'] = M('collocation_list')->where(['prom_id' => $goods['prom_id'], 'goods_id' => ['in', $goods_list]])->select();
        }
    }
    //拼团活动
    if ($goods['prom_type'] == 6) {
        $prominfo = $prom1;
        if ($prominfo == null)
            $prominfo = M('teamlist')->where($where)->where('is_show', 1)->find();
        if (!empty($prominfo)) {
            $prom['start'] = $prominfo["start_time"];
            $prom['end'] = $prominfo["end_time"];
            $prom['goods_num'] = $prominfo['goods_num'];
            $prom['buy_num'] = $prominfo['buy_num'];
            $prom['onlybuy'] = $prominfo['goods_num'] - $prominfo['buy_num'];
            if ($prominfo['goods_num'] <= $prominfo['buy_num']) {
                $prom['is_end'] = 2;//已售馨
                //$prom['price'] = $prominfo['price'];
            } else {
                $prom['price'] = $prominfo['price'];
                //单是阶梯团的时候,应该是付定金
                if ($prominfo['kttype'] == 3) {
                    $prom['price'] = $prominfo['yf_price'];
                }
                if ($prominfo['buy_limit'] == 0) {
                    $prom['buy_limit'] = 100000;
                } else {
                    //核查用户购买数量
                    $where = "user_id = :user_id and order_status in(0,1,2,4,6) and pt_status<>3 and pt_status<>0 and add_time>" . $prominfo['start_time'] . " and add_time<" . $prominfo['end_time'];
                    $order_id_arr = M('order')->where($where)->bind(['user_id' => $user_id])->getField('order_id', true);
                    if ($order_id_arr) {
                        $goods_num = M('order_goods')->where("prom_id={$goods['prom_id']} and prom_type={$goods['prom_type']} and order_id in (" . implode(',', $order_id_arr) . ")")->sum('goods_num');
                        if ($goods_num == null) $goods_num = 0;
                        if ($goods_num < $prominfo['buy_limit']) {
                            $prom['buy_limit'] = $prominfo['buy_limit'] - $goods_num;
                        } else {
                            $prom['is_end'] = 3;//已经超出限购数量
                            $prom['buy_limit'] = 0;
                        }
                    } else {
                        $prom['buy_limit'] = $prominfo['buy_limit'];
                    }
                }
            }
        } else {
            $prom['is_end'] = 4;//未找到活动
        }
    }
    if (!empty($prominfo)) {
        $prom['start_time'] = $prominfo['start_time'];
        $prom['end_time'] = $prominfo['end_time'];
    } else {
        $prom['prom_type'] = $prom['prom_id'] = 0;//活动已过期
        $prom['is_end'] = 1;//已结束
    }
    if ($prom['prom_id'] == 0) {
        //M('goods')->where("goods_id", $goods_id)->save($prom);
    }
    return $prom;
}
/**
 * 查看订单是否满足条件参加活动
 * @param order_amount 订单应付金额
 */
function get_order_promotion($order_amount, $stoid)
{
    $parse_type = array('0' => '满额打折', '1' => '满额优惠金额', '2' => '满额送倍数积分', '3' => '满额送优惠券', '4' => '满额免运费');
    $now = time();
    $prom = M('prom_order')->where("type<2 and is_end=0 and end_time>$now and start_time<$now and money<=$order_amount")->where('store_id', $stoid)->order('money desc')->find();
    $res = array('order_amount' => $order_amount, 'order_prom_id' => 0, 'order_prom_amount' => 0);
    if ($prom) {
        if ($prom['type'] == 0) {
            $res['order_amount'] = round($order_amount * $prom['expression'] / 100, 2);//满额打折
            $res['order_prom_amount'] = $order_amount - $res['order_amount'];
            $res['order_prom_id'] = $prom['id'];
        } elseif ($prom['type'] == 1) {
            $res['order_amount'] = $order_amount - $prom['expression'];//满额优惠金额
            $res['order_prom_amount'] = $prom['expression'];
            $res['order_prom_id'] = $prom['id'];
        }
    }
    return $res;
}
/**
 * 计算订单金额,没用使用订单优惠的一部分
 * @param type $user_id 用户id
 * @param type $order_goods 购买的商品
 * @param type $shipping 物流code
 * @param type $shipping_price 物流费用, 如果传递了物流费用 就不在计算物流费
 * @param type $province 省份
 * @param type $city 城市
 * @param type $district 县
 * @param type $pay_points 积分
 * @param type $user_money 余额
 * @param type $coupon_id 优惠券
 * @param type $couponCode 优惠码
 */
function calculate_price($user_id = 0, $order_goods, $shipping_code = '', $shipping_price = 0, $province = 0, $city = 0, $district = 0, $pay_points = 0, $user_money = 0, $coupon_id = 0, $couponCode = '', $store_id = 0, $exptype = 0, $userarr = null)
{
    if (empty($store_id)) {
        $store_id = getMobileStoId();
    }
    if (empty($order_goods)) {
        return array('status' => -9, 'msg' => '商品列表不能为空', 'result' => '');
    }
    $cartLogic = new app\home\logic\CartLogic();
    //$user = M('users')->where("user_id", $user_id)->find();// 找出这个用户
    $user = null;
    if (empty($userarr))
        $user = M('users')->where("user_id", $user_id)->find();// 找出这个用户
    else
        $user = $userarr;
    $goods_id_arr = get_arr_column($order_goods, 'goods_id');
    $goods_arr = M('goods')->where("goods_id in(" . implode(',', $goods_id_arr) . ")")
        ->getField('goods_id,weight,market_price,is_free_shipping,exp_sum_type,uniform_exp_sum'); // 商品id 和重量对应的键值对
    $goods_piece = -1;//商品件数
    $shipping_price = 0;//总运费
    $goods_weight = -1;
    $goods_price = 0;
    $cut_fee = 0;
    $anum = 0;
    $dis = 0;//优惠专用
    foreach ($order_goods as $key => $val) {
        // 如果传递过来的商品列表没有定义会员价
        if (!array_key_exists('member_goods_price', $val)) {
            $user['discount'] = $user['discount'] ? $user['discount'] : 1; // 会员折扣 不能为 0
            $order_goods[$key]['member_goods_price'] = $val['member_goods_price'] = $val['goods_price'] * $user['discount'];
        }
        //如果商品不是包邮的,且不是自提
        $isfeelexp = $goods_arr[$val['goods_id']]['is_free_shipping'];
        if ($isfeelexp == 0) {
            switch ($goods_arr[$val['goods_id']]['exp_sum_type']) {
                case 1:
                    //统一运费
                    if (!empty($shipping_code))
                        $shipping_price += $goods_arr[$val['goods_id']]['uniform_exp_sum'];
                    break;
                case 2:
                    //累积商品重量 每种商品的重量 * 数量
                    $goods_weight += $goods_arr[$val['goods_id']]['weight'] * $val['goods_num'];
                    if ($goods_weight < 0) $goods_weight = 0;
                    break;
                case 3:
                    //累积商品数量
                    $goods_piece += $val['goods_num'];
                    if ($goods_piece < 0) $goods_piece = 0;
                    break;
            }
        }
        $order_goods[$key]['goods_fee'] = $val['goods_num'] * $val['member_goods_price'];    // 小计
        $order_goods[$key]['store_count'] = getGoodNum($val['goods_id'], $val['spec_key']); // 最多可购买的库存数量
        if ($order_goods[$key]['store_count'] <= 0)
            return array('status' => -10, 'msg' => $order_goods[$key]['goods_name'] . "库存不足,请重新下单", 'result' => '');
        $goods_price += $order_goods[$key]['goods_fee']; // 商品总价
        $cut_fee += $val['goods_num'] * $val['market_price'] - $val['goods_num'] * $val['member_goods_price']; // 共节约
        $anum += $val['goods_num']; // 购买数量
    }
    // 优惠券处理操作
    $coupon_price = 0;
    if (!empty($coupon_id)) {
        if ($coupon_id && $user_id) {
            $coupon_price = $cartLogic->getCouponMoney($user_id, $coupon_id, 1); // 下拉框方式选择优惠券
        }
        if ($couponCode && $user_id) {
            $coupon_result = $cartLogic->getCouponMoneyByCode($couponCode, $goods_price); // 根据 优惠券 号码获取的优惠券
            if ($coupon_result['status'] < 0)
                return $coupon_result;
            $coupon_price = $coupon_result['result'];
        }
    }
    $freight_free = tpCache('shopping.freight_free', $store_id); // 全场满多少免运费
    // 处理物流
    if (!empty($shipping_code[0]) && !empty($province)) {
        /*--自提--*/
        if ($exptype == 1) {
            $shipping_price = 0;
        } else {
            if ($goods_weight > -1)
                $shipping_price += $cartLogic->cart_freight2($shipping_code, $province, $city, $district, $goods_weight, $store_id);
            if ($goods_piece > -1)
                $shipping_price += $cartLogic->cart_piece2($shipping_code, $province, $city, $district, $goods_piece, $store_id);
        }
    }
    //获取线下积分
    if ($pay_points > 0) {
        $tk = M("store")->where("store_id", $store_id)->find();
        //$map['Id'] = array('=', $user['erpvipid']);
        //$rs = getApiData('wxd.vip.vipinfo.list.get', $tk['api_token'], null, $map);
        //$d = json_decode($rs, true);
        if(empty($user['erpvipid']))  return array('status' => -5, 'msg' => "未找到会员积分", 'result' => '');
        $d =get_erpvipinfo($user['erpvipid'],$tk['ERPId']);
        if (empty($d)) {
            return array('status' => -5, 'msg' => "未找到会员积分", 'result' => ''); // 返回结果状态
        }
        $integ = $d['Integral'];
        if ($pay_points > $integ)
            return array('status' => -5, 'msg' => "你积分不足", 'result' => ''); // 返回结果状态
    }
    //在算物流的时候 = 商品价格 + 物流费 - 优惠券 - 优惠、搭配促销
    $wuliu = $goods_price - $coupon_price;
    if ($freight_free > 0 && $wuliu >= $freight_free) {
        $shipping_price = 0;
    }
    //if ($user_money && ($user_money > $user['user_money']))
    //return array('status' => -6, 'msg' => "你的账户可用余额为:" . $user['user_money'], 'result' => ''); // 返回结果状态
    $order_amount = $goods_price + $shipping_price - $coupon_price; // 应付金额 = 商品价格 + 物流费 - 优惠券
    $user_money1 = ($user_money > $order_amount) ? $order_amount : $user_money;  // 余额支付原理等同于积分
    $order_amount2 = $order_amount - $user_money1; //  余额支付抵应付金额
    /*判断能否使用积分---这一部分先不使用
    1..积分低于多少时,不可使用
    2.在不使用积分的情况下, 计算商品应付金额
    3.原则上, 积分支付不能超过商品应付金额的50%, 该值可在平台设置
    @{ */
    // $point_rate = tpCache('shopping.point_rate',$store_id); //兑换比例: 如果拥有的积分小于该值, 不可使用
    //$min_use_limit_point = tpCache('shopping.point_min_limit',$store_id); //最低使用额度: 如果拥有的积分小于该值, 不可使用
    //$use_percent_point = tpCache('shopping.point_use_percent',$store_id);     //最大使用限制: 最大使用积分比例, 例如: 为50时, 未50% , 那么积分支付抵扣金额不能超过应付金额的50%
    //if ($min_use_limit_point > 0 && $pay_points > 0 && $pay_points < $min_use_limit_point) {
    // return array('status' => -1, 'msg' => "您使用的积分必须大于{$min_use_limit_point}才可以使用", 'result' => ''); // 返回结果状态
    //}
    // 计算该笔订单最多使用多少积分
    //  $limit = $order_amount * ($use_percent_point / 100) * $point_rate;
//    if(($use_percent_point !=100 ) && $pay_points > $limit) {
//        return array('status'=>-1,'msg'=>"该笔订单, 您使用的积分不能大于{$limit}",'result'=>'积分'); // 返回结果状态
//    }
    // }
//    $pay_points = ($pay_points / tpCache('shopping.point_rate',$store_id)); // 积分支付 100 积分等于 1块钱
//    $pay_points = ($pay_points > $order_amount) ? $order_amount : $pay_points; // 假设应付 1块钱 而用户输入了 200 积分 2块钱, 那么就让 $pay_points = 1块钱 等同于强制让用户输入1块钱
    //$order_amount = $order_amount - $pay_points; //  积分抵消应付金额
    $total_amount = $goods_price + $shipping_price;
    //订单总价  应付金额  物流费  商品总价 节约金额 共多少件商品 积分  余额  优惠券
    $result = array(
        'total_amount' => round($total_amount, 2), // 购买总价
        'order_amount' => round($order_amount2, 2), // 应付金额
        'order_amount1' => round($order_amount, 2), // 应付金额,不包含余额的那部分
        'shipping_price' => round($shipping_price, 2), //物流费
        'goods_price' => round($goods_price, 2), // 会员购买商品总价
        'cut_fee' => round($cut_fee, 2), // 共节约多少钱
        'anum' => $anum, // 商品总共数量
        'integral_money' => round($pay_points, 2),  // 积分抵消金额
        'user_money' => round($user_money1, 2), // 使用余额
        'coupon_price' => round($coupon_price, 2),// 优惠券抵消金额
        'order_goods' => $order_goods, // 商品列表多加几个字段原样返回
    );
    return array('status' => 1, 'msg' => "计算价钱成功", 'result' => $result); // 返回结果状态
}
/**
 * 计算订单金额,没用使用订单优惠的一部分
 * @param type $user_id 用户id
 * @param type $order_goods 购买的商品
 * @param type $shipping 物流code
 * @param type $shipping_price 物流费用, 如果传递了物流费用 就不在计算物流费
 * @param type $province 省份
 * @param type $city 城市
 * @param type $district 县
 * @param type $pay_points 积分
 * @param type $user_money 余额
 * @param type $coupon_id 优惠券
 * @param type $couponCode 优惠码
 *
 * 计算优惠券使用
 * @param type $wlist 线下商品id组
 * @param type $sumlist 线下商品的金额组
 *
 */
function calculate_price2($fuser, $order_goods, $shipping_code = '', $shipping_price = 0, $province = 0, $city = 0, $district = 0, $pay_points = 0, $user_money = 0, $coupon_id = 0, $couponCode = '', $store_id = 0, $exptype = 0, $discount = null, $wlist = null, $sumlist = null)
{
    if (empty($store_id)) {
        $store_id = getMobileStoId();
    }
    if (empty($order_goods)) {
        return array('status' => -9, 'msg' => '商品列表不能为空', 'result' => '');
    }
    $cartLogic = new app\home\logic\CartLogic();
    //$user = M('users')->where("user_id", $user_id)->find();// 找出这个用户
    $user = $fuser;
    $user_id = $user['user_id'];
    $goods_id_arr = get_arr_column($order_goods, 'goods_id');
    $goods_arr = M('goods')->where("goods_id in(" . implode(',', $goods_id_arr) . ")")
        ->getField('goods_id,weight,market_price,is_free_shipping,exp_sum_type,uniform_exp_sum'); // 商品id 和重量对应的键值对
    $goods_piece = -1;//商品件数
//  $shipping_price = 0;//总运费
    $goods_weight = -1;
    $prom = $prom0 = array();
    $count = $main = array();
    if (empty($discount)) {
        foreach ($order_goods as $key => $val) {
            if ($val['prom_type'] == 3 && $val['is_gift'] == 0 && $val['is_collocation'] == 0) {
                $prom[$val['prom_id']]['num'] += $val['goods_num'];
                $prom[$val['prom_id']]['price'] += $val['goods_price'] * $val['goods_num'];
            }
        }
        if (!empty($prom)) {
            mlog("1-" . json_encode($prom), "calculate_price2/" . $store_id);
            foreach ($prom as $kk => $vv) {
                $prominfo = M('prom_goods')->where(['start_time' => ['lt', time()], 'end_time' => ['gt', time()], 'id' => $kk, 'is_end' => 0])
                    ->where('store_id', $store_id)
                    ->field('id,is_bz')->find();
                if (!empty($prominfo)) {
                    $prom0[$kk] = discount($vv['price'], $prominfo['id'], $vv['num'], $user_id, $prominfo['is_bz']);
                    $main[$kk] = $prom0[$kk]['is_past'];
                }
            }
        }
    } else {
        foreach ($discount as $key => $val) {
            $main[$key] = $val['is_past'];
            $prom0[$key]['price'] = $val['price'];
            $prom[$key]['price'] = $val['all_price'];
        }
    }
    $goods_price = 0;
    $cut_fee = 0;
    $anum = 0;
    $dis = 0;//优惠专用
    //查一下是否有包邮券
    $by_q = M('user_feemail')->where('no', $coupon_id)
        ->where('user_id', $user_id)
        ->field('id')->find();
    foreach ($order_goods as $key => $val) {
        // 如果传递过来的商品列表没有定义会员价
        if (!array_key_exists('member_goods_price', $val)) {
            $user['discount'] = $user['discount'] ? $user['discount'] : 1; // 会员折扣 不能为 0
            $order_goods[$key]['member_goods_price'] = $val['member_goods_price'] = $val['goods_price'] * $user['discount'];
        }
        //如果商品不是包邮的,且不是自提
        $isfeelexp = $goods_arr[$val['goods_id']]['is_free_shipping'];
        if ($val['prom_type'] == 3 && $main[$val['prom_id']] == 1) {
            $isfeelexp = 1;
        }
        if ($isfeelexp == 0) {
            switch ($goods_arr[$val['goods_id']]['exp_sum_type']) {
                case 1:
                    //统一运费
                    if (!empty($shipping_code))
                        $shipping_price += $goods_arr[$val['goods_id']]['uniform_exp_sum'];
                    break;
                case 2:
                    if ($goods_weight < 0) $goods_weight = 0;
                    //累积商品重量 每种商品的重量 * 数量
                    $goods_weight += $goods_arr[$val['goods_id']]['weight'] * $val['goods_num'];
                    break;
                case 3:
                    if ($goods_piece < 0) $goods_piece = 0;
                    //累积商品数量
                    $goods_piece += $val['goods_num'];
                    break;
            }
        }
        $order_goods[$key]['goods_fee'] = $val['goods_num'] * $val['member_goods_price'];    // 小计
        mlog($val['goods_id'] . '-' . $order_goods[$key]['goods_fee'] . '-num:' . $val['goods_num'], 'goods_fee/' . $store_id);
        $order_goods[$key]['store_count'] = getGoodNum($val['goods_id'], $val['spec_key']); // 最多可购买的库存数量
        $salerule = tpCache('basic.sales_rules', $user["store_id"]);
        if ($order_goods[$key]['store_count'] <= 0 && $salerule != 2)
            return array('status' => -10, 'msg' => $order_goods[$key]['goods_name'] . "库存不足,请重新下单", 'result' => '');
        if ($val['is_gift'] == 1) {
            $val['shop_price'] = 0;
        }
        $goods_price += $order_goods[$key]['goods_fee']; // 商品总价
        //$prom0实际判断活动是否存在
        if ($val['prom_type'] == 3 && $prom0) {
            if ($count[$val['prom_id']] == 0) {
                mlog(":" . $val['prom_id'], "calculate_price2/" . $store_id);
                $cut = 0;
                $cut = $prom[$val['prom_id']]['price'] - $prom0[$val['prom_id']]['price'];
                $cut_fee += $cut;
                $prom0[$val['prom_id']]['dis'] = $cut;
                $dis += $cut;
            }
            $count[$val['prom_id']] += 1;
        } else {
            $cut_fee += $val['goods_num'] * $val['shop_price'] - $val['goods_num'] * $val['member_goods_price']; // 共节约
        }
        $anum += $val['goods_num']; // 购买数量
    }
    $prompt = null;
    if ($prom0) {
        foreach ($prom0 as $k => $v) {
            $ispt = 0;
            $rs = M('prom_goods')->where('id', $k)->where('store_id', $store_id)->field('is_goodspt')->find();
            if ($rs['is_goodspt']) $ispt = $rs['is_goodspt'];
            $prompt[] = ['prom_id' => $k, 'dis' => $v['dis'], 'ispt' => $ispt];
        }
    }
    $freight_free = tpCache('shopping.freight_free', $store_id); // 全场满多少免运费
    //自提和全场包邮
    if ($exptype == 1 || $by_q) {
        //--自提--
        $shipping_price = 0;
    } else if (!empty($shipping_code[0]) && !empty($province)) {
//            $freight_free = tpCache('shopping.freight_free', $store_id); // 全场满多少免运费
//            if ($freight_free > 0 && $goods_price >= $freight_free) {
//                $shipping_price = 0;
//            } else {
        if ($goods_weight > -1)
            $shipping_price += $cartLogic->cart_freight2($shipping_code, $province, $city, $district, $goods_weight, $store_id);
        if ($goods_piece > -1)
            $shipping_price += $cartLogic->cart_piece2($shipping_code, $province, $city, $district, $goods_piece, $store_id);
//            }
    }
    // 优惠券处理操作,当不是包邮券的时候
    $coupon_price = 0;
    $yuihui_arr = null;
    if (!empty($coupon_id) && empty($by_q)) {
        if ($coupon_id && $user_id) {
            $erpid = tpCache('shop_info.ERPId', $store_id);
            //$coupon_price = $cartLogic->getCouponMoney($user_id, $coupon_id, 0,$user,$erpid); // 下拉框方式选择优惠券
            $rs_arr = $cartLogic->getCouponMoney2($user_id, $coupon_id, $user, $erpid, $wlist, $sumlist); // 下拉框方式选择优惠券
            $coupon_price = $rs_arr['result'];
            $yuihui_arr = $rs_arr['arr'];
        }
        if ($couponCode && $user_id) {
            $coupon_result = $cartLogic->getCouponMoneyByCode($couponCode, $goods_price); // 根据 优惠券 号码获取的优惠券
            if ($coupon_result['status'] < 0)
                return $coupon_result;
            $coupon_price = $coupon_result['result'];
        }
    }
    //--优惠券优惠的券计算--
    if ($coupon_price > $goods_price - $dis) {
        $cp_num = $coupon_price - $goods_price - $dis;
        $coupon_price = $goods_price - $dis;
        foreach ($yuihui_arr as $kk => $vv) {
            if ($cp_num > $vv['WareCashSum']) {
                $cp_num -= $vv['WareCashSum'];
                unset($yuihui_arr[$kk]);
            } else {
                $yuihui_arr['WareCashSum'] = $yuihui_arr['WareCashSum'] - $cp_num;
            }
        }
    }
    //获取线下积分
    //$tk = M("store")->where("store_id", getMobileStoId())->field("api_token")->find();
    //$tk=tpCache("shop_info.api_token",getMobileStoId());
    //$map['Id'] = array('=', $user['erpvipid']);
    //$rs = getApiData('wxd.vip.vipinfo.list.get', $tk, null, $map);
    //$d = json_decode($rs, true);
    //$integ=$d['data'][0]['Integral'];
    //if ($pay_points && ($pay_points > $integ))
    // return array('status' => -5, 'msg' => "你的账户可用积分为:" . $integ, 'result' => ''); // 返回结果状态
    if ($user_money && ($user_money > $user['user_money']))
        return array('status' => -6, 'msg' => "你的账户可用余额为:" . $user['user_money'], 'result' => ''); // 返回结果状态
    //在算物流的时候 = 商品价格 - 优惠券 - 优惠、搭配促销
    $wuliu = $goods_price - $coupon_price - $dis;
    if ($freight_free > 0 && $wuliu >= $freight_free) {
        $no_ex_id = tpCache('shopping.no_ex_id', $store_id);
        if ($no_ex_id) {
            //判断是否包邮
            $is_by = $cartLogic->isby2($province, $city, $district, $no_ex_id);
            if ($is_by == 1) $shipping_price = 0;
        } else {
            $shipping_price = 0;
        }
    }
    $order_amount = $goods_price + $shipping_price - $coupon_price - $dis; // 应付金额 = 商品价格 + 物流费 - 优惠券 - 优惠、搭配促销
    //订单满额优惠处理
    $dd_amount = $goods_price - $coupon_price - $dis;
    //$order_prom = get_order_promotion($order_amount, $store_id);
    $order_prom = get_order_promotion($dd_amount, $store_id);
    $order_prom_id = $order_prom['order_prom_id'];
    $order_prom_amount = $order_prom['order_prom_amount'];
    //应付金额 = 商品价格 + 物流费 - 优惠券-订单优惠
    $order_amount = round($order_amount - $order_prom_amount, 2);
    if ($order_amount < 0) {
        $order_amount = 0;
    }
    $user_money1 = ($user_money > $order_amount) ? $order_amount : $user_money;  // 余额支付原理等同于积分
    $order_amount2 = $order_amount - $user_money1; //  余额支付抵应付金额
    /*判断能否使用积分---这一部分先不使用
    1..积分低于多少时,不可使用
    2.在不使用积分的情况下, 计算商品应付金额
    3.原则上, 积分支付不能超过商品应付金额的50%, 该值可在平台设置
    @{ */
    // $point_rate = tpCache('shopping.point_rate',$store_id); //兑换比例: 如果拥有的积分小于该值, 不可使用
    //$min_use_limit_point = tpCache('shopping.point_min_limit',$store_id); //最低使用额度: 如果拥有的积分小于该值, 不可使用
    //$use_percent_point = tpCache('shopping.point_use_percent',$store_id);     //最大使用限制: 最大使用积分比例, 例如: 为50时, 未50% , 那么积分支付抵扣金额不能超过应付金额的50%
    //if ($min_use_limit_point > 0 && $pay_points > 0 && $pay_points < $min_use_limit_point) {
    // return array('status' => -1, 'msg' => "您使用的积分必须大于{$min_use_limit_point}才可以使用", 'result' => ''); // 返回结果状态
    //}
    // 计算该笔订单最多使用多少积分
    //  $limit = $order_amount * ($use_percent_point / 100) * $point_rate;
//    if(($use_percent_point !=100 ) && $pay_points > $limit) {
//        return array('status'=>-1,'msg'=>"该笔订单, 您使用的积分不能大于{$limit}",'result'=>'积分'); // 返回结果状态
//    }
    // }
//    $pay_points = ($pay_points / tpCache('shopping.point_rate',$store_id)); // 积分支付 100 积分等于 1块钱
//    $pay_points = ($pay_points > $order_amount) ? $order_amount : $pay_points; // 假设应付 1块钱 而用户输入了 200 积分 2块钱, 那么就让 $pay_points = 1块钱 等同于强制让用户输入1块钱
    //$order_amount = $order_amount - $pay_points; //  积分抵消应付金额
    $total_amount = $goods_price + $shipping_price;
    //订单总价  应付金额  物流费  商品总价 节约金额 共多少件商品 积分  余额  优惠券
    $result = array(
        'total_amount' => round($total_amount, 2), // 购买总价
        'order_amount' => round($order_amount2, 2), // 应付金额
        'order_amount1' => round($order_amount, 2), // 应付金额,不包含余额的那部分
        'shipping_price' => round($shipping_price, 2), //物流费
        'goods_price' => round($goods_price, 2), // 会员购买商品总价
        'cut_fee' => round($cut_fee, 2), // 共节约多少钱
        'anum' => $anum, // 商品总共数量
        'integral_money' => round($pay_points, 2),  // 积分抵消金额
        'user_money' => round($user_money1, 2), // 使用余额
        'coupon_price' => round($coupon_price, 2),// 优惠券抵消金额
        'order_goods' => $order_goods, // 商品列表多加几个字段原样返回
        'order_prom_id' => $order_prom_id,
        'order_prom_amount' => $order_prom_amount,
        'discount' => round($dis, 2),//优惠促销优惠金额
        'good_prom' => $prompt,//优惠促销优惠金额
        'youhui' => $yuihui_arr,
    );
    return array('status' => 1, 'msg' => "计算价钱成功", 'result' => $result); // 返回结果状态
}
/*--积分购专门计算--*/
function calculate_price3($fuser, $order_goods, $shipping_code = '', $shipping_price = 0, $province = 0, $city = 0, $district = 0, $pay_points = 0, $user_money = 0, $coupon_id = 0, $couponCode = '', $store_id = 0, $exptype = 0)
{
    if (empty($store_id)) {
        $store_id = getMobileStoId();
    }
    if (empty($order_goods)) {
        return array('status' => -9, 'msg' => '商品列表不能为空', 'result' => '');
    }
    $cartLogic = new app\home\logic\CartLogic();
    $user = $fuser;// 找出这个用户
    $user_id = $user['user_id'];
    $goods_id_arr = get_arr_column($order_goods, 'goods_id');
    $goods_arr = M('goods')->where("goods_id in(" . implode(',', $goods_id_arr) . ")")
        ->getField('goods_id,weight,market_price,is_free_shipping,exp_sum_type,uniform_exp_sum'); // 商品id 和重量对应的键值对
    $goods_piece = -1;//商品件数
    $shipping_price = 0;//总运费
    $goods_weight = -1;
    $goods_price = 0;
    $cut_fee = 0;
    $anum = 0;
    $dis = 0;//优惠专用
    foreach ($order_goods as $key => $val) {
        // 如果传递过来的商品列表没有定义会员价
        if (!array_key_exists('member_goods_price', $val)) {
            $user['discount'] = $user['discount'] ? $user['discount'] : 1; // 会员折扣 不能为 0
            $order_goods[$key]['member_goods_price'] = $val['member_goods_price'] = $val['goods_price'] * $user['discount'];
        }
        //如果商品不是包邮的,且不是自提
        $isfeelexp = $goods_arr[$val['goods_id']]['is_free_shipping'];
        if ($isfeelexp == 0) {
            switch ($goods_arr[$val['goods_id']]['exp_sum_type']) {
                case 1:
                    //统一运费
                    if (!empty($shipping_code))
                        $shipping_price += $goods_arr[$val['goods_id']]['uniform_exp_sum'];
                    break;
                case 2:
                    if ($goods_weight < 0) $goods_weight = 0;
                    //累积商品重量 每种商品的重量 * 数量
                    $goods_weight += $goods_arr[$val['goods_id']]['weight'] * $val['goods_num'];
                    break;
                case 3:
                    if ($goods_piece < 0) $goods_piece = 0;
                    //累积商品数量
                    $goods_piece += $val['goods_num'];
                    break;
            }
        }
        mlog($order_goods[0]['goods_id'] . "商品是否包邮" . $isfeelexp, "calculate_price3/" . $store_id);
        mlog($order_goods[0]['goods_id'] . "商品重量" . $goods_weight, "calculate_price3/" . $store_id);
        mlog($order_goods[0]['goods_id'] . "商品数量" . $goods_piece, "calculate_price3/" . $store_id);
        $order_goods[$key]['goods_fee'] = $val['goods_num'] * $val['member_goods_price'];    // 小计
        $order_goods[$key]['store_count'] = getGoodNum($val['goods_id'], $val['spec_key']); // 最多可购买的库存数量
        if ($order_goods[$key]['store_count'] <= 0)
            return array('status' => -10, 'msg' => $order_goods[$key]['goods_name'] . "库存不足,请重新下单", 'result' => '');
        $goods_price += $order_goods[$key]['goods_fee']; // 商品总价
        $cut_fee += $val['goods_num'] * $val['market_price'] - $val['goods_num'] * $val['member_goods_price']; // 共节约
        $anum += $val['goods_num']; // 购买数量
    }
    // 优惠券处理操作
    $coupon_price = 0;
    if (!empty($coupon_id)) {
        if ($coupon_id && $user_id) {
            $coupon_price = $cartLogic->getCouponMoney($user_id, $coupon_id, 1); // 下拉框方式选择优惠券
        }
        if ($couponCode && $user_id) {
            $coupon_result = $cartLogic->getCouponMoneyByCode($couponCode, $goods_price); // 根据 优惠券 号码获取的优惠券
            if ($coupon_result['status'] < 0)
                return $coupon_result;
            $coupon_price = $coupon_result['result'];
        }
    }
    $freight_free = tpCache('shopping.freight_free', $store_id); // 全场满多少免运费
    mlog($order_goods[0]['goods_id'] . "全场是否包邮" . $freight_free, "calculate_price3/" . $store_id);
    mlog($order_goods[0]['goods_id'] . "--exptype--" . $exptype, "calculate_price3/" . $store_id);
    mlog($order_goods[0]['goods_id'] . "--shipping_code[0]--" . $shipping_code[0], "calculate_price3/" . $store_id);
    mlog($order_goods[0]['goods_id'] . "--province--" . $province, "calculate_price3/" . $store_id);
    //自提和全场包邮
    if ($exptype == 1) {
        //--自提--
        $shipping_price = 0;
    } else if (!empty($shipping_code[0]) && !empty($province)) {
        $freight_free = tpCache('shopping.freight_free', $store_id); // 全场满多少免运费
        mlog($order_goods[0]['goods_id'] . "--freight_free--" . $freight_free . "---goods_price---" . $goods_price,
            "calculate_price3/" . $store_id);
        if ($freight_free > 0 && $goods_price >= $freight_free) {
            $shipping_price = 0;
        } else {
            mlog($order_goods[0]['goods_id'] .
                "计算物流费-" .
                $shipping_code . "-" . $province . "-" . $city . "-" . $district . "-" . $goods_weight . "-" . $store_id,
                "calculate_price3/" . $store_id);
            if ($goods_weight > -1)
                $shipping_price += $cartLogic->cart_freight2($shipping_code, $province, $city, $district, $goods_weight, $store_id);
            if ($goods_piece > -1)
                $shipping_price += $cartLogic->cart_piece2($shipping_code, $province, $city, $district, $goods_piece, $store_id);
        }
    }
    mlog($order_goods[0]['goods_id'] . "物流费" . $shipping_price, "calculate_price3/" . $store_id);
    //获取线下积分
    if ($pay_points > 0) {
        //获取积分
        $integ = get_userpoints($user, $store_id, tpCache('shop_info.ERPId', $store_id));
        if ($pay_points > $integ)
            return array('status' => -5, 'msg' => "你积分不足", 'result' => ''); // 返回结果状态
    }
    //在算物流的时候 = 商品价格 + 物流费 - 优惠券 - 优惠、搭配促销
    $wuliu = $goods_price - $coupon_price;
    if ($freight_free > 0 && $wuliu >= $freight_free) {
        $shipping_price = 0;
    }
    mlog($order_goods[0]['goods_id'] . "计算是否包邮2" . $wuliu . ":" . $shipping_price,
        "calculate_price3/" . $store_id);
    $order_amount = $goods_price + $shipping_price - $coupon_price; // 应付金额 = 商品价格 + 物流费 - 优惠券
    $user_money1 = ($user_money > $order_amount) ? $order_amount : $user_money;  // 余额支付原理等同于积分
    $order_amount2 = $order_amount - $user_money1; //  余额支付抵应付金额
    $total_amount = $goods_price + $shipping_price;
    //订单总价  应付金额  物流费  商品总价 节约金额 共多少件商品 积分  余额  优惠券
    $result = array(
        'total_amount' => round($total_amount, 2), // 购买总价
        'order_amount' => round($order_amount2, 2), // 应付金额
        'order_amount1' => round($order_amount, 2), // 应付金额,不包含余额的那部分
        'shipping_price' => round($shipping_price, 2), //物流费
        'goods_price' => round($goods_price, 2), // 会员购买商品总价
        'cut_fee' => round($cut_fee, 2), // 共节约多少钱
        'anum' => $anum, // 商品总共数量
        'integral_money' => round($pay_points, 2),  // 积分抵消金额
        'user_money' => round($user_money1, 2), // 使用余额
        'coupon_price' => round($coupon_price, 2),// 优惠券抵消金额
        'order_goods' => $order_goods, // 商品列表多加几个字段原样返回
    );
    return array('status' => 1, 'msg' => "计算价钱成功", 'result' => $result); // 返回结果状态
}
/**
 * 计算订单金额,没用使用订单优惠的一部分,送礼神器专用
 * @param type $user_id 用户id
 * @param type $order_goods 购买的商品
 * @param type $shipping 物流code
 * @param type $shipping_price 物流费用, 如果传递了物流费用 就不在计算物流费
 * @param type $pay_points 积分
 * @param type $user_money 余额
 * @param type $coupon_id 优惠券
 * @param type $couponCode 优惠码
 */
function calculate_price4($fuser, $order_goods, $shipping_code = '', $shipping_price = 0, $pay_points = 0, $user_money = 0, $coupon_id = 0, $couponCode = '', $store_id = 0, $exptype = 0, $discount = null)
{
    if (empty($store_id)) {
        $store_id = getMobileStoId();
    }
    if (empty($order_goods)) {
        return array('status' => -9, 'msg' => '商品列表不能为空', 'result' => '');
    }
    $cartLogic = new app\home\logic\CartLogic();
    //$user = M('users')->where("user_id", $user_id)->find();// 找出这个用户
    $user = $fuser;
    $user_id = $user['user_id'];
    $goods_id_arr = get_arr_column($order_goods, 'goods_id');
    $goods_arr = M('goods')->where("goods_id in(" . implode(',', $goods_id_arr) . ")")
        ->getField('goods_id,weight,market_price,is_free_shipping,exp_sum_type,uniform_exp_sum'); // 商品id 和重量对应的键值对
    $goods_piece = -1;//商品件数
//    $shipping_price = 0;//总运费
    $goods_weight = -1;
    $prom = $prom0 = array();
    $count = $main = array();
    if (empty($discount)) {
        foreach ($order_goods as $key => $val) {
            if ($val['prom_type'] == 3 && $val['is_gift'] == 0 && $val['is_collocation'] == 0) {
                $prom[$val['prom_id']]['num'] += $val['goods_num'];
                $prom[$val['prom_id']]['price'] += $val['shop_price'] * $val['goods_num'];
            }
        }
        if (!empty($prom)) {
            foreach ($prom as $kk => $vv) {
                $prominfo = M('prom_goods')->where(['start_time' => ['lt', time()], 'end_time' => ['gt', time()], 'id' => $kk, 'is_end' => 0])->field('id')->find();
                if (!empty($prominfo)) {
                    $prom0[$kk] = discount($vv['price'], $prominfo['id'], $vv['num'], $user_id);
                    $main[$kk] = $prom0[$kk]['is_past'];
                }
            }
        }
    } else {
        foreach ($discount as $key => $val) {
            $main[$key] = $val['is_past'];
            $prom0[$key]['price'] = $val['price'];
            $prom[$key]['price'] = $val['all_price'];
        }
    }
    $goods_price = 0;
    $cut_fee = 0;
    $anum = 0;
    $dis = 0;//优惠专用
    foreach ($order_goods as $key => $val) {
        // 如果传递过来的商品列表没有定义会员价
        if (!array_key_exists('member_goods_price', $val)) {
            $user['discount'] = $user['discount'] ? $user['discount'] : 1; // 会员折扣 不能为 0
            $order_goods[$key]['member_goods_price'] = $val['member_goods_price'] = $val['goods_price'] * $user['discount'];
        }
        //如果商品不是包邮的,且不是自提
        $isfeelexp = $goods_arr[$val['goods_id']]['is_free_shipping'];
        if ($val['prom_type'] == 3 && $main[$val['prom_id']] == 1) {
            $isfeelexp = 1;
        }
        if ($isfeelexp == 0) {
            switch ($goods_arr[$val['goods_id']]['exp_sum_type']) {
                case 1:
                    //统一运费
                    if (!empty($shipping_code))
                        $shipping_price += $goods_arr[$val['goods_id']]['uniform_exp_sum'];
                    break;
                case 2:
                    if ($goods_weight < 0) $goods_weight = 0;
                    //累积商品重量 每种商品的重量 * 数量
                    $goods_weight += $goods_arr[$val['goods_id']]['weight'] * $val['goods_num'];
                    break;
                case 3:
                    if ($goods_piece < 0) $goods_piece = 0;
                    //累积商品数量
                    $goods_piece += $val['goods_num'];
                    break;
            }
        }
        $order_goods[$key]['goods_fee'] = $val['goods_num'] * $val['member_goods_price'];    // 小计
        mlog($val['goods_id'] . '-' . $order_goods[$key]['goods_fee'] . '-num:' . $val['goods_num'], 'goods_fee/' . $store_id);
        $order_goods[$key]['store_count'] = getGoodNum($val['goods_id'], $val['spec_key']); // 最多可购买的库存数量
        $salerule = tpCache('basic.sales_rules', $user["store_id"]);
        if ($order_goods[$key]['store_count'] <= 0 && $salerule != 2)
            return array('status' => -10, 'msg' => $order_goods[$key]['goods_name'] . "库存不足,请重新下单", 'result' => '');
        if ($val['is_gift'] == 1) {
            $val['shop_price'] = 0;
        }
        $goods_price += $order_goods[$key]['goods_fee']; // 商品总价
        if ($val['prom_type'] == 3) {
            if ($count[$val['prom_id']] == 0) {
                $cut_fee += $prom[$val['prom_id']]['price'] - $prom0[$val['prom_id']]['price'];
                $dis += $prom[$val['prom_id']]['price'] - $prom0[$val['prom_id']]['price'];
            }
            $count[$val['prom_id']] += 1;
        } else {
            $cut_fee += $val['goods_num'] * $val['shop_price'] - $val['goods_num'] * $val['member_goods_price']; // 共节约
        }
        $anum += $val['goods_num']; // 购买数量
    }
    // 优惠券处理操作
    $coupon_price = 0;
    if (!empty($coupon_id)) {
        if ($coupon_id && $user_id) {
            $coupon_price = $cartLogic->getCouponMoney($user_id, $coupon_id, 1); // 下拉框方式选择优惠券
        }
        if ($couponCode && $user_id) {
            $coupon_result = $cartLogic->getCouponMoneyByCode($couponCode, $goods_price); // 根据 优惠券 号码获取的优惠券
            if ($coupon_result['status'] < 0)
                return $coupon_result;
            $coupon_price = $coupon_result['result'];
        }
    }
    $freight_free = tpCache('shopping.freight_free', $store_id); // 全场满多少免运费
    //自提和全场包邮
    if (($freight_free > 0 && $goods_price >= $freight_free)) {
        //--自提--
        $shipping_price = 0;
    } else {
        $giftconfig = M('giftuser_config')->where('store_id', $store_id)->field('add_expressprice')->find();
        $shipping_price = $giftconfig['add_expressprice'];
    }
    if ($user_money && ($user_money > $user['user_money']))
        return array('status' => -6, 'msg' => "你的账户可用余额为:" . $user['user_money'], 'result' => ''); // 返回结果状态
    $order_amount = $goods_price + $shipping_price - $coupon_price - $dis; // 应付金额 = 商品价格 + 物流费 - 优惠券 - 优惠、搭配促销
    //订单满额优惠处理
    $order_prom = get_order_promotion($order_amount, $store_id);
    $order_prom_id = $order_prom['order_prom_id'];
    $order_prom_amount = $order_prom['order_prom_amount'];
    //应付金额 = 商品价格 + 物流费 - 优惠券-订单优惠
    $order_amount = round($order_amount - $order_prom_amount, 2);
    $user_money1 = ($user_money > $order_amount) ? $order_amount : $user_money;  // 余额支付原理等同于积分
    $order_amount2 = $order_amount - $user_money1; //  余额支付抵应付金额
    $total_amount = $goods_price + $shipping_price;
    //订单总价  应付金额  物流费  商品总价 节约金额 共多少件商品 积分  余额  优惠券
    $result = array(
        'total_amount' => round($total_amount, 2), // 购买总价
        'order_amount' => round($order_amount2, 2), // 应付金额
        'order_amount1' => round($order_amount, 2), // 应付金额,不包含余额的那部分
        'shipping_price' => round($shipping_price, 2), //物流费
        'goods_price' => round($goods_price, 2), // 会员购买商品总价
        'cut_fee' => round($cut_fee, 2), // 共节约多少钱
        'anum' => $anum, // 商品总共数量
        'integral_money' => round($pay_points, 2),  // 积分抵消金额
        'user_money' => round($user_money1, 2), // 使用余额
        'coupon_price' => round($coupon_price, 2),// 优惠券抵消金额
        'order_goods' => $order_goods, // 商品列表多加几个字段原样返回
        'order_prom_id' => $order_prom_id,
        'order_prom_amount' => $order_prom_amount,
        'discount' => round($dis, 2),//优惠促销优惠金额
    );
    return array('status' => 1, 'msg' => "计算价钱成功", 'result' => $result); // 返回结果状态
}
/**
 * 获取商品一二三级分类
 * @return type
 */
function get_goods_category_tree()
{
    $arr = $result = array();
    $cat_list = M('goods_category')->where("is_show = 1 ")->order('sort_order')->select();//所有分类
    if (empty($cat_list)) return "";
    if (!isset($cat_list)) return "";
    foreach ($cat_list as $val) {
        if ($val['level'] == 2) {
            $arr[$val['parent_id']][] = $val;
        }
        if ($val['level'] == 3) {
            $crr[$val['parent_id']][] = $val;
        }
        if ($val['level'] == 1) {
            $tree[] = $val;
        }
    }
    foreach ($arr as $k => $v) {
        foreach ($v as $kk => $vv) {
            $arr[$k][$kk]['sub_menu'] = empty($crr[$vv['id']]) ? array() : $crr[$vv['id']];
        }
    }
    foreach ($tree as $val) {
        $val['tmenu'] = empty($arr[$val['id']]) ? array() : $arr[$val['id']];
        $result[$val['id']] = $val;
    }
    return $result;
}
/**
 * 获取商品一二三级分类
 * @return type
 */
function get_goods_category_tree_mobile()
{
    $id = getMobileStoId();
    $arr = $result = array();
    $cat_list = M('goods_category')->where("is_show = 1")->where("store_id", $id)
        ->order('sort_order')->cache("cat_list_" . $id,TPSHOP_CACHE_TIME)->select();//所有分类
    if (empty($cat_list)) return "";
    if (!isset($cat_list)) return "";
    foreach ($cat_list as $val) {
        if ($val['level'] == 2) {
            $arr[$val['parent_id']][] = $val;
        }
        if ($val['level'] == 3) {
            $crr[$val['parent_id']][] = $val;
        }
        if ($val['level'] == 1) {
            $tree[] = $val;
        }
    }
    if ($arr) {
        foreach ($arr as $k => $v) {
            foreach ($v as $kk => $vv) {
                $arr[$k][$kk]['sub_menu'] = empty($crr[$vv['id']]) ? array() : $crr[$vv['id']];
            }
        }
    }
    if ($tree) {
        foreach ($tree as $val) {
            $val['tmenu'] = empty($arr[$val['id']]) ? array() : $arr[$val['id']];
            $result[$val['id']] = $val;
        }
    }
    return $result;
}
/**
 * 写入静态页面缓存
 */
function write_html_cache($html)
{
    $html_cache_arr = C('HTML_CACHE_ARR');
    $request = think\Request::instance();
    $m_c_a_str = $request->module() . '_' . $request->controller() . '_' . $request->action(); // 模块_控制器_方法
    $m_c_a_str = strtolower($m_c_a_str);
    //exit('write_html_cache写入缓存
');
    if(!$html_cache_arr) return false;
    foreach ($html_cache_arr as $key => $val) {
        $val['mca'] = strtolower($val['mca']);
        if ($val['mca'] != $m_c_a_str) //不是当前 模块 控制器 方法 直接跳过
            continue;
        if (!is_dir(RUNTIME_PATH . 'html'))
            mkdir(RUNTIME_PATH . 'html');
        $filename = RUNTIME_PATH . 'html' . DIRECTORY_SEPARATOR . $m_c_a_str;
        // 组合参数
        if (isset($val['p'])) {
            foreach ($val['p'] as $k => $v)
                $filename .= '_' . $_GET[$v];
        }
        $filename .= '.html';
        file_put_contents($filename, $html);
    }
}
/**
 * 读取静态页面缓存
 */
function read_html_cache()
{
    $html_cache_arr = C('HTML_CACHE_ARR');
    $request = think\Request::instance();
    $m_c_a_str = $request->module() . '_' . $request->controller() . '_' . $request->action(); // 模块_控制器_方法
    $m_c_a_str = strtolower($m_c_a_str);
    //exit('read_html_cache读取缓存
');
    if(!$html_cache_arr) return false;
    foreach ($html_cache_arr as $key => $val) {
        $val['mca'] = strtolower($val['mca']);
        if ($val['mca'] != $m_c_a_str) //不是当前 模块 控制器 方法 直接跳过
            continue;
        $filename = RUNTIME_PATH . 'html' . DIRECTORY_SEPARATOR . $m_c_a_str;
        // 组合参数
        if (isset($val['p'])) {
            foreach ($val['p'] as $k => $v)
                $filename .= '_' . $_GET[$v];
        }
        $filename .= '.html';
        if (file_exists($filename)) {
            echo file_get_contents($filename);
            exit();
        }
    }
}
/*--自定义方法,手机端使用获取门店ID--*/
function getMobileStoId()
{
    $id = I("stoid");
    return $id;
}
/*--自定义方法,手机端使用获取门店ID--*/
function getMobileSupplyId($sid)
{
    if ($sid == null) return "";
    if ($sid == '') return "";
    $supplyid = cookie("newshop_mobile_supplyid");
    if ($supplyid == null) {
        return seleSupplyId($sid);
    } else if (empty($supplyid)) {
        return seleSupplyId($sid);
    } else {
        return $supplyid;
    }
}
function seleSupplyId($stoid)
{
    $res = M("store")->where("store_id", $stoid)->find();
    if ($res) {
        Cookie::set("newshop_mobile_supplyid", $res["supplyid"]);
        return $res["supplyid"];
    } else return "";
}
/*--自定义方法,手机端where条件--*/
function getMobileStoWhere()
{
    $id = getMobileStoId();
    return "and store_id=" . $id;
}
function getMobileSupplyIdWhere()
{
    $id = getMobileSupplyId();
    return "and supplyid='" . $id . "'";
}
/*--跳转页面--*/
function goUrl($url)
{
    Header("Location:$url");
    die;
}
/*------Key=KEY值------*/
function getErpKey()
{
    $key = "wxdkey123456";
    return $key;
}
/*--自定义方法,手机端使用获取门店ID--*/
function getAdminId()
{
    $id = cookie("newshop_admin_id");
    return $id;
}
/*--自定义方法,获取用户ID where条件--*/
function getAdmStoId()
{
    $id = cookie("newshop_admin_stoid");
    return $id;
}
/*--自定义方法,获取用户ID where条件--*/
function getStoWhere()
{
    $id = cookie("newshop_admin_stoid");
    return "and store_id=" . $id;
}
/*--自定义方法,获取用户ID where条件--*/
function getAdminWhere()
{
    $id = cookie("newshop_admin_id");
    return "and admin_id='" . $id . "'";
}
/*------获取账套-----*/
function getERPId()
{
    return cookie('newshop_admin_erpid');
}
/*------获取supplyid-----*/
function getAdmSupplyId()
{
    return cookie('newshop_admin_supplyid');
}
/*---获取地区全名--*/
function getRgName($rid)
{
    $name = "";
    $rs = M("region")->where('id', $rid)->find();
    if ($rs) {
        $lev = (int)$rs["level"];
        $name = $rs['name'];
        $id = $rs['parent_id'];
        for ($i = 1; $i < $lev; $i++) {
            $rss = M("region")->where('id', $id)->find();
            $name = $rss['name'] . '-' . $name;
            $id = $rss['parent_id'];
        }
        return $name;
    } else {
        return "";
    }
}
//生成签名字链接地址
function GetSignUrl(array $get_data)
{
    //生成签名
    //数组按照键值正序排顺
    $get_data["timestamp"] = time();
    ksort($get_data);
    //
    if (isset($get_data['sign'])) {
        unset($get_data['sign']);
    }
    $sign_data = '';
    $str = '';
    //循环把键值拼接
    foreach ($get_data as $key => $val) {
        $sign_data[] = $key . $val;
        $str .= "&" . $key . "=" . $val;
    }
    //再拼接成字符串
    $res = implode('', $sign_data);
    //md5 加密
    $md5data = md5($res);
    //对md5字符串进行字母大写
    $md5data = strtoupper($md5data);
    $str = substr($str, 1);
    $url = WXDURL . "?" . $str . "&sign=" . $md5data;
    mlog($url, "GetSignUrl");
    return $url;
}
function parameter_connect(array $list)
{
    $str = '';
    foreach ($list as $key => $val) {
        $str .= "&" . $key . "=" . $val;
    }
    $str = substr($str, 1);
    return $str;
}
//设置要获取缓存的字段
function getCachaArr($stoid)
{
    $arr = ["system_menu",
        "shop_info",
        "basic",
        "mobilebase",
        "shopping",
        "sms",
        "water",
        "distribut",
        "saleTop",
        "userTop",
        "user_order",
        "finance",
        "cart_hot_goods",
        "cart2_shipping",
        "categoryList_ad",
        "filter_goods_id",
        "good_list_goods_category",
        "search_filter_goods_id",
        "search_goods_category",
        "brandstreet",
        "goods_list_goods_images",
        "goods_images",
        "boutique_goods",
        "new_goods",
        "hot_goods",
        "favourite_goods",
        "More_favourite_goods",
        "top_ad_5",
        "ad_300",
        "ad_301",
        "ad_302",
        "ad_303",
        "ad_304",
        "ad_305",
        "ad_306",
        "ad_307",
        "ad_308",
        "ad_309",
        "category_id_arr",
        "son_id_arr",
        "order_goods",
        "jisuan_goods",
        "cat_list",
        "storage_category",
        "shippingList",
        "wx_user",
        "ppgg",
        "shopfooter",
        "goodscategory",
        "goodsbrand",
        "cardsetup"
    ];
    foreach ($arr as &$b) {
        $b = $b . "_" . $stoid;
    }
    return $arr;
}
//清除缓存
function ClearALLCache()
{
    $arr = getCachaArr(getAdmStoId());
    foreach ($arr as $b) {
        Cache::rm($b);
    }
    clearRedisKey("goods","goodsinfo","all_card_".getAdmStoId());
}
/*--post json--*/
function http_post_json($url, $jsonStr, $token = "")
{
    try {
        $ch = curl_init();
        //不验证https
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=utf-8',
                'token:' . $token,
                'Content-Length: ' . strlen($jsonStr)
            )
        );
        curl_setopt($ch, CURLOPT_TIMEOUT, 6);
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        return array($response, $httpCode);
    } catch (Exception $e) {
        return null;
    }
}
/*---post 数组---*/
/**
 * 发送post请求
 * @param string $url 请求地址
 * @param array $post_data post键值对数据
 * @return string
 */
function send_post($url, $post_data)
{
    $postdata = http_build_query($post_data);
    $options = array(
        'http' => array(
            'method' => 'POST',
            'header' => 'Content-type:application/x-www-form-urlencoded',
            'content' => $postdata,
            'timeout' => 15 * 60 // 超时时间(单位:s)
        )
    );
    $context = stream_context_create($options);
    $result = file_get_contents($url, false, $context);
    return $result;
}
/*--更新线下会员信息ZXH--*/
function update_erpvip_info($user_id, $stoid, $date, $api_token = "")
{
    if ($api_token == "") {
        $tk = M("store")->where("store_id", $stoid)->field("api_token")->find();
        $api_token = $tk['api_token'];
    }
    $rs = getApiData("wxd.vip.vipinfo.edit", $api_token, array($date));
    /*--
    $list =array("access_token"=>"wxd.vip.vipinfo.edit");
    $array =array(
        'token'=>$api_token,
        'data' => array($date),
        'map'=>'',
        'order'=>"",
    );
    $json=json_encode($array);
    $url=GetSignUrl($list);
    if(empty($url)){
        return json(["code"=>"-1","msg"=>"生成签名错误"]);
    }
    $rs=http_post_json($url,$json);--*/
    $qlist = json_decode(urldecode($rs), true);
    return $qlist;
}
/*--插入线下会员信息,并返回插入的信息ZXH--*/
function add_erpvip_info($stoid, $date, $api_token = "")
{
    if ($api_token == "") {
        $tk = M("store")->where("store_id", $stoid)->field("api_token")->find();
        $api_token = $tk['api_token'];
    }
    $rs = getApiData("wxd.vip.vipinfo.add", $api_token, array($date));
    /*---
    $list =array("access_token"=>"wxd.vip.vipinfo.add");
    $array =array(
        'token'=>$api_token,
        'data' => array($date),
        'map'=>'',
        'order'=>"",
    );
    $json=json_encode($array);
    mlog($json,"adduser");
    $url=GetSignUrl($list);
    if(empty($url)){
        return json(["code"=>"-1","msg"=>"生成签名错误"]);
    }
    $rs=http_post_json($url,$json);
    mlog($rs[0],"adduser");
    $qlist=json_decode(urldecode($rs[0]),true);--*/
    return $rs;
}
//生成erpid
function erp_uuid()
{
    $charid = md5(uniqid(mt_rand(), true));
    $hyphen = chr(45);// "-"
    $uuid = chr(123)// "{"
        . substr($charid, 0, 8) . $hyphen
        . substr($charid, 8, 4) . $hyphen
        . substr($charid, 12, 4) . $hyphen
        . substr($charid, 16, 4) . $hyphen
        . substr($charid, 20, 12)
        . chr(125);// "}"
    return $uuid;
}
function uuid($prefix = '')
{
    $chars = md5(uniqid(mt_rand(), true));
    $uuid = substr($chars, 0, 8) . '-';
    $uuid .= substr($chars, 8, 4) . '-';
    $uuid .= substr($chars, 12, 4) . '-';
    $uuid .= substr($chars, 16, 4) . '-';
    $uuid .= substr($chars, 20, 12);
    return $prefix . $uuid;
}
/*--获取接口数据分装 _新
 *param $acctk方法
 *param $tk token
 *param $data
 *param $map
 *param $page
 *return $rs接口返回的内容
 */
function getApiData_java($apiname, $accdb, $data = null, $page = 1, $len = 10, $order = null,$timeout=10)
{
    try {
        $res_token = getapi_token($accdb);
        $res_token = $res_token;
        $token = "";
        if (empty($res_token))
        {
            return json_encode(array('code' => -1, 'msg' => '获取TOKEN为空'));
        }
        if (!array_key_exists("code", $res_token))
        {
            return json_encode(array('code' => -1, 'msg' => '获取不包含code'));
        }
        if ($res_token['code'] != 0) {
            return json_encode(array('code' => -1, 'msg' => 'code值不等于0'));
        }
        $token_data = $res_token['data'];
        if ($token_data && $token_data['token']) {
            $token = $token_data['token'];
            $curlhttp = $_SERVER['SERVER_NAME'];
            if ($curlhttp == "mshop.yolipai.net") {
                $apiHost = $token_data['apiHost'];//正式环境都上传
            } else {
                $apiHost = "http://open.xinda100.com";//测试环境
            }
        }
        $token=preg_replace("/(\s|\ \;| |\xc2\xa0)/","",$token);
        $newsstr = "?token=" . $token;
        if ($data) {
            foreach ($data as $key => $val) {
                if ($newsstr) {
                    $newsstr .= "&" . $key . "=" . $val;
                }
            }
        }
        $newsstr .= "&page=" . $page;
        $newsstr .= "&pageSize=" . $len;
        $url = $apiHost . "/" . $apiname . $newsstr;
        if (empty($url)) {
            return json_encode(array('code' => -1, 'msg' => '接口地址不能为空'));
        }
        mlog("url:" . $url, "apidatajava/" . $accdb."/".urlencode($apiname));
        $rs = httpRequest($url,"GET",null,array(),true,$timeout,$accdb);
        mlog("返回:" . $rs, "apidatajava/" . $accdb."/".urlencode($apiname));
        return $rs;
    } catch (Exception $ex) {
        mlog("异常出错getApiData_java:" . $ex, "apidatajava/" . $accdb."/".urlencode($apiname));
        return json_encode(array('code' => -1, 'msg' => '异常出错'));
    }
}
function getApiData_java2($apiname, $accdb, $data = null, $page = 1, $len = 10, $order = null,$timeout=10)
{
    try {
        $res_token = getapi_token($accdb);
        $res_token = $res_token;
        $token = "";
        if (empty($res_token))
        {
            return json_encode(array('code' => -1, 'msg' => '获取TOKEN为空'));
        }
        if (!array_key_exists("code", $res_token))
        {
            return json_encode(array('code' => -1, 'msg' => '获取不包含code'));
        }
        if ($res_token['code'] != 0) {
            return json_encode(array('code' => -1, 'msg' => 'code值不等于0'));
        }
        $token_data = $res_token['data'];
        if ($token_data && $token_data['token']) {
            $token = $token_data['token'];
            $curlhttp = $_SERVER['SERVER_NAME'];
            if ($curlhttp == "mshop.yolipai.net") {
                $apiHost = $token_data['apiHost'];//正式环境都上传
            } else {
                $apiHost = "http://open.xinda100.com";//测试环境
            }
        }
        $token=preg_replace("/(\s|\ \;| |\xc2\xa0)/","",$token);
        $newsstr = "?token=" . $token;
        if ($data) {
            foreach ($data as $key => $val) {
                if ($newsstr) {
                    $newsstr .= "&" . $key . "=" . $val;
                }
            }
        }
        $newsstr .= "&page=" . $page;
        $newsstr .= "&pageSize=" . $len;
        $url = $apiHost . "/" . $apiname . $newsstr;
        if (empty($url)) {
            return json_encode(array('code' => -1, 'msg' => '接口地址不能为空'));
        }
        $rs = httpRequest($url,"GET",null,array(),true,$timeout,$accdb);
        return $rs;
    } catch (Exception $ex) {
        return json_encode(array('code' => -1, 'msg' => '异常出错'));
    }
}
/*--获取接口数据分装 _新
 *param $acctk方法
 *param $tk token
 *param $data
 *param $map
 *param $page
 *param $isjson 是否json格式
 * $is_newpost 是否要把8282端口改成8283
 *return $rs接口返回的内容
 */
function getApiData_java_p($apiname, $accdb, $data = null, $page = 1, $len = 10, $order = null, $method = "GET", $isjson = 0,$is_newpost=0,$timeout=15)
{
    try {
        $res_token = getapi_token($accdb);
        $res_token = $res_token;
        $token = "";
        if (empty($res_token))
        {
            return json_encode(array('code' => -1, 'msg' => '获取TOKEN为空'));
        }
        if (!array_key_exists("code", $res_token))
        {
            return json_encode(array('code' => -1, 'msg' => '获取不包含code'));
        }
        if ($res_token['code'] != 0) {
            return json_encode(array('code' => -1, 'msg' => 'code值不等于0'));
        }
        $token_data = $res_token['data'];
        if ($token_data && $token_data['token']) {
            $token = $token_data['token'];
            $curlhttp = $_SERVER['SERVER_NAME'];
            if ($curlhttp == "mshop.yolipai.net") {
                $apiHost = $token_data['apiHost'];//正式环境都上传
            } else {
              //  $apiHost = $token_data['apiHost'];//正式环境都上传
                $apiHost = "http://open.xinda100.com";//测试环境open.xinda100.com     http://172.20.3.132:8282
                //$apiHost="http://172.20.3.132:8282";
            }
        }
        if ($is_newpost)
        {
            $apiHost=str_replace("8282","8283",$apiHost);
        }
        $token=preg_replace("/(\s|\ \;| |\xc2\xa0)/","",$token);
        if ($method == "GET" || $method == "DELETE") {
            $newsstr = "?token=" . $token;
            if ($data) {
                foreach ($data as $key => $val) {
                    if ($newsstr) {
                        $newsstr .= "&" . $key . "=" . $val;
                    }
                }
            }
            $newsstr .= "&page=" . $page;
            $newsstr .= "&pageSize=" . $len;
            $url = $apiHost . "/" . $apiname . $newsstr;
            if (empty($url)) {
                return json_encode(array('code' => -1, 'msg' => '接口地址不能为空'));
            }
            mlog("url:" . $url, "apidatajava/" . $accdb."/".urlencode($apiname));
            $rs = httpRequest($url,$method,null,array(),true,$timeout,$accdb);
            mlog("返回值:" . $rs, "apidatajava/" . $accdb."/".urlencode($apiname));
            return $rs;
        } else {
            $url = $apiHost . "/" . $apiname;
            if ($isjson) {
                $header = array(
                    'Content-Type: application/json; charset=utf-8',
                    'token:' . $token,
                    'Content-Length: ' . strlen($data)
                );
                $rs = httpRequest($url, $method, $data, $header);
            } else {
                $newsstr["token"] = $token;
                if ($data) {
                    foreach ($data as $key => $val) {
                        if ($newsstr) {
                            $newsstr["" . $key . ""] = urldecode($val);
                        }
                    }
                }
                $newsstr["page"] = $page;
                $newsstr["pageSize"] = $len;
                if (empty($url)) {
                    return json_encode(array('code' => -1, 'msg' => '接口地址不能为空'));
                }
                mlog("post:" . json_encode($newsstr), "apidatajava/" . $accdb."/".urlencode($apiname));
                mlog("url:" . $url, "apidatajava/" . $accdb."/".urlencode($apiname));
                mlog("token:" . $token, "apidatajava/" . $accdb."/".urlencode($apiname));
                $rs = httpRequest($url, $method, $newsstr,array(),true,$timeout,$accdb);
            }
            mlog("返回值:" . $rs, "apidatajava/" . $accdb."/".urlencode($apiname));
            return $rs;
        }
    } catch (Exception $ex) {
        mlog("异常出错getApiData_java_p:" . $ex, "apidatajava_ex/" . $accdb."/".urlencode($apiname));
        return json_encode(array('code' => -1, 'msg' => '异常出错'));
    }
}
//新接口token
function getapi_token($accdb)
{
    if (empty($accdb)) {
        return array('code' => -1, 'msg' => '失败');
    }
    $accdb = strtolower($accdb);
    $wxdtoken_access_data = cache_new("common", "wxderp", "wxdtoken_access_data:" . $accdb);
    $wxdtoken_access_time = cache_new("common", "wxderp", "wxdtoken_access_time:" . $accdb);
    $is_has=1;
    if(empty($wxdtoken_access_data)) $is_has=0;
    else{
        if(empty($wxdtoken_access_data['apiHost'])) $is_has=0;
    }
    if ($wxdtoken_access_time && $wxdtoken_access_data && $wxdtoken_access_time >= time() && $is_has) {
        return array('code' => 0, 'msg' => 'ok', 'data' => $wxdtoken_access_data, 'acctoken_time' => $wxdtoken_access_time);
    }
    $url = WXD_OPENURL . '/api/auth/token/?accdb=' . $accdb;
    $res = httpRequest($url, 'get');
    if (empty($res)) {
        return array('code' => -1, 'msg' => '失败');
    }
    mlog("004001:" . $res, "getapi_token/" . $accdb);
    $getAccessToken = json_decode($res, true);
    if ($getAccessToken['code'] == 0 && $getAccessToken['data']) {
        $wxdtoken_access_data = $getAccessToken['data'];
        $wxdtoken_access_time = time() + 72000;
        cache_new("common", "wxderp", "wxdtoken_access_data:" . $accdb, $wxdtoken_access_data);
        cache_new("common", "wxderp", "wxdtoken_access_time:" . $accdb, $wxdtoken_access_time);
        return array('code' => 0, 'msg' => 'ok', 'data' => $wxdtoken_access_data, 'acctoken_time' => $wxdtoken_access_time);
    } else {
        return $res;
    }
}
function getApiData($acctk, $tk, $data = null, $map = null, $page = null, $len = null, $order = null)
{
    $list = array("access_token" => $acctk, 'page' => $page, 'length' => $len);
    $array = array(
        'token' => $tk,
        'data' => $data,
        'map' => $map,
        'order' => $order,
    );
    $json = json_encode($array);
    mlog($json . ':start' . $acctk . ':' . $tk, 'getapi1/' . $tk . '/' . $acctk);
    $url = GetSignUrl($list);
    if (empty($url)) {
        mlog('接口错误', 'api');
        return null;
    }
    mlog('接口时间', 'getapi1/' . $tk . '/' . $acctk);
    mlog('url:' . $url, 'getapi1/' . $tk . '/' . $acctk);
    $rs = http_post_json($url, $json);
    mlog('接口时间', 'getapi1/' . $tk . '/' . $acctk);
    mlog("返回值 :" . json_encode($rs), 'getapi1/' . $tk . '/' . $acctk);
    $qlist = urldecode($rs[0]);
    mlog('url:' . $url . '---' . $qlist . ':back' . $tk . ':' . $tk, 'getapi1/' . $tk . '/' . $acctk);
    return $qlist;
}
function return_id($ordid, $gid)
{
    $rs = M("return_goods")->where('order_id', $ordid)->where("goods_id=" . $gid . " or find_in_set($gid,goods_id_list)")->find();
    return $rs['id'];
}
/*---是否退货中---*/
function isReturn($ordid, $gid)
{
    $rs = M("return_goods")->where("order_id", $ordid)->where("goods_id=" . $gid . " or find_in_set($gid,goods_id_list)")->where('status', array('lt', 3))->find();
    if (!empty($rs)) {
        return 1;
    }
    return 0;
}
function getOrdState($ordinfo)
{
    $r = M('return_goods')->where('order_id', $ordinfo["order_id"])->select();
    $goods_id_list = get_arr_column($r, "goods_id");
    if ($r) {
        $ordglist = M('order_goods')->where('order_id', $ordinfo["order_id"])->select();
        foreach ($ordglist as $k => $v) {
            if (!in_array($v['goods_id'], $goods_id_list)) {
                return '部分退款';
            }
        }
        return '退款中';
    } else {
        return $ordinfo['order_status_desc'];
    }
}
function admin_getOrdState($ordinfo)
{
    return $ordinfo['order_status_desc'];
}
function isallreturn($ordid)
{
    $r = M('return_goods')->where('order_id', $ordid)->select();
    if (!empty($r[0]['goods_id_list'])) {
        return 1;
    } else {
        $goods_id_list = get_arr_column($r, "goods_id");
        if ($r) {
            foreach ($r as $m => $n) {
                if ($n['status'] == 3) {
                    return 0;
                }
            }
            $ordglist = M('order_goods')->where('order_id', $ordid)->select();
            foreach ($ordglist as $k => $v) {
                if (!in_array($v['goods_id'], $goods_id_list)) {
                    return 0;
                }
            }
            return 1;
        } else {
            return 0;
        }
    }
}
/*--退货状态--*/
function getRStatus($ind)
{
    switch ($ind) {
        case "0":
            return '退款申请中';
        case "1":
            return '退款处理中';
        case "2":
            return '退货退款完成';
        case "3":
            return '拒绝退货退款';
    }
    return "无";
}
/*--退货类型--*/
function getRType($ind)
{
    switch ($ind) {
        case "0":
            return '退货';
        case "1":
            return '换货';
    }
    return "无";
}
/*---退款状态---*/
function ReturnType($ordid, $gid)
{
    $rs = M("return_goods")->where("order_id", $ordid)->where("goods_id=" . $gid)->find();
    if (empty($rs))
        $rs = M("return_goods")->where("order_id", $ordid)->where("find_in_set($gid,goods_id_list)")->find();
    if (!empty($rs)) {
        return getRStatus($rs['status']);
    }
    return '未知';
}
/*--短信记录表操作   重要:一定要先更新商家的短信数量后再调用次函数。
 *param $stoid门店ID
 */
function smsHandle($store_id, $remark)
{
    $store = M('store')->where('store_id', $store_id)->field('smsqty')->find();
    $smsqty = $store['smsqty'];
    $data['store_id'] = $store_id;
    $data['add_time'] = time();
    $data['endqty'] = $smsqty;
    $data['remark'] = $remark;
    $r = D('sms_inoutlist')->add($data);
}
function is_https()
{
    if (!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off') {
        return TRUE;
    } elseif (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') {
        return TRUE;
    } elseif (!empty($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off') {
        return TRUE;
    }
    return FALSE;
}
function curPageURL()
{
    $pageURL = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
    if ($_SERVER["SERVER_PORT"] != "80") {
        $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
    } else {
        $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
    }
    return $pageURL;
}
/**
 * @param $cartarr 购物车列表
 * @param $stoid  门店ID
 */
function getcountarr($cartarr, $stoid)
{
    if (empty($cartarr)) {
        return null;
    }
    $tk = M("store")->where("store_id", $stoid)->field("api_token")->find();
    $where1 = "";
    $arrdata = null;
    $arrgoodis = null;
    foreach ($cartarr as $kr => $vr) {
        $dd11 = M('goods')->where('goods_id', $vr['goods_id'])->find();
        $dd22 = M('pick_up')->where('pickup_id', $vr['pick_id'])->find();
        $wid[] = $dd11['erpwareid'];
        $storageid[] = $dd22['keyid'];
        //$where1.="(WareId='".$dd11['erpwareid']."' and  storageid='".$dd22['keyid']."') or";
        $arrdata[$dd22['keyid']] = $vr['pick_id'];
        $arrgoodis[$dd11['erpwareid']] = $vr['goods_id'];
        /*--产品和门店对--*/
        $grouparr[] = [$dd11['erpwareid'], $dd22['keyid']];
    }
    /*---
    $where1['WareId'] = array('in', $wid);
    $where1['StorageId'] = array('in', $storageid);
    $where1['CanOutQty'] = array('>', 0);
    $rs = getApiData("wxd.sto.vstorages.list.get", $tk['api_token'], null, $map = $where1, null, null, null);
    ---*/
    $wdata['WareIds'] = urlencode(implode(',', $wid));
    $wdata['StorageIds'] = urlencode(implode(',', $storageid));
    $accdb = tpCache("shop_info.ERPId", $stoid);
    mlog("获取线下库存:" . json_encode($wdata), "getcountarr/" . $stoid);
    $rs = getApiData_java("api/erp/sto/storages/page", $accdb, $wdata, 1, 1000);
    if ($rs) {
        $dt = json_decode($rs, true);
        //$dt=ext_json_decode($rs,true);
        $dt = $dt['data'];
        if (!empty($dt)) {
            if ($dt['pageData']) {
                foreach ($dt['pageData'] as $kk1 => $vv1) {
                    $arrt = [$vv1['WareId'], $vv1['StorageId']];
                    if (in_array($arrt, $grouparr)) {
                        $pid = $arrdata[$vv1['StorageId']];
                        $gid = $arrgoodis[$vv1['WareId']];
                        $key = $pid . $gid;
                        $t_count[$key] = $vv1['CanOutQty'];
                    }
                }
                return $t_count;
            } else {
                return null;
            }
        } else {
            return null;
        }
    } else {
        return null;
    }
}
/**
 *合并获取所有的订单商品
 * @param $psn订单父单号
 **/
function ord_goods_he($psn)
{
    $orderarr = M('order')->where("parent_sn", $psn)->select();
    $allgaarr = [];
    if ($orderarr) {
        foreach ($orderarr as $kl => $vl) {
            $garr = M('order_goods')->where('order_id', $vl['order_id'])->order('rec_id', 'asc')->select();
            foreach ($garr as $k0 => $v0) {
                $garr[$k0]['pick_id'] = $orderarr[$kl]['pickup_id'];
            }
            $allgaarr = array_merge($garr, $allgaarr);
        }
    }
    return $allgaarr;
}
/**
 * @param $goodsid   商品id
 * @param $pickupid  门店id
 * @param $stoid     商家ID
 * @return float|int
 */
function getpickwarecount($goodsid, $pickupid, $stoid)
{
    $tk = M("store")->where("store_id", $stoid)->field("api_token")->find();
    /*---有显示的门店---*/
    $pick = M('pick_up')->where('pickup_id', $pickupid)->find();
    $ware = M('goods')->where('goods_id', $goodsid)->find();
    $where1['WareId'] = array('=', $ware['erpwareid']);
    $where1['StorageId'] = array('=', $pick['keyid']);
    $where1['CanOutQty'] = array('>', 0);
    //$rs = getApiData("wxd.sto.vstorages.list.get", $tk['api_token'], null, $map = $where1, null, null, null);
    $rs = getApiData("wxd.sto.storages.list.get", $tk['api_token'], null, $map = $where1, null, null, null);
    if ($rs) {
        $dt = json_decode($rs, true);
        if (empty($dt['data'])) {
            return -1;
        } else {
            return floor($dt['data'][0]['CanOutQty']);
        }
    } else {
        return -1;
    }
}
/**
 * 计算商品数组中的商品的线下库存
 * @param $gidarr  商品id数组(线上goods_id 和线下wareid的集合)
 * @param $stoid 门店ID
 * @param $dis 商品配送方式
 */
function getblinesto($gidarr, $stoid, $dis)
{
    $tk = tpCache("shop_info.api_token", $stoid);
    $accdb = tpCache("shop_info.ERPId", $stoid);
    $res0 = M("storage_category")->where('store_id', $stoid)->where('is_show', 0)->field("cat_id")->select();
    $res0 = get_arr_column($res0, 'cat_id');
    $wh = "1=1";
    if (!empty($res0))
        $wh = "a.category_id not in(" . implode(',', $res0) . ")";
    if ($dis == 0) {
        $where1 = "1=1";
    } else {
        $where1 = "a.distr_type=" . $dis . " or a.distr_type=0";
    }
    $pick = M('pick_up')->alias('a')->join('storage_category b', 'a.category_id=b.cat_id', 'left')
        ->where('a.store_id', $stoid)->where('a.isstop', 0)->where($wh)
        ->where($where1)->field('a.*,b.cat_name')->select();
    if (empty($pick)) {
        return -3;
    }
    foreach ($pick as $k6 => $v6) {
        $dstoid = $v6['keyid'];
        $pickupid[] = $dstoid;
        $pickup_no[]=$v6['pickup_no'];
        $pick_change[$dstoid] = $v6['pickup_id'];
        $pick_namearr[$dstoid] = $v6['pickup_name'];
        $distri_type_arr[$dstoid] = $v6['distr_type'];
        $pick_cat[$dstoid] = $v6['category_id'];
        $addr_arr[$dstoid] = $v6['fulladdress'];
        if (empty($cat_namearr[$v6['category_id']])) {
            $cat_namearr[$v6['category_id']] = $v6['cat_name'];
        }
    }
    foreach ($gidarr as $k5 => $v5) {
        $blinegidarr[] = $k5;
    }
    $where1 = null;
    $wdata['WareIds'] = urlencode(implode(',', $blinegidarr));
    $wdata['StorageNos'] = urlencode(implode(',', $pickup_no));
    mlog("获取线下库存:" . json_encode($wdata), "cart2/" . getMobileStoId());
    $rs = getApiData_java("api/erp/sto/storages/page", $accdb, $wdata, 1, 1000);
    mlog("获取线下库存结果:" . $rs, "cart2/" . getMobileStoId());
    if (empty($rs)) {
        $rs = getApiData_java("api/erp/sto/storages/page", $accdb, $wdata, 1, 1000);
    }
    if ($rs) {
        $dt = json_decode($rs, true);
        $dt = $dt['data'];
        if (!empty($dt)) {
            if ($dt['pageData']) {
                $def_list=[];
                foreach ($dt['pageData'] as $kk1 => $vv1) {
                    /*--数组拼装--*/
                    $thisgid = $gidarr[$vv1['WareId']];   //获取商品goods_id
                    if (empty($res[$thisgid])) $res[$thisgid] = ['gid' => $thisgid];
                    $pkid = $pick_change[$vv1['StorageId']];
                    $caid = $pick_cat[$vv1['StorageId']];
                    $pickname = $pick_namearr[$vv1['StorageId']];
                    $cat_name1 = $cat_namearr[$caid];
                    $distri_type = $distri_type_arr[$vv1['StorageId']];
                    $addr=$addr_arr[$vv1['StorageId']];
                    $cart_array1 = ['cid' => $caid, 'cat_name' => $cat_name1];
                    if (empty($res[$thisgid]['cat_list'])) {
                        $res[$thisgid]['cat_list'] = [];
                    }
                    if (!in_array($cart_array1, $res[$thisgid]['cat_list'])) {
                        $res[$thisgid]['cat_list'][] = $cart_array1;
                    }
                    if($pkid==null) continue;
                    $res[$thisgid]['list'][] = ['pickup_id' => $pkid, 'pickup_name' => $pickname, 'distr_type' => $distri_type,"fulladdress"=>$addr,
                            'cat_id' => $caid, 'count' => floor($vv1['CanOutQty'])];
                    if($kk1<5){
                        $def_list[]=['pickup_id' => $pkid, 'pickup_name' => $pickname, 'distr_type' => $distri_type,"fulladdress"=>$addr,
                            'cat_id' => $caid, 'count' => floor($vv1['CanOutQty'])];
                    }
                }
                return ['res' => $res,'def_list'=>$def_list];
            } else {
                return -2;
            }
        } else {
            return -1;
        }
    } else {
        return -1;
    }
}
/*---获取商品的实际价格---*/
function getActualPrice($v)
{
    $ty = $v['prom_type'];
    if ($ty == 0 || $ty == 3 || $ty == 5) {
        return "¥" . $v['shop_price'];
    } else {
        $now0 = time();
        switch ($ty) {
            case 1: //秒杀
                $table = "flash_sale";
                $where0 = [
                    'end_time' => ['>=', $now0],
                    'show_time' => ['<=', $now0],
                    'goods_id' => $v['goods_id'],
                    'is_end' => 0
                ];
                break;
            case 2: //团购
                $table = "group_buy";
                $where0 = [
                    'end_time' => ['>=', $now0],
                    'start_time' => ['<=', $now0],
                    'goods_id' => $v['goods_id'],
                    'is_end' => 0
                ];
                break;
            case 4: //积分购
                $table = "integral_buy";
                $where0 = [
                    'end_time' => ['>=', $now0],
                    'start_time' => ['<=', $now0],
                    'goods_id' => $v['goods_id'],
                    'is_end' => 0,
                    'is_show' => 1
                ];
                break;
        }
        $rs0 = M($table)->where($where0)->find();
        if ($ty == 4) {
            if (empty($rs0)) {
                //return "¥".$v['shop_price'];
                return "¥" . $v['shop_price'];
            } else {
                //$rtprice = $rs0['integral'] . "积分";
                $rtprice = $rs0['integral'] . "积分";
                if ($rs0['addmoney'] > 0) {
                    $rtprice .= "+¥" . $rs0['addmoney'] . "";
                }
                return $rtprice;
            }
        } else {
            if (empty($rs0)) {
                //return "¥".$v['shop_price'];
                return "¥" . $v['shop_price'];
            } else {
                //return "¥" . $rs0['price'];
                return "¥" . $rs0['price'];
            }
        }
    }
}
/*---获取商品的实际价格---*/
function getActualPrice2($v)
{
    $ty = $v['prom_type'];
    $user = session('user');
    $mz = $user['is_mzvip'];//美妆
    $rank = $user['card_field'];//等级
    $rand_end = empty($user['card_expiredate']) ? 0 : strtotime($user['card_expiredate']);
    $now = time();
    $rank_switch = tpCache('shopping.rank_switch', getMobileStoId());//等级开关
    $mz_switch = tpCache('shopping.is_beauty', getMobileStoId());//美妆开关
    if ($ty == 0 || $ty == 3 || $ty == 5) {
        if ($ty == 0) {
            if (!empty($rank_switch)) {
                if (!empty($rank) && $v[$rank] > 0 && $rand_end > $now) {
                    $v['shop_price'] = $v[$rank];
                }
            } else if (!empty($mz) && $v['mz_price'] > 0 && !empty($mz_switch)) {
                $v['shop_price'] = $v['mz_price'];
            }
        }
        return "¥" . $v['shop_price'];
    } else {
        $now0 = time();
        switch ($ty) {
            case 1: //秒杀
                $table = "flash_sale";
                $where0 = [
                    'end_time' => ['>=', $now0],
                    'show_time' => ['<=', $now0],
                    'goods_id' => $v['goods_id'],
                    'is_end' => 0
                ];
                break;
            case 2: //团购
                $table = "group_buy";
                $where0 = [
                    'end_time' => ['>=', $now0],
                    'start_time' => ['<=', $now0],
                    'goods_id' => $v['goods_id'],
                    'is_end' => 0
                ];
                break;
            case 4: //积分购
                $table = "integral_buy";
                $where0 = [
                    'end_time' => ['>=', $now0],
                    'start_time' => ['<=', $now0],
                    'goods_id' => $v['goods_id'],
                    'is_end' => 0,
                    'is_show' => 1
                ];
                break;
            case 6: //天天拼单
                $table = "teamlist";
                $where0 = [
                    'end_time' => ['>=', $now0],
                    'start_time' => ['<=', $now0],
                    'goods_id' => $v['goods_id'],
                    'is_end' => 0,
                    'is_show' => 1
                ];
                break;
        }
        $rs0 = M($table)->where($where0)->find();
        if ($ty == 4) {
            if (empty($rs0)) {
                return "¥" . $v['shop_price'];
            } else {
                $rtprice = $rs0['integral'] . "积分";
                if (!empty($rs0['addmoney'])) {
                    $rtprice .= "+¥" . $rs0['addmoney'];
                }
                return $rtprice;
            }
        } else {
            if (empty($rs0)) {
                return "¥" . $v['shop_price'];
            } else {
                return "¥" . $rs0['price'];
            }
        }
    }
}
/*----获取商品要下划线的价格---*/
function getUnderlinePrice($v)
{
    $ty = $v['prom_type'];
    if ($ty == 1 || $ty == 2 || $ty == 4) {
        return $v['market_price'];
    } else {
        return $v['market_price'];
    }
}
//------获取config-----
function getManagerConf($data = null)
{
    $conf = null;
    if (empty($data)) {
        $conf = Cache::get('manager_config');
        if (empty($conf)) {
            $conf = M('manager_config')->find();
            Cache::set('manager_config', $conf);
        }
    } else {
        $data = I('post.');
        $r = M('manager_config')->where('id', 1)->save($data);
        $conf = M('manager_config')->find();
        Cache::set('manager_config', $conf);
    }
    return $conf;
}
/*--套接字--*/
function doRequest($url, $param = array(), $port)
{
    $urlinfo = parse_url($url);
    $host = $urlinfo['host'] ? $urlinfo['host'] : "localhost";
    $path = $urlinfo['path'];
    $query = isset($param) ? http_build_query($param) : '';
    $port = $port;
    $errno = 0;
    $errstr = '';
    $timeout = 10;
    $fp = fsockopen($host, $port, $errno, $errstr, $timeout);
    $out = "GET " . $path . " HTTP/1.1\r\n";
    $out .= "host:" . $host . "\r\n";
    $out .= "connection:close\r\n\r\n";
    $out .= $query;
    echo $out;
    fputs($fp, $out);
    //忽略执行结果
    while (!feof($fp)) {
        echo fgets($fp, 128);
    }
    fclose($fp);
}
/*--------------自定义模板添加,nyf,2017.7.20----------------*/
function get_m_type($ind)
{
    switch ($ind) {
        case 0:
            return "商家自定义模板";
        case 1:
            return "免费模板";
        case 2:
            return "收费模板";
        case 3:
            return "空白模板";
    }
    return "";
}
/*------函数-------*/
function get_ad_position($stoid)
{
    mlog("000", "index/" . $stoid);
    $rs = Cache::get('ppgg_' . $stoid);
    if (!empty($rs)) {
        return $rs;
    }
    mlog("111", "index/" . $stoid);
    $tu = M("store")->where("store_id", $stoid)->getField('ERPId');
    $purl = httpRequest(WXDURL . '/?access_token=wxdoa.shoppc.url.get');
    if ($purl) {
        $data = json_decode($purl, true);
        if ($data && $data['code'] == 1) {
            mlog("333", "index/" . $stoid);
            $url = $data['data']['url'] . "/?access_token=ylp.getad&ERP_Id=" . $tu . "&ad_id=00000146";
            $rs = myHttpRspone($url);
            mlog("444", "index/" . $stoid);
            Cache::set('ppgg_' . $stoid, $rs, 3600 * 24);
            return $rs;
        }
    }
    mlog("222", "index/" . $stoid);
    return null;
}
/**
 * 计算商品数组中的商品的线下库存,并且按照远近排序
 * @param $gidarr  商品id数组(线上goods_id 和线下wareid的集合),x1是精读,y1是维度
 * @param $stoid 门店ID
 *
 */
function getblinesto_sortlocation($gidarr, $stoid, $gid, $x, $y, $dis)
{
    $res = [];
    $tk = tpCache("shop_info.api_token", $stoid);
    /*---有显示的门店---*/
    $res0 = M("storage_category")->where('store_id', $stoid)->where('is_show', 0)->field("cat_id")->select();
    $res0 = get_arr_column($res0, 'cat_id');
    $wh = "1=1";
    //如果分类不为空,且分类并没有全部关闭
    if (!empty($res0))
        $wh = "a.category_id not in(" . implode(',', $res0) . ")";
    if ($dis == 0) {
        $where1 = "1=1";
    } else {
        $where1 = "a.distr_type=" . $dis . " or a.distr_type=0";
    }
    if($x || $y){
        $pick = M('pick_up')->alias('a')->join('storage_category b', 'a.category_id=b.cat_id', 'left')
            ->where('a.store_id', $stoid)->where('a.isstop', 0)->where($wh)
            ->where($where1)
            ->field('a.*,b.cat_name,st_distance (POINT (lat,lon),POINT('.$y.','.$x.')) * 111195 AS distance')
            ->order('distance asc,a.pickup_id asc')
            ->select();
    }else{
        $pick = M('pick_up')->alias('a')->join('storage_category b', 'a.category_id=b.cat_id', 'left')
            ->where('a.store_id', $stoid)->where('a.isstop', 0)->where($wh)
            ->where($where1)
            ->field("a.*,b.cat_name,'null' AS distance")
            ->order('distance asc,a.pickup_id asc')
            ->select();
    }
    if (empty($pick)) { return -3; }
    foreach ($pick as $k6 => $v6) {
        $dstoid = $v6['keyid'];
        $pickupid[] = $dstoid;
        $pickup_no[]=$v6['pickup_no'];
        $pick_change[$dstoid] = $v6['pickup_id'];       //门店的线上id
        $pick_namearr[$dstoid] = $v6['pickup_name'];    //门店的名称
        $pick_cat[$dstoid] = $v6['category_id'];        //门店的分类ID
        $distri_type_arr[$dstoid] = $v6['distr_type'];  //门店的distri_type
        $addr[$dstoid] = $v6['fulladdress'];  //门店的distri_type
        /*-------求俩点的距离-------*/
        $pick_locaion[$dstoid] =$v6['distance'];
        if (empty($cat_namearr[$v6['category_id']])) {
            $cat_namearr[$v6['category_id']] = $v6['cat_name'];
        }
    }
    foreach ($gidarr as $k5 => $v5) {
        $blinegidarr[] = $k5;
    }
    $wdata['WareIds'] = urlencode(implode(',', $blinegidarr));
    $wdata['StorageNos'] = urlencode(implode(',', $pickup_no));
    $accdb = tpCache("shop_info.ERPId", $stoid);
    mlog("获取线下库存:" . json_encode($wdata), "cart2/" . getMobileStoId());
    $rs = getApiData_java("api/erp/sto/storages/page", $accdb, $wdata, 1, 1000);
    if (empty($rs)) {
        $rs = getApiData_java("api/erp/sto/storages/page", $accdb, $wdata, 1, 1000);
    }
    $mindata = [];
    $def_list = [];
    if ($rs) {
        $dt = json_decode($rs, true);
        $dt = $dt['data'];
        if (!empty($dt)) {
            if ($dt['pageData']) {
                foreach ($dt['pageData'] as $kk1 => $vv1) {
                    /*--数组拼装--*/
                    $thisgid = $gidarr[$vv1['WareId']];   //获取商品goods_id
                    if (empty($res[$thisgid])) $res[$thisgid] = ['gid' => $thisgid];
                    $pkid = $pick_change[$vv1['StorageId']];
                    $caid = $pick_cat[$vv1['StorageId']];
                    $pickname = $pick_namearr[$vv1['StorageId']];
                    $cat_name1 = $cat_namearr[$caid];
                    $cart_array1 = ['cid' => $caid, 'cat_name' => $cat_name1];
                    $dis1 = $pick_locaion[$vv1['StorageId']];
                    $distri_type = $distri_type_arr[$vv1['StorageId']];
                    $f_addr = $addr[$vv1['StorageId']];
                    if (empty($res[$thisgid]['cat_list'])) {
                        $res[$thisgid]['cat_list'] = [];
                    }
                    if (!in_array($cart_array1, $res[$thisgid]['cat_list'])) {
                        $res[$thisgid]['cat_list'][] = $cart_array1;
                    }
                    $res[$thisgid]['list'][] = ['pickup_id' => $pkid, 'pickup_name' => $pickname, 'distr_type' => $distri_type,
                        'cat_id' => $caid, 'count' => floor($vv1['CanOutQty']), 'distance' => $dis1,'fulladdress'=>$f_addr];
                     //--组装def数组--
                    if($kk1<5){
                        $def_list[]= ['pickup_id' => $pkid, 'pickup_name' => $pickname, 'distr_type' => $distri_type,
                            'cat_id' => $caid, 'count' => floor($vv1['CanOutQty']), 'distance' => $dis1,'fulladdress'=>$f_addr];
                    }
                }
                $mindata = $def_list[0];
                return ['res' => $res, 'min' => $mindata,'def_list'=>$def_list];
            } else {
                return -2;
            }
        } else {
            return -1;
        }
    } else {
        return -1;
    }
}
//门店价$shop_price,优惠主表$prominfo,购买量$goods_num,
function discount($price, $prom_id, $goods_num, $user_id, $is_bz = 0)
{
    $prom_list = M('prom_goods_list')->where('prom_id', $prom_id)
        ->field('preferential_type,prom_type,condition')->order('condition', 'asc')->select();
    $prom['prom_type'] = 3;
    $prom['prom_id'] = $prom_id;
    $prom['is_end'] = 0;
    $prom['price'] = $price;
    $prom['int'] = 0;
    $prom['coupon_id'] = 0;
    mlog(json_encode($prom_list), "cart3_yhui/usr/" . $user_id);
    foreach ($prom_list as $v) {
        $rule = json_decode($v['preferential_type'], true);
        $condition = 0;
        $condition1 = 0;
        //当是价格条件是,要减一些价钱,在判断有没有符合条件
        if ($v['prom_type'] == 0) {
            $condition = $price;
        } else {
            $condition = $goods_num;
        }
        if ($condition >= $v['condition']) {
            /*---
            if ($rule['money'] > 0){
                $condition1 = $price- $rule['money'];
            }else if ($rule['sale'] > 0) {
                $condition1 = $price * $rule['sale'] / 10;
            }---*/
            $num = 1;
            if ($is_bz == 1) {
                //$num = $condition / $v['condition'];
                //$num = (int)$num;
                $num= ceil(round(($condition/$v['condition']),1));
                if($num*$v['condition']>$condition) $num=$num-1;
            }
            $condition1 = $condition;
            $prom['goods_id'] = '';
            if ($rule['money'] > 0) {
                if ($price <= $rule['money']) {
                    $prom['price'] = 0;
                } else {
                    $prom['price'] = $price - $num * $rule['money'];  //当是减价的时候,要翻倍
                    if ($prom['price'] < 0) $prom['price'] = 0;
                }
            } else if ($rule['sale'] > 0) {
                $prom['price'] = $price * $rule['sale'] / 10;//当是打折的时候,不要翻倍
            } else {
                $prom['price'] = $price;
            }
            $condition1 = $condition1 . "";
            mlog($condition1 . "-" . $v['condition'], "cart3_yhui/usr/" . $user_id);
            if ($condition1 && $condition1 >= $v['condition']) {
                if ($rule['gift'] > 0) {
                    //$receive = M('gift_receive')->where(['prom_id' => $prom_id, 'gift_id' => $rule['gift'], 'user_id' => $user_id])->count();
                    $receive = M('gift_receive')->where(['prom_id' => $prom_id, 'gift_id' => $rule['gift'], 'user_id' => $user_id])->sum("gift_num");
                    $gift = M('gift')->where(['id' => $rule['gift'], 'start_time' => ['lt', time()], 'end_time' => ['gt', time()], 'goods_num' => ['>', 0], 'is_end' => 0])->field('goods_id,goods_name,limit_num,goods_num')->find();
                    if ($receive < $gift['limit_num'] && !empty($gift)) {
                        $prom['goods_id'] = $gift['goods_id'];
                        $prom['goods_name'] = $gift['goods_name'];
                        $prom['limit_num'] = $gift['limit_num'] - (int)$receive;
                        $prom['gift_id'] = $rule['gift'];
                        $prom['gift_storecount'] = $gift['goods_num'];
                    }
                }
                $prom['int'] = $num * $rule['int'];
                $prom['coupon_id'] = $rule['coupon'];
                $prom['libao'] = $rule['libao'];
                $prom['is_past'] = $rule['is_past'];
                $prom['is_bz'] = $is_bz;
                $prom['condition'] = $v['condition'];
                $prom['condition_ty'] = $v['prom_type'];
                if ($is_bz == 1) {
                    $prom['bs'] = $num;
                    if ($prom['libao']) $prom['lb_num'] = $num;
                    if ($prom['coupon_id']) $prom['coupon_num'] = $num;
                } else
                    $prom['bs'] = 1;
            }
        } else {
            $prom['condition'] = $v['condition'];
            $prom['type'] = $v['prom_type'];
            $prom['rule'] = $rule;
            break;
        }
    }
    return $prom;
}
/*---统一获取access_token---*/
//$isupdate = 是否强制更新
function m_get_access_token($weixinconfig = null, $stoid = null, $isupdate = 0)
{
    //判断是否过了缓存期
    $wechat = null;
    if ($weixinconfig)
        $wechat = $weixinconfig;
    else
        $wechat = M('wx_user')->where('store_id=' . $stoid)->find();
    if (empty($stoid)) {
        $stoid = $wechat['store_id'];
    }
    //第三方平台授权对应access_token
    if (empty($isupdate)) {
        $expire_time = $wechat['authorizer_expires'];
        mlog($expire_time . ">" . time() . "=" . ($expire_time > time()), "authorizer_access_token/" . $stoid);
        if ($expire_time && $wechat['authorizer_access_token'] && $expire_time > time()) {
            return $wechat['authorizer_access_token'];
        }
    }
    $url = 'https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token=' . getcomponent_access_token();
    $data_string = '{"component_appid":"' . open_appId . '" ,"authorizer_appid": "' . $wechat['appid'] . '", "authorizer_refresh_token": "' . $wechat['authorizer_refresh_token'] . '" }';
    mlog("获取值url:" . $url, "authorizer_access_token/" . $stoid);
    mlog("获取值post:" . $data_string, "authorizer_access_token/" . $stoid);
    $return = httpRequest($url, 'POST', $data_string);
    mlog("获取值【" . getIP() . "】:" . json_encode($return), "authorizer_access_token/" . $stoid);
    $return = json_decode($return, 1);
    $where = array();
    $web_expires = time() + 7000; // 7000秒过期
    if ($return['authorizer_access_token']) {
        if ($stoid) {
            $where['store_id'] = $stoid;
        }
        if ($wechat['id']) {
            $where['id'] = $wechat['id'];
        }
        $rs = M('wx_user')->where($where)->save(array('authorizer_access_token' => $return['authorizer_access_token'], 'authorizer_refresh_token' => $return['authorizer_refresh_token'], 'authorizer_expires' => $web_expires));
        if ($rs) {
            mlog("刷新数据库成功:" . $return['authorizer_access_token'], "authorizer_access_token/" . $stoid);
        } else {
            mlog("刷新数据库失败:" . $return['authorizer_access_token'], "authorizer_access_token/" . $stoid);
        }
    }
    mlog("重新获取IP【" . getIP() . "】:" . $return['authorizer_access_token'], "authorizer_access_token/" . $stoid);
    return $return['authorizer_access_token'];
}
/*---小程序统一获取access_token---*/
//$isupdate = 是否强制更新
function weapp_get_access_token($weixinconfig = null, $stoid = null, $isupdate = 0)
{
    //判断是否过了缓存期
    $wechat = null;
    if ($weixinconfig)
        $wechat = $weixinconfig;
    else
        $wechat = M('weapp')->where('store_id=' . $stoid)->find();
    if (empty($stoid)) {
        $stoid = $wechat['store_id'];
    }
    //第三方平台授权对应access_token
    if (empty($isupdate)) {
        $expire_time = $wechat['authorizer_expires'];
        mlog($expire_time . ">" . time() . "=" . ($expire_time > time()), "weapp_get_access_token/" . $stoid);
        if ($expire_time && $wechat['authorizer_access_token'] && $expire_time > time()) {
            cache_new("wechat", "component", "authorizer_access_token:" . $wechat['appid'] . "", $wechat['authorizer_access_token']);
            cache_new("wechat", "component", "authorizer_access_token_time:" . $wechat['appid'] . "", $expire_time);
            return json_encode(array('errcode' => 0, 'authorizer_access_token' => $wechat['authorizer_access_token']));
        }
    }
    $url = 'https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token=' . getcomponent_access_token();
    $data_string = '{"component_appid":"' . open_appId . '" ,"authorizer_appid": "' . $wechat['appid'] . '", "authorizer_refresh_token": "' . $wechat['authorizer_refresh_token'] . '" }';
    mlog("获取值url:" . $url, "weapp_get_access_token/" . $stoid);
    mlog("获取值post:" . $data_string, "weapp_get_access_token/" . $stoid);
    $return = httpRequest($url, 'POST', $data_string);
    mlog("获取值【" . getIP() . "】:" . json_encode($return), "weapp_get_access_token/" . $stoid);
    $return = json_decode($return, 1);
    if ($return['errcode'] != 0) {
        return json_encode($return);
    }
    $where = array();
    $web_expires = time() + 7000; // 7000秒过期
    if ($return['authorizer_access_token']) {
        //xxx:xxxx:wechat:component:authorizer_access_token:具体的appid
        cache_new("wechat", "component", "authorizer_access_token:" . $wechat['appid'] . "", $return['authorizer_access_token']);
        cache_new("wechat", "component", "authorizer_access_token_time:" . $wechat['appid'] . "", $web_expires);
        if ($stoid) {
            $where['store_id'] = $stoid;
        }
        if ($wechat['id']) {
            $where['id'] = $wechat['id'];
        }
        $rs = M('weapp')->where($where)->save(array('authorizer_access_token' => $return['authorizer_access_token'], 'authorizer_refresh_token' => $return['authorizer_refresh_token'], 'authorizer_expires' => $web_expires));
        if ($rs) {
            mlog("刷新数据库成功:" . $return['authorizer_access_token'], "weapp_get_access_token/" . $stoid);
        } else {
            mlog("刷新数据库失败:" . $return['authorizer_access_token'], "weapp_get_access_token/" . $stoid);
        }
        mlog("重新获取IP【" . getIP() . "】:" . $return['authorizer_access_token'], "weapp_get_access_token/" . $stoid);
        return json_encode(array('errcode' => 0, 'authorizer_access_token' => $return['authorizer_access_token']));
    } else {
        return json_encode($return);
    }
}
/*---小程序统一获取access_token---*/
//$isupdate = 是否强制更新
function weapp_appid_get_access_token($weixinconfig = null, $appid = null, $isupdate = 0)
{
    //判断是否过了缓存期
    $wechat = null;
    if ($weixinconfig)
        $wechat = $weixinconfig;
    else
        $wechat = M('weapp')->where(array('appid' => $appid))->find();
    if (empty($appid)) {
        $appid = $wechat['appid'];
    }
    //第三方平台授权对应access_token
    if (empty($isupdate)) {
        $expire_time = $wechat['authorizer_expires'];
        mlog($expire_time . ">" . time() . "=" . ($expire_time > time()), "weapp_get_access_token/" . $appid);
        if ($expire_time && $wechat['authorizer_access_token'] && $expire_time > time()) {
            cache_new("wechat", "component", "authorizer_access_token:" . $wechat['appid'] . "", $wechat['authorizer_access_token']);
            cache_new("wechat", "component", "authorizer_access_token_time:" . $wechat['appid'] . "", $expire_time);
            return json_encode(array('errcode' => 0, 'authorizer_access_token' => $wechat['authorizer_access_token']));
        }
    }
    $url = 'https://api.weixin.qq.com/cgi-bin/component/api_authorizer_token?component_access_token=' . getcomponent_access_token();
    $data_string = '{"component_appid":"' . open_appId . '" ,"authorizer_appid": "' . $wechat['appid'] . '", "authorizer_refresh_token": "' . $wechat['authorizer_refresh_token'] . '" }';
    mlog("获取值url:" . $url, "weapp_get_access_token/" . $appid);
    mlog("获取值post:" . $data_string, "weapp_get_access_token/" . $appid);
    $return = httpRequest($url, 'POST', $data_string);
    mlog("获取值【" . getIP() . "】:" . json_encode($return), "weapp_get_access_token/" . $appid);
    $return = json_decode($return, 1);
    if ($return['errcode'] != 0) {
        return json_encode($return);
    }
    $where = array();
    $web_expires = time() + 7000; // 7000秒过期
    if ($return['authorizer_access_token']) {
        //xxx:xxxx:wechat:component:authorizer_access_token:具体的appid
        cache_new("wechat", "component", "authorizer_access_token:" . $wechat['appid'] . "", $return['authorizer_access_token']);
        cache_new("wechat", "component", "authorizer_access_token_time:" . $wechat['appid'] . "", $web_expires);
        if ($appid) {
            $where['appid'] = $appid;
        }
        if ($wechat['id']) {
            $where['id'] = $wechat['id'];
        }
        $rs = M('weapp')->where($where)->save(array('authorizer_access_token' => $return['authorizer_access_token'], 'authorizer_refresh_token' => $return['authorizer_refresh_token'], 'authorizer_expires' => $web_expires));
        if ($rs) {
            mlog("刷新数据库成功:" . $return['authorizer_access_token'], "weapp_get_access_token/" . $appid);
        } else {
            mlog("刷新数据库失败:" . $return['authorizer_access_token'], "weapp_get_access_token/" . $appid);
        }
        mlog("重新获取IP【" . getIP() . "】:" . $return['authorizer_access_token'], "weapp_get_access_token/" . $appid);
        return json_encode(array('errcode' => 0, 'authorizer_access_token' => $return['authorizer_access_token']));
    } else {
        return json_encode($return);
    }
}
//erp专用
function erp_get_access_token($weixinconfig = null, $stoid = null, $isupdate = 0)
{
    // 公众号本身
    //判断是否过了缓存期
    $wechat = null;
    if ($weixinconfig)
        $wechat = $weixinconfig;
    else
        $wechat = M('wx_user')->where('store_id=' . $stoid)->find();
    if (empty($stoid)) {
        $stoid = $wechat['store_id'];
    }
    if (empty($isupdate)) {
        $expire_time = $wechat['web_expires'];
        if ($expire_time && $wechat['web_access_token'] && $expire_time > time()) {
            return $wechat['web_access_token'];
        }
    }
    $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $wechat['appid'] . '&secret=' . $wechat['appsecret'];
    $return = httpRequest($url, 'GET');
    mlog($return, "erp_get_access_token/" . $stoid);
    $return = json_decode($return, 1);
    $where = array();
    $web_expires = time() + 7000; // 7000秒过期
    if ($return['access_token']) {
        if ($stoid) {
            $where['store_id'] = $stoid;
        }
        if ($wechat['id']) {
            $where['id'] = $wechat['id'];
        }
        $rs = M('wx_user')->where($where)->save(array('web_access_token' => $return['access_token'], 'web_expires' => $web_expires));
        if ($rs) {
        } else {
        }
    }
    return $return['access_token'];
}
//第三方平台component_token
function getcomponent_access_token()
{
    $getcomponent_access_time = cache_new("wechat", "component", "component_access_time");
    $getcomponent_access_token = cache_new("wechat", "component", "component_access_token");
    mlog("001:" . $getcomponent_access_time . "|" . $getcomponent_access_token, "getcomponent_access_token");
    if ($getcomponent_access_time && $getcomponent_access_token && $getcomponent_access_time >= time()) {
        return $getcomponent_access_token;
    }
    $component_verify_ticket = cache_new("wechat", "component", "component_verify_ticket");
    $component_verify_ticket_time = cache_new("wechat", "component", "component_verify_ticket_time");
    mlog("00101:" . $component_verify_ticket . "|" . $component_verify_ticket_time, "getcomponent_access_token");
    $getcomponent_verify_ticket = "";//最新令牌
    //&& $component_verify_ticket_time && $component_verify_ticket_time>=time()
    if ($component_verify_ticket && $component_verify_ticket_time >= time()) {
        $getcomponent_verify_ticket = $component_verify_ticket;
    } else {
        $getcomponent_verify_ticket = file_get_contents(dirname(__FILE__) . "/index/controller/static/component_verify_ticket.txt");//正式
        $getcomponent_verify_tickettime = file_get_contents(dirname(__FILE__) . "/index/controller/static/component_verify_ticket_time.txt");//正式
        cache_new("wechat", "component", "component_verify_ticket", $getcomponent_verify_ticket);
        cache_new("wechat", "component", "component_verify_ticket_time", $getcomponent_verify_tickettime + 600);
    }
    $url = 'https://api.weixin.qq.com/cgi-bin/component/api_component_token';
    $data_string = '{"component_appid":"' . open_appId . '" ,"component_appsecret": "' . open_appSecret . '", "component_verify_ticket": "' . $getcomponent_verify_ticket . '" }';
    mlog("004000:" . $data_string, "getcomponent_access_token");
    $res = httpRequest($url, 'POST', $data_string);
    mlog("004001:" . $res, "getcomponent_access_token");
    $getAccessToken = json_decode($res);
    $component_access_token = $getAccessToken->component_access_token;
    if ($component_access_token) {
        mlog("004:" . (time() + 7000) . "|" . $component_access_token, "getcomponent_access_token");
        cache_new("wechat", "component", "component_access_token", $component_access_token);
        cache_new("wechat", "component", "component_access_time", time() + 7000);
    }
    return $component_access_token;
}
//判断美妆会员条件$order:订单详情,$user_id:用户id
function mz_condition($order, $user_id)
{
    $store_id = $order['store_id'];
    mlog('美妆user_id:' . $user_id, 'mz_price/' . $store_id);
    $mz = tpCache('shopping.mzprice_list', $store_id);
    mlog('美妆价条件:' . $mz, 'mz_price/' . $store_id);
    $mz_list = json_decode($mz, true);
    if ($mz_list['is_beauty']) {//美妆价开关
        if (session('?user')) {
            $user = session('user');
            $status = 1;//是否重定义session
        } else {
            $user = M('users')->where(['user_id' => $user_id, 'store_id' => $store_id])->find();
            $status = 0;
        }
        $money = 0;//总订单价格
        $count = 0;//订单数
        $remark = '';//成为美妆价条件
        if ($user['is_mzvip'] == 0) {//用户不是美妆会员进入判断
            $order_list = M('order')->where(['user_id' => $user_id, 'order_status' => [['=', 2], ['=', 4], 'or'], 'add_time' => ['gt', $mz_list['mz_time']]])
                ->field('user_money,order_amount')->select();//查找符合条件的订单
            if (!empty($order_list)) {
                $count = count($order_list);
                foreach ($order_list as $v) {
                    $money += $v['user_money'] + $v['order_amount'];
                }
            }
            $condition = $mz_list['mz_con'];
            switch ($condition) {
                case  0:
                case  3:
                    if ($count >= $mz_list['mz_tran']) {
                        mlog('美妆价条件0:订单数-' . $mz_list['mz_tran'], 'mz_price/' . $store_id);
                        $remark = '{"mz_condition":"满订单数-' . $mz_list['mz_tran'] . '","mz_time":"' . date('Y-m-d H:i:s') . '"}';
                    }
                    break;
                case  1:
                case  3:
                    if ($money >= $mz_list['mz_money']) {
                        mlog('美妆价条件1:金额-' . $mz_list['mz_money'], 'mz_price/' . $store_id);
                        $remark = '{"mz_condition":"满金额-' . $mz_list['mz_money'] . '","mz_time":"' . date('Y-m-d H:i:s') . '"}';
                    }
                    break;
                case  2:
                case  3:
                    $goods = M('order_goods')->where(['order_id' => $order['order_id'], 'goods_id' => $mz_list['mz_goods_id']])->field('rec_id')->find();
                    if (!empty($goods)) {
                        mlog('美妆价条件2:商品-' . $mz_list['mz_goods_name'], 'mz_price/' . $store_id);
                        $remark = '{"mz_condition":"购买' . $mz_list['mz_goods_name'] . '","goods_id":"商品id:"' . $mz_list['mz_goods_id'] . ',"mz_time":"' . date('Y-m-d H:i:s') . '"}';
                    }
                    break;
            }
        }
        if (!empty($remark)) {
            M('users')->where(['user_id' => $user_id, 'store_id' => $store_id])->save(['is_mzvip' => 1, 'mzvip_remark' => $remark]);
            $user['is_mzvip'] = 1;
        }
        if ($status)
            session('user', $user);  //覆盖session 中的 user
    }
}
//优惠促销送优惠券,送积分
function give_discount($user_id, $int, $coupon_id, $store_id = 0, $order = null)
{
    if (empty($store_id)) {
        $store_id = getMobileStoId();
    }
    $user_info = M('users')->alias('a')->join('store b', 'a.store_id=b.store_id')
        ->where(array('a.user_id' => $user_id, 'a.store_id' => $store_id))->field("a.*,b.api_token,b.ERPId")->find();
    if ($int > 0) {
        mlog("80优惠送积分:" . $int, 'smslog/' . $store_id);
        if ($user_info['api_token']) {
            /*--
            $data = array(
                'Id' => $user_info["erpvipid"],//会员id
                'Integral' => $int,//积分
                'Remark' => '优惠送积分',
            );
            $add_rs = getApiData("wxd.vip.addreduce", $user_info['api_token'], array($data));
            mlog("801优惠送积分:" . json_encode($data) . "返回:" . $add_rs, 'smslog/' . $store_id);--*/
            com_update_integral($user_info['ERPId'],$user_info,$int,'优惠送积分');
        } else {
            accountLog($user_info["user_id"], 0, $int, '优惠送积分', 0, $store_id, $user_info["pay_points"]);//线上表
        }
    }
    if (!empty($coupon_id)) {
        $coupon = M("coupon")->where(['id' => ['in', $coupon_id]])->select();
        if (empty($order)) {
            mlog("81", 'smslog/' . $store_id);
            foreach ($coupon as $value) {
                give_send_quan($value, $user_info, $store_id);
            }
        } else {
            if ($order['g_coupon_num']) {
                $dd = json_decode($order['g_coupon_num'], true);
                foreach ($dd as $k => $v) {
                    $ddd[$v['c_id']] = $v['num'];
                }
                //倍增送券
                foreach ($coupon as $value) {
                    $n = $ddd[$value['id']];
                    for ($i = 0; $i < $n; $i++) {
                        give_send_quan($value, $user_info, $store_id);
                    }
                }
            } else {
                foreach ($coupon as $value) {
                    give_send_quan($value, $user_info, $store_id);
                }
            }
        }
    }
    if ($order['give_lb_id']) {
        $libao_id = $order['give_lb_id'];
        $bao = M("libao_form")->where(['id' => ['in', $libao_id]])->select();
        if ($order['g_lb_num']) {
            //计算翻倍的情况下
            $dd = json_decode($order['g_lb_num'], true);
            foreach ($dd as $k => $v) {
                $ddd[$v['l_id']] = $v['num'];
            }
            //倍增送券
            foreach ($bao as $value) {
                $n = $ddd[$value['id']];
                for ($i = 0; $i < $n; $i++) {
                    give_send_libao($value, $user_info, $store_id);
                }
            }
        } else {
            foreach ($bao as $value) {
                give_send_libao($value, $user_info, $store_id);
            }
        }
    }
}
//赠送,送一张券
function give_send_quan($value, $user_info, $store_id)
{
    $erp = tpCache("shop_info.ERPId", $store_id);
    if ($value["send_end_time"] > time()) {
        $CashRepNo = "1005" . date("ymdHis") . get_total_millisecond();
        $coupon = $value;
        if ($erp) {
            $data = array(
                'CashRepNo' => $CashRepNo,//券号
                'VIPId' => $user_info["erpvipid"],//会员id
                'Sum' => $value["money"],//金额
                'SendMan' => '优惠活动',//发放类型
                'Operator' => '微信商城',//来源
                'BuySum' => $value["condition"],//满多少才能使用
                'Remark' => '优惠送微券【消费满' . $value["condition"] . '元可用】',
            );
            if ($value['useobjecttype']) {
                $data['UseObjectType'] = $value['useobjecttype'];
                $data['UseObjectID'] = $value['useobjectid'];
                $data['UseObjectNo'] = $value['useobjectno'];
                $data['UseObjectName'] = $value['useobjectname'];
            }
            //如果有设置有效期
            if ($coupon['endtype'] == 1) {
                $data['BeginDate'] = date('Y-m-d');//使用开始日期
                if ($coupon['days'] > 0) {
                    $ed = strtotime("+" . $coupon['days'] . " day");
                    $data['ValidDate'] = date('Y-m-d', $ed);//截止期限
                }
            } else {
                if ($coupon["use_start_time"] != "") {
                    $data['BeginDate'] = date('Y-m-d', $coupon["use_start_time"]);//使用开始日期
                }
                if ($coupon["use_end_time"] != "") {
                    $data['ValidDate'] = date('Y-m-d', $coupon["use_end_time"]);//截止期限
                }
            }
            $add_rs = getApiData_java_p("/api/erp/vip/cash/insert", $erp, $data, null, null, null, "POST");
            mlog("811优惠送微券:" . json_encode($data) . "返回:" . $add_rs, 'smslog/' . $store_id);
        }
        //插入线上优惠券领取表
        $coupon_list['cid'] = $value['id'];
        $coupon_list['type'] = 2;
        $coupon_list['uid'] = $user_info['user_id'];
        $coupon_list['send_time'] = time();
        $coupon_list['code'] = $CashRepNo;
        $coupon_list['store_id'] = $store_id;
        if ($coupon['endtype'] == 1) {
            $coupon_list['begintime'] = time();
            if ($coupon['days'] > 0)
                $coupon_list['validtime'] = strtotime("+" . $coupon['days'] . " day");
            else
                $coupon_list['validtime'] = 0;
        } else {
            $coupon_list['begintime'] = $coupon["use_start_time"];
            $coupon_list['validtime'] = $coupon["use_end_time"];
        }
        $coupon_list['sum'] = $value["money"];
        $coupon_list['buysum'] = $value["condition"];
        $coupon_list['remark'] = '优惠送微券【消费满' . $value["condition"] . '元可用】';
        $add_couponinfo = add_coupon($coupon_list, $user_info, $store_id);
    }
}
//赠送,送一个礼包张券
function give_send_libao($value, $user_info, $store_id)
{
    $lbnumber = 'lb' . date("YmdHis") . rand(1000, 9999);
    $userid = $user_info['user_id'];
    $data['user_id'] = $userid;
    $data['store_id'] = $store_id;
    $data['lbid'] = $value['id'];
    $data['expdate'] = strtotime('+' . $value['expday'] . ' day', time());
    $data['number'] = $lbnumber;
    $data['paytype'] = 1;
    $data['fbillstate'] = 1;
    $data['add_time'] = time();
    $uselbid = M('libao_formvip')->add($data);
    $list = M('libao_list')->where(array('store_id' => $store_id, 'lbid' => $value['id']))->select();
    if ($list) {
        for ($i = 0; $i < count($list); $i++) {
            unset($data);
            $data['user_id'] = $userid;
            $data['store_id'] = $store_id;
            $data['lbvipid'] = $uselbid;
            $data['goods_num'] = $list[$i]['goods_num'];
            $data['goods_name'] = $value['lbtype'] == 1 ? $list[$i]['goods_name'] : $list[$i]['cpid'];
            $data['goods_sn'] = $list[$i]['goods_sn'];
            $data['lb_state'] = $list[$i]['state'];
            M('libao_listvip')->add($data);
        }
    }
    M('libao_form')->where('id=' . $value['id'])->setInc('salenum');
}
function dirty_read_start()
{
    Db::query('SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED');
}
function dirty_read_end()
{
    Db::query('SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ');
}
//清空未支付秒杀订单,超时时间默认10分钟,并且清空缓存
function clear_flash_Order($stoid)
{
    $tt = strtotime("-5 minute");
    //$tt=time();
    $odlist = M('order')
        ->where('pay_status', 0)
        ->where('is_zsorder', 0)
        ->where("coupon_no='' or coupon_no is null")
        ->where('order_status between 0 and 1')
        ->where("redis_no<>''")
        ->where('order_amount>0')
        ->where('add_time<' . $tt)
        ->where('store_id', $stoid)->field('order_id,user_money,user_id')->select();
    $odarr = get_arr_column($odlist, 'order_id');
    //$redis = new \Redis();
    //$redis->connect(redisip, 6379);
    $redis = get_redis_handle();
    if ($odlist) {
        foreach ($odlist as $k => $v) {
            //先修改订单状态
            $ru = M('order')
                ->where('order_id', $v['order_id'])
                ->where('pay_status', 0)
                ->where('order_status<>3')
                ->save(['order_status' => 3]);
            if ($ru) {
                if ($v['user_money'] > 0) {
                    //解冻冻余额
                    $rs = M('Users')->where("user_id", $v['user_id'])
                        ->where('frozen_money>=' . $v['user_money'])->find();
                    if ($rs) {
                        M('Users')->where("user_id", $v['user_id'])->setDec('frozen_money', $v['user_money']);
                    }
                }
                $hh = M('order_goods')->where('order_id', $v['order_id'])
                    ->where('prom_type', 1)->where('store_id', $stoid)
                    ->field('order_id,goods_num,prom_id,order_sn,rec_id')->select();
                if ($hh) {
                    $odarr0 = get_arr_column($hh, 'order_id');
                    //增加队列
                    foreach ($hh as $k => $v) {
                        //$name0 ='ms'.$v['prom_id'] . '-' . $stoid;
                        $name0 = get_redis_name($v['prom_id'], 1, $stoid);
                        //不重复退回redis
                        if (!doublefind($redis, $name0, $v['rec_id'])) {
                            for ($i = 0; $i < $v['goods_num']; $i++) {
                                $redis->lPush($name0, $v['rec_id'] . '_' . $i);
                            }
                            $jsda['num'] = $v['goods_num'];
                            $jsda['order_sn'] = $v['order_sn'];
                            $jsda['type'] = 1;  //1是5分钟自动补回
                            mlog(json_encode($jsda), 'flash_log/' . $stoid . '/' . $v['prom_id']);
                        }
                    }
                }
                $hh2 = M('order_goods')->where('order_id', $v['order_id'])
                    ->where('prom_type', 2)->where('store_id', $stoid)
                    ->field('order_id,goods_num,prom_id,order_sn,rec_id')->select();
                if ($hh2) {
                    $odarr0 = get_arr_column($hh, 'order_id');
                    //增加队列
                    foreach ($hh2 as $k => $v) {
                        //$name_g ='grb'.$v['prom_id'] . '-' . $stoid;
                        $name_g = get_redis_name($v['prom_id'], 2, $stoid);
                        //不重复退回redis
                        if (!doublefind($redis, $name_g, "2" . $v['rec_id'])) {
                            for ($i = 0; $i < $v['goods_num']; $i++) {
                                $redis->lPush($name_g, "2" . $v['rec_id'] . '_' . $i);
                            }
                            $jsda['num'] = $v['goods_num'];
                            $jsda['order_sn'] = $v['order_sn'];
                            $jsda['type'] = 1;  //1是5分钟自动补回
                            mlog(json_encode($jsda), 'group_buy_log/' . $stoid . '/' . $v['prom_id']);
                        }
                    }
                }
            }
        }
    }
    //清理一些不提交订单,却影响到redis的位子,在清理之前,要看redis_no是否有值!
    //redis要加入set中,编号,类型,活动id,数量,时间,stoid
    $p_name = get_redis_set_name($stoid);
    $dd = $redis->sMembers($p_name);
    if ($dd) {
        foreach ($dd as $k => $v) {
            $dda = explode('-', $v);
            if ($dda[1] == "1") {
                //当订单不存在的时候才能改
                $odr = M('order')->where('store_id', $stoid)->where('redis_no', $dda[0])
                    ->field('order_id')
                    ->find();
                if (empty($odr)) {
                    $tt = strtotime("+5 minute", (int)$dda[4]);
                    if ($tt < time()) {
                        //$name0 = 'ms' . $dda[2] . '-' . $stoid;
                        $name0 = get_redis_name($dda[2], 1, $stoid);
                        if (!doublefind($redis, $name0, $dda[0])) {
                            for ($i = 0; $i < $dda[3]; $i++) {
                                $redis->lPush($name0, $dda[0] . '_' . $i);
                            }
                            $jsda['num'] = $dda[3];
                            $jsda['order_sn'] = $dda[0];
                            $jsda['type'] = 1;  //1是5分钟自动补回
                            mlog(json_encode($jsda), 'flash_log/' . $stoid . '/' . $dda[2] . "_2");
                            $redis->sRem($p_name, $v);
                        }
                    }
                }
            }
        }
    }
    //清理一些不提交订单,却影响到redis的位子,在清理之前,要看redis_no是否有值!
    //redis要加入set中,编号,类型,活动id,数量,时间,stoid
    $p_name = get_redis_set_name($stoid);
    $dd = $redis->sMembers($p_name);
    foreach ($dd as $k => $v) {
        $dda = explode('-', $v);
        if ($dda[1] == "2") {
            //当订单不存在的时候才能改
            $odr = M('order')->where('store_id', $stoid)->where('redis_no', $dda[0])
                ->field('order_id')
                ->find();
            if (empty($odr)) {
                $tt = strtotime("+5 minute", (int)$dda[4]);
                if ($tt < time()) {
                    //$name0 = 'grb' . $dda[2] . '-' . $stoid;
                    $name0 = get_redis_name($dda[2], 2, $stoid);
                    if (!doublefind($redis, $name0, 'g' . $dda[0])) {
                        for ($i = 0; $i < $dda[3]; $i++) {
                            $redis->lPush($name0, 'g' . $dda[0] . '_' . $i);
                        }
                        $jsda['num'] = $dda[3];
                        $jsda['order_sn'] = $dda[0];
                        $jsda['type'] = 1;  //1是5分钟自动补回
                        mlog(json_encode($jsda), 'group_log/' . $stoid . '/' . $dda[2] . "_2");
                        $redis->sRem($p_name, $v);
                    }
                }
            }
        }
    }
}
//清空未支付拼单订单,超时时间默认5分钟,并且清空缓存
function clear_pind_Order($stoid)
{
    $tt = strtotime("-5 minute");
    //$tt=time();
    $odlist = M('order')->where('pt_status', 0)->where('is_zsorder>1')
        ->where('order_status=0 or order_status=1')->where('add_time<' . $tt)
        ->where('order_amount>0')
        ->where('store_id', $stoid)->field('order_id,pt_listno,pt_prom_id,is_zsorder,user_money,user_id,is_pt_tz')->select();
    $odarr = get_arr_column($odlist, 'order_id');
    //$redis = new \Redis();
    //$redis->connect(redisip, 6379);
    $redis = get_redis_handle();
    if ($odlist) {
        //查找会员团,要补回人数
        foreach ($odlist as $k => $v) {
            //修改订单是状态
            $ru = M('order')->where('order_id', $v['order_id'])
                ->where('pay_status', 0)
                ->where('order_status<>3')
                ->save(['order_status' => 3]);
            if ($ru) {
                if ($v['is_zsorder'] == 3) {
                    //$name2 = 'pind' . $v['pt_prom_id'] . '-' . $v['pt_listno'] . $stoid;
                    $name2 = get_redis_name($v['pt_prom_id'], 6, $stoid) . ":" . $v['pt_listno'];
                    if (!doublefind($redis, $name2, $v['order_id'])) {
                        $redis->lPush($name2, $v['order_id'] . '_0');
                    }
                    //$len = $redis->lLen($name2);
                    //如果这个团,全部补回,那这个单就没有意思了,要delete掉
                    //$teamnum = M('teamlist')->field('ct_num')
                    //    ->where('id', $v['pt_prom_id'])->find();
                    //当取消的单是本人开的团,那么这个团要取消掉
                    if ($v['is_pt_tz'] == 1) {
                        //$redis->delete($name2);
                        del_redis($redis, $name2);
                        //要取消这个团
                        $da['state'] = 1;
                        $map['team_id'] = $v['pt_prom_id'];
                        $map['listno'] = $v['pt_listno'];
                        $map['store_id'] = $stoid;
                        M('teamgroup')->where($map)->save($da);
                    }
                }
                if ($v['user_money'] > 0) {
                    //解冻冻余额
                    $rs = M('Users')->where("user_id", $v['user_id'])
                        ->where('frozen_money>=' . $v['user_money'])->find();
                    if ($rs) {
                        M('Users')->where("user_id", $v['user_id'])->setDec('frozen_money', $v['user_money']);
                    }
                }
                //补回购买的数量
                $hh = M('order_goods')->where('order_id', $v['order_id'])
                    ->where('prom_type', 6)->where('store_id', $stoid)
                    ->field('order_id,goods_num,prom_id,rec_id,order_sn')->select();
                if ($hh) {
                    //增加队列
                    foreach ($hh as $k => $v) {
                        //$name0 ='pind'.$v['prom_id'] . '-' . $stoid;
                        $name0 = get_redis_name($v['prom_id'], 6, $stoid);
                        if (!doublefind($redis, $name0, $v['rec_id'])) {
                            for ($i = 0; $i < $v['goods_num']; $i++) {
                                $redis->lPush($name0, $v['rec_id'] . "_" . $i);
                                $jsda['num'] = $v['goods_num'];
                                $jsda['order_sn'] = $v['order_sn'];
                                $jsda['type'] = 1;  //1是5分钟自动补回
                                mlog(json_encode($jsda), 'pt_log/' . $stoid . '/' . $v['prom_id']);
                            }
                        }
                    }
                }
            }
        }
    }
    //清理一些不提交订单,却影响到redis的位子
    //redis要加入set中,编号,类型,活动id,数量,时间,stoid
    $p_name = get_redis_set_name($stoid);
    $dd = $redis->sMembers($p_name);
    if ($dd) {
        foreach ($dd as $k => $v) {
            $dda = explode('-', $v);
            if ($dda[1] == "6") {
                $tt = strtotime("+5 minute", (int)$dda[4]);
                if ($tt < time()) {
                    //$name0 ='pind'. $dda[2] . '-' . $stoid;
                    $name0 = get_redis_name($dda[2], 6, $stoid);
                    $odr = M('order')->where('store_id', $stoid)->where('redis_no', $dda[0])
                        ->field('order_id')
                        ->find();
                    if (empty($odr)) {
                        if (!doublefind($redis, $name0, $dda[0])) {
                            for ($i = 0; $i < $dda[3]; $i++) {
                                $redis->lPush($name0, $dda[0] . '_' . $i);
                                $jsda['num'] = $dda[3];
                                $jsda['order_sn'] = $dda[0];
                                $jsda['type'] = 1;  //1是5分钟自动补回
                                mlog(json_encode($jsda), 'pt_log/' . $stoid . '/' . $dda[2] . "_2");
                            }
                            if ($dda[5]) {
                                $name2 = $name0 . ':' . $dda[5];
                                $redis->lPush($name0, $dda[0]);
                            }
                        }
                    }
                    $redis->sRem($p_name, $v);
                }
            }
        }
    }
}
function countbuynum($mid)
{
    $c1 = M('store_renew_module')->where('module_id', $mid)->count();
    return $c1;
}
function m_clearC($b)
{
    Cache::rm($b);
}
//获取分销商的数量
function get_vali_num($stoid)
{
    $count = M('users')->where('store_id', $stoid)->where('is_distribut', 1)->count();
    return $count;
}
//获取等级卡会员的数量
function get_vali_num2($stoid)
{
    $count = M('users')->where('store_id', $stoid)->where("card_field<>''")->count();
    return $count;
}
//获取差多少会成团
function get_team_need($qh, $team_man_num, $stoid)
{
    $num = M('order')->where('pt_listno', $qh)
        ->where('store_id', $stoid)
        ->where('order_status<>3')
        ->where('pt_status<>0 and pt_status<>3')
        ->count();
    return $team_man_num - $num;
}
//获取差多少会成团
function get_team_need2($qh, $teamjson, $stoid)
{
    $num = M('order')->where('pt_listno', $qh)
        ->where('store_id', $stoid)
        ->where('order_status<>3')
        ->where('pt_status<>0 and pt_status<>3')
        ->count();
    $max = 0;
    $jsd = json_decode($teamjson, true);
    foreach ($jsd as $kj => $vj) {
        if ($vj['rynum'] > $max) $max = $vj['rynum'];
    }
    return $max - $num;
}
//还差多少时间结束
function get_team_t_need($end_time)
{
    return $end_time - time() > 0 ? $end_time - time() : 0;
}
//拼单活动的提取
function get_pt_promotion($goods, $prom1 = null, $user_id = 0, $qh = "")
{
    $now = time();
    $where = [
        'start_time' => ['lt', $now],
        'id' => $goods['prom_id'],
        'is_end' => 0,
        'is_show' => 1,
    ];
    $prom['price'] = $goods['shop_price'];
    $prom['prom_type'] = $goods['prom_type'];
    $prom['prom_id'] = $goods['prom_id'];
    $prom['is_end'] = 0;
    $prom['store_count'] = $goods['store_count'];
    //拼团活动
    if ($goods['prom_type'] == 6) {
        $prominfo = $prom1;
        if ($prominfo == null)
            $prominfo = M('teamlist')->where($where)->find();
        if (!empty($prominfo)) {
            //要读取开团的时间,看团的时间是不是过期
            $tgr = M('teamgroup')
                ->where('team_id', $goods['prom_id'])
                ->where('store_id', $prominfo['store_id'])
                ->where('listno', $qh)->find();
            $tt = $tgr['kt_end_time'];
            if ($tt < time()) {
                $prom['is_end'] = 1;//活动已经过期
                $prom['prom_type'] = $prom['prom_id'] = 0;//活动已过期
            } else {
                $prom['start'] = $prominfo["start_time"];
                $prom['end'] = $prominfo["end_time"];
                $prom['goods_num'] = $prominfo['goods_num'];
                $prom['buy_num'] = $prominfo['buy_num'];
                $prom['onlybuy'] = $prominfo['goods_num'] - $prominfo['buy_num'];
                if ($prominfo['goods_num'] <= $prominfo['buy_num']) {
                    $prom['is_end'] = 2;//已售馨
                    //$prom['price'] = $prominfo['price'];
                } else {
                    $prom['price'] = $prominfo['price'];
                    //单是阶梯团的时候,应该是付定金
                    if ($prominfo['kttype'] == 3) {
                        $prom['price'] = $prominfo['yf_price'];
                    }
                    //核查用户购买数量
                    $where = "user_id = :user_id and order_status in(0,1,2,4,6) and pt_status<>3 and pt_status<>0  and pt_prom_id>0 and  add_time>" . $prominfo['start_time'] . " and add_time<" . $prominfo['end_time'];
                    $order_id_arr = M('order')->where($where)->bind(['user_id' => $user_id])->getField('order_id', true);
                    if ($order_id_arr) {
                        $goods_num = M('order_goods')->where("prom_id={$goods['prom_id']} and prom_type={$goods['prom_type']} and order_id in (" . implode(',', $order_id_arr) . ")")->sum('goods_num');
                        if ($goods_num == null) $goods_num = 0;
                        if ($goods_num < $prominfo['buy_limit']) {
                            $prom['buy_limit'] = $prominfo['buy_limit'] - $goods_num;
                        } else {
                            $prom['is_end'] = 3;//已经超出限购数量
                            $prom['buy_limit'] = 0;
                        }
                    } else {
                        $prom['buy_limit'] = $prominfo['buy_limit'];
                    }
                }
            }
        } else {
            $prom['is_end'] = 4;//未找到活动
        }
    }
    if (!empty($prominfo)) {
        $prom['start_time'] = $prominfo['start_time'];
        $prom['end_time'] = $prominfo['end_time'];
    } else {
        $prom['prom_type'] = $prom['prom_id'] = 0;//活动已过期
        $prom['is_end'] = 1;//已结束
    }
    if ($prom['prom_id'] == 0) {
        //M('goods')->where("goods_id", $goods_id)->save($prom);
    }
    return $prom;
}
//订单团过期,要自动退款
function pt_auto_refund($tgr, $pdact)
{
    $et = strtotime('+' . $pdact['kt_time'] . ' hour', $tgr['buystartdate']);
    //当团的时间已经过期且团没有满团,
    //而且团的状态还未修改
    if ($et < time() && $tgr['state'] != 1 && $tgr['state'] != 3) {
        //订单和期号的都要修改状态
        M('order')->where('store_id', $tgr['store_id'])->where('pt_listno', $tgr['listno'])
            ->where('pt_prom_id', $tgr['team_id'])->save(['order_status' => 3]);
        M('teamgroup')->where('store_id', $tgr['store_id'])->where('listno', $tgr['listno'])
            ->where('team_id', $tgr['team_id'])->save(['state' => 1]);
        //$redis = new \Redis();
        //$redis->connect(redisip, 6379);
        $redis = get_redis_handle();
        $id = $tgr['team_id'];
        $qh = $tgr['listno'];
        $stoid = $tgr['store_id'];
        //清除会员团的队列
        if ($pdact['kttype'] == 2) {
            //$name2='pind'.$id.'-'.$qh.$stoid;
            $name2 = get_redis_name($id, 6, $stoid) . ":" . $qh;
            //$redis->delete($name2);
            del_redis($redis, $name2);
        }
        //拼单活动要补回队列库存
        //$name='pind'.$id.'-'.$stoid;
        $name = get_redis_name($id, 6, $stoid);
        $ordlist = M('order')->where('store_id', $tgr['store_id'])->where('pt_listno', $tgr['listno'])
            ->where('pt_prom_id', $tgr['team_id'])->field('order_id')->select();
        $ordarr = get_arr_column($ordlist, 'order_id');
        if ($ordarr) {
            //不重复退回redis
            if (!doublefind($redis, $name, $tgr['team_id'])) {
                $num = M('order_goods')->where('order_id', 'in', $ordarr)->where('store_id', $tgr['store_id'])
                    ->sum('goods_num');
                //此团购买的数量
                for ($i = 0; $i < $num; $i++) {
                    $redis->lPush($name, $tgr['team_id'] . '_0');
                }
            }
        }
    }
}
//获取拼单参加拼团人员的头像
function get_pt_headpic_list($actid, $listno, $stoid)
{
    $list = M('order')->alias('a')->join('users b', 'a.user_id=b.user_id')
        ->where('a.store_id', $stoid)
        ->where('a.pt_prom_id', $actid)
        ->where('a.pt_listno', $listno)
        ->where("a.pt_listno<>''")
        ->where("a.pay_time>0")
        ->field('b.head_pic')->limit(2)
        ->order('a.is_pt_tz desc')
        ->select();
    return $list;
}
//更新尾款资料
//$tail_type 是拼单状态
function update_pt_wk($order_no, $stoid, $ord, $tail_type = 0, $transaction_id = 0)
{
    //更新订单状态
    M('order')->where('order_sn', $order_no)->where('store_id', $stoid)
        ->save(['pt_status' => 4, 'tail_pay_type' => $tail_type, 'pay_status' => 1, 'pt_pay_sn' => $transaction_id]);
    //当所有人都支付尾款,要更新teamgroup
    $count = M('order')
        ->where('pt_listno', $ord['pt_listno'])
        ->where('pt_prom_id', $ord['pt_prom_id'])->where('pt_status', 4)
        ->where('store_id', $stoid)
        ->count();
    $tgr = M('teamgroup')->where('listno', $ord['pt_listno'])
        ->where('team_id', $ord['pt_prom_id'])
        ->where('store_id', $stoid)->find();
    //当付尾款的人等于成团时的人数
    if ($count == $tgr['jt_ct_num']) {
        //团期尾款支付完成结束团
        M('teamgroup')->where('listno', $ord['pt_listno'])
            ->where('team_id', $ord['pt_prom_id'])
            ->where('store_id', $stoid)
            ->save(['state' => 3]);
        M('order')->where('pt_listno', $ord['pt_listno'])
            ->where('pt_prom_id', $ord['pt_prom_id'])
            ->where('store_id', $stoid)
            ->save(['pay_status' => 1, 'pt_status' => 5]);
        //如果是满团,就要进行推送
        //$timer = new \app\timer\controller\Index();
        //$olist=M('order')
        //->where('pt_listno', $ord['pt_listno'])
        //->where('pt_prom_id', $ord['pt_prom_id'])
        //->where('store_id',$stoid)->select();
        /*--
        if($olist){
            foreach ($olist as $k=>$v){
                $stoid=$v['store_id'];
                $title='拼团尾款都支付成功';
                $remark='感谢您的参与~';
                $usr=M('users')->where('user_id',$v['user_id'])->field('erpvipid')->find();
                $erpid=tpCache('shop_info.ERPId',$stoid);
                $gd=M('order_goods')->where('order_id',$v['order_id'])->field('goods_name')->find();
                $teamlist=M('teamlist')->where('id',$v['pt_prom_id'])->field('ct_num')->find();
                $timer->post_msg($stoid,$erpid,$usr['erpvipid'],$title,$gd['goods_name'],$teamlist['ct_num'],$remark);
            }
        }---*/
    }
    return true;
}
//页面显示
function return_team($act_id)
{
    $team = M("teamlist")->where('id', $act_id)->field('ct_num,buy_num')->find();
    return '
已团' . $team['buy_num'] . '件 ' . $team['ct_num'] . '人团
'; } //$redis为队列,listname为队列名,order_sn为补回的订单,对半快速查找 function doublefind($redis, $listname, $sn) { $sn = $sn . '_0'; $len = $redis->lLen($listname); $n = $len / 2 + 1; for ($i = 0; $i < $n; $i++) { $str = $redis->lIndex($listname, $i); if ($sn == $str) { return true; } $end = $len - $i - 1; if ($end >= 0) { $str = $redis->lIndex($listname, $end); if ($sn == $str) { return true; } } } return false; } //$order_id订单号 平摊优惠金额到具体单价 function disoucponpt($order) { $order_id = $order['order_id']; mlog("执行" . $order['order_sn'], "disoucponpt/" . $order['store_id']); //是否启用平摊 $switch = tpCache('shopping.switch_list', $order['store_id']);//获取开关json $switch_list = json_decode($switch, true);//获取开关列表 $dissum = 0; $ordergoods_list = M('order_goods')->where(array('order_id' => $order_id, 'goods_price' => array('neq', 0))) ->order('goods_price desc')->select(); //订单详情 mlog("执行" . $order['order_sn'] . "从表值:" . json_encode($ordergoods_list), "disoucponpt/" . $order['store_id']); if (empty($switch_list['ispt_goods'])) {//0或空值 代表平摊 $orderlist = $order; $dissum = $orderlist['discount_amount'] + $orderlist['order_prom_amount']; //促销优惠金额 + 订单优惠 } $sumdissum = $dissum; $sumgoods_dissum = 0; mlog("执行" . $order['order_sn'] . "优惠金额:" . $dissum, "disoucponpt/" . $order['store_id']); //优惠金额 if ($dissum) { //获取所有商品单价 $getall_goodsprice = 0;//所有商品去掉代金券金额 foreach ($ordergoods_list as $k => $val) { $v = $val['goods_id']; $newpro[$v] = $val['goods_price']; // $getsignle_goodsprice = $val['goods_price'] * $val['goods_num']; $getsignle_goodsprice1 = $getsignle_goodsprice - $val['quan_num']; if ($getsignle_goodsprice1 <= 0) { $getsignle_goodsprice1 = 0; } $getall_goodsprice = $getall_goodsprice + $getsignle_goodsprice1; } //判断实收金额小于等于优惠总金额 if ($getall_goodsprice <= $dissum) { $allordergoods_data['account'] = 0; $allordergoods_data['account_yu'] = 0; $resone = M('order_goods')->where(array('order_id' => $order_id))->save($allordergoods_data); } else { if (count($ordergoods_list) == 1 && $ordergoods_list[0]["goods_num"] == 1)//只有一件商品 { $one_data['account'] = $ordergoods_list[0]["goods_price"] - $dissum - $ordergoods_list[0]['quan_num']; if ($one_data['account'] < 0) { $one_data['account'] = 0; } $resone = M('order_goods')->where(array('order_id' => $order_id, 'rec_id' => $ordergoods_list[0]['rec_id']))->save($one_data); } else if (count($ordergoods_list) == 1 && $ordergoods_list[0]["goods_price"] * $ordergoods_list[0]["goods_num"] - $dissum - $ordergoods_list[0]['quan_num'] <= 0) { $one_data['account'] = 0; $one_data['account_yu'] = 0; $resone = M('order_goods')->where(array('order_id' => $order_id, 'rec_id' => $ordergoods_list[0]['rec_id']))->save($one_data); } else { $amountprice = $orderlist['goods_price']; //商品总价 $per_price = $dissum / $getall_goodsprice; $fect_price=$getall_goodsprice-$dissum; $account_all=0; //平摊后单价总实收 //---比例要大于0.001,太小无法平摊---- if ($per_price >= 0.001) { //$singleprice = getFloatValue($per_price, 3);//floor($dissum/$amountprice*100)/100;; //每一元可优惠金额(保留2为小数,不四舍五入) $singleprice=floor($per_price*10000)/10000; $singleprice=$singleprice-0.001; //---分配account值---- for ($i = 0; $i < count($ordergoods_list); $i++) { unset($data); unset($tempprice); //单件商品总价 $getsiglesum = $ordergoods_list[$i]['goods_price'] * $ordergoods_list[$i]['goods_num']; //单件商品总价大于优惠券价格才优惠计算 if ($getsiglesum > $ordergoods_list[$i]['quan_num']) { $getsiglesum1 = $getsiglesum - $ordergoods_list[$i]['quan_num'];//单条商品去掉优惠券总金额 if ($getsiglesum1 > 0.1) { $goods_dissum = $getsiglesum1 * $singleprice;//单条商品总优惠 $goods_dissum = ($goods_dissum * 1000) / 1000; } else { $goods_dissum = $getsiglesum1; } $goods_dissum = getFloatValue($goods_dissum, 2); $goods_dissum1 = $getsiglesum1 - $goods_dissum;//单条商品剩余应收金额 $tempprice = ($goods_dissum1 * 1000 / $ordergoods_list[$i]['goods_num']) / 1000; $tempprice = getFloatValue($tempprice, 2); $ordergoods_list[$i]['account'] = $tempprice;//floor($tempprice*100)/100; //平摊后价格保留2位小数 $ordergoods_list[$i]['account_yu'] = 0; //$sumgoods_dissum += $goods_dissum;//商品总优惠 $account_all+=$tempprice*$ordergoods_list[$i]['goods_num']; } else { $ordergoods_list[$i]['account'] = 0; $ordergoods_list[$i]['account_yu'] = 0; } //------在此时分配商品优惠券的余数(多出来的)------- $data = $ordergoods_list[$i]; $updategoodsinfo = M('order_goods')->where(array('order_id' => $order_id, 'rec_id' => $ordergoods_list[$i]['rec_id']))->save($data); mlog("执行" . $order['order_sn'] . "更新:" . $updategoodsinfo, "disoucponpt/" . $order['store_id']); } //$otherprice = ((string)$sumdissum * 1000 - (string)$sumgoods_dissum * 1000) / 1000; $otherprice = ((string)$account_all * 1000 - (string)$fect_price * 1000) / 1000; $otherprice = getFloatValue($otherprice, 2); //重新验加起来是否等于余额 $getnew_prom_price = 0; $new_order_goodsinfo = M('order_goods')->where(array('order_id' => $order_id, 'account' => array('neq', 0)))->order('goods_num asc,goods_price desc')->select(); mlog("执行" . $order['order_sn'] . "最新:" . json_encode($new_order_goodsinfo), "disoucponpt/" . $order['store_id']); if ($new_order_goodsinfo) { foreach ($new_order_goodsinfo as $y => $v) { $getnew_prom_price += $v['account'] * $v['goods_num']; } } mlog("执行" . $order['order_sn'] . "用余额:" . $order['user_money'], "disoucponpt/" . $order['store_id']); mlog("执行" . $order['order_sn'] . "订单优惠:" . $order['order_amount'], "disoucponpt/" . $order['store_id']); $getorder_pay_price = $order['user_money'] + $order['order_amount']+$order['order_prom_amount']; mlog("执行" . $order['order_sn'] . "实际支付:" . $getorder_pay_price, "disoucponpt/" . $order['store_id']); mlog("执行" . $order['order_sn'] . "计算支付:" . $getnew_prom_price, "disoucponpt/" . $order['store_id']); if ($getnew_prom_price === $getorder_pay_price && $otherprice > 0) { $otherprice = 0; mlog("执行" . $order['order_sn'] . "余数01:" . $otherprice, "disoucponpt/" . $order['store_id']); } else if ($getorder_pay_price < $getnew_prom_price) { $otherprice = $getnew_prom_price - $getorder_pay_price; mlog("执行" . $order['order_sn'] . "余数00:" . $otherprice, "disoucponpt/" . $order['store_id']); } mlog("执行" . $order['order_sn'] . "余数:" . $otherprice, "disoucponpt/" . $order['store_id']); if ($otherprice != 0) //除不尽余额尚未分配 { if ($new_order_goodsinfo[0]['goods_num'] == 1)//如果商品购买数量为1时,直接account=account -account_yun { $newdata['account'] = $new_order_goodsinfo[0]['account'] - $otherprice; if ($new_order_goodsinfo[0]['account'] < 0) { $newdata['account'] = 0; } } else { $newdata['account_yu'] = $otherprice; } $updategoodsinfo1 = M('order_goods')->where(array('order_id' => $order_id, 'rec_id' => $new_order_goodsinfo[0]['rec_id']))->save($newdata); mlog("执行" . $order['order_sn'] . "余数:是否更新成功:" . $updategoodsinfo1, "disoucponpt/" . $order['store_id']); } // } //----否则不平摊---- else { Db::execute("update __PREFIX__order_goods set account=goods_price where order_id=" . $order_id); //---商品循环,分配出优惠券的金额---- foreach ($ordergoods_list as $kl => $vl) { $data = null; if ($vl['quan_num'] > 0) { $data['account'] = 0; if ($vl['goods_num'] == 1) { $data['account'] = $vl['goods_price'] - $vl['quan_num']; } else { $dis = intval($vl['quan_num'] * 100 / $vl['goods_num']) / 100; $data['account'] = $vl['account'] - $dis; $yu = ($vl['quan_num'] * 100) % $vl['goods_num']; $data['account_yu'] = $yu / 100; } //优惠活动没有办法平摊,所以把优惠活动的金额放到一个商品的余数里面去,前台会减掉这一部分的钱 if ($kl == 0) { $data['account_yu'] += $dissum; } M('order_goods')->where(array('order_id' => $order_id, 'rec_id' => $vl['rec_id']))->save($data); } else { //优惠活动没有办法平摊,所以把优惠活动的金额放到一个商品的余数里面去,前台会减掉这一部分的钱 if ($kl == 0) { $data['account_yu'] = $dissum; M('order_goods')->where(array('order_id' => $order_id, 'rec_id' => $vl['rec_id']))->save($data); } } } } } } } else { Db::execute("update __PREFIX__order_goods set account=goods_price where order_id=" . $order_id); //---商品循环,分配出优惠券的金额---- foreach ($ordergoods_list as $kl => $vl) { $data = null; if ($vl['quan_num'] > 0) { if ($vl['goods_num'] == 1) { $data['account'] = $vl['goods_price'] - $vl['quan_num']; } else { $dis = intval($vl['quan_num'] * 100 / $vl['goods_num']) / 100; $data['account'] = $vl['account'] - $dis; $yu = ($vl['quan_num'] * 100) % $vl['goods_num']; $data['account_yu'] = $yu / 100; } M('order_goods')->where(array('order_id' => $order_id, 'rec_id' => $vl['rec_id']))->save($data); } } } } //不四舍五入保留小数 function getFloatValue($f, $len) { //return round($f,$len); $amountprice2 = explode('.', $f); if (strlen($amountprice2[1]) <= $len) { return $f; } $tmpInt = intval($f); $tmpDecimal = $f - $tmpInt; $str = "$tmpDecimal"; $subStr = strstr($str, '.'); if (!$subStr) { return $f; } else { if (strlen($subStr) < $len + 1) { $repeatCount = $len + 1 - strlen($subStr); $str = $str . "" . str_repeat("0", $repeatCount); } return $tmpInt . "" . substr($str, 1, 1 + $len); } } //返利的代码 function tz_fl($order) { $qh = $order['pt_listno']; //会员团的时候要计算返利 if ($order['is_zsorder'] == 3) { $stoid = $order['store_id']; $rso = M("teamlist")->where("id", $order['pt_prom_id']) ->field('id,store_id,ct_num,actno,kt_time,kttype,tz_yhjgtype,tz_yyhjg')->find(); //$data['order_status'] = 2; // 已收货 //$data['pay_status'] = 1; // 已付款 $odls = M('order')->where('pt_prom_id', $rso['id'])->where('pt_listno', $order['pt_listno']) ->where('pt_status=1 or pt_status=2') ->where('order_status=4 or order_status=2') ->where('store_id', $order['store_id'])->count(); if ($odls == $rso['ct_num']) { //成团后要判断进行返利,团长获得 switch ($rso['tz_yhjgtype']) { case 2://免单处理 $odr = M("order")->where('pt_prom_id', $rso['id']) ->where('pt_listno', $qh)->where('is_pt_tz', 1) ->where('is_pt_rebate', 0) ->where('store_id', $stoid)->find(); if ($odr) { //$money = $odr['user_money'] + $odr['order_amount']; $money = $odr['user_money'] + $odr['order_amount']-$odr['shipping_price']; $sql = "update wxd_users set user_money=user_money+" . $money . " where user_id=" . $odr['user_id']; $rs1 = Db::execute($sql); if ($rs1) { $odata['user_id'] = $odr['user_id']; $odata['create_time'] = time(); $odata['money'] = $money; $odata['remark'] = "团长免单"; $odata['store_id'] = $odr['store_id']; $odata['order_sn'] = $odr['order_sn']; $odata['status'] = 1; $odata['type'] = 3; //返利 M('withdrawals')->save($odata); M('order')->where('order_id', $odr['order_id'])->save(['is_pt_rebate' => 1]); } else { mlog("团长免单,", 'refund/' . $odr['store_id']); } } break; case 3://优惠金额 $odr = M("order")->where('pt_prom_id', $rso['id']) ->where('pt_listno', $qh)->where('is_pt_tz', 1) ->where('is_pt_rebate', 0) ->where('store_id', $stoid)->find(); if ($odr) { $money = $rso['tz_yyhjg']; if ($money > 0) { $sql = "update wxd_users set user_money=user_money+" . $money . " where user_id=" . $odr['user_id']; $rs1 = Db::execute($sql); if ($rs1) { $odata['user_id'] = $odr['user_id']; $odata['create_time'] = time(); $odata['money'] = $money; $odata['remark'] = "团长优惠"; $odata['store_id'] = $odr['store_id']; $odata['order_sn'] = $odr['order_sn']; $odata['status'] = 1; $odata['type'] = 3;//返利 M('withdrawals')->save($odata); M('order')->where('order_id', $odr['order_id'])->save(['is_pt_rebate' => 1]); } else { mlog("团长优惠,", 'refund/' . $odr['store_id']); } } } break; } } } } /** * 根据 order_goods 表扣除商品库存 * @param type $order_id 订单id */ function check_team($order_id, $qh = "") { $orderGoodsArr = M('OrderGoods')->where("order_id", $order_id) ->field('store_id,prom_type,prom_id')->select(); $stoid = $orderGoodsArr[0]['store_id']; foreach ($orderGoodsArr as $key => $val) { //更新活动商品购买量 if ($val['prom_type'] == 6) { $tb = 'teamlist'; //商家团要开始分期号,会员团和阶梯团要看是否满团,满团要 $rso = M($tb)->where("id", $val['prom_id'])->where('store_id', $stoid) ->field('id,store_id,ct_num,actno,kt_time,kttype')->find(); if ($rso['kttype'] == 1) { //判断是否有在进行中的团 //if ($tgr) { //--- $tgr = M('teamgroup')->where('team_id', $val['prom_id']) ->where("store_id", $rso['store_id'])->where('state', 2) ->field('id,listno,member_num') ->find(); if (!$tgr) $tgr['id'] = 0; //--参加一个团,自增参团,使用乐观锁,不用悲观锁,避免锁表,好多商家都再用-- $str = "update wxd_teamgroup set member_num=member_num+1 WHERE member_num