<?php

// 公共助手函数

use app\apidata\Config;
use app\common\model\TabConf;
use app\index\model\OrderGoodsModel;
use Symfony\Component\VarExporter\VarExporter;
use think\Db;
use think\Exception;
use wanghua\general_utility_tools_php\tool\Tools;

if (!function_exists('__')) {

    /**
     * 获取语言变量值
     * @param string $name 语言变量名
     * @param array  $vars 动态变量值
     * @param string $lang 语言
     * @return mixed
     */
    function __($name, $vars = [], $lang = '')
    {
        if (is_numeric($name) || !$name) {
            return $name;
        }
        if (!is_array($vars)) {
            $vars = func_get_args();
            array_shift($vars);
            $lang = '';
        }
        return \think\Lang::get($name, $vars, $lang);
    }
}

if (!function_exists('format_bytes')) {

    /**
     * 将字节转换为可读文本
     * @param int    $size      大小
     * @param string $delimiter 分隔符
     * @return string
     */
    function format_bytes($size, $delimiter = '')
    {
        $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
        for ($i = 0; $size >= 1024 && $i < 6; $i++) {
            $size /= 1024;
        }
        return round($size, 2) . $delimiter . $units[$i];
    }
}

if (!function_exists('datetime')) {

    /**
     * 将时间戳转换为日期时间
     * @param int    $time   时间戳
     * @param string $format 日期时间格式
     * @return string
     */
    function datetime($time, $format = 'Y-m-d H:i:s')
    {
        $time = is_numeric($time) ? $time : strtotime($time);
        return date($format, $time);
    }
}

if (!function_exists('human_date')) {

    /**
     * 获取语义化时间
     * @param int $time  时间
     * @param int $local 本地时间
     * @return string
     */
    function human_date($time, $local = null)
    {
        return \fast\Date::human($time, $local);
    }
}

if (!function_exists('cdnurl')) {

    /**
     * 获取上传资源的CDN的地址
     * @param string  $url    资源相对地址
     * @param boolean $domain 是否显示域名 或者直接传入域名
     * @return string
     */
    function cdnurl($url, $domain = false)
    {
        $regex = "/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i";
        $url = preg_match($regex, $url) ? $url : \think\Config::get('upload.cdnurl') . $url;
        if ($domain && !preg_match($regex, $url)) {
            $domain = is_bool($domain) ? request()->domain() : $domain;
            $url = $domain . $url;
        }
        return $url;
    }
}


if (!function_exists('is_really_writable')) {

    /**
     * 判断文件或文件夹是否可写
     * @param string $file 文件或目录
     * @return    bool
     */
    function is_really_writable($file)
    {
        if (DIRECTORY_SEPARATOR === '/') {
            return is_writable($file);
        }
        if (is_dir($file)) {
            $file = rtrim($file, '/') . '/' . md5(mt_rand());
            if (($fp = @fopen($file, 'ab')) === false) {
                return false;
            }
            fclose($fp);
            @chmod($file, 0777);
            @unlink($file);
            return true;
        } elseif (!is_file($file) or ($fp = @fopen($file, 'ab')) === false) {
            return false;
        }
        fclose($fp);
        return true;
    }
}

if (!function_exists('rmdirs')) {

    /**
     * 删除文件夹
     * @param string $dirname  目录
     * @param bool   $withself 是否删除自身
     * @return boolean
     */
    function rmdirs($dirname, $withself = true)
    {
        if (!is_dir($dirname)) {
            return false;
        }
        $files = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($dirname, RecursiveDirectoryIterator::SKIP_DOTS),
            RecursiveIteratorIterator::CHILD_FIRST
        );

        foreach ($files as $fileinfo) {
            $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
            $todo($fileinfo->getRealPath());
        }
        if ($withself) {
            @rmdir($dirname);
        }
        return true;
    }
}

if (!function_exists('copydirs')) {

    /**
     * 复制文件夹
     * @param string $source 源文件夹
     * @param string $dest   目标文件夹
     */
    function copydirs($source, $dest)
    {
        if (!is_dir($dest)) {
            mkdir($dest, 0755, true);
        }
        foreach (
            $iterator = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
                RecursiveIteratorIterator::SELF_FIRST
            ) as $item
        ) {
            if ($item->isDir()) {
                $sontDir = $dest . DS . $iterator->getSubPathName();
                if (!is_dir($sontDir)) {
                    mkdir($sontDir, 0755, true);
                }
            } else {
                copy($item, $dest . DS . $iterator->getSubPathName());
            }
        }
    }
}

