<?php
// 应用公共文件

use app\common\arw\adjfut\src\Exception\ErrorMsg;
use app\BaseController;
use think\facade\Request;
use think\facade\Validate;
use think\Collection;
use think\db\Query;
use think\Validate as ThinkValidate;

const DS = DIRECTORY_SEPARATOR;

function fump($var, $echo = true, $label = null, $flags = ENT_SUBSTITUTE)
{
    $label = (null === $label) ? '' : rtrim($label) . ':';

    ob_start();
    var_dump($var);
    $output = preg_replace('/\]\=\>\n(\s+)/m', '] => ', ob_get_clean());

    if (!extension_loaded('xdebug')) {
        $output = htmlspecialchars($output, $flags);
    }

    $output = '<pre>' . $label . $output . '</pre>';

    if ($echo) {
        echo ($output);
        return;
    }

    return $output;
}

/**
 * 抛出业务异常
 *
 * @param string $msg
 * @param integer $code
 * @return void
 * @throws ErrorMsg
 * @date 2022-12-27
 * @example
 * @author admin
 * @since 1.0.0
 */
function throwErrorMsg(string $msg, int $code = 1): void
{
    throw new ErrorMsg($msg, $code);
}

/**
 * 计算年龄
 *
 * @param string $birthday Y-m-d
 * @return int
 * @date 2022-03-11
 * @example
 * @author admin
 * @since 1.0.0
 */
function sumAge($birthday): int
{
    $age = 0;
    try {
        if (!is_string($birthday)) {
            throw new ErrorMsg("非法日期", 1);
        }
        $birthday = explode("-", date('Y-m-d', strtotime($birthday)));
        $date = explode("-", date('Y-m-d'));
        if (count($birthday) === 3) {
            list($y, $m, $d) = $birthday;
        } else {
            list($y, $m, $d) = $date;
        }
        // list($y, $m, $d) = $birthday;
        list($dy, $dm, $dd) = $date;

        $age = $dy - $y;
        if ($dm >= $m) {
            if ($dm == $m) {
                if ($dd >= $d) {
                } else {
                    $age--;
                }
            }
        } else {
            $age--;
        }
        return $age;
    } catch (\Throwable $th) {
    }
    return $age;
}

Validate::maker(function (ThinkValidate $validate) {
    $validate->extend(
        'string',
        function ($value) {
            return is_string($value);
        },
        ':attribute 数据类型非法 不是字符串'
    );
});

/**
 * 接口返回封装
 */
function msg(...$arr)
{
    $msg_data = ['code' => 0];
    $default_code_msg = [0 => '操作成功!', 1 => '操作失败!'];

    //data数据构建
    function constructData(&$msg_data, $code, $msg_str, &$arr2)
    {
        $msg_data['code'] = $code;
        $msg_data['msg'] = $msg_str;
        if (is_array($arr2)) { //数组
            $msg_data['data'] = $arr2;
        }
        if (is_object($arr2)) { //查询对象
            $obj = $arr2;
            $soft_delete_field = '_delete_time'; //软删除默认后缀
            //模型层 || Db层
            if ($obj instanceof think\db\Query || $obj instanceof think\Collection) {
                //join软删除字段过滤补全(暂时只适应软删除为 【前缀名_delete_time】存储为datetime 的设计)
                if (isset($obj->getOptions()['join']) && $join_data = $obj->getOptions('join')) {
                    $join_soft_delete = [];
                    foreach ($join_data as $key => $join) {
                        $join_table_name = is_array($join[0]) ? array_keys($join[0])[0] : $join[0]; //联表表名
                        $join_soft_delete[] = [$join_table_name . $soft_delete_field, 'NULL', null];
                    }
                    $obj = $obj->where($join_soft_delete);
                }
                //select()、count()补全
                $msg_data['data'] = $obj->page((int) Request::param('page', 1), (int) Request::param('limit', 10))->select();
                $msg_data['count'] = $obj->count();
            } else {
                return ['code' => 444, 'msg' => '对象只允许传递来自think\db\Query类和instanceof think\Collection类的实例!'];
            }
        }
    };

    switch (count($arr)) {
        case 1: //单参数
            constructData($msg_data, 0, '查询成功!', $arr[0],);
            if (is_string($arr[0])) $msg_data['msg'] = $arr[0];
            if (is_int($arr[0])) {
                $msg_data['code'] = $arr[0];
                $msg_data['msg'] = $default_code_msg[$arr[0]];
            }
            break;
        case 2: //双参数
            if (is_int($arr[0]) && is_string($arr[1])) {
                $msg_data['code'] = $arr[0];
                $msg_data['msg'] = $arr[1];
            } else {
                constructData($msg_data, 0, $arr[0], $arr[1]);
            }
            break;
        case 3: //三参数
            $msg_data['code'] = $arr[0];
            $msg_data['msg'] = $arr[1];
            if (is_object($arr[2])) {
                $msg_data['data'] = $arr[2];
            } else {
                foreach ($arr[2] as $key => $val)
                    $msg_data[$key] = $val;
            }
            break;
        default:
            return ['code' => 444, 'msg' => 'msg()最多参数只允许3个!'];
    }

    return $msg_data;
}
