<?php

namespace app\admin\controller\member;

use app\admin\service\member\MemberService;
use app\controller\Curd;
use app\model\CouponDetail;
use app\model\Member;
use app\model\MemberRole;
use app\model\SysDept;
use app\model\SysUser;
use support\Request;

class FranchiseeController extends Curd
{
    public function list(Request $request)
    {
        $page = $request->get('page', 1);
        $pageSize = $request->get('pageSize', 10);
        $name = $request->get('name', '');
        $nickname = $request->get('nickname', '');
        $mobile = $request->get('mobile', '');
        $level = $request->get('level', '');
        $isAuth = $request->get('is_auth', '');
        $addtime = $request->get('member_addtimes', []);
        $type = $request->get('type', '');
        $status = $request->get('member_status', '');
        $memberIsFranchisee = $request->get('member_is_franchisee', '');

        // 兼容老等级搜索
        $levelIds = [];
        if (!empty($level)) {
            $levelName = MemberRole::where('member_role_id', $level)->value('member_role_name');
            if (!empty($levelName)) {
                $levelIds = MemberRole::where('member_role_name', $levelName)->pluck('member_role_id')->toArray();
            }
        }

        $rows = Member::with([
            'account' => function ($query) {
                $query->where('member_account_status', 'ACTIVED');
            }
        ])->where('member_is_owner', 'N')
            ->where('member_mobile', '<>', '0000')
            ->leftJoin('member_info', 'member_info.join_info_member_id', 'member.member_id')
            ->leftJoin('member_cert', 'member_cert.join_cert_member_id', 'member.member_id')
            ->leftJoin('member_role', 'member_role.member_role_id', 'member.join_member_role_id')
            ->when($name != '', function ($query) use ($name) {
                $query->where('member_cert.member_cert_name', 'like', '%' . $name . '%');
            })->when($mobile != '', function ($query) use ($mobile) {
                $query->where('member.member_mobile', 'like', '%' . $mobile . '%');
            })->when($level != '', function ($query) use ($level, $levelIds) {
                if ($level == 'other') {
                    $query->where('member.join_member_role_id', NULL)->orWhere('member.join_member_role_id', '');
                } else if ($level == 'VIP') {
                    $query->where('member.member_is_vip', 'Y');
                } else if (!empty($levelIds)) {
                    $query->whereIn('member_role.member_role_id', $levelIds);
                } else {
                    $query->where('member_role.member_role_id', $level);
                }
            })->when($isAuth != '', function ($query) use ($isAuth) {
                if ($isAuth == 'Y') {
                    $query->where('member_cert.member_cert_name', '<>', NULL)->where('member_cert.member_cert_nbr', '<>', NULL)->where('member_cert.member_cert_name', '<>', '')->where('member_cert.member_cert_nbr', '<>', '');
                } else {
                    $query->where('member_cert.member_cert_name', NULL)->orWhere('member_cert.member_cert_nbr', NULL)->orWhere('member_cert.member_cert_name', '')->orWhere('member_cert.member_cert_nbr', '');
                }
            })->when(!empty($addtime), function ($query) use ($addtime) {
                $addtime[0] = strtotime($addtime[0]);
                $addtime[1] = strtotime($addtime[1]);
                $query->whereRaw("CAST(UNIX_TIMESTAMP(JSON_UNQUOTE(JSON_EXTRACT(member_franchisee_json,'$.datetime'))) as SIGNED) >= {$addtime[0]}")
                    ->whereRaw("CAST(UNIX_TIMESTAMP(JSON_UNQUOTE(JSON_EXTRACT(member_franchisee_json,'$.datetime'))) as SIGNED) <= {$addtime[1]}");
            })->when(!empty($type), function ($query) use ($type) {
                if ($type == 'todayAdd') {
                    $addtime[0] = strtotime(date('Y-m-d') . ' 00:00:00');
                    $addtime[1] = strtotime(date('Y-m-d') . ' 23:59:59');
                } else if ($type == 'monthAdd') {
                    $addtime[0] = strtotime(date('Y-m-01') . ' 00:00:00');
                    $addtime[1] = strtotime(date('Y-m-t') . ' 23:59:59');
                }
                $query->whereBetween('member.member_addtimes', $addtime);
            })->when(!empty($nickname), function ($query) use ($nickname) {
                $query->where(function ($query2) use ($nickname) {
                    $query2->where('member_info.member_info_nickname', 'like', '%' . $nickname . '%')->orWhere('member.member_mobile', 'like', '%' . $nickname . '%');
                });
            })->when(!empty($status), function ($query) use ($status) {
                $query->where('member_status', $status);
            })->when(!empty($memberIsFranchisee), function ($query) use ($memberIsFranchisee) {
                if ($memberIsFranchisee == 'Y') {
                    $query->where('member_is_franchisee', 'Y');
                }
            })
            ->select('member_id', 'member_is_vip', 'member_is_owner', 'join_invite_member_id', 'member_is_partner','member_is_franchisee', 'member_is_referrer', 'member_classify', 'member_status', 'member_mobile', 'member_from', 'member_addtimes', 'member_extend_json',
                'member_info.member_info_nickname', 'member_info.member_info_headimg', 'member_info.member_info_referee', 'member_info.member_info_business', 'member_info.member_info_service', 'member_info.member_info_city', 'member_info.member_info_address', 'member_info.member_info_gender', 'member_info.member_info_birthday',
                'member_role.member_role_id', 'member_role.member_role_name',
                'member_cert.member_cert_birth', 'member_cert.member_cert_gender', 'member_cert.member_cert_name', 'member_cert.member_cert_nbr', 'member_cert.member_cert_province', 'member_cert.member_cert_addr', 'member_cert.member_cert_face', 'member_cert.member_cert_photo', 'member_cert.member_cert_nation'
//                'member_account.member_account_surplus'
            )->selectRaw("CAST(UNIX_TIMESTAMP(JSON_UNQUOTE(JSON_EXTRACT(member_franchisee_json,'$.datetime'))) as SIGNED) as franchisee_add_times");
        // 总条数
        $total = $rows->count('member_id');
        // 已认证条数
        $authModel = clone $rows;
        $authTotal = $authModel->where('member_cert.member_cert_name','<>','')
            ->where('member_cert.member_cert_nbr','<>','')
            ->count();

        $rows = $rows->orderBy('franchisee_add_times', 'DESC')
            ->forPage($page, $pageSize)
            ->get()
            ->toArray();

        foreach ($rows as &$row) {
            $row['franchisee_add_times'] = date('Y-m-d H:i:s',$row['franchisee_add_times']);
            $row['coupon_count'] = CouponDetail::where('join_coupon_detail_member_id', $row['member_id'])->count();
            $row['member_mobile'] = substr($row['member_mobile'], 0, 3) . '****' . substr($row['member_mobile'], 7);
            // 推荐人
            if (!empty($row['join_invite_member_id'])) {
                $row['referrer_name'] = MemberService::getMemberNameByMemberId($row['join_invite_member_id']);
            }
            $row['info'] = [
                'member_info_nickname' => !empty($row['member_info_nickname']) ? $row['member_info_nickname'] : substr($row['member_mobile'], -4, 4) . '会员',
                'member_info_headimg' => !empty($row['member_info_headimg']) ? $row['member_info_headimg'] : '',
                'member_info_referee' => !empty($row['member_info_referee']) ? $row['member_info_referee'] : '',
                'member_info_business' => !empty($row['member_info_business']) ? $row['member_info_business'] : '',
                'member_info_service' => !empty($row['member_info_service']) ? $row['member_info_service'] : '',
                'member_info_city' => !empty($row['member_info_city']) ? explode('-', $row['member_info_city']) : '',
                'member_info_address' => !empty($row['member_info_address']) ? $row['member_info_address'] : '',
                'member_info_birthday' => !empty($row['member_info_birthday']) ? $row['member_info_birthday'] : '',
                'member_info_gender' => !empty($row['member_info_gender']) ? $row['member_info_gender'] : '',
            ];
            if (substr($row['info']['member_info_headimg'], 0, 2) == '..') {
                $row['info']['member_info_headimg'] = '';
            }
            if (!empty($row['info']['member_info_address']) && in_array($row['info']['member_info_address'], ['请选择', '省-市-区'])) {
                $row['info']['member_info_address'] = '';
            }

            $row['cert'] = [
                'member_cert_birth' => $row['member_cert_birth'],
                'member_cert_gender' => $row['member_cert_gender'],
                'member_cert_name' => $row['member_cert_name'],
                'member_cert_nbr' => $row['member_cert_nbr'],
                'member_cert_province' => !empty($row['member_cert_province']) && is_json($row['member_cert_province']) ? json_decode($row['member_cert_province']) : '',
                'member_cert_addr' => $row['member_cert_addr'],
                'member_cert_face' => !empty($row['member_cert_face']) ? getenv('STORAGE_DOMAIN') . $row['member_cert_face'] : '',
                'member_cert_photo' => !empty($row['member_cert_photo']) ? getenv('STORAGE_DOMAIN') . $row['member_cert_photo'] : '',
                'member_cert_nation' => $row['member_cert_nation'],
            ];
            $account = [];
            if (!empty($row['account'])) {
                foreach ($row['account'] as $item) {
                    if ($item['member_account_classify'] == 'WELFARE') {
                        $account['welfare'] = [
                            'member_account_name' => $item['member_account_name'],
                            'member_account_income' => $item['member_account_income'],
                            'member_account_expend' => $item['member_account_expend'],
                            'member_account_surplus' => $item['member_account_surplus'],
                            'member_account_added' => $item['member_account_added'],
                        ];
                    } else if ($item['member_account_classify'] == 'POINTS') {
                        $account['points'] = [
                            'member_account_name' => $item['member_account_name'],
                            'member_account_income' => $item['member_account_income'],
                            'member_account_expend' => $item['member_account_expend'],
                            'member_account_surplus' => $item['member_account_surplus'],
                            'member_account_added' => $item['member_account_added'],
                        ];
                    } else if ($item['member_account_classify'] == 'CASH') {
                        $account['cash'] = [
                            'member_account_name' => $item['member_account_name'],
                            'member_account_income' => $item['member_account_income'],
                            'member_account_expend' => $item['member_account_expend'],
                            'member_account_surplus' => $item['member_account_surplus'],
                            'member_account_added' => $item['member_account_added'],
                        ];
                    } else if ($item['member_account_classify'] == 'CARD') {
                        $account['card'] = [
                            'member_account_name' => $item['member_account_name'],
                            'member_account_income' => $item['member_account_income'],
                            'member_account_expend' => $item['member_account_expend'],
                            'member_account_surplus' => $item['member_account_surplus'],
                            'member_account_added' => $item['member_account_added'],
                        ];
                    } else if ($item['member_account_classify'] == 'VIP') {
                        $account['vip'] = [
                            'member_account_name' => $item['member_account_name'],
                            'member_account_income' => $item['member_account_income'],
                            'member_account_expend' => $item['member_account_expend'],
                            'member_account_surplus' => $item['member_account_surplus'],
                            'member_account_added' => $item['member_account_added'],
                        ];
                    }
                }
            }
            $row['account'] = $account;

            $row['is_auth'] = "未认证";
            if (!empty($row['member_cert_nbr']) && !empty($row['member_cert_name'])) {
                $row['is_auth'] = "已认证";
            }

            $row['source'] = "APP";
            $row['belong'] = [];
            $row['referee'] = [];
            if (!empty($row['member_extend_json'])) {
                $extendJson = json_decode($row['member_extend_json'], true);
                if (isset($extendJson['come_from'])) {
                    $row['source'] = $extendJson['come_from'] ?? '';
                }
                if (isset($extendJson['belong'])) {
                    $user = SysUser::where('user_id', $extendJson['belong']['user_id'])->select('user_name', 'user_mobile')->first();
                    if ($user) {
                        $row['belong']['user_id'] = $extendJson['belong']['user_id'];
                        $row['belong']['username'] = $user->user_name;
                        $row['belong']['user_mobile'] = $user->user_mobile;
                    }
                    $row['belong']['deptName'] = SysDept::where('dept_id', $extendJson['belong']['premises'])->value('dept_name');
                }
                if (isset($extendJson['referee'])) {
                    foreach ($extendJson['referee'] as $key => $referee) {
                        if (preg_match('/^1[3-9]\d{9}$/', $referee)) {
                            $member = Member::with([
                                'cert' => function ($query) {
                                    $query->select('join_cert_member_id', 'member_cert_name');
                                }
                            ])->where('member_mobile', $referee)->where('member_status', 'ACTIVED')
                                ->first();
                            if ($member->cert && $member->cert->member_cert_name) {
                                $referee = $member->cert->member_cert_name . '-' . $referee;
                            }
                        }
                        $row['referee'][] = [
                            'name' => $referee,
                            'time' => $key
                        ];
                    }
                }
            }
            // 粉丝
            $fans1 = Member::where('join_invite_member_id', $row['member_id'])
                ->select('member_id')
                ->get()
                ->toArray();
            $fans1Ids = array_column($fans1, 'member_id');
            $fans2Count = Member::whereIn('join_invite_member_id', $fans1Ids)
                ->count();
            $row['fans_total'] = count($fans1) + $fans2Count;
        }

        return json_success('', compact('rows', 'page', 'pageSize', 'total','authTotal'));
    }
}