if (!function_exists('mb_ucfirst')) {
    function mb_ucfirst($string)
    {
        return mb_strtoupper(mb_substr($string, 0, 1)) . mb_strtolower(mb_substr($string, 1));
    }
}

if (!function_exists('addtion')) {

    /**
     * 附加关联字段数据
     * @param array $items  数据列表
     * @param mixed $fields 渲染的来源字段
     * @return array
     */
    function addtion($items, $fields)
    {
        if (!$items || !$fields) {
            return $items;
        }
        $fieldsArr = [];
        if (!is_array($fields)) {
            $arr = explode(',', $fields);
            foreach ($arr as $k => $v) {
                $fieldsArr[$v] = ['field' => $v];
            }
        } else {
            foreach ($fields as $k => $v) {
                if (is_array($v)) {
                    $v['field'] = isset($v['field']) ? $v['field'] : $k;
                } else {
                    $v = ['field' => $v];
                }
                $fieldsArr[$v['field']] = $v;
            }
        }
        foreach ($fieldsArr as $k => &$v) {
            $v = is_array($v) ? $v : ['field' => $v];
            $v['display'] = isset($v['display']) ? $v['display'] : str_replace(['_ids', '_id'], ['_names', '_name'], $v['field']);
            $v['primary'] = isset($v['primary']) ? $v['primary'] : '';
            $v['column'] = isset($v['column']) ? $v['column'] : 'name';
            $v['model'] = isset($v['model']) ? $v['model'] : '';
            $v['table'] = isset($v['table']) ? $v['table'] : '';
            $v['name'] = isset($v['name']) ? $v['name'] : str_replace(['_ids', '_id'], '', $v['field']);
        }
        unset($v);
        $ids = [];
        $fields = array_keys($fieldsArr);
        foreach ($items as $k => $v) {
            foreach ($fields as $m => $n) {
                if (isset($v[$n])) {
                    $ids[$n] = array_merge(isset($ids[$n]) && is_array($ids[$n]) ? $ids[$n] : [], explode(',', $v[$n]));
                }
            }
        }
        $result = [];
        foreach ($fieldsArr as $k => $v) {
            if ($v['model']) {
                $model = new $v['model'];
            } else {
                $model = $v['name'] ? \think\Db::name($v['name']) : \think\Db::table($v['table']);
            }
            $primary = $v['primary'] ? $v['primary'] : $model->getPk();
            $result[$v['field']] = $model->where($primary, 'in', $ids[$v['field']])->column("{$primary},{$v['column']}");
        }

        foreach ($items as $k => &$v) {
            foreach ($fields as $m => $n) {
                if (isset($v[$n])) {
                    $curr = array_flip(explode(',', $v[$n]));

                    $v[$fieldsArr[$n]['display']] = implode(',', array_intersect_key($result[$n], $curr));
                }
            }
        }
        return $items;
    }
}

if (!function_exists('var_export_short')) {

    /**
     * 返回打印数组结构
     * @param string $var 数组
     * @return string
     */
    function var_export_short($var)
    {
        return VarExporter::export($var);
    }
}

if (!function_exists('letter_avatar')) {
    /**
     * 首字母头像
     * @param $text
     * @return string
     */
    function letter_avatar($text)
    {
        $total = unpack('L', hash('adler32', $text, true))[1];
        $hue = $total % 360;
        list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);

        $bg = "rgb({$r},{$g},{$b})";
        $color = "#ffffff";
        $first = mb_strtoupper(mb_substr($text, 0, 1));
        $src = base64_encode('<svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="100" width="100"><rect fill="' . $bg . '" x="0" y="0" width="100" height="100"></rect><text x="50" y="50" font-size="50" text-copy="fast" fill="' . $color . '" text-anchor="middle" text-rights="admin" alignment-baseline="central">' . $first . '</text></svg>');
        $value = 'data:image/svg+xml;base64,' . $src;
        return $value;
    }
}

