<?php
if(file_exists(DOXCX_FRAME_PATH . "/fun/YiLianYunPrinter.class.php")){
	require_once DOXCX_FRAME_PATH . "/fun/YiLianYunPrinter.class.php";
}

if(file_exists(DOXCX_FRAME_PATH . "/fun/alipay/aop/AopClient.php")){
	require_once DOXCX_FRAME_PATH . "/fun/alipay/aop/AopClient.php";
}

if(file_exists(DOXCX_FRAME_PATH . "/fun/alipay/aop/request/AlipayTradeCreateRequest.php")){
	require_once DOXCX_FRAME_PATH . "/fun/alipay/aop/request/AlipayTradeCreateRequest.php";
}
/**
 * 获取管理员用户对象
 * @return Model
 */
function get_user_agency() {
    $uid = Session::get('uid');
    $user = (new Model('user'))->find(['id' => $uid]);
    if ($user->agid) {
        $agency = (new Model('user_agency'))->find(['id' => $user->agid]);
    } else {
        $agency = (new Model('user_agency'))->find(['un' => 'admin']);
    }
    return $agency;
}




/**
 * 统一的短信发送
 * @param $uid int user表的id
 * @param $tel string 手机号
 * @param $content  string 短信内容
 * @return bool
 */
function send_sms($uid, $tel, $content) {
    if (!$uid) {
        return false;
    }
    // 准备参数
    //$agency = get_user_agency();
    $user = (new Model('user'))->where(['id' => $uid])->find();
   if ($user->agid) {
        $agency = (new Model('user_agency'))->find(['id' => $user->agid]);
    } else {
        $agency = (new Model('user_agency'))->find(['isadmin' => 1]);
    }
    if ($user->surplus_sms <= 0) {
        return false;
    }
    $message_sign = $agency->message_sign;
    $raw_content = $content = $content . "【" . $message_sign . "】";
    $message_id = $agency->message_id;
    $message_pwd = $agency->message_pwd;
    $url = "http://service.winic.org:8009/sys_port/gateway/index.asp?";
    $data = "id=%s&pwd=%s&to=%s&Content=%s&time=";
    $id = urlencode(iconv("utf-8", "gb2312", "$message_id"));
    $pwd = $message_pwd;
    $to = $tel;
    $content = urlencode(iconv("UTF-8", "GB2312", $content));
    $rdata = sprintf($data, $id, $pwd, $to, $content);
    // 发送短信
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $rdata);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    curl_close($ch);
    $return = substr($result, 0, 3);
    // 剩余次数-1
    $user->surplus_sms = $user->surplus_sms - 1;
    $user->save();
    // 创建发送记录
    $rec = new Model('sms_send_record');
    $rec->uid = $uid;
    $rec->tel = $tel;
    $rec->content = $raw_content;
    $rec->ctime = time();
    $rec->return_code = $return;
    if ($return == '000') {
        // 发送成功
        $rec->status = 1;
        $rec->save();
        return true;
    } else {
        // 发送失败
        $rec->status = 0;
        $rec->save();
        return false;
    }
}

function get_vip_level($level_json, $total_point) {
    $levels = json_decode($level_json, 1);
    usort($levels, function ($a, $b) {
        if ($a['total_point'] == $b['total_point']) {
            return 0;
        }
        return ($a['total_point'] < $b['total_point']) ? 1 : -1;
    });
    foreach ($levels as $level) {
        if ($total_point > $level['total_point']) {
            return $level;
        }
    }
    return [
        'name'        => '无',
        'total_point' => 0,
        'discount'    => 0
    ];
}

/**
 * 微信解密库，解密出用户绑定的手机号
 * @param $appid
 * @param $sessionKey
 * @param $iv
 * @param $encryptedData
 * @return string
 */
function wxBizDecode($appid, $sessionKey, $iv, $encryptedData) {
    require_once "wxBizDataCrypt/wxBizDataCrypt.php";
    $pc = new WXBizDataCrypt($appid, $sessionKey);
    $errCode = $pc->decryptData($encryptedData, $iv, $data);
    if ($errCode == 0) {
        return json_decode($data, true);
    } else {
        diy_log($errCode);
        return '';
    }
}

function sendTemplateMsg($wid, $data) {
    try {
        $access_token = WX_getAccessToken($wid);
        $send_url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' . $access_token;
        $send_data = json_encode($data);//保留消息模板发送数据
        diy_log($data);
//        if(is_numeric(key($data))){ //如果没有指定key就是要
//
//        }
        $json_data = HttpCurl::post($send_url, $send_data);
        $resp = json_decode($json_data, true);
        diy_log(['发送模板消息', $data, $resp]);
        return $resp;
    } catch (Exception $e) {
        // 防爆
    }
    return false;
}

/**
 * 获取模板配置
 * @param $wid
 * @param $tpl_id
 * @return array
 */
function get_tplConfig($wid,$tpl_id){
    //获取指定模板id的模板，然后找到对应配置
    $template_info = (new Model("vshop_tplmsg_config"))->where(["is_enable"=>1,'wid'=>$wid,"template_id"=>$tpl_id])->find()->get_model_array_with_id();

    if(!$template_info['id'])return [];
    $tpl_config=\Addons\TemplateMsg\Helper::getInstance()->template_config($template_info['type']);
    if(!isset($tpl_config[$template_info['tpl_key']]))return [];
    $data=array_merge($tpl_config[$template_info['tpl_key']],$template_info);
    return $data;
}

/**
 * @param $wid
 * @param $openid
 * @param $tpl_id
 * @param $data
 * @param $page
 * @return bool|mixed
 */
function sendSubscribeMsg($wid,$openid, $tpl_id ,$data,$page= '/pages/index/index') {
    try {
        $access_token = WX_getAccessToken($wid);
        $send_url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' . $access_token;
        if(is_numeric(key($data))){ //如果没有指定key就使用配置初始化项目
            //获取指定模板id的模板，然后找到对应配置
            $template_info = get_tplConfig($wid,$tpl_id);
            if (empty($template_info))return false;
            $temp_data=[];
            foreach ($template_info['keyword_list'] as $key=>$item){
                $temp_data[$item['key']] = !empty($data[$key]) ?  $data[$key] : '';
            }
            $data=$temp_data;
        }
        $send_data = json_encode([
            'touser'      => $openid,
            'template_id' => $tpl_id,
            'page'        => $page,
            'data'=>$data
        ]);//保留消息模板发送数据
        $json_data = HttpCurl::post($send_url, $send_data);
        $resp = json_decode($json_data, true);
        Log::error(json_encode(["发送订阅消息", $send_data, $resp]));
        diy_log(['发送订阅消息', $data, $resp]);
        return $resp;
    } catch (Exception $e) {
        // 防爆
    }
    return false;
}
//暂时不使用企业名片功能忽略掉
function sendTplMsg_new_msg($wid,$tpl,$openid,$formId,$nickName,$card_id){
    return sendSubscribeMsg($wid,$openid,$tpl, [
             [
                "value" => $nickName,
                "color" => "#173177"
            ],
            [
                "value" => date('Y-m-d H:i:s',time()),
                "color" => "#173177"
            ],
            [
                "value" => '您好，有商家客服联系你了，点击进入对话。',
                "color" => "#173177"
            ],

    ],'/pages/index/index?scene=supercard_'.$card_id);
}

//账户积分变动提醒 - 1003
function sendTplMsg_point_change($wid, $tpl, $openid, $formId, $addPoint, $nowPoint, $totalPoint) {
    return sendSubscribeMsg($wid,$openid,$tpl, [
        [
            "value" => '增加积分：' . $addPoint."累积积分：".$totalPoint,
            "color" => "#173177"
        ],
        [
            "value" => $nowPoint,
            "color" => "#173177"
        ],


    ]);
}
//充值成功通知 - 6083
function sendTplMsg_vip_recharge($wid, $tpl, $openid, $formId, $rechargeMoney, $extMoney, $nowMoney, $extPoint, $nowPoint) {
    return sendSubscribeMsg($wid,$openid,$tpl, [
        [
            "value" => date('Y-m-d H:i:s', time()),
            "color" => "#173177"
        ],
        [
            "value" => $rechargeMoney,
            "color" => "#173177"
        ],[
            "value" => $nowMoney,
            "color" => "#173177"
        ]


    ]);
}
//支付成功通知 - 3745
function sendTplMsg_vip_pay_success($wid, $tpl, $openid, $order_no, $order_count, $pay_money, $vip_discount, $point_discount, $balance, $add_point, $point) {
    return sendSubscribeMsg($wid,$openid,$tpl, [
        [
            "value" => $order_no,
            "color" => "#173177"
        ],
        [
            "value" => date('Y-m-d H:i:s', time()),
            "color" => "#173177"
        ],[
            "value" => $pay_money,
            "color" => "#173177"
        ],[
            "value" => "获得积分：$add_point,可用积分:$point",
            "color" => "#173177"
        ]


    ]);
}
//暂未使用，不做处理
function sendTplMsg_share_get_coupon_success($wid, $tpl, $openid, $formId, $coupon_name, $coupon_type, $discount_money, $expiry_date) {
    return sendTemplateMsg($wid, [
        'touser'      => $openid,
        'template_id' => $tpl,
        'page'        => '/pages/index/index',
        'form_id'     => $formId,
        'data'        => [
            "keyword1" => [ //卡券名称
                            "value" => '' . $coupon_name,
                            "color" => "#173177"
            ],
            "keyword2" => [ //卡券类别
                            "value" => '' . $coupon_type,
                            "color" => "#173177"
            ],
            "keyword3" => [ //优惠金额
                            "value" => '' . $discount_money,
                            "color" => "#173177"
            ],
            "keyword4" => [ //领取时间
                            "value" => '' . date('Y-m-d H:i:s', time()),
                            "color" => "#173177"
            ],
            "keyword5" => [ //有效日期
                            "value" => "" . $expiry_date,
                            "color" => "#173177"
            ],
        ]
    ]);
}

