<?php

namespace app\admin\service\member;

use app\model\Member;
use app\model\MemberCert;
use app\model\MemberInfo;
use app\model\SysSerial;
use support\Db;
use support\Request;

class OwnerService
{
    public static function list(Request $request)
    {
        $page = $request->get('page', 1);
        $pageSize = $request->get('pageSize', 10);
        $name = $request->get('name', '');
        $mobile = $request->get('mobile', '');
        $rows = Member::where('member_is_owner', 'Y')
            ->leftJoin('member_info', 'member_info.join_info_member_id', 'member.member_id')
            ->leftJoin('member_cert', 'member_cert.join_cert_member_id', 'member.member_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 . '%');
            })->select('member_id', 'member_is_owner', 'member_classify', 'member_status', 'member_mobile', 'member_from', 'member_addtimes',
                'member_info.member_info_nickname', 'member_info.member_info_headimg',
                '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'
            );

        // 总条数
        $total = $rows->count('member_id');
        $rows = $rows->orderBy('member_addtimes', 'DESC')
            ->forPage($page, $pageSize)
            ->get()
            ->toArray();

        foreach ($rows as &$row) {
            $row['info'] = [
                'member_info_nickname' => $row['member_info_nickname'] ?? '',
                'member_info_headimg' => !empty($row['member_info_headimg']) ? getenv('STORAGE_DOMAIN') . $row['member_info_headimg'] : ''
            ];
            $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'],
            ];
            $row['is_auth'] = "未认证";
            if (!empty($row['member_cert_nbr']) && !empty($row['member_cert_face']) && !empty($row['member_cert_photo'])) {
                $row['is_auth'] = "已认证";
            }
        }

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

    /**
     * @Desc 添加会员
     * @Author Gorden
     * @Date 2024/3/25 13:40
     *
     * @param $params
     * @return \support\Response
     */
    public static function add($params)
    {
        Db::beginTransaction();
        try {
            $memberId = self::generateMemberId();
            // 先写主表，要ID
            $memberData = [
                'member_id' => $memberId,
                'member_is_owner' => $params['is_owner'],
                'member_classify' => $params['classify'],
                'member_status' => $params['status'],
                'member_mobile' => $params['mobile'],
                'member_from' => $params['source'],
                'member_addtimes' => time(),
            ];
            Member::insert($memberData);
            // member cert
            $certData = [
                'join_cert_member_id' => $memberId,
                'member_cert_nation' => $params['member_cert_nation'] ?? '',
                'member_cert_name' => $params['cert_name'] ?? '',
                'member_cert_nbr' => $params['cert_nbr'] ?? '',
                'member_cert_birth' => $params['birth'] ?? '',
                'member_cert_gender' => $params['gender'] ?? '',
                'member_cert_province' => $params['province'] ? json_encode($params['province'], JSON_UNESCAPED_UNICODE) : '[]',
                'member_cert_city' => $params['city'] ?? '',
                'member_cert_addr' => $params['addr'] ?? '',
                'member_cert_face' => str_replace(getenv('STORAGE_DOMAIN'), '', $params['member_cert_face']),
                'member_cert_photo' => str_replace(getenv('STORAGE_DOMAIN'), '', $params['member_cert_photo']),
            ];
            MemberCert::insert($certData);
            // member info
            $infoData = [
                'join_info_member_id' => $memberId,
                'member_info_nickname' => $params['account_name'],
                'member_info_headimg' => str_replace(getenv('STORAGE_DOMAIN'), '', $params['avatar'])
            ];
            MemberInfo::insert($infoData);

            Db::commit();
        } catch (\Exception $e) {
            Db::rollBack();
            dump($e->getMessage() . ';line:' . $e->getLine());
            return json_fail("数据添加失败");
        }

        return json_success('数据添加成功');
    }

    private static function generateMemberId()
    {
        $id = SysSerial::getSerial();

        return "ME" . str_pad($id, 16, "0", STR_PAD_LEFT) . random_string(8);
    }
}