if (!function_exists('hsv2rgb')) {
    function hsv2rgb($h, $s, $v)
    {
        $r = $g = $b = 0;

        $i = floor($h * 6);
        $f = $h * 6 - $i;
        $p = $v * (1 - $s);
        $q = $v * (1 - $f * $s);
        $t = $v * (1 - (1 - $f) * $s);

        switch ($i % 6) {
            case 0:
                $r = $v;
                $g = $t;
                $b = $p;
                break;
            case 1:
                $r = $q;
                $g = $v;
                $b = $p;
                break;
            case 2:
                $r = $p;
                $g = $v;
                $b = $t;
                break;
            case 3:
                $r = $p;
                $g = $q;
                $b = $v;
                break;
            case 4:
                $r = $t;
                $g = $p;
                $b = $v;
                break;
            case 5:
                $r = $v;
                $g = $p;
                $b = $q;
                break;
        }

        return [
            floor($r * 255),
            floor($g * 255),
            floor($b * 255)
        ];
    }
}

if (!function_exists('check_nav_active')) {
    /**
     * 检测会员中心导航是否高亮
     */
    function check_nav_active($url, $classname = 'active')
    {
        $auth = \app\common\library\Auth::instance();
        $requestUrl = $auth->getRequestUri();
        $url = ltrim($url, '/');
        return $requestUrl === str_replace(".", "/", $url) ? $classname : '';
    }
}

if (!function_exists('check_cors_request')) {
    /**
     * 跨域检测
     */
    function check_cors_request()
    {
        if (isset($_SERVER['HTTP_ORIGIN']) && $_SERVER['HTTP_ORIGIN']) {
            $info = parse_url($_SERVER['HTTP_ORIGIN']);
            $domainArr = explode(',', config('fastadmin.cors_request_domain'));
            $domainArr[] = request()->host(true);
            if (in_array("*", $domainArr) || in_array($_SERVER['HTTP_ORIGIN'], $domainArr) || (isset($info['host']) && in_array($info['host'], $domainArr))) {
                header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
            } else {
                header('HTTP/1.1 403 Forbidden');
                exit;
            }

            header('Access-Control-Allow-Credentials: true');
            header('Access-Control-Max-Age: 86400');

            if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
                if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
                    header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
                }
                if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
                    header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
                }
                exit;
            }
        }
    }
}

if (!function_exists('xss_clean')) {
    /**
     * 清理XSS
     */
    function xss_clean($content, $is_image = false)
    {
        return \app\common\library\Security::instance()->xss_clean($content, $is_image);
    }
}


if (!function_exists('set_result')) {
    /**
     * @deprecated 以后的开发中禁止使用
     *
     *
     * desc：
     * author：wh
     * @param int $code
     * @param string $message
     * @param array $data
     * @return array|\think\response\Json
     */
    function set_result(int $code, string $message='', $data=[]){
        //$data_packet = [
        //    'code'=>$code,
        //    'msg'=>$message,
        //    'data'=>$data,
        //];
        //return request()->isAjax()?json_encode($data_packet, JSON_UNESCAPED_UNICODE):$data_packet;
        return [
            'code'=>$code,
            'msg'=>$message,
            'data'=>$data,
        ];
    }
}


/**
 * 注：tp5.0不支持大写
 * desc：cdn
 * author：wh
 * @return string
 */
function __cdn__(){
    //这里后续可以扩展到数据配置
    return '';
}