// 智慧餐厅订单支付成功模板消息
function sendTplMsg_zhct_order_pay_success($wid, $tpl, $openid, $formId, $total_price, $ctime, $pay_time, $order_no, $prod_name, $remark) {
//    智慧餐厅模板-1036
    return sendSubscribeMsg($wid,$openid,$tpl, [
        [
            "value" => $total_price,
            "color" => "#173177"
        ],
        [
            "value" => $pay_time,
            "color" => "#173177"
        ],[
            "value" => $prod_name,
            "color" => "#173177"
        ],[
            "value" => $remark ? $remark : "-",
            "color" => "#173177"
        ],


    ]);
}

/**
 * 酒店支付成功模板消息 预约成功通知  - 1787
 * @param $wid
 * @param $tpl
 * @param $order
 * @return bool|mixed
 */
function sendTplMsg_jd_pay_success($wid, $tpl, $order) {
    if ($order->cancel = 0) {
        $remark = '随时取消';
    } else if ($order->cancel == 1) {
        $remark = '18点前取消';
    } else if ($order->cancel == 2) {
        $remark = '不可取消';
    } else {
        $remark = ' ';
    }
    //    酒店系统模板-1787
    return sendSubscribeMsg($wid,$order->openid,$tpl, [
        [
            "value" => $order->order_no,
            "color" => "#173177"
        ],
        [
            "value" => "离店时间:{$order->edate},{$remark}",
            "color" => "#173177"
        ],[
            "value" => $order->sdate,
            "color" => "#173177"
        ],[
            "value" =>  $order->name,
            "color" => "#173177"
        ],[
            "value" => $order->phone,
            "color" => "#173177"
        ],


    ]);

}

/**
 * 获取大转盘的设置参数
 * @param $wid
 * @return Model
 */
function get_dzp_setting($wid) {
    $setting = (new Model('dzp_setting'))->find(['wid' => $wid]);
    if (!$setting->id) {
        $setting = new Model('dzp_setting');
        $setting->wid = $wid;
        $setting->save();
    }
    return $setting;
}

/**
 * 大转盘抽奖模板消息 大转盘-中奖结果通知 580
 * @param $wid
 * @param $tpl
 * @param $order
 * @return bool|mixed
 */
function sendTplMsg_dzp_success($wid, $tpl, $openid, $formId, $name, $zjtime) {
//    营销活动模板-580
    return sendSubscribeMsg($wid,$openid,$tpl, [
        [
            "value" => $name,
            "color" => "#173177"
        ],
        [
            "value" => $zjtime,
            "color" => "#173177"
        ]

    ]);
}
//订单状态通知 1036
function shopTplMsg_order_status($wid, $tpl,$openid, $order_no, $order_money, $create_time,$goods_name,$remark,$return_data=false){
    $data=[

        [
            "value" => $order_money,
            "color" => "#173177"
        ],[
            "value" => $create_time,
            "color" => "#173177"
        ],[
            "value" =>  $goods_name,
            "color" => "#173177"
        ],[
            "value" => $remark ? $remark : "-",
            "color" => "#173177"
        ],


    ];
    if($return_data){
        return $data;
    }else{
        return sendSubscribeMsg($wid,$openid,$tpl, $data);
    }


}
/**
 * 订单发送订阅消息通知 1036
 * @param $wid
 * @param $tpl
 * @param $openid
 * @param $order_no [订单号]
 * @param $order_money [订单金额]
 * @param $pay_time [支付时间]
 * @param $goods_name [商品名称]
 * @param $remark [备注]
 * @return bool|mixed
 */
function shopTplMsg_order_pay_success($wid, $tpl,$openid, $order_no, $order_money, $pay_time,$goods_name,$remark,$return_data=false){
    $data=[
        [
            "value" => $order_money,
            "color" => "#173177"
        ],
        [
            "value" => $pay_time ,
            "color" => "#173177"
        ],[
            "value" =>  $goods_name,
            "color" => "#173177"
        ],[
            "value" => $remark ? $remark : "-",
            "color" => "#173177"
        ],


    ];
    if($return_data){
        return $data;
    }else{
        return sendSubscribeMsg($wid,$openid,$tpl, $data);
    }


}
function upload_file($field, $path) {
    if (!key_exists($field, $_FILES)) {
        return false;
    }
    $ext = explode('.', $_FILES[$field]["name"]);
    $ext = $ext[count($ext) - 1];
    try {
        mkdir($path);
    } catch (Exception $e) {
    }
    $path = $path . '/' . md5_file($_FILES[$field]['tmp_name']) . '.' . $ext;
    $saveImg = move_uploaded_file($_FILES[$field]['tmp_name'], $path);
    return $saveImg ? $path : $saveImg;
} 

function upload_oss_qiniu($filePath){
    $agency = get_user_agency();
    $imgTruePath = str_replace('\\', '/', DOXCX_FRAME_PATH . '/pub/' . $filePath);  // 文件在本地硬盘的路径
    $realUrl = '';
    if (!$agency->oss_status && !$agency->qiniu_status) {
        $is_oss = 0;
        $is_qiniu = 0;
        // $realUrl = $h->get_http_server_name().$filePath;
        $realUrl = $filePath;
    } else if ($agency->oss_status) {
        $is_oss = 1;
        $is_qiniu = 0;
        // 对接阿里OSS，本地文件上传到OSS，得到云地址
        require_once DOXCX_FRAME_PATH . "/fun/aliyun-oss/autoload.php";
        try {
            $ossClient = new \OSS\OssClient($agency->oss_id, $agency->oss_secret, $agency->oss_endpoint);
            // 判断存储空间是否存在
            if (!$ossClient->doesBucketExist($agency->bucket_name)) {
                $ossClient->createBucket($agency->bucket_name, \OSS\OssClient::OSS_ACL_TYPE_PUBLIC_READ);
            } else {
                $ossClient->putBucketAcl($agency->bucket_name, \OSS\OssClient::OSS_ACL_TYPE_PUBLIC_READ);
            }
            $uploadOssRes = $ossClient->uploadFile($agency->bucket_name, basename($filePath), $imgTruePath);
            $realUrl = $uploadOssRes['info']['url'];
            if (!$realUrl) {
                // 没获取到Url
                // return error('上传失败，请重试');
               return ['realUrl'=>'','msg'=>'上传oos失败,上传到本地'];
            }else{
                unlink($imgTruePath);
            }
        } catch (\OSS\Core\OssException $e) {
            return ['realUrl'=>'','msg'=>'上传到阿里云OSS失败，请联系代理商检查配置：' . $e->getMessage()];
        }
    } else if ($agency->qiniu_status) {
        $is_qiniu = 1;
        $is_oss = 0;
        require_once DOXCX_FRAME_PATH . "/fun/qiniu-oss/autoload.php";
        $accessKey = $agency->qiniu_key;
        $secretKey = $agency->qiniu_secret;
        $auth = new \Qiniu\Auth($accessKey, $secretKey);
        $bucket = $agency->qiniu_bucket_name;
        $token = $auth->uploadToken($bucket);
        $key = basename($filePath);
        $uploadMgr = new \Qiniu\Storage\UploadManager();
        list($ret, $err) = $uploadMgr->putFile($token, $key,$imgTruePath);
        if ($err !== null) {
            return ['realUrl'=>'','msg'=>'上传到七牛失败，请联系代理商检查配置'];
        }else{
            unlink($imgTruePath);
        }
        $realUrl = 'http://' . $agency->qiniu_domain . '/' . $ret['key'];
    }
    return ['realUrl'=>$realUrl,'msg'=>'ok'];
}

function sendError($msg, $data = null) {
    sendResponse(['status' => 'error', 'msg' => $msg, 'data' => $data], true);
}

function sendSuccess($msg, $data = null) {
    sendResponse(['status' => 'success', 'msg' => $msg, 'data' => $data], true);
}

function setApi() {
    Page::$need_view = false;
    header('Content-Type:application/json');
}

function gget($key) {
    return arr_get($_GET, $key);
}

function pget($key, $default = null) {
    return arr_get($_POST, $key, $default);
}

function arr_to_model(&$model, $arr) {
    foreach ($arr as $k => $v) {
        $model->$k = $v;
    }
}


/**
 * Class CustomForm
 * 自定义表单所需属性和方法封装
 */
class CustomForm
{
    public $fieldMap = [
        'text'        => ['name' => '单行文本', 'attr' => ['title', 'desc', 'required']],
        'num'         => ['name' => '数字', 'attr' => ['title', 'desc', 'required']],
        'email'       => ['name' => '邮箱', 'attr' => ['title', 'desc', 'required']],
        'idcard'      => ['name' => '身份证', 'attr' => ['title', 'desc', 'required']],
        'phone'       => ['name' => '手机号', 'attr' => ['title', 'desc', 'required']],
        'multitext'   => ['name' => '多行文本', 'attr' => ['title', 'desc', 'required']],
        'line'        => ['name' => '分割线', 'attr' => ['title', 'desc', 'title_align', 'desc_align']],
        'menu'        => ['name' => '选择菜单', 'attr' => ['title', 'desc', 'required', 'options']],
        'oneselect'   => ['name' => '单选', 'attr' => ['title', 'desc', 'required', 'options']],
        'multiselect' => ['name' => '多选', 'attr' => ['title', 'desc', 'required', 'options', 'select_control',]],
        'date'        => ['name' => '日期', 'attr' => ['title', 'desc', 'required', 'date_format']],
        'addr'        => ['name' => '省市区', 'attr' => ['title', 'desc', 'required']],
        'file'        => ['name' => '附件', 'attr' => ['title', 'desc', 'required', 'file_max']],
        'img'         => ['name' => '图片', 'attr' => ['desc', 'desc_align', 'src', 'url']],
    ];
    public $attrMap = [
        'title'          => '标题',
        'desc'           => '描述文字',
        'required'       => '是否必选',
        'title_align'    => '标题对齐方式',
        'desc_align'     => '描述对齐方式',
        'options'        => '选项列表',
        'select_control' => '选择数量控制，最多、最少、恰好选择，以及数量控制',  // 单独处理
        'file_max'       => '最多上传多少图片',
        'src'            => '图片链接',
        'url'            => '图片点击跳转地址',
        'date_format'    => '日期格式',
    ];

