api/app/service/UserService.php
2019-06-23 22:28:55 +08:00

115 lines
3.4 KiB
PHP

<?php
/**
* Created by PhpStorm.
* User: home
* Date: 2019/6/21
* Time: 14:13
*/
namespace app\service;
use app\model\UserDetail;
use app\model\UserInfo;
use app\util\ErrorCode;
use app\util\ListCountData;
use app\util\WechatUtil;
use think\facade\Config;
class UserService
{
const AllData = -1;
public static function search(
int $isFirst = -1, int $gender = -1, int $province = -1, int $city = -1, string $name = null, int $page = 1, int $pageSize = 20
)
{
$userDetail = new UserDetail();
$userInfo = new UserInfo();
$model = $userDetail->db()->alias('d')
->join($userInfo->getTableName() . ' u', 'u.id = d.uid');
// 首次进藏
if ($isFirst != self::AllData) {
$model->where('is_first_to_tibet', $isFirst);
}
// 性别
if ($gender != self::AllData) {
$model->where('gender', $gender);
}
// 性别
if ($province != self::AllData) {
$model->where('province', $province);
}
// 性别
if ($city != self::AllData) {
$model->where('city', $city);
}
if (!empty($name)) {
//, ['name' => ""]
$model->where("(u.nickname LIKE '%{$name}%' OR d.realname LIKE '%{$name}%')");
}
$dataArray = $model->limit(($page - 1) & $pageSize, $pageSize)// 分页
->field('u.nickname,u.open_id,u.avatarUrl,d.*')// 查询字段
->select()->toArray(); // 获取结果
$count = $userInfo->count(); // 查询总数
self::parseArray($dataArray);
return ListCountData::Create($count, $dataArray);
}
private static function parseArray(&$dataArray)
{
$userData = Config::get('app.user.subject');
foreach ($dataArray as $key => &$item) {
// $item['is_first_to_tibet'] = $item['is_first_to_tibet'] == 1 ? '是' : '否';
$item['smoke'] = $userData['smoke'][$item['smoke']];
$item['medical_history'] = empty($item['medical_history']) ? [] : self::getDataFromArray(
$userData['medical_history'],
explode(',', $item['medical_history'])
);
}
}
private static function getDataFromArray(array $datas, array $keys)
{
foreach ($keys as $key => $v) {
$keys[$key] = $datas[$v];
}
return $keys;
}
public static function getSessionByCode(string $code): array
{
$wechat = new WechatUtil();
$session = $wechat->codeToSession($code);
if (isset($session['errcode']) && $session['errcode'] != 0) {
throw new \Exception($session['errmsg'], ErrorCode::User_Login_Fail);
}
return $session;
}
/**
* 更新数据
* @param $data
* @param UserInfo $userInfo
* @return UserDetail|array|null|\think\Model
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\exception\DbException
*/
public static function saveDetail($data, UserInfo $userInfo)
{
$detail = UserDetail::where('uid', $userInfo->id)->find();
$data['uid'] = $userInfo->id;
if (empty($detail)) {
$detail = UserDetail::create($data);
} else {
$detail = UserDetail::update($data, ['uid' => $userInfo->id]);
}
return $detail;
}
}