if(!function_exists('wxConfDefaultByDomain')){
    /**
     * description：获取公众号配置
     * author：wanghua
     * @param $key
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    function wxConfDefaultByDomain($field){
        $config = config('pay_config.wechat');

        $conf = \think\Db::table(\app\common\model\TabConf::$fa_wechat_pay_public_acc_domain)->select();
        $arr = \wanghua\general_utility_tools_php\tool\Tools::key_val_arr($conf,'domain','public_acc');

        $domain = request()->host();

        $pay_firm = isset($arr[$domain])?$arr[$domain]:'';

        return isset($config[$pay_firm][$field])?$config[$pay_firm][$field]:'';
    }
}


if(!function_exists('wxConfPublicAcc')){
    /**
     * description：获取公众号信息
     * author：wanghua
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    function wxConfPublicAcc(){
        $config = config('pay_config.wechat');

        $conf = \think\Db::table(\app\common\model\TabConf::$fa_wechat_pay_public_acc_domain)->select();
        $arr = \wanghua\general_utility_tools_php\tool\Tools::key_val_arr($conf,'domain','public_acc');

        $domain = request()->host();


        $pay_firm = isset($arr[$domain])?$arr[$domain]:'';

        if(empty($config[$pay_firm])) throw new Exception('wx public acc conf error.');

        return isset($config[$pay_firm])?$config[$pay_firm]:'';
    }
}
if(!function_exists('wxConfOrderPayFirm')){
    /**
     * description：获取订单支付主体对应的公众号信息
     * author：wanghua
     * @param $key
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    function wxConfOrderPayFirm(){
        $config = config('pay_config.wechat');
        $pay_firm = 'origin_fruits';
        return $config[$pay_firm];
    }
}
if(!function_exists('pay_firm')){
    /**
     * 【当前系统，支付主体要根据域名切换，掌驰和小白菜商城支付域名分别独立】
     *
     * description：支付主体
     *
     *
     * author：wanghua
     * @param $key
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    function pay_firm(){

        return \app\common\tools\ServerTools::getPayFirmForDomain();
    }
}

if(!function_exists('admin_username')) {
    /**
     * desc：管理员账号
     * author：wh
     * @return mixed
     */
    function admin_username()
    {
        return session('admin.username');
    }
}
if(!function_exists('admin_openid')) {
    /**
     * desc：管理员账号
     * author：wh
     * @return mixed
     */
    function admin_openid()
    {
        return session('admin.openid');
    }
}
if(!function_exists('admin_nickname')) {
    /**
     * desc：管理员昵称
     * author：wh
     * @return mixed
     */
    function admin_nickname()
    {
        return session('admin.nickname');
    }
}

if(!function_exists('index_user')) {
    /**
     * desc：用户的微信信息
     * author：wh
     * @return mixed
     */
    function index_user()
    {
        return session('wx_user_info');
    }
}

if(!function_exists('index_user_info')) {
    /**
     * desc：用户表用户信息
     * author：wh
     * @return mixed
     */
    function index_user_info($key = '')
    {
        $openid = session('wx_user_info.openid');
        $info = Db::table(TabConf::$fa_wechatuser)
            ->where('openid',$openid)
            ->find();
        if($key){
            return $info[$key];
        }
        return $info;
    }
}


if(!function_exists('index_user_openid')) {
    /**
     * desc：
     * author：wh
     * @return mixed
     */
    function index_user_openid()
    {
        return session('wx_user_info.openid');
    }
}
if(!function_exists('index_user_unionid')) {
    /**
     * desc：
     * author：wh
     * @return mixed
     */
    function index_user_unionid()
    {
        return session('wx_user_info.unionid');
    }
}
if(!function_exists('index_user_card_phone')) {
    /**
     * desc：会员卡手机号
     * author：wh
     * @return mixed
     */
    function index_user_card_phone()
    {
        $openid = session('wx_user_info.openid');
        $phone = Db::table(TabConf::$fa_platformmembercard)
            ->where('openid',$openid)
            ->value('phone');
        return $phone;
    }
}

if(!function_exists('index_user_nickname')) {
    /**
     * desc：
     * author：wh
     * @return mixed
     */
    function index_user_nickname()
    {
        return session('wx_user_info.nickname');
    }
}
if(!function_exists('index_user_headimg')) {
    /**
     * desc：头像
     * author：wh
     * @return mixed
     */
    function index_user_headimg()
    {
        return session('wx_user_info.headimgurl');
    }
}
if(!function_exists('index_user_member_type')) {
    /**
     * desc：会员类型
     * author：wh
     * @return mixed
     */
    function index_user_member_type()
    {
        $type = \think\Db::table(\app\common\model\TabConf::$fa_platformmembercard)
            ->where('openid',session('wx_user_info.openid'))
            ->cache(3600)
            ->value('type');
        if(empty($type)){
            return '普通会员';
        }
        $arr = [
            1=>'省钱宝会员',
            2=>'赚钱宝会员',
        ];
        return $arr[$type];
    }
}