    /**
     * 获取tpye所对应的字段类型
     * @param $type
     * @return null
     */
    public function getNameStr($type) {
        return $this->fieldMap[$type]['name'];
    }
}

function wid_to_uid($wid) {
    $pub = (new Model('pubs'))->find(['id' => $wid]);
    if ($pub->id) {
        return $pub->uid;
    }
    return false;
}

function getRandomOrderNo($start = '') {
    $dt = date('YmdHis', time());
    $rand = rand(10000000, 99999999);
    return $start . $dt . $rand;
}

function is_mobile($text) {
    $search = '/^0?1[3|4|5|6|7|8|9][0-9]\d{8}$/';
    if (preg_match($search, $text)) {
        return true;
    } else {
        return false;
    }
}

function is_email($email) {
    if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
        return true;
    } else {
        return false;
    }
}

function is_idcard($card) {
    if (preg_match('/^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$/', $card) || preg_match('/^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{4}$/', $card))
        return true;
    else
        return false;
}

function wechat_prepay($wid, $openid, $money, $notifyUrl, $OrderNo, $remark, $attach = '') {
    // Conf::$http_path_api . "Payment/Wxpay/wxRechargeNotify-" . arr_get($req, 'wid') . ".html"
    if (!$attach) {
        $attach = json_encode([]);
    }
    $payParams = db_query("SELECT * FROM vshop_weixin_pay WHERE wid=?", [$wid])[0];
    $time = time();
    $nonce_str = md5(time() . rand() . rand() . '微信支付');
    $body = $remark;

    if($payParams['status']==1){
        $params = [
        'appid'            => $payParams['AppId'],//小程序ID
        'mch_id'           => $payParams['PartnerId'],//商户号
        'nonce_str'        => $nonce_str,//随机字符串
        'body'             => $body,//商品描述(可以拼接字符串生成)
        'out_trade_no'     => $OrderNo,//商品订单号
        'total_fee'        => $money * 100,//总金额
        'spbill_create_ip' => '192.168.1.1',//终端IP
        'notify_url'       => $notifyUrl,//通知地址
        'trade_type'       => 'JSAPI',//交易类型(小程序固定是JSAPI)
        'openid'           => $openid,//用户的openid
        'attach'           => $attach
    ];
    }else{
        $params = [
        'appid' => $payParams['sAppId'],//服务商ID
        'mch_id' => $payParams['PartnerId'],//商户号
        'sub_appid' => $payParams['AppId'],//小程序的APPID
        'sub_mch_id' => $payParams['sPartnerId'],//子商户号

        'nonce_str'        => $nonce_str,//随机字符串
        'body'             => $body,//商品描述(可以拼接字符串生成)
        'out_trade_no'     => $OrderNo,//商品订单号
        'total_fee'        => $money * 100,//总金额
        'spbill_create_ip' => '192.168.1.1',//终端IP
        'notify_url'       => $notifyUrl,//通知地址
        'trade_type'       => 'JSAPI',//交易类型(小程序固定是JSAPI)
        'sub_openid'           => $openid,//用户的openid
        'attach'           => $attach
    ];
    }


    $params['sign'] = make_sign($params, $payParams['PartnerKey']);
    $xml_params = array_to_cdata_xml($params);
    $resp = postXmlCurl('https://api.mch.weixin.qq.com/pay/unifiedorder', $xml_params);
    $resp_arr = xml_to_array($resp);
    diy_log(['调起支付返回参数：', $resp_arr]);
    //判断预支付订单是否已经创建成功
    if ($resp_arr['return_code'] == 'SUCCESS') {//请求下单成功
        if ($resp_arr['result_code'] == 'SUCCESS') {//生成预支付订单成功
            //签名gaode
            $paySign = make_sign([
                'appId'     => $payParams['AppId'],
                'timeStamp' => "" . $time,
                'nonceStr'  => $resp_arr['nonce_str'],
                'package'   => 'prepay_id=' . $resp_arr['prepay_id'],
                'signType'  => 'MD5',
            ], $payParams['PartnerKey']);
            //要返回的数据
            $respData = [
                'timeStamp' => "" . $time,
                'nonceStr'  => $resp_arr['nonce_str'],
                'package'   => 'prepay_id=' . $resp_arr['prepay_id'],
                'signType'  => 'MD5',
                'paySign'   => $paySign,
            ];
            return $respData;
        } else {
            diy_log($resp_arr);
            return false;
        }
    } else {
        diy_log($resp_arr);
        return false;
    }
}

//商云客支付
function syk_prepay($wid, $openid, $money, $notifyUrl, $OrderNo, $remark) {
    $sykConfig = new Model('vshop_syk_pay');
    $sykConfig->find(array('wid' => $wid));
    $data='p0_Cmd=PreCreate&p1_Account='. $sykConfig->username .'&p2_Amt='.$money.'&p3_ProductCode=QR_CODE_OFFLINE&p4_subject='.$remark.'&p7_plat='. $sykConfig->plat .'&p8_Channel=7&p9_Notify_Url='.$notifyUrl.'&p10_Attach='.$wid.'&p11_MerOrderNo='.$OrderNo.'&p13_memo='.$remark.'&p17_OpenID='.$openid;
    $hmac=strtoupper(md5($data.'&key=D81243076DDAD150A1034725E56511F8'));//加密校验串
    $get=$data.'&hmac='.$hmac;
    $url='https://a.xfpay.cn/Api/ApiHandler.ashx?'.$get;
    $json_data=curlGets($url);
    $resp = json_decode($json_data,true);
    $jsPrepayInfo = $resp['data']['js_prepay_info'];//预付单信息
    $result_code = $resp['result'];
    if($result_code == 100){//预下单成功
        //要返回的数据
            $respData = [
                'timeStamp' => trim(str2arr($jsPrepayInfo)["'timeStamp'"],"'"),
                'nonceStr'  => trim(str2arr($jsPrepayInfo)["'nonceStr'"],"'"),
                'package'   => trim(str2arr($jsPrepayInfo)["'package'"],"'"),
                'signType'  => trim(str2arr($jsPrepayInfo)["'signType'"],"'"),
                'paySign'   => trim(str2arr($jsPrepayInfo)["'paySign'"],"'"),
            ];
            return $respData;
    }else{
            file_put_contents(DOXCX_FRAME_PATH.'/log/info/'.date('Y_m_d',time()).'.log', date('H:i:s',time()).'nim: '.$json_data,FILE_APPEND);
            return false;
    }
}

//商云客退款
function syk_refund($wid,$money,$OrderNo){
    $sykConfig = new Model('vshop_syk_pay');
    $sykConfig->find(array('wid' => $wid));
    $data='p0_Cmd=Refund&p1_Account='. $sykConfig->username .'&p4_refund_amount='. $money .'&p5_mer_order_no='. $OrderNo .'&p6_pwd=' . strtoupper(md5($sykConfig->pwd));
    $hmac=strtoupper(md5($data.'&key=9652130BAA71D1DAB5A1921A03A8A928'));//加密校验串
    $get=$data.'&hmac='.$hmac;
    $url='https://a.xfpay.cn/Api/ApiHandler.ashx?'.$get;
    $json_data=curlGets($url);
    $resp = json_decode($json_data,true);
    return $resp['result'];//100退款成功 111退款提交成功
}

function str2arr ($str,$sp=",",$kv=":"){
    $arr = str_replace(array($kv,$sp),array('"=>"','","'),'array("'.$str.'")');
    eval("\$arr"." = $arr;");   // 把字符串作为PHP代码执行
    return $arr;
}
//百度支付函数开始

    /**
     * @desc 私钥生成签名字符串
     * @param array $assocArr
     * @param $rsaPriKeyStr
     * @return bool|string
     * @throws Exception
     */
    function genSignWithRsa(array $assocArr, $rsaPriKeyStr)
    {
        $sign = '';
        if (empty($rsaPriKeyStr) || empty($assocArr)) {
            return $sign;
        }

        if (!function_exists('openssl_pkey_get_private') || !function_exists('openssl_sign')) {
            throw new Exception("openssl扩展不存在");
        }

        $priKey = openssl_pkey_get_private($rsaPriKeyStr);

        if (isset($assocArr['sign'])) {
            unset($assocArr['sign']);
        }

        ksort($assocArr); //按字母升序排序

        $parts = array();
        foreach ($assocArr as $k => $v) {
            $parts[] = $k . '=' . $v;
        }
        $str = implode('&', $parts);
        openssl_sign($str, $sign, $priKey);
        openssl_free_key($priKey);

        return base64_encode($sign);
    }
   /**
     * @desc 公钥校验签名
     * @param array $assocArr
     * @param $rsaPubKeyStr
     * @return bool
     * @throws Exception
     */
     function checkSignWithRsa(array $assocArr, $rsaPubKeyStr)
    {

        if (!isset($assocArr['sign']) || empty($assocArr) || empty($rsaPubKeyStr)) {
            return false;
        }

        if (!function_exists('openssl_pkey_get_public') || !function_exists('openssl_verify')) {
            throw new Exception("openssl扩展不存在");
        }

        $sign = $assocArr['sign'];
        unset($assocArr['sign']);

        if (empty($assocArr)) {
            return false;
        }
        ksort($assocArr); //按字母升序排序
        $parts = array();
        foreach ($assocArr as $k => $v) {
            $parts[] = $k . '=' . $v;
        }
        $str = implode('&', $parts);

        $sign = base64_decode($sign);

        $pubKey = openssl_pkey_get_public($rsaPubKeyStr);

        $result = (bool)openssl_verify($str, $sign, $pubKey);
        openssl_free_key($pubKey);

        return $result;
    }
    /**
     * @desc 密钥由字符串（不换行）转为PEM格式
     * @param $rsaKeyStr
     * @param int $keyType 0:公钥，1:私钥
     * @return string
     * @throws SF_Exception_InternalException
     */
  function convertRSAKeyStr2Pem($rsaKeyStr, $keyType = 0)
    {
        $rsaKeyPem = '';

        $beginPublicKey   = '-----BEGIN PUBLIC KEY-----';
        $endPublicKey     = '-----END PUBLIC KEY-----';
        $beginPrivateKey  = '-----BEGIN PRIVATE KEY-----';
        $endPrivateKey    = '-----END PRIVATE KEY-----';

        $keyPrefix = $keyType ? $beginPrivateKey : $beginPublicKey;
        $keySuffix = $keyType ? $endPrivateKey : $endPublicKey;

        $rsaKeyPem .= $keyPrefix. "\n";
        $rsaKeyPem .= wordwrap($rsaKeyStr, 64, "\n", true) . "\n";
        $rsaKeyPem .= $keySuffix;

        if(!function_exists('openssl_pkey_get_public') || !function_exists('openssl_pkey_get_private')){
            return false;
        }

        if($keyType == 0 && false == openssl_pkey_get_public($rsaKeyPem)){
            return false;
        }

        if($keyType == 1 && false == openssl_pkey_get_private($rsaKeyPem)){
            return false;
        }

        return $rsaKeyPem;
    }
