1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
<?php
 
namespace app\api\model\branch;
 
use app\api\model\user\User;
use app\common\enum\order\OrderPayTypeEnum;
use app\common\model\branch\ActivityUser as ActivityUserModel;
use app\api\model\branch\Member as MemberModel;
use app\api\model\branch\Activity as ActivityModel;
use app\api\service\order\paysuccess\type\BranchActivityPaySuccessService;
use app\api\service\order\PaymentService;
use app\common\enum\order\OrderTypeEnum;
use app\common\model\settings\Setting as SettingModel;
use app\common\enum\user\balanceLog\BalanceLogSceneEnum;
use app\common\model\user\BalanceLog as BalanceLogModel;
use app\common\model\branch\User as BranchUserModel;
use app\common\model\branch\Setting as BranchSettingModel;
use app\common\model\settings\Region as RegionModel;
use app\api\model\user\User as UserModel;
/**
 * 用户模型
 */
 
class ActivityUser extends ActivityUserModel
{
    // 订单模型
    public $model;
    /**
     * 隐藏字段
     */
    protected $hidden = [
        // 'create_time',
        'update_time',
    ];
    
    /**
     * 获取用户报名的活动列表
     */
    public function getListForUser($user_id, $params = [])
    {
        // 构建查询规则
        $model = $this->alias('A')->with(['activity' => ['branch', 'image'],'branch'])
            ->join('branch_activity B', 'B.activity_id = A.activity_id')
            ->field('A.*')
            ->visible(['activity' => ['name', 'image' => ['file_path'], 'branch' => ['name']]])
            ->where('A.user_id', '=', $user_id)
            ->where('A.status', '=', 1)
            ->where('A.is_delete', '=', 0)
            ->order(['A.create_time' => 'desc']);
        // 查询条件
        if (!empty($params['keyword'])) {
            $model = $model->where('B.name', 'like', '%' . $params['keyword'] . '%');
        }
        if (isset($params['verify_status']) && $params['verify_status'] >= 0) {
            $model = $model->where('is_verify', '=', $params['verify_status']);
        }
        // 获取列表数据
        return $model->paginate($params);
    }
 
    /**
     * 获取报名用户列表
     */
    public function getListForActivity($params = [], $is_page = true, $limit = false)
    {
        // 构建查询规则
        $model = $this->alias('auser')
            ->with('branch')
            ->field('auser.*,user.nickName,auser.real_name,user.avatarUrl')
            ->join('user', 'user.user_id = auser.user_id')
            ->where('auser.is_delete', '=', 0)
            ->where('auser.status', '=', 1)
            ->order(['auser.create_time' => 'desc']);
        // 查询条件
        if (!empty($params['keyword'])) {
            $model = $model->where('user.nickName|user.real_name|user.mobile', 'like', '%' . $params['keyword'] . '%');
        }
        if (!empty($params['activity_id'])) {
            $model = $model->where('auser.activity_id', '=', $params['activity_id']);
        }
        if (isset($params['verify_status']) && $params['verify_status'] != -1) {
            $model = $model->where('auser.is_verify', '=', $params['verify_status']);
        }
        // 如果不分页
        if (!$is_page) {
            if ($limit) {
                $model = $model->limit($limit);
            }
            return $model->select();
        }
        // 获取列表数据
        return $model->paginate($params);
    }
 