if(!function_exists('index_user_shop_member_card_balance')) {
    /**
     * desc：店铺会员水果卡余额
     * author：wh
     * @return mixed
     */
    function index_user_shop_member_card_balance()
    {
        $card = \app\index\model\ShopMemberFruitsCardModel::getCard(session('wx_user_info.openid'));
        //$wx_user = \app\index\model\Shop::getWxUserByOpenid(session('wx_user_info.openid'));
        return $card['balance'];
    }
}
if(!function_exists('index_user_shop_member_card_discount')) {
    /**
     * desc：店铺会员水果卡实际折扣（固定折扣-活跃折扣）
     * author：wh
     * @return mixed
     */
    function index_user_shop_member_card_discount()
    {
        $card = \app\index\model\ShopMemberFruitsCardModel::getCard(session('wx_user_info.openid'));
        if(empty($card)){
            return 1;//无会员卡，不打折
        }
        if(empty(1*$card['discount'])){
            return 1;
        }
        $disc = $card['discount']-$card['active_discount'];//折扣过于低视为异常
        if($disc < 0.85){
            throw new \Exception('该顾客折扣异常');
        }
        return $disc;
    }
}

if(!function_exists('index_user_phone')) {
    /**
     * desc：
     * author：wh
     * @return mixed
     */
    function index_user_phone()
    {
        return session('wx_user_info.phone');
    }
}
/**
 * desc：目标用户所属分组
 * author：wh
 */
function index_user_arm_group(){
    return session('wx_user_info.arm_group');
}

/**
 * desc：实时获取用户身上的积分
 * author：wh
 * @return float|mixed|string
 */
function index_user_score(){
    return \app\index\model\WechatUserModel::getUserScore();
}
/**
 * desc：实时获取用户身上的水滴
 * author：wh
 * @return float|mixed|string
 */
function index_user_water(){
    return \app\index\model\WechatUserModel::getUserWater();
}
/**
 * desc：实时获取用户身上的微信拼团收益
 * author：wh
 * @return float|mixed|string
 */
function index_user_group_buy_earnings(){
    return \app\index\model\WechatUserModel::getUserEarnings();
}

/**
 * desc：统计我的邀请数量
 *
 * author：wh
 * @return int|string
 * @throws Exception
 */
function index_user_invite_num(){
    //统计我的邀请数量
    $invite_num = Db::table(TabConf::$fa_platformmember_invite_relation)
        ->where('father_openid',index_user_openid())
        ->count('id');
    return $invite_num;
}
/**
 * desc：获取当前用户用户类型
 *
 * 商户（merchant）或者个人(person)
 *
 * author：wh
 * @return float|mixed|string
 */
function index_user_type($openid=''){
    return \app\index\model\WechatUserModel::getUserTypeByOpenid($openid?$openid:index_user_openid());
}

/**
 * desc：根据当前用户类型获取商品售价
 *
 * 商户 | 普通用户
 *
 * author：wh
 */
function get_goods_price_by_user_type(array $goods){
    $user_type = \app\index\model\WechatUserModel::getUserTypeByOpenid(index_user_openid());
    if($user_type == 'merchant'){
        return isset($goods['merchant_price'])?$goods['merchant_price']:0;
    }
    return $goods['sale_price'];
}


if(!function_exists('is_super_admin')) {
    /**
     * desc：是否是超级管理员
     * author：wh
     * @return mixed
     */
    function is_super_admin()
    {
        $obj = \think\Db::table(\app\common\model\TabConf::$fa_auth_group_access);
        $access = $obj
            ->where('uid',session('admin.id'))
            ->value('group_id');
        return $access==1;
    }
}

if(!function_exists('is_login')) {
    /**
     * desc：是否是超级管理员
     * author：wh
     * @return mixed
     */
    function is_login()
    {
        return !empty(session('wx_user_info'));
    }
}


if(!function_exists('get_brand_byid')) {
    /**
     * desc：根据id查询品牌名称
     * author：wh
     * @param $id
     * @return float|mixed|string
     */
    function get_brand_byid($id){
        return (new \app\admin\model\Brand())->where('id',$id)->cache(3600)->value('name');
    }
}

/**
 * desc：实时统计销量
 * author：wh
 */
function count_sale_num($goods_id){
    return (new \app\admin\model\Settle())->where('goods_id',$goods_id)->cache(3600)->count('id');
}

/**
 * desc：规格
 * author：wh
 * @param $id
 * @return float|mixed|string
 */
function get_specification_name($id){
    return (new \app\admin\model\Specification())->where('id',$id)->cache(3600)->value('name');

}