//百度支付
function baidu_prepay($wid, $money, $notifyUrl, $OrderNo, $remark, $attach) {
     $payParams = db_query("SELECT * FROM bd_vshop_weixin_pay WHERE wid=?", [$wid])[0];
     $rsaPrivateKeyStr = $payParams['privateKey'];
     $requestParamsArr = array(
        'dealId' => $payParams['dealId'],
        'appKey' => $payParams['payAppKey'],
        'totalAmount' => $money*100,
        'tpOrderId' => $OrderNo
     );
     //生成签名
        $rsaSign = genSignWithRsa($requestParamsArr, $rsaPrivateKeyStr);
        $orderInfo = array();
        $orderInfo['orderInfo']['dealId'] = $payParams['dealId'];
        $orderInfo['orderInfo']['appKey'] = $payParams['payAppKey'];
        $orderInfo['orderInfo']['totalAmount'] = $money*100;
        $orderInfo['orderInfo']['dealTitle'] = $remark;
        $orderInfo['orderInfo']['tpOrderId'] = $OrderNo;
        $orderInfo['orderInfo']['rsaSign'] = $rsaSign;

        $orderInfo['orderInfo']['bizInfo']['tpData']['appkey'] = $payParams['payAppKey'];
        $orderInfo['orderInfo']['bizInfo']['tpData']['dealId'] = $payParams['dealId'];
        $orderInfo['orderInfo']['bizInfo']['tpData']['tpOrderId'] = $OrderNo;
        $orderInfo['orderInfo']['bizInfo']['tpData']['rsaSign'] = $rsaSign;
        $orderInfo['orderInfo']['bizInfo']['tpData']['totalAmount'] = $money*100;
        $orderInfo['orderInfo']['bizInfo']['tpData']['payResultUrl'] = $notifyUrl;
        $orderInfo['orderInfo']['bizInfo']['tpData']['returnData'] = $attach;

        return $orderInfo;
}

//取消核销
function baidu_refund_first($wid,$tradeNo,$BdUserId){
     $payParams = db_query("SELECT * FROM bd_vshop_weixin_pay WHERE wid=?", [$wid])[0];
     $rsaPrivateKeyStr = $payParams['privateKey'];
     $requestParamsArr = array(
        'method' => 'nuomi.cashier.syncorderstatus',
        'orderId' => $tradeNo,
        'userId' => $BdUserId,
        'type' => '3',
        'appKey' =>  $payParams['payAppKey']
     );
    //生成签名
    $rsaSign = genSignWithRsa($requestParamsArr, $rsaPrivateKeyStr);
    $url = 'https://nop.nuomi.com/nop/server/rest?method=nuomi.cashier.syncorderstatus&orderId=' . $tradeNo . '&userId=' . $BdUserId . '&type=3&appKey=' . $payParams['payAppKey'] . '&rsaSign=' . UrlEncode($rsaSign);
    $res = json_decode(curlGets($url));
     if($res->errno==0){
         //取消审核成功
         return true;
     }else{
         return false;
     }

}
//发起退款
function baidu_refund_second($wid,$tradeNo,$BdUserId,$OrderNo){
     $payParams = db_query("SELECT * FROM bd_vshop_weixin_pay WHERE wid=?", [$wid])[0];
     $rsaPrivateKeyStr = $payParams['privateKey'];
     $requestParamsArr = array(
        'method' => 'nuomi.cashier.applyorderrefund',
        'orderId' => $tradeNo, //百度订单号
        'userId' => $BdUserId, //百度用户id
        'refundType' => '1',
        'refundReason' => '用户退款',
        'tpOrderId' => $OrderNo,    //系统订单号
        'appKey' =>  $payParams['payAppKey']
     );
      //生成签名
      $rsaSign = genSignWithRsa($requestParamsArr, $rsaPrivateKeyStr);
      $url = 'https://nop.nuomi.com/nop/server/rest?method=nuomi.cashier.applyorderrefund&orderId=' . $tradeNo . '&userId=' . $BdUserId . '&refundType=1&refundReason=用户退款&tpOrderId=' . $OrderNo . '&appKey=' .  $payParams['payAppKey'] . '&rsaSign=' . UrlEncode($rsaSign);
      $res = json_decode(curlGets($url));
       if($res->errno==0){
           //发起退款成功
           return true;
       }else{
           return false;
       }
}

//发起退款（新版）
function baidu_refund($wid,$tradeNo,$BdUserId,$OrderNo,$money){
     $payParams = db_query("SELECT * FROM bd_vshop_weixin_pay WHERE wid=?", [$wid])[0];
     $rsaPrivateKeyStr = $payParams['privateKey'];
     $requestParamsArr = array(
        'method' => 'nuomi.cashier.applyorderrefund',
        'orderId' => $tradeNo, //百度订单号
        'userId' => $BdUserId, //百度用户id
        'refundType' => '1',
        'refundReason' => '用户退款',
        'tpOrderId' => $OrderNo,    //系统订单号
        'appKey' =>  $payParams['payAppKey'],
        'applyRefundMoney' => $money * 100,
        'bizRefundBatchId' => $OrderNo
     );
      //生成签名
      $rsaSign = genSignWithRsa($requestParamsArr, $rsaPrivateKeyStr);
      $url = 'https://nop.nuomi.com/nop/server/rest?method=nuomi.cashier.applyorderrefund&orderId=' . $tradeNo . '&userId=' . $BdUserId . '&refundType=1&refundReason=用户退款&tpOrderId=' . $OrderNo . '&appKey=' .  $payParams['payAppKey'] . '&applyRefundMoney='. $money * 100 .'&bizRefundBatchId='. $OrderNo .'&rsaSign=' . UrlEncode($rsaSign);
      $res = json_decode(curlGets($url));
      return $res;
}

//百度支付函数结束


//支付宝支付
function ali_prepay($wid, $openid, $money, $notifyUrl, $OrderNo, $body) {
     //获取小程序配置信息
     $zfbInfo = new Model('zfb_vshop_weixin_pay');
     $zfbInfo->find(array('wid' => $wid));

     $aop = new AopClient ();
     $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
     $aop->appId =$zfbInfo->AppId;
     $aop->rsaPrivateKey = $zfbInfo->privateKey;
     $aop->alipayrsaPublicKey= $zfbInfo->publicKey;
     $aop->apiVersion = '1.0';
     $aop->signType = 'RSA2';
     $aop->postCharset='UTF-8';
     $aop->format='json';
     $requestTradeCreate = new AlipayTradeCreateRequest ();
     $requestTradeCreate->setNotifyUrl($notifyUrl);
     $requestTradeCreate->setBizContent("{" .
                                        "\"out_trade_no\":\"$OrderNo\"," .           //商户订单号
                                        "\"seller_id\":\"$zfbInfo->sellerId\"," .    //卖家支付宝用户ID。 如果该值为空，则默认为商户签约账号对应的支付宝用户ID
                                        "\"total_amount\":\"$money\"," .             //订单总金额，单位为元，精确到小数点后两位
                                        "\"subject\":\"$body\"," .                   //订单标题
                                        "\"body\":\"$body\"," .                      //对交易或商品的描述
                                        "\"buyer_id\":\"$openid\"" .                 //买家的支付宝唯一用户号（openid）
                                        "}");
     $resultTradeCreate = $aop->execute ($requestTradeCreate);
     return $resultTradeCreate;
}

//支付宝验签
function ali_check_sign($wid,$posts){
    //获取小程序配置信息
    $zfbInfo = new Model('zfb_vshop_weixin_pay');
    $zfbInfo->find(array('wid' => $wid));
    $aop = new AopClient ();
    $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
    $aop->appId =$zfbInfo->AppId;
    $aop->rsaPrivateKey = $zfbInfo->privateKey;
    $aop->alipayrsaPublicKey= $zfbInfo->publicKey;
    $aop->apiVersion = '1.0';
    $aop->signType = 'RSA2';
    $aop->postCharset='UTF-8';
    $aop->format='json';
    $checkSign=$aop->rsaCheckV1($posts, NULL,$aop->signType);
    return $checkSign;
}