    /**
     * 添加报名用户
     */
    public function addUser($user, $params)
    {
        $detail = ActivityModel::detail($params["activity_id"]);
        // 如果用户还没加入连盟并且不是帮朋友报名
        /*if (!$params['is_member'] && !$params['is_friend']) {
            $this->addMember($detail, $params, $user);
        }*/
        // 验证数据
        if (!$this->validateData($detail, $params, $user)) {
            return false;
        }
 
        $data = [
            'user_id' => $user['user_id'],
            'order_no' => $this->orderNo(),
            'activity_id' => $detail['activity_id']?:0,
            'total_price' => $detail['fee']?:0,
            'pay_price' => $detail['fee']?:0,
            'points_num' => $params['points_num']?:0, // 积分抵扣数量
            'points_money' => $params['points_money']?:0, // 积分抵扣金额
            'balance' => $params['balance']?:0, // 余额
            'online_money' => $params['online_money']?:0, // 需在线支付的金额
            'status' => $params['online_money'] > 0 ? 0 : 1, //报名状态,如果不需要在线支付则则直接报名成功
            'pay_type' => $params['pay_type']?:0,
            'in_radius' => $params['in_radius']?:0,
            'province_id' => $params['province_id']?:0,
            'city_id' => $params['city_id']?:0,
            'region_id' => $params['region_id']?:0,
            'company' => $params['company']?:'',
            'recommend_name' => $params['recommend_name']?:'',
            'recommend_mobile' => $params['recommend_mobile']?:'',
            'real_name' => $params['real_name']?:'',
            'mobile' => $params['mobile']?:'',
            'branch_id' => $params['branch_id']?:0,
            'app_id' => self::$app_id,
        ];
        // 如果是帮朋友报名,把用户信息记录下来
        if ($params['is_friend']) {
            $data['real_name'] = $params['real_name'];
            $data['mobile'] = $params['mobile'];
            $data['company'] = $params['company'];
            $data['is_friend'] = 1;
            $data['reg_user_id'] = $user['user_id']; // 记录是谁帮注册的,因为核销的时候会把user_id改为实际报名人的
        }
        $data['trade_no'] = $data['order_no'];
        $refereeUser=(new UserModel())->where(['real_name'=>$params['recommend_name'],'mobile'=>$params['recommend_mobile']])->find();
        if ($refereeUser){
            $data['referee_id']=$refereeUser['user_id'];
        }
        $this->save($data);
        // 如果不需要在线支付
        if ($data['online_money'] == 0) {
            $this->onPayOffline($data['order_no']);
        }
        return $this;
    }
    public function getRegistrationInformation($user_id,$activity_id=0)
    {
        $list=$this->where('user_id', '=', $user_id)
            ->order('create_time', 'desc')->find();
        $data=[
            'province_id'=>'',
            'city_id'=>'',
            'region_id'=>'',
            'recommend_name'=>'',
            'recommend_mobile'=>'',
            'real_name'=>'',
            'mobile'=>'',
            'branch_id'=>'',
            'company'=>'',
            'branch_name'=>'',
            'region'=>'',
        ];
        if ($list){
            $branch=(new Branch())->detail($list['branch_id']);
            $data=[
                'province_id'=>$list['province_id'],
                'city_id'=>$list['city_id'],
                'region_id'=>$list['region_id'],
                'recommend_name'=>$list['recommend_name'],
                'recommend_mobile'=>$list['recommend_mobile'],
                'real_name'=>$list['real_name'],
                'mobile'=>$list['mobile'],
                'branch_id'=>$list['branch_id'],
                'company'=>$list['company'],
                'branch_name'=>$branch?$branch['name']:'',
                'region'=>RegionModel::getNameById($list['province_id']).','.RegionModel::getNameById($list['city_id']).','.RegionModel::getNameById($list['region_id']),
 
            ];
        }
        if($activity_id){
            $activity=(new ActivityModel())->find($activity_id);
            if ($activity){
                $data['activity_number']=(new ActivityModel())->where(['branch_id'=>$activity['branch_id'],'category_id'=>$activity['category_id']])->count();
            }
        }
        return $data;
    }
    public function addMember($activity, $params, $user)
    {
        $data = [
            'user_id' => $user['user_id'],
            'branch_id' => $params['branch_id'],
            'real_name' => $params['real_name'],
            'mobile' => $params['mobile'],
            'company' => $params['company'],
            'app_id' => self::$app_id,
        ];
        (new MemberModel())->add($data);
    }
 
    /**
     * 构建线下支付(积分、余额)请求的参数
     */
    public function onPayOffline($order_no)
    {
        // 获取订单详情
        $PaySuccess = new BranchActivityPaySuccessService($order_no);
        // 发起支付
        return $PaySuccess->onPaySuccess(OrderPayTypeEnum::BALANCE);
    }
 
    /**
     * 构建支付请求的参数
     */
    public static function onOrderPayment($user, $order_no, $payType, $pay_source, $online_money)
    {
        //如果来源是h5,首次不处理,payH5再处理
        // if ($pay_source == 'h5') {
        //     return [];
        // }
        if ($payType == OrderPayTypeEnum::WECHAT) {
            return self::onPaymentByWechat($user, $order_no, $pay_source, $online_money);
        }
        return [];
    }
 
    /**
     * 构建微信支付请求
     */
    protected static function onPaymentByWechat($user, $order_no, $pay_source, $online_money)
    {
        return PaymentService::wechat(
            $user,
            $order_no,
            OrderTypeEnum::BRANCHACTIVITY,
            $pay_source,
            $online_money
        );
    }
 