/**
 * desc：平台范围名称
 * author：wh
 * @param int $id
 * @return array|bool|PDOStatement|string|\think\Model|null
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function get_scope_name_by_id(int $id){
    return \app\index\model\PlatformscopeModel::getNameById($id);
}

/**
 * desc：验证优惠券用户归属
 *
 * true 属于当前用户
 *
 * false 不属于
 *
 * author：wh
 */
function check_coupon_user_affiliation($coupon_openid=''){
    return $coupon_openid&&index_user_openid()==$coupon_openid;//优惠券目标用户openid和当前登录用户openid比较
}

/**
 * desc：验证优惠券用户分组归属
 *
 * true 属于当前用户分组
 *
 * false 不属于
 *
 * author：wh
 * @param string $coupon_arm_group
 * @return bool
 */
function check_coupon_user_group_affiliation($coupon_arm_group=''){
    return $coupon_arm_group&&in_array(index_user_arm_group(),explode(',',$coupon_arm_group));
}

/**
 * desc：根据配送范围id获取名称
 * author：wh
 * @param int $id
 * @return float|mixed|string
 */
function get_platformscope_name_by_id(int $id){
    return \think\Db::table(\app\common\model\TabConf::$fa_platformscope)
        ->where('id',$id)
        ->value('name');
}


/**
 * desc：获取商品预定的商品单位
 * author：wh
 * @param string $key
 * @return string
 */
function get_goods_buy_unit_text(string $key){
    //单位:j
    $arr = ['jin'=>'斤',
        'gen'=>'根',
        'liang'=>'两',
        'jie'=>'节',
        'ge'=>'个'];
    return isset($arr[$key])?$arr[$key]:'';
}


/**
 * desc：获取商品预订单配送状态
 * author：wh
 * @param $key
 * @return string
 */
function get_goods_buy_send_status_text($key){
    //配送状态:
    $arr = [
        '0'=>'待支付',
        '1'=>'待配送',
        '2'=>'配送中',
        '3'=>'已送达'
    ];
    return $arr[$key];
}

/**
 * desc：订单状态
 * author：wh
 * @param int $key
 * @return string
 */
function get_order_status_text(int $key,string $orderid){
    //订单状态:0=待支付,200=支付成功,500=支付失败,600=取消订单
    $arr = [
        '0'=>'待支付',
        '200'=>'支付成功',
        '500'=>'支付失败',
        '3'=>'已送达'
    ];
    //追加配送状态
    //配送状态:new=待接单,sending=已接单，配送中,sended=已送达,error=配送异常,complaint=投诉订单,cancel=取消配送
    $order = \app\index\model\OrderSendedModel::getSendOrderByOrderid($orderid);
    $status_arr = [
        'new'=>'待接单',
        'sending'=>'配送中',
        'sended'=>'已送达',
        'error'=>'配送异常',
        'complaint'=>'投诉订单',
        'cancel'=>'取消配送'
    ];

    $str = empty($status_arr[$order['status']])?'':','.$status_arr[$order['status']];
    return $arr[$key].$str;
}

/**
 * desc：获取平台配送费
 * author：wh
 * @return float|mixed|string
 */
function get_platform_ship_fee(){
    $fee = Config::sundryConfigVal('platform_ship_fee');
    return sprintf('%.2f',$fee);
}

/**
 * desc：金钱保留2位小数
 * author：wh
 * @param int $money
 * @return string
 */
function money_float_two($money=0){
    return sprintf('%.2f',$money);
}

/**
 * desc：商品封面图片
 * author：wh
 * @param int $goods_id
 * @return float|mixed|string
 */
function get_goods_cover_img(int $goods_id){
    return \app\index\model\GoodsModel::getGoodsCoverImg($goods_id);
}

/**
 * desc：根据订单号查询订单商品
 *
 * author：wh
 * @param array $order
 * @return bool|PDOStatement|string|\think\Collection
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function get_order_goods_by_orderid(array $order){
    return OrderGoodsModel::getUserOrderGoodsByOrderid($order['orderid']);
}

/**
 * desc：获取门店-店铺名称
 * author：wh
 * @return float|mixed|string
 */
function get_shop_name_origin_fruits_sir(){
    return Config::sundryConfigVal('shop_name_origin_fruits_sir');
}

/**
 * desc：验证是否允许退款
 *
 * author：wh
 * @param $time
 * @return bool
 */