//头条支付
function tt_prepay($wid, $openid, $money, $notifyUrl, $OrderNo, $body) {
    $body=str_replace(" ",'',$body);
    $ttConfig = new Model('vshop_tt_pay');
    $ttConfig->find(array('wid' => $wid));
    $time=time();
    $bizContent = [
        "out_order_no" => $OrderNo,
        "uid"=> $openid,
        "merchant_id"=> $ttConfig->merchantId,
        "total_amount"=> $money * 100,//分为单位
        "currency"=> "CNY",
        "subject"=> $body,
        "body"=> $body,
        "trade_time"=> $time,
        "valid_time"=> "86400",
        "notify_url"=> $notifyUrl,
        "risk_info"=> ["ip"=>"127.0.0.1"]
    ];
    $bizContentJson = json_encode($bizContent, 320);
    $params = [
        'app_id' => $ttConfig->payAppId,
        'charset' => 'utf-8',
        'format' => 'JSON',
        'method' => 'tp.trade.create',
        'sign_type' => 'MD5',
        'timestamp' => $time,
        'version'   => '1.0',
        'biz_content' => $bizContentJson
    ];
    $sign=tt_sign($params,$ttConfig->paySecret);
    $url='https://tp-pay.snssdk.com/gateway?app_id='.$ttConfig->payAppId.'&method=tp.trade.create&format=JSON&charset=utf-8&sign_type=MD5&timestamp='. $time . '&version=1.0&biz_content=' . $bizContentJson . '&sign='.$sign;
    $resp = HttpCurl::post($url, '{}');
    $respArr=json_decode($resp,1);
    $tradeNo = $respArr['response']['trade_no'];//头条订单号

    //构造业务请求参数的集合(订单信息)
    $zfbbizContent = array();
    $zfbbizContent['subject'] = $body;
    $zfbbizContent['out_trade_no'] = $OrderNo;//平台订单号
    $zfbbizContent['total_amount'] = "".$money;//单位元
    $zfbbizContent['product_code'] = "QUICK_MSECURITY_PAY";//销售产品码,固定值
    $zfbbizContentJson = json_encode($zfbbizContent,320);//$content是biz_content的值,将之转化成json字符串
    //公共参数
    $aop = new AopClient ();//实例化支付宝sdk里面的AopClient类,下单时需要的操作,都在这个类里面
    $zfbparams['app_id'] = $ttConfig->zfbAppId;
    $zfbparams['method'] = 'alipay.trade.app.pay';//接口名称，固定值
    $zfbparams['charset'] = 'utf-8';//请求使用的编码格式
    $zfbparams['sign_type'] = 'RSA2';//商户生成签名字符串所使用的签名算法类型
    $zfbparams['timestamp'] = date("Y-m-d H:i:s",$time);//发送请求的时间
    $zfbparams['version'] = '1.0';//调用的接口版本，固定为：1.0
    $zfbparams['notify_url'] = $notifyUrl;
    $zfbparams['biz_content'] = $zfbbizContentJson;//业务请求参数的集合,长度不限,json格式，即前面一步得到的

    $paramsStr = $aop->getSignContent($zfbparams);//组装请求签名参数
    $RSAsign = $aop->alonersaSign($paramsStr, $ttConfig->privateKey, 'RSA2');//生成签名
    $zfbparams['sign'] = $RSAsign;
    $zfbstr = $aop->getSignContentUrlencode($zfbparams);//最终请求参数
    //支付参数
    $payparams = [
        'app_id' => $ttConfig->payAppId,
        'sign_type' => 'MD5',
        'timestamp' => "".$time,
        'trade_no' => $tradeNo,
        'merchant_id' => $ttConfig->merchantId,
        'uid' => $openid,
        'total_amount' => $money * 100,//单位分
        'params' => json_encode(["url"=>$zfbstr])
    ];
    $paysign=tt_sign($payparams,$ttConfig->paySecret);
    $payparams['sign']=$paysign;
    $payparams['url']=$zfbstr;
     //file_put_contents(DOXCX_FRAME_PATH.'/log/info/'.date('Y_m_d',time()).'.log', date('H:i:s',time()).':'.$zfbstr,FILE_APPEND);
    return $payparams;
}

//支付宝APP支付验签（头条APP支付）
function tt_check_sign($wid,$posts){
    //获取小程序配置信息
    $ttConfig = new Model('vshop_tt_pay');
    $ttConfig->find(array('wid' => $wid));
    $aop = new AopClient ();
    $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
    $aop->appId =$ttConfig->zfbAppId;
    $aop->rsaPrivateKey = $ttConfig->privateKey;
    $aop->alipayrsaPublicKey= $ttConfig->publicKey;
    $aop->apiVersion = '1.0';
    $aop->signType = 'RSA2';
    $aop->postCharset='UTF-8';
    $aop->format='json';
    $checkSign=$aop->rsaCheckV1($posts, NULL,$aop->signType);
    return $checkSign;
}

function tt_sign($params, $key)
{
  ksort($params);
  $string = array_to_string($params);  //参数进行拼接key=value&k=v
  //签名步骤二：在string后加入KEY
  $string = $string . $key;
  //签名步骤三：MD5加密
  $result = md5($string);
  return $result;
}
/**
 * 打印商城订单
 */
function print_shop_order($orderId) {
    // 获取订单内容
    $order = (new Model('vshop_order'))->find(['id' => $orderId])->get_model_array();
    if (!$order['id']) {
        return false;
    }
    // 获取基本参数
    $wid = $order['wid'];
    $printerHandle = new YiLianYunPrinter();
    // 获取商户信息
    $shopSet = (new Model('vshop_set'))->find(['wid' => $wid])->get_model_array();
    // 获取打印机配置信息
    $pub = (new Model('pubs'))->find(['id' => $wid])->get_model_array();
    if (!$wid || !$pub['id'] || !$shopSet['id'] || !$pub['printer_partner'] || !$pub['printer_apikey']) {
        return false;
    }
    // 获取打印机列表
    $printerList = (new Model('printer'))->where(['wid' => $wid, 'use@~' => '商城'])->list_all_array();
    $address = json_decode($order['address'], true);
    // 生成打印内容
    $template_head = <<<TPL
<FH><FB><center>%s</center></FB></FH>
********************************
<FH>
  姓名：%s
  电话：%s
  地址：%s
  日期：%s
  单号：%s</FH>
********************************<FH>
  <table><tr><td>名称</td><td>单价</td><td>数量</td><td>总价</td></tr>

TPL;
    $content = sprintf($template_head, $shopSet['name'], $address['receiver'], $address['phone'], $address['FullAddress'], $order['create_time'], $order['OrderNo']);
    $product_tpl = <<<TPL
  <tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>
  
TPL;

    foreach (json_decode($order['items'], true) as $product) {
        $content .= sprintf($product_tpl, $product['Name'], $product['Price'], $product['Count'], $product['Price'] * $product['Count']);
    }
	$content .= <<<TPL
  </table>
  
TPL;
    $template_foot = <<<TPL
买家备注：%s
</FH>
********************************
<FH>
  <right>总价：%s元</right>
  <right>实际支付：%s元</right>
</FH>
<FB><center>%s</center></FB>
TPL;
    $content .= sprintf($template_foot, $order['remark'], $order['payAmount'], $order['is_vip_pay'] ? $order['vip_pay_money'] : $order['payAmount'], $shopSet['name']);
    // 循环多次打印订单
    $results = [];
    foreach ($printerList as $printer) {
        for ($i = 0; $i < $printer['pnum']; ++$i) {
            $res = $printerHandle->action_print($pub['printer_partner'], $printer['tid'], $content, $pub['printer_apikey'], $printer['key']);
            $results[] = json_decode($res, true);
        }
    }
    return $results;
}

// 打印智慧餐厅小票
function print_zhct_order($orderId) {
    // 获取订单内容
    $order = (new Model('zhct_order'))->find(['id' => $orderId])->get_model_array();
    if (!$order['id']) {
        diy_log(['智慧餐厅小票打印失败，订单找不到']);
        return false;
    }
    $wid = $order['wid'];
    $order['address'] = json_decode($order['address'], true);
    // 获取基本参数
    $printerHandle = new YiLianYunPrinter();
    // 获取商户信息
    $shopSet = (new Model('vshop_set'))->find(['wid' => $wid])->get_model_array();
    // 获取打印机配置信息
    $pub = (new Model('pubs'))->find(['id' => $wid])->get_model_array();
    if (!$wid || !$pub['id'] || !$shopSet['id'] || !$pub['printer_partner'] || !$pub['printer_apikey']) {
        diy_log(['智慧餐厅打印参数缺失']);
        return false;
    }
    // 获取打印机列表
    $printer_type = $order['type'] == 0 ? '餐饮' : '外卖';
    $printerList = (new Model('printer'))->where(['wid' => $wid, 'use@~' => $printer_type])->list_all_array();
    $address = json_decode($order['address'], true);
    if ($order['type'] == 0) {
        // 餐饮订单
        $table = (new Model('zhct_table'))->find(['wid' => $wid, 'id' => $order['table_id']]);
        // 生成打印内容
        $template_head = <<<TPL
<FH><FB><center>%s</center></FB></FH>
********************************
<FH>
  桌台：%s
  日期：%s
  单号：%s</FH>
********************************<FH>
  <table><tr><td>名称</td><td>单价</td><td>数量</td><td>总价</td></tr>

TPL;
        $content = sprintf($template_head, $shopSet['name'], $table->name, $order['ctime'], $order['order_no']);
        $product_tpl = <<<TPL
  <tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>
  
TPL;
        foreach (json_decode($order['cart'], true) as $c) {
            $product = $c['prod'];
            $spec = $c['sp'];
            $content .= sprintf($product_tpl, $product['name'] . ' ' . $spec['name'], $spec['price'], $c['num'], $spec['price'] * $c['num']);
        }
		$content .= <<<TPL
  </table>
  
TPL;
        diy_log(['3', $content]);
        $template_foot = <<<TPL
买家备注：%s
首单优惠：%s
满减优惠：%s
用券抵扣：%s
</FH>
********************************
<FH>
  <right>实际支付：%s元</right>
</FH>
<FB><center>%s</center></FB>
TPL;
        $content .= sprintf(
            $template_foot,
            $order['remark'],
            $order['is_first'] ? $order['first_discount'] : '无',
            $order['is_full'] ? $order['full_discount'] : '无',
            $order['is_coupon'] ? $order['coupon_discount'] : '无',
            $order['total_price'],
            $shopSet['name']
        );
    } else {
        // 外卖订单
        // 生成打印内容
        $template_head = <<<TPL
<FH><FB><center>%s</center></FB></FH>
********************************
<FH>
  姓名：%s
  手机：%s
  地址：%s
  单号：%s</FH>
********************************<FH>
  <table><tr><td>名称</td><td>单价</td><td>数量</td><td>总价</td></tr>

TPL;
        $content = sprintf($template_head, $shopSet['name'], $order['address']['userName'], $order['address']['telNumber'], $order['address']['provinceName'] . $order['address']['cityName'] . $order['address']['countyName'] . $order['address']['detailInfo'], $order['order_no']);
        $product_tpl = <<<TPL
  <tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>
  
TPL;

        foreach (json_decode($order['cart'], true) as $c) {
            $product = $c['prod'];
            $spec = $c['sp'];
            $content .= sprintf($product_tpl, $product['name'] . ' ' . $spec['name'], $spec['price'], $c['num'], $spec['price'] * $c['num']);
        }
		$content .= <<<TPL
  </table>
  
TPL;
        $template_foot = <<<TPL
买家备注：%s
打包费用：%s
配送费用：%s
首单优惠：%s
满减优惠：%s
用券抵扣：%s
</FH>
********************************
<FH>
  <right>实际支付：%s元</right>
</FH>
<FB><center>%s</center></FB>
TPL;
        $content .= sprintf(
            $template_foot,
            $order['remark'],
            $order['pkg_price'] ? $order['pkg_price'] : 0,
            $order['wm_price'] ? $order['wm_price'] : 0,
            $order['is_first'] ? $order['first_discount'] : '无',
            $order['is_full'] ? $order['full_discount'] : '无',
            $order['is_coupon'] ? $order['coupon_discount'] : '无',
            $order['total_price'],
            $shopSet['name']
        );
    }
    // 循环多次打印订单
    $results = [];
    foreach ($printerList as $printer) {
        for ($i = 0; $i < $printer['pnum']; ++$i) {
            $res = $printerHandle->action_print($pub['printer_partner'], $printer['tid'], $content, $pub['printer_apikey'], $printer['key']);
            $results[] = json_decode($res, true);
        }
    }
    diy_log(['智慧餐厅打印', $content]);
    return $results;
}