    /**
     * 验证报名数据
     */
    public function validateData($activity, &$params, $user) {
        if ($activity["status_text"]["reg_status"] == 0){
            $this->error = '报名未开始';
            return false;
        }
        if ($activity["status_text"]["reg_status"] == 2){
            $this->error = '报名已结束';
            return false;
        }
        if ($activity["limit_num"] > 0 && $activity["total"] >= $activity["limit_num"]){
            $this->error = '报名名额已满';
            return false;
        }
        // 如果是帮朋友报名,验证手机号是不是已报过
        if ($params['is_friend'] && ActivityUserModel::isRegByFriend($params['mobile'], $activity['activity_id'])) {
            $this->error = '该手机号已经报过名了';
            return false;
        }
        // 如果需要支付报名费
        $params['online_money'] = 0;
        if ($activity['fee'] > 0) {
            $online_money = $activity['fee'];
            // 积分设置
            $pointsSetting = SettingModel::getItem('points');
            if ($params['points_num'] > $user['points']) {
                $this->error = '可用' . $pointsSetting['points_name'] . '不足';
                return false;
            }
            // 重新计算积分抵扣金额
            $params['points_money'] = bcmul($params['points_num'], $pointsSetting['discount']['discount_ratio']);
            $online_money -= $params['points_money'];
            if ($params['is_use_balance']) {
                $params['balance'] = min($online_money, $user['balance']);
            } else {
                $params['balance'] = 0;
            }
            $online_money -= $params['balance'];
            if ($online_money && empty($params['pay_type'])) {
                $this->error = '请选择支付方式';
                return false;
            }
            $params['online_money'] = $online_money;
        }
        return true;
    }
 
    /**
     * 检查用户有没有核销权限
     */
    public static function checkVerifyUser($user_id, $branch_id, $verify_user_ids)
    {
        $can_verify = false;
        if (in_array($user_id, explode(',', $verify_user_ids))) {
            $can_verify = true;
        } else {
            // 检查是不是管理员
            if(BranchUserModel::detail(['user_id' => $user_id, 'branch_id' => $branch_id])) {
                $can_verify = true;
            }
        }
        return $can_verify;
    }
 
    /**
     * 完成核销
     */
    public function onVerify($user, $activity_id, $params = [])
    {
        $activity = ActivityModel::detail($activity_id);
        if ($activity['status_text']['status'] == 2) {
            $this->error = '活动已经结束了,不能签到啦';
            return false;
        }
        $detail = ActivityUserModel::detail(['activity_id' => $activity_id, 'user_id' => $user['user_id'], 'is_friend' => 0]);
        if (!$detail) {
            // 如果朋友帮报名
            if (!empty($params['verify_mobile'])) {
                $detail = ActivityUserModel::detail(['activity_id' => $activity_id, 'mobile' => $params['verify_mobile'], 'is_friend' => 1]);
                if (!$detail) {
                    $this->error = '很抱歉,没有找到报名记录';
                    return false;
                }
                // 更新信息
                $userData = [];
                if ($user['real_name'] == '') {
                    $userData['real_name'] = $detail['real_name'];
                }
                if ($user['mobile'] == '') {
                    $userData['mobile'] = $detail['mobile'];
                }
                if ($userData) {
                    $user->save($userData);
                }
            } else {
                $this->error = 'not_reg';
                return false;
            }
        }
        if($detail['is_verify'] == 1) {
            $this->error = '您已经签到过啦';
            return false;
        }
        $data = [
            'is_verify' => 1,
            'verify_time' => time()
        ];
        // 如果是帮报名的签到,将user_id改成真正报名的人
        if (!empty($params['verify_mobile'])) {
           $data['user_id'] = $user['user_id'];
        }
        $detail->save($data);
        // 发放奖励
        $setting = BranchSettingModel::getItem('basic');
        $participate_points = $setting['participate_user'];
        $member = MemberModel::detail($user['user_id'], ['position']);
        if ($member && $member['position'] && $member['position']['participate_points'] > 0) {
            $participate_points = $member['position']['participate_points'];
        }
        if ($participate_points > 0) {
            $describe = "活动签到获得奖励[活动ID:{$activity_id}]";
            $user->setIncPoints($participate_points, $describe);
        }
        return true;
    }
 
}