function is_can_refund($time){
    $dateObj = new \wanghua\general_utility_tools_php\Date();
    $store_allow_refund_hours = Config::sundryConfigVal('store_allow_refund_hours');

    $now = Tools::get_now_date();
    $hours = $dateObj->timeReduceTime($now,$time,'h');
    return $hours>$store_allow_refund_hours?false:true;
}

/**
 * desc：获取公众号名称
 *
 * author：wh
 * @return float|mixed|string
 */
function wechat_public_no_name(){
    return Config::sundryConfigVal('wechat_public_no_name');
}

/**
 * desc：n时间以前
 * 例如：1分钟以前，20分钟以前，3小时以前，1天以前，3天以前，18天以前，1个月以前
 *
 * $date 2021-02-13 12:33:43
 * author：wh
 */
function nTimeBefore($date){
    if(empty($date)){
        return '';
    }
    $time = time()-strtotime($date);
    //一个月默认30天
    $day_time = 86400;
    //月
    if($time >= 30*$day_time){
        return floor($time/30*$day_time).'月以前';
    }
    //半个月
    if($time >= 15*$day_time){
        return '半个月以前';
    }
    //天
    if($time >= $day_time){
        return floor($time/$day_time).'天以前';
    }
    $hour_time = 3600;
    //小时
    if($time >= $hour_time){
        return floor($time/$hour_time).'小时以前';
    }
    $min_hour = 60;
    //分钟
    if($time >= $min_hour){
        return floor($time/$min_hour).'分钟以前';
    }
    //秒
    return (floor($time/$day_time)?:1).'秒以前';
}

/**
 * desc：随机取一个搜索词
 *
 * author：wh
 */
function wechat_gtoupbuy_list_search_words(){
    $wechat_gtoupbuy_list_search_words = Config::sundryConfigVal('wechat_gtoupbuy_list_search_words');

    $arr = explode(',',$wechat_gtoupbuy_list_search_words);

    if(empty($arr)){
        return '';
    }
    $len = count($arr);
    $mt_rand = mt_rand(0,$len-1);
    return $arr[$mt_rand];
}

/**
 * desc：获取收银台商品单位
 *
 * author：wh
 */
function get_checkstandgoodsbasicunit_by_id($id){
    return Db::table(TabConf::$fa_checkstandgoodsbasicunit)
        ->cache(true)
        ->where('id',$id)
        ->value('name');
}

/**
 * desc：获取计价方式
 *
 * author：wh
 * @param string $key
 * @return string
 */
function get_count_price_method($key=''){

    $arr = ['weight'=>'计重','num'=>'计数'];
    return empty($arr[$key])?'':$arr[$key];

}

/**
 * desc：收银台获取商品会员价
 *
 * author：wh
 * @param $goods_id
 * @return float|mixed|string
 */
function check_stand_get_goods_member_price($goods_id,$phone){
    //是秒杀则返回秒杀价
    $goods = Db::table(TabConf::$fa_checkstandgoods)
        ->where('id',$goods_id)
        ->find();
    $card = Db::table(TabConf::$fa_platformmembercard)
        ->where('phone',$phone)
        ->find();
    if($goods['is_seckill']=='yes'){
        $check_res = \app\index\logic\CheckstandLogic::is_join_seckill($goods,$card);
        if($check_res['code'] == 200){
            return $goods['seckill_price'];
        }
    }
    return $goods['member_price'];
}

/**
 * desc：该用户当前商品在商品秒杀活动的周期内是否参与了活动
 *
 * author：wh
 * @param $goods_id 商品ID
 * @param $phone 会员手机号
 * @return mixed|string
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function check_stand_is_join_seckill_before($goods_id,$phone){
    //是秒杀则返回秒杀价
    $goods = Db::table(TabConf::$fa_checkstandgoods)
        ->where('id',$goods_id)
        ->find();
    $card = Db::table(TabConf::$fa_platformmembercard)
        ->where('phone',$phone)
        ->find();
    $check_res = \app\index\logic\CheckstandLogic::is_join_seckill($goods,$card);
    if($check_res['code'] == 200){
        return $goods['seckill_price'];
    }
    //200 未参与，500 已参与
    return $check_res['code'] == 200?'no':'yes';
}


/**
 * desc：订单支付类型
 *
 * author：wh
 * @param $code
 * @return string
 */