/**
 * 打印酒店订单
 */
function print_jd_order($orderId) {
    // 获取订单内容
    $order = (new Model('jd_order'))->find(['id' => $orderId])->get_model_array();
    if (!$order['id']) {
        return false;
    }
    // 获取基本参数
    $wid = $order['wid'];
    $printerHandle = new YiLianYunPrinter();
    // 获取商户信息
    $shopSet = (new Model('vshop_set'))->find(['wid' => $wid])->get_model_array();
    // 获取打印机配置信息
    $pub = (new Model('pubs'))->find(['id' => $wid])->get_model_array();
    if (!$wid || !$pub['id'] || !$shopSet['id'] || !$pub['printer_partner'] || !$pub['printer_apikey']) {
        return false;
    }
    // 获取打印机列表
    $printerList = (new Model('printer'))->where(['wid' => $wid, 'use@~' => '酒店'])->list_all_array();
    // 生成打印内容
    $template_head = <<<TPL
<FH><FB><center>%s</center></FB></FH>
********************************
<FH>
  单号：%s
  姓名：%s
  电话：%s
  酒店名称：%s
  客房名称：%s
  套餐类型：%s
  起止日期：%s
  房间数量：%s
  取消限制：%s</FH>
TPL;
    $kf=(new Model('jd_kf'))->find(['id'=>$order['kf_id']])->get_model_array();
    $jd=(new Model('jd_jd'))->find(['id'=>$kf['id']])->get_model_array();
    if($order['cancel']==0){
        $cText='随时取消';
    }else if($order['cancel']==1){
        $cText='当天18点前';
    }else if($order['cancel']==2){
        $cText='不可取消';
    }
    $content = sprintf(
        $template_head,
        $shopSet['name'],
        $order['order_no'],
        $order['name'],
        $order['phone'],
        $jd['name'],
        $kf['name'],
        $order['tc_name'],
        $order['sdate'].' ~ '.$order['edate'],
        $order['num'],
        $cText
    );
    $template_foot = <<<TPL
</FH>
********************************
<FH>
  <right>总价：%s元</right>
</FH>
<FB><center>%s</center></FB>
TPL;
    $content .= sprintf(
        $template_foot,
        $order['total_price'],
        $shopSet['name']
    );
    // 循环多次打印订单
    $results = [];
    foreach ($printerList as $printer) {
        for ($i = 0; $i < $printer['pnum']; ++$i) {
            $res = $printerHandle->action_print($pub['printer_partner'], $printer['tid'], $content, $pub['printer_apikey'], $printer['key']);
            $results[] = json_decode($res, true);
        }
    }
    return $results;
}


function is_post() {
    if (strtoupper($_SERVER['REQUEST_METHOD']) == 'POST') {
        return true;
    } else {
        return false;
    }
}

function kefu_send($wid, $data) {
    try {
        $access_token = WX_getAccessToken($wid);
        diy_log($access_token);

        $send_url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=' . $access_token;
        $send_data = json_encode($data, JSON_UNESCAPED_UNICODE);
        diy_log($send_data);
        $json_data = HttpCurl::post($send_url, $send_data);
        $resp = json_decode($json_data, 1);
        diy_log($resp);
        return $resp;
    } catch (Exception $e) {
        // 防爆
        return false;
    }
}

function kefu_send_text($wid, $toUser, $content) {
    $data = [
        "touser"  => $toUser,
        "msgtype" => "text",
        "text"    => [
            "content" => $content
        ]
    ];
    try {
        $send = kefu_send($wid, $data);
        if ($send['errcode'] == 0) {
            $saveMsg = new Model('kefu_msg');
            $saveMsg->wid = $wid;
            $saveMsg->openid = $toUser;
            $saveMsg->type = 1;
            $saveMsg->ctime = time();
            $saveMsg->MsgType = 'text';
            $saveMsg->Content = $content;
            $saveMsg->is_read = 1;
            $saveMsg->save();
            $mc = (new Model('kefu_msgcount'))->find(['wid' => $wid, 'openid' => $toUser]);
            $mc->count = $mc->count == 0 ? 0 : $mc->count - 1;
            $mc->save();
        }
    } catch (Exception $e) {
        $send = false;
    }
    return $send;
}

function kefu_send_tuwen($wid, $toUser, $title, $desc, $url, $thumbUrl) {
    $data = [
        "touser"  => $toUser,
        "msgtype" => "link",
        "link"    => [
            "title"       => $title,
            "description" => $desc,
            "url"         => $url,
            "thumb_url"   => $thumbUrl
        ]
    ];
    try {
        $send = kefu_send($wid, $data);
    } catch (Exception $e) {
        $send = false;
    }
    return $send;
}

function kefu_send_img($wid, $toUser, $mediaId, $imgUrl) {
    $data = [
        "touser"  => $toUser,
        "msgtype" => "image",
        "image"   => [
            "media_id" => '' . $mediaId
        ]
    ];
    try {
        $send = kefu_send($wid, $data);
        if ($send['errcode'] == 0) {
            $saveMsg = new Model('kefu_msg');
            $saveMsg->wid = $wid;
            $saveMsg->openid = $toUser;
            $saveMsg->type = 1;
            $saveMsg->ctime = time();
            $saveMsg->MsgType = 'image';
            $saveMsg->PicUrl = $imgUrl;
            $saveMsg->MediaId = $mediaId;
            $saveMsg->is_read = 1;
            $saveMsg->save();
            $mc = (new Model('kefu_msgcount'))->find(['wid' => $wid, 'openid' => $toUser]);
            $mc->count = $mc->count == 0 ? 0 : $mc->count - 1;
            $mc->save();
        }
    } catch (Exception $e) {
        $send = false;
    }
    return $send;
}

function get_image_media_id($wid, $imagePath) {
    $access_token = WX_getAccessToken($wid);
    $api = 'https://api.weixin.qq.com/cgi-bin/media/upload?access_token=' . $access_token . '&type=image';
    // $file=new CurlFile(dirname(__FILE__).'/'.$imagePath);
    if (class_exists('CURLFile')) {
      $file=new CurlFile(str_replace('\\', '/', DOXCX_FRAME_PATH . '/pub/' . $imagePath));
    }else{
      $file='@' . str_replace('\\', '/', DOXCX_FRAME_PATH . '/pub/' . $imagePath);
    }
    $data = [
      'media' => $file,
    ];
    diy_log($data);
    $res = HttpCurl::post($api, $data);
    diy_log(json_decode($res));
    return json_decode($res, true);
}

function import_shopping_cart($wid,$openid,$proId,$SKU_Id){
    $productInfo = (new Model('vshop_product'))->find($proId);
    $rowtemp = json_decode($productInfo->rowtemp,true);
    if(!$SKU_Id){
        $goods_no = $rowtemp[0]['goods_no'];
        $sell_price = $rowtemp[0]['sell_price'];//销售价格
        $market_price = $rowtemp[0]['market_price'];//市场原价
    }else{
        foreach ($rowtemp as $_row){
          $spec_array = $_row['spec_array'][0];//一条的属性
          if(md5($spec_array) == md5($SKU_Id[0])){
            $goods_no = $_row['goods_no'];
            $sell_price = $_row['sell_price'];//销售价格
            $market_price = $_row['market_price'];//市场原价
          }
        }
    }
    $data=[
        "user_open_id" => $openid,"sku_product_list" =>[
        "0" =>["item_code" => $productInfo->id,"title" => $productInfo->name, "desc" => "",
        "category_list" =>["0" => "服装", "1" => "上衣", "2" => "短袖衬衫"],
        "image_list"=>["0" => $productInfo->pic],
        "src_wxapp_path" => "pages/index/index" ,"attr_list" => [
        /**"0" => ["name" => "材质" ,"value" => "纯棉"] ,
        "1" => ["name" => "款式","value" => "短袖"] ,
        "2" => ["name" => "季度" ,"value" => "2018年秋"]*/
        ],
        "version" => "" ,"update_time" => "" ,"sku_info" => [
        "sku_id" => $goods_no,"price" => $sell_price * 100 ,"original_price" => $market_price * 100,"status" => "1" ,"sku_attr_list" => [
        /**"0" =>["name" => "颜色" ,"value" => "黑色"] ,
        "1" => ["name" => "码数" ,"value" => "XXL" ]*/
        ],
        "version" => ""]]]
        ];
        $access_token = WX_getAccessToken($wid);
        $send_url = 'https://api.weixin.qq.com/mall/addshoppinglist?access_token=' . $access_token;
        $send_data = json_encode($data, 320);
        $json_data = HttpCurl::post($send_url, $send_data);
         file_put_contents(DOXCX_FRAME_PATH.'/log/info/'.date('Y_m_d',time()).'.log', date('H:i:s',time()).'收藏: '. $json_data,FILE_APPEND);
        $resp = json_decode($json_data, 1);
        return $resp;
}

function import_purchased_orders($wid,$openid,$orderId,$paymentType){
    $m = new Model('vshop_order');
    $m->find(['wid' => $wid, 'OrderNo' => $orderId, 'wxid' => $openid]);
    //商品列表
    $item = json_decode($m->items);
    foreach ($item as $_ite) {
          $pro = new Model('vshop_product');
          $pro->find($_ite->ProductId);
          if ($pro->id) {
            $rowtemp = json_decode($pro->rowtemp, true);//商品属性
            foreach ($rowtemp as $_k => $_v) {
                    if ($_v['goods_no'] == $_ite->goods_no) {
                        $productArray[]=[
                        "item_code"=>$pro->id,"sku_id"=>$_v['goods_no'],"amount"=>$_ite->Count,"total_fee"=>$_ite->Count * $_v['sell_price'] * 100,"thumb_url"=>$_ite->ImageUrl,"title" =>$_ite->Name,"desc"=>"","unit_price"=> $_v['sell_price'] * 100,"original_price"=>$_v['market_price'] * 100,
                        "stock_attr_info"=>[],
                        "category_list" =>["0"=>"衣服","1"=>"T-shirt"],
                        "item_detail_page"=>["path" =>"pages/index/index"]
                        ];
                    }
            }
          }
        }
    $data=[
            "order_list"=>[
            "0"=>[
            "order_id"=>$orderId,"create_time"=>strtotime($m->create_time),"pay_finish_time"=>time(),"desc"=>"","fee"=>$m->payAmount * 100,"trans_id"=>$m->tradeNo,"status"=>3,
            "ext_info"=>[
            "product_info"=>[
            "item_list"=>$productArray
            /**["0"=>[
            "item_code"=>"00003563372839_00000010001xxx","sku_id"=>"00003563372839_10000010014xxx","amount"=>1,"total_fee"=>1,"thumb_url"=>"https://shp.qpic.cn/wechat_bs/0/4eb3dcee0edcd34939b87f232e9fxxxx","title" =>"潮流T恤","desc"=>"xxxx","unit_price"=> 1,"original_price"=>2,
            "stock_attr_info"=>[
            "0" =>[
            "attr_name"=>["name"=>"尺码"],
            "attr_value"=>["name"=>"L"]]],
            "category_list" =>["0"=>"衣服","1"=>"T-shirt"],
            "item_detail_page"=>["path" =>"/portal/xxxx/detail?code=00003563372839_00000010001xxx"]]]*/
            ],
            "express_info" =>[
            "name" =>"","phone"=>"","address"=>"","price"=>0,"national_code"=>"","country"=>"","province"=>"","city"=>"","district"=>"",
            "express_package_info_list"=>[
            /**"0"=>[
            "express_company_id"=>"2001","express_company_name"=>"圆通","express_code"=>"88627337387xxx","ship_time" =>"1517713509",
            "express_page"=>["path"=>"/libs/xxxxx/portal/express-detail/xxxxx"],
            "express_goods_info_list"=>[
            "0"=>[
            "item_code"=>"00003563372839_00000010001xxx", "sku_id"=>"00003563372839_10000010014xxx"]]]*/
            ]],
            "promotion_info" =>["discount_fee"=>$m->couponAmount * 100],
            "brand_info"=>["phone"=> "","contact_detail_page"=>["path" =>""]],
            "invoice_info"=>[
            "type" => 0,"title"=>"空","tax_number"=>"","company_address"=>"","telephone" =>"","bank_name"=>"","bank_account" =>"",
            "invoice_detail_page"=>["path" =>"pages/index/index"]],"payment_method"=>$paymentType ,"user_open_id"=>$openid,
            "order_detail_page"=>["path" =>"pages/index/index"]]]]
            ];
        $access_token = WX_getAccessToken($wid);
        $send_url = 'https://api.weixin.qq.com/mall/importorder?action=add-order&access_token=' . $access_token;
        $send_data = json_encode($data, 320);
        $json_data = HttpCurl::post($send_url, $send_data);
         file_put_contents(DOXCX_FRAME_PATH.'/log/info/'.date('Y_m_d',time()).'.log', date('H:i:s',time()).'已购: '. $json_data,FILE_APPEND);
        $resp = json_decode($json_data, 1);
        return $resp;
}

//Shopping cart rights Start
//导入收藏
function import_cart_collection($wid,$openid,$proId,$SKU_Id){
    $productInfo = (new Model('vshop_product'))->find($proId);
    $rowtemp = json_decode($productInfo->rowtemp,true);
    if(!$SKU_Id){
        $goods_no = $rowtemp[0]['goods_no'];
        $sell_price = $rowtemp[0]['sell_price'];//销售价格
        $market_price = $rowtemp[0]['market_price'];//市场原价
    }else{
        foreach ($rowtemp as $_row){
          $spec_array = $_row['spec_array'][0];//一条的属性
          if(md5($spec_array) == md5($SKU_Id[0])){
            $goods_no = $_row['goods_no'];
            $sell_price = $_row['sell_price'];//销售价格
            $market_price = $_row['market_price'];//市场原价
          }
        }
    }
    //分类
    $category = new Model('vshop_category');
    $categoryRes = $category->where(array('wid'=>$wid))->order('sort asc')->list_all();
    foreach($categoryRes as $_category){
        $categoryList[]=$_category->name;
    }

    $data=[
        "user_open_id" => $openid,"sku_product_list" =>[
        "0" =>["item_code" => $productInfo->id,"title" => $productInfo->name, "desc" => "",
        "category_list" =>$categoryList,
        "image_list"=>["0" => $productInfo->pic],
        "src_wxapp_path" => "pages/index/index" ,"attr_list" => [
        /**"0" => ["name" => "材质" ,"value" => "纯棉"] ,
        "1" => ["name" => "款式","value" => "短袖"] ,
        "2" => ["name" => "季度" ,"value" => "2018年秋"]*/
        ],
        "version" => "" ,"update_time" => "" ,"sku_info" => [
        "sku_id" => $goods_no,"price" => $sell_price * 100 ,"original_price" => $market_price * 100,"status" => "1" ,"sku_attr_list" => [
        /**"0" =>["name" => "颜色" ,"value" => "黑色"] ,
        "1" => ["name" => "码数" ,"value" => "XXL" ]*/
        ],
        "version" => ""]]]
        ];
        $access_token = WX_getAccessToken($wid);
        $send_url = 'https://api.weixin.qq.com/mall/addshoppinglist?access_token=' . $access_token;
        $send_data = json_encode($data, 320);
        $json_data = HttpCurl::post($send_url, $send_data);
         file_put_contents(DOXCX_FRAME_PATH.'/log/info/'.date('Y_m_d',time()).'.log', date('H:i:s',time()).'收藏: '. $json_data,FILE_APPEND);
        $resp = json_decode($json_data, 1);
        return $resp;
}

//导入订单
function import_cart_orders($wid,$openid,$OrderNo,$paymentType){
    $m = new Model('vshop_order');
    $m->find(['wid' => $wid, 'OrderNo' => $OrderNo, 'wxid' => $openid]);
    $address = json_decode($m->address);//地址
    $delivery = json_decode($m->delivery);//运费
    //分类
    $category = new Model('vshop_category');
    $categoryRes = $category->where(array('wid'=>$wid))->order('sort asc')->list_all();
    foreach($categoryRes as $_category){
        $categoryList[]=$_category->name;
    }
    //商品列表
    $item = json_decode($m->items);
    foreach ($item as $_ite) {
          $pro = new Model('vshop_product');
          $pro->find($_ite->ProductId);
          if ($pro->id) {
            $rowtemp = json_decode($pro->rowtemp, true);//商品属性
            foreach ($rowtemp as $_k => $_v) {
                    if ($_v['goods_no'] == $_ite->goods_no) {
                        $productArray[]=[
                        "item_code"=>$pro->id,"sku_id"=>$_v['goods_no'],"amount"=>$_ite->Count,"total_fee"=>$_ite->Count * $_v['sell_price'] * 100,"thumb_url"=>$_ite->ImageUrl,"title" =>$_ite->Name,"desc"=>"","unit_price"=> $_v['sell_price'] * 100,"original_price"=>$_v['market_price'] * 100,
                        "stock_attr_info"=>[],
                        "category_list" =>$categoryList,
                        "item_detail_page"=>["path" =>"pages/index/index"]
                        ];
                    }
            }
          }
        }
    $data=[
            "order_list"=>[
            "0"=>[
            "order_id"=>$OrderNo,"create_time"=>strtotime($m->create_time),"pay_finish_time"=>time(),"desc"=>"","fee"=>$m->payAmount * 100,"trans_id"=>$m->tradeNo,"status"=>3,
            "ext_info"=>[
            "product_info"=>[
            "item_list"=>$productArray
            /**["0"=>[
            "item_code"=>"00003563372839_00000010001xxx","sku_id"=>"00003563372839_10000010014xxx","amount"=>1,"total_fee"=>1,"thumb_url"=>"https://shp.qpic.cn/wechat_bs/0/4eb3dcee0edcd34939b87f232e9fxxxx","title" =>"潮流T恤","desc"=>"xxxx","unit_price"=> 1,"original_price"=>2,
            "stock_attr_info"=>[
            "0" =>[
            "attr_name"=>["name"=>"尺码"],
            "attr_value"=>["name"=>"L"]]],
            "category_list" =>["0"=>"衣服","1"=>"T-shirt"],
            "item_detail_page"=>["path" =>"/portal/xxxx/detail?code=00003563372839_00000010001xxx"]]]*/
            ],
            "express_info" =>[
            "name" =>$address->receiver,"phone"=>$address->phone,"address"=>$address->FullAddress,"price"=>$delivery->Fee * 100,"national_code"=>$address->address_id,"country"=>"中国","province"=>$address->PName,"city"=>$address->CName,"district"=>$address->DName,
            "express_package_info_list"=>[
            /**"0"=>[
            "express_company_id"=>"2001","express_company_name"=>"圆通","express_code"=>"88627337387xxx","ship_time" =>"1517713509",
            "express_page"=>["path"=>"/libs/xxxxx/portal/express-detail/xxxxx"],
            "express_goods_info_list"=>[
            "0"=>[
            "item_code"=>"00003563372839_00000010001xxx", "sku_id"=>"00003563372839_10000010014xxx"]]]*/
            ]],
            "promotion_info" =>["discount_fee"=>$m->couponAmount * 100],
            "brand_info"=>["phone"=> "","contact_detail_page"=>["path" =>""]],
            "invoice_info"=>[
            "type" => 0,"title"=>"空","tax_number"=>"","company_address"=>"","telephone" =>"","bank_name"=>"","bank_account" =>"",
            "invoice_detail_page"=>["path" =>"pages/index/index"]],"payment_method"=>$paymentType ,"user_open_id"=>$openid,
            "order_detail_page"=>["path" =>"pages/index/index"]]]]
            ];
        $access_token = WX_getAccessToken($wid);
        $send_url = 'https://api.weixin.qq.com/mall/importorder?action=add-order&access_token=' . $access_token;
        $send_data = json_encode($data, 320);
        $json_data = HttpCurl::post($send_url, $send_data);
         file_put_contents(DOXCX_FRAME_PATH.'/log/info/'.date('Y_m_d',time()).'.log', date('H:i:s',time()).'已购: '. $json_data,FILE_APPEND);
        $resp = json_decode($json_data, 1);
        return $resp;
}