function order_pay_type($code){
    //支付类型:0=微信,1=支付宝,2=现金,3=数字人民币,4=银行卡,5=信用卡
    $arr = [
        '微信',
        '支付宝',
        '现金',
        '数字人民币',
        '银行卡',
        '信用卡',
    ];
    return empty($arr[$code])?'':$arr[$code];
}

/**
 * desc：订单支付状态
 *
 * author：wh
 */
function get_order_pay_status_txt($code){
    //支付状态:new=待支付,success=成功,fail=失败,close=关闭
    $arr = [
        'new'=>'待支付',
        'success'=>'成功',
        'fail'=>'失败',
        'close'=>'关闭',
    ];
    return empty($arr[$code])?'':$arr[$code];
}

/**
 * desc：获取小白菜商城微信支付配置
 *
 * author：wh
 */
function get_origin_fruits_wechat_config(){

    $wxconfig = config('app.pay_config.wechat');
    $wxconfig = $wxconfig['origin_fruits'];
    return $wxconfig;
}
/**
 * desc：获取爆品联盟微信支付配置
 *
 * author：wh
 */
function get_boom_union_wechat_config(){

    $wxconfig = config('app.pay_config.wechat');
    $wxconfig = $wxconfig['boom_union'];
    return $wxconfig;
}

/**
 * 是否移动端访问访问
 *
 * @return bool
 */
function is_mobile_client()
{
    // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
    if (isset($_SERVER['HTTP_X_WAP_PROFILE'])) {
        return true;
    }

//如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
    if (isset($_SERVER['HTTP_VIA'])) {
        //找不到为flase,否则为true
        return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
    }

//判断手机发送的客户端标志
    if (isset($_SERVER['HTTP_USER_AGENT'])) {
        $clientkeywords = [
            'nokia', 'sony', 'ericsson', 'mot', 'samsung', 'htc', 'sgh', 'lg', 'sharp',
            'sie-', 'philips', 'panasonic', 'alcatel', 'lenovo', 'iphone', 'ipod', 'blackberry', 'meizu',
            'android', 'netfront', 'symbian', 'ucweb', 'windowsce', 'palm', 'operamini', 'operamobi',
            'openwave', 'nexusone', 'cldc', 'midp', 'wap', 'mobile','alipay'
        ];

// 从HTTP_USER_AGENT中查找手机浏览器的关键字
        if (preg_match("/(".implode('|', $clientkeywords).")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
            return true;
        }
    }

//协议法，因为有可能不准确，放到最后判断
    if (isset($_SERVER['HTTP_ACCEPT'])) {
        // 如果只支持wml并且不支持html那一定是移动设备
        // 如果支持wml和html但是wml在html之前则是移动设备
        if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
            return true;
        }
    }

    return false;
}
/**
 * 判断是否微信内置浏览器访问
 * @return bool
 */
function is_wx_client()
{
    return strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false;
}

/**
 * 判断是否支付宝内置浏览器访问
 * @return bool
 */
function is_ali_client()
{
    return strpos($_SERVER['HTTP_USER_AGENT'], 'Alipay') !== false;
}

/**
 * desc：获取爆品联盟微信支付配置
 *
 * author：wh
 */
function get_wechat_config()
{

    $wxconfig = config('pay_config.wechat');
    $wx_mini_game_defaul_acc_conf = \wanghua\general_utility_tools_php\SundryConfig::val('wx_mini_game_defaul_acc_conf');
    if (empty($wx_mini_game_defaul_acc_conf)) {
        throw new \Exception('小游戏默认账户配置错误');
    }
    $wxconfig = $wxconfig[$wx_mini_game_defaul_acc_conf];
    return $wxconfig;
}

function api_user_openid()
{
    $openid = session('api_user_info.openid');
    $openid2 = input('openid');
    if(empty($openid) && empty($openid2)){
        throw new \Exception('openid不能为空');
    }
    return $openid?:$openid2;
}

function api_user_info($field = '')
{
    $api_user_info = session('api_user_info');
    $openid2 = input('openid');
    if(empty($api_user_info) && empty($openid2)){
        throw new \Exception('openid不能为空');
    }
    if($api_user_info){
        return $api_user_info;
    }
    $api_user_info = Db::table(TabConf::$fa_users)->where('openid',$openid2)->find();
    return $field?$api_user_info[$field]:$api_user_info;
}