//修改订单状态 订单状态，4：已发货 5：已退款 12：已取消 100: 已完成
function update_cart_orders($wid,$orderid,$status){
    $m = new Model('vshop_order');
    $m->find($orderid);
    $address = json_decode($m->address);//地址
    $delivery = json_decode($m->delivery);//运费
    //商品列表
    $item = json_decode($m->items);
    foreach ($item as $_ite) {
        $productArray[]=["item_code" =>$_ite->ProductId,"sku_id" =>$_ite->goods_no];
    }

    $data=[
        "order_list" =>[
        "0" =>[
        "order_id"=>$m->OrderNo,"trans_id"=>$m->tradeNo,"status" => $status ,"ext_info" => [
        "express_info" =>[
        "name" => $address->receiver, "phone" => $address->phone ,"address" => $address->FullAddress,"price" => $delivery->Fee * 100,"national_code" => $address->address_id,"country" => "中国" ,"province" => $address->PName,"city" => $address->CName ,"district"=> $address->DName,
        "express_package_info_list" =>[
        "0" =>[
        "express_company_id" => "9999" ,"express_company_name" => "xxx", "express_code" => "xxx" ,"ship_time" => strtotime($m->delivertime),"express_page" =>[
        "path" => "pages/index/index"],"express_goods_info_list" => $productArray
        ]]],
        "invoice_info" =>[
        "type" => 0 ,"title" => "空","tax_number" => "" ,"company_address" => "","telephone" => "","bank_name" => "","bank_account" => "",
        "invoice_detail_page" =>[
        "path" =>"pages/index/index"
        ]],
        "user_open_id" => $m->wxid,"order_detail_page" =>["path" => "pages/index/index"]
        ]]]
        ];

    $access_token = WX_getAccessToken($wid);
    $send_url = 'https://api.weixin.qq.com/mall/importorder?action=update-order&access_token=' . $access_token;
    $send_data = json_encode($data, 320);
    $json_data = HttpCurl::post($send_url, $send_data);
    file_put_contents(DOXCX_FRAME_PATH.'/log/info/'.date('Y_m_d',time()).'.log', date('H:i:s',time()).'修改订单状态: '. $json_data,FILE_APPEND);
    $resp = json_decode($json_data, 1);
    return $resp;
}

//修改商品信息
function update_cart_product($wid,$productId){
    $m = new Model('vshop_product');
    $m->find($productId);
    $rowtemp = json_decode($m->rowtemp, true);//商品属性
    foreach ($rowtemp as $_k => $_v) {
        $skuList[]=[
                "sku_id" => $_v['goods_no'] ,"price" => $_v['sell_price'] * 100,"original_price" => $_v['market_price'] * 100,"status" => 1 ,
                "sku_attr_list" =>[/** "0" => ["name" => "颜色","value" => "白色" ] ,"1" => ["name" => "码数","value" => "L" ]*/],
                "version" => "","poi_list" => [/**
                "0" => ["longitude" => "116.32676" ,"latitude" => "40.003305", "radius" => "4" ,"business_name" => "肯德基", "branch_name" => "珠江新城店" ],
                "1" => ["longitude" => "117.32676","latitude" => "41.003305","radius" => "5","business_name" => "肯德基","branch_name" => "客村店" ]*/]
                ];
    }
    //分类
    $category = new Model('vshop_category');
    $categoryRes = $category->where(array('wid'=>$wid))->order('sort asc')->list_all();
    foreach($categoryRes as $_category){
        $categoryList[]=$_category->name;
    }

    $data=[
        "product_list" =>[
        "0" =>["item_code" => $productId,"title" => $m->name,"desc" => "",
        "category_list" => $categoryList,"image_list" => ["0" => $m->pic],
        "src_wxapp_path" => "pages/index/index",
        "attr_list" => [
        /**"0" => ["name" => "材质","value" => "纯棉" ] ,"1" => ["name" => "款式","value" => "短袖"],"2" => ["name" => "季度","value" => "2018年秋" ]*/
        ],"version" => "",
        "sku_list" =>$skuList
        /**[
        "0" => ["sku_id" => "sku_id1" ,"price" => "10000","original_price" => "20010","status" => 1 ,
        "sku_attr_list" =>[ "0" => ["name" => "颜色","value" => "白色" ] ,"1" => ["name" => "码数","value" => "L" ]],
        "version" => "1200","poi_list" => [
        "0" => ["longitude" => "116.32676" ,"latitude" => "40.003305", "radius" => "4" ,"business_name" => "肯德基", "branch_name" => "珠江新城店" ],
        "1" => ["longitude" => "117.32676","latitude" => "41.003305","radius" => "5","business_name" => "肯德基","branch_name" => "客村店" ]]
        ],
        "1" => ["sku_id" => "sku_id2","price" => "10010 ","status" => 1 ,
        "sku_attr_list" => [ "0" => ["name" => "颜色","value" => "黑色" ] ,"1" =>["name" => "码数","value" => "XXL"]] ,
        "poi_list" =>[
        "0" => ["longitude" => "116.32676","latitude" => "40.003305" ,"radius" => 4 ,"business_name" => "肯德基","branch_name" => "珠江新城店" ],
        "1" => ["longitude" => "117.32676","latitude" => "41.003305","radius" => 5 ,"business_name" => "肯德基" ,"branch_name" => "客村店" ]]
        ]
        ]*/
        ]
        ]
        ];

    $access_token = WX_getAccessToken($wid);
    $send_url = 'https://api.weixin.qq.com/mall/importproduct?access_token=' . $access_token;
    $send_data = json_encode($data, 320);
    $json_data = HttpCurl::post($send_url, $send_data);
    file_put_contents(DOXCX_FRAME_PATH.'/log/info/'.date('Y_m_d',time()).'.log', date('H:i:s',time()).'修改商品信息: '. $json_data,FILE_APPEND);
    $resp = json_decode($json_data, 1);
    return $resp;
}

function getOrCreateModel($table_name, $conditions, $initData=null) {
  $m = (new Model($table_name))->find($conditions);
  if (!$m->id) {
    unset($m);
    $m = new Model($table_name);
    if($initData==null){
      $initData=[];
    }
    arr_to_model($m, $initData);
    $m->save();
    return $m;
  } else {
    return $m;
  }
}

function arr_remove_keys (&$arr,$keys=[]) {
  foreach ($keys as $key) {
    if(array_key_exists($arr, $key)){
      unset($arr[$key]);
    }
  }
}

/**
 * 启动laravel db类
 */
//function use_laravel_db(){
//    static $capsule;
//    if($capsule instanceof Illuminate\Database\Capsule\Manager)return true;
//    require_once "../../vendor/autoload.php";
//
//
//    $database = [
//        'driver' => 'mysql',
//        'host' => Conf::$db_host,
//        'database' => Conf::$db_dbname,
//        'username' => Conf::$db_username ,
//        'port'  => Conf::$db_port ? Conf::$db_port : 3306,
//        'password' => Conf::$db_password,
//        'charset' => 'utf8',
//        'collation' => 'utf8_unicode_ci',
//        'prefix' => Conf::$db_tablePrefix,
//        'strict' => true,
//    ];
//
//    $capsule = new Illuminate\Database\Capsule\Manager;
//// 创建链接
//    $capsule->addConnection($database);
//
//// 设置全局静态可访问DB
//    $capsule->setAsGlobal();
//
//// 启动Eloquent
//    $capsule->bootEloquent();
//}
//
//use_laravel_db();
/**
 * 后台路径进行安全处理
 * @param string $file
 * @return string
 */
function resolve_admin($file=''){
    if(preg_match('/^addons\/[_a-zA-Z0-9]+\/admin/i',$file)){
        return '/'.$file;
    }else{
        return '/admin/'.$file;
    }
}

/**
 * 取得laravel orm模型实例
 * @param $table_name
 */
function model($table_name='')
{
    $model=new \Models\DBModel();
    $model->setTable($table_name);
    return $model;
}
