<?php
namespace app\admin\server\user;

use app\admin\model\Package;
use app\admin\model\UserAuth;
use app\admin\model\UserBasicHealthData;
use app\admin\model\UserBasicHealthDataLog;
use app\admin\model\UserDoctorsLog;
use app\admin\model\UserMedicalExaminationReport;
use app\admin\model\User;
use app\admin\model\IntelligenceLog;
use app\admin\model\IntelligenceEquipment;
use app\admin\model\UserPackageLog;
use app\admin\server\package\PackageServer;
use app\admin\model\UserRelatives;
use app\admin\model\UserProperty;

/**
 * 会员服务层
 * Class UsersServer
 * @package app\admin\server\user
 */
class UsersServer
{
    /**
     * Notes:会员信息
     * @param int $user_id
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     * User: yym
     * Date: 2022/7/26
     */
    public static function getUserInfo(int $user_id)
    {
        $info =  User::getUserInfo($user_id);
        if(empty($info))
        {
            throw new \Exception('查无此会员信息');
        }
        $info['user_category']    = User::USER_CATEGORY[$info['user_type']] ?? '';
        $info['user_create_time'] = date("Y-m-d H:i:s", $info['user_create_time']);
        $info['member_is_owner']  = User::USER_OWNER[$info['user_is_owner']] ?? '';
        $auth_status = '';
        $auth_status_msg = '';
        if(empty($info['member_auth_list']))
        {
            $auth_status = '未认证';
            $auth_status_msg = '实名认证';
        }elseif((count($info['member_auth_list']) == 1 || count($info['member_auth_list']) == 2) && !empty($info['member_auth'])){
            $auth_status = UserAuth::MEMBER_AUTH_STATUS[$info['member_auth']['auth_status']];
            $auth_status_msg = '会员升级';
        }elseif((count($info['member_auth_list']) == 1 || count($info['member_auth_list']) == 2) && empty($info['member_auth'])){
            $auth_status = '认证通过';
            $auth_status_msg = '会员升级';
        }
        $info['auth_status']     = $auth_status;
        $info['auth_status_msg'] = $auth_status_msg;
        if(!empty($info['member_auth_list']))
        {
            foreach ($info['member_auth_list'] as $k => $item)
            {
                if($item['auth_type'] == '0')
                {
                    $info['member_auth_list'][$k]['auth_content'] = json_decode($item['auth_content'], true);
                }

            }
        }
        unset($info['member_certinfo']);
        return $info;
    }

    /**
     * Notes:会员列表
     * @param string $keywords
     * @param int $category
     * @param int $status
     * @param int $page
     * @param int $limit
     * @return array
     * User: yym
     * Date: 2022/8/4
     */
    public static function getUserList(string $keywords, int $category, int $status , int $pid, int $page, int $limit, string $user_create_time)
    {
        [$list, $count] = User::getUserList($keywords, $category, $status, $pid, $user_create_time, $page, $limit);
        if(!empty($list))
        {
            foreach ($list as &$row)
            {
                $row['user_category']   = User::USER_CATEGORY[$row['user_type']] ?? '';
                $row['user_create_time']= date("Y-m-d H:i:s", $row['user_create_time']);
                $row['member_is_owner'] = User::USER_OWNER[$row['user_is_owner']] ?? '';
                $row['sonnum'] = User::where('user_spread_uid',$row['user_id'])->count();
                $row['rejectMsg'] = '';
                $auth_status = '';
                $auth_status_msg = '';
                $auth_status_type = '';
                if(empty($row['member_auth_list']))
                {
                    $auth_status = '未认证';
                    $auth_status_msg = '实名认证';
                    $auth_status_type = '未认证';
                }elseif (count($row['member_auth_list']) == 1 && empty($row['member_auth'])){
                    $auth_status = '已实名认证';
                    $auth_status_msg = '实名认证';
                    $auth_status_type = '未购买';
                    $row['rejectMsg'] = $row['member_auth_list'][0]['auth_content'];
                }elseif (count($row['member_auth_list']) == 1 && !empty($row['member_auth'])){
                    $auth_status = '已提交认证';
                    $auth_status_msg = '实名认证';
                    $auth_status_type = UserAuth::MEMBER_AUTH_STATUS[$row['member_auth']['auth_status']];
                    $row['rejectMsg'] = $row['member_auth_list'][0]['auth_content'];
                }elseif (count($row['member_auth_list']) == 2 && empty($row['member_auth'])){
                    $auth_status = '已升级认证';
                    $auth_status_msg = '会员升级';
                    $auth_status_type = '已购买';
                    $row['rejectMsg'] = $row['member_auth_list'][1]['auth_content'];
                }elseif (count($row['member_auth_list']) == 2 && !empty($row['member_auth'])){
                    $auth_status = '已提交认证';
                    $auth_status_msg = '会员升级';
                    $auth_status_type = '已购买';
                    $row['rejectMsg'] = $row['member_auth_list'][1]['auth_content'];
                }
                $row['auth_status']      = $auth_status;
                $row['auth_status_msg']  = $auth_status_msg;
                $row['auth_status_type'] = $auth_status_type;
                if(!empty($row['member_auth_list']))
                {
                    foreach ($row['member_auth_list'] as $k => $item)
                    {
                        if($item['auth_type'] == '0')
                        {
                            $row['member_auth_list'][$k]['auth_content'] = json_decode($item['auth_content'], true);
                        }

                    }
                }
                unset($row['member_certinfo']);
            }
            unset($row);
        }
        return compact('list', 'count');
    }

    /**
     * Notes:营销活动排行列表
     * @param int $page
     * @param int $limit
     * @return array
     * User: ycp
     * Date: 2023/3/1
     */
    public static function getRankList($act,$s_time,$e_time)
    {
        $list = User::getRankList($act,$s_time,$e_time);
        return $list;
    }

    /**
     * Notes:营销活动拉新列表
     * @param int $page
     * @param int $limit
     * @return array
     * User: ycp
     * Date: 2023/3/1
     */
    public static function getActLog($act,$page,$limit)
    {
        [$list, $count] = User::getActLog($act,$page,$limit);
        if(!empty($list))
        {
            foreach ($list as &$row)
            {
                $row['user_create_time']= date("Y-m-d H:i:s", $row['user_create_time']);
            }
            unset($row);
        }
        return compact('list', 'count');
    }

    /**
     * Notes: 添加设备
     * @return int
     * User: ZQ
     * Date: 2022/11/14
     */
    public static function userInsert($user_account,$user_login_pwd,$user_again_pwd,$user_nickname,$user_headimgurl,$user_sex,$user_birthday,$user_age,$user_register_address,$user_phone,$user_status,$user_real_name,$user_card_id,$user_certinfo,$user_is_owner,$user_type,$user_spread_uid,$user_source,$admin_id,$user_register_type)
    {

        User::affairBegin();
        $data = [];
        //判断账号是否唯一
        $account = User::getUserAccount($user_account);
        try {
            
            /*if (!empty($account)){
                throw new \Exception($user_account.'会员账号已存在！');
            }
            //判断身份证是否唯一
            if (!empty($user_card_id)){
                $card = User::getUserCard($user_card_id);
                if (!empty($card)){
                    throw new \Exception('会员身份证已存在！');
                }
            }
            $data['user_account'] = $user_account;
            if ($user_login_pwd == $user_again_pwd){
                $data['user_login_pwd'] = md5(sha1($user_login_pwd));
            }else{
                throw new \Exception('两次密码不一致！');
            }*/
            if (!$account){
                $data['user_account'] = $user_account;
                $data['user_nickname'] = $user_nickname;
                $data['user_headimgurl'] = $user_headimgurl;
                $data['user_sex'] = $user_sex;
                $data['user_birthday'] = $user_birthday;
                $data['user_age'] = $user_age;
                $data['user_register_address'] = $user_register_address;
                $data['user_phone'] = $user_phone;
                $data['user_package_status'] = 0;
                $data['user_package_id'] = 0;
                $data['user_status'] = $user_status;
                $data['user_real_name'] = $user_real_name;
                $data['user_card_id'] = $user_card_id;
                $data['user_certinfo'] = $user_certinfo ? implode(',',$user_certinfo) : '';
                $data['user_is_owner'] = $user_is_owner;
                $data['user_type'] = $user_type;
                $data['user_register_type'] = $user_register_type;
                if ($user_type == 2){
                    throw new \Exception('会员身份选择错误！');
                }
                $data['user_spread_uid'] = $user_spread_uid;
                $data['user_spread_time'] = $user_spread_uid ? time() : '';
                $data['user_source'] = $user_source;
                $data['user_create_time'] = time();
                $result =  User::insertGetId($data);
                if ($user_type == 1){
                    $auth = [];
                    $auth['auth_user_id'] = $result;
                    $auth['auth_type'] = 0;
                    $auth['auth_content'] = json_encode(['card_front'=>$user_certinfo[0],'card_side'=>$user_certinfo[1]]);
                    $auth['auth_status'] = 1;
                    $auth['auth_status_info'] = '添加新会员实名认证审核';
                    $auth['auth_admin_id'] = $admin_id;
                    $auth['auth_examine_time'] = time();
                    $auth['auth_create_time'] = time();
                    $mation = UserAuth::insertGetId($auth);
                    if (empty($mation)){
                        User::affairRollback();
                        throw new \Exception('添加失败！');
                    }
                }
                if (!empty($result)){
                    $msg = '管理员：' . $admin_id . '在：' . date("Y-m-d H:i:s", time()) . '添加会员-编号: ' . $result;
                    plog('user-equipment-create', '公共-会员-添加会员', $msg);
                    User::affairCommit();
                    return $result;
                }
                throw new \Exception('添加失败！');
            }else{
                User::affairCommit();
                return true;
            }
            
        }catch (\Exception $exception){
            User::affairRollback();
            throw new \Exception($exception->getMessage(), 500);
        }
    }

    /**
     * Notes:会员审核操作
     * @param int $admin_id
     * @param int $user_id
     * @param string $status
     * @param string $content
     * @param string $category
     * @return bool
     * @throws \Exception
     * User: yym
     * Date: 2022/8/4
     */
    public static function authUser(int $admin_id, int $user_id, string $status, string $content, string $category)
    {
        User::affairBegin();
        try {
            if($status == UserAuth::RETURN && empty($content))
            {
                throw new \Exception('审核驳回，驳回理由不能为空！');
            }
            $update = array(
                'auth_status'       => $status,
                'auth_status_info'  => $content,
                'auth_admin_id'     => $admin_id,
                'auth_examine_time' => time()
            );
            $result1 = true;
            $auth_type = 0;
            //审核通过  更新会员等级
            if($status == UserAuth::DONE && $category == '实名认证')
            {
                $auth_type = 0;
                $result1 = User::updateMember($user_id, ['user_type' => User::ORDINARY, 'user_real_status' => User::REAL_YES]);
                events('createUserNews', ['log_type' => 0, 'log_uid' => $user_id, 'log_content' => '您的'.$category.'审核成功了！']);
            }
            //审核通过  更新会员等级
            if($status == UserAuth::DONE && $category == '会员升级')
            {
                $auth_type = 1;
                $result1 = User::updateMember($user_id, ['user_type' => User::FORMAL, 'user_package_status' => User::PACKAGE_YES]);
                events('createUserNews', ['log_type' => 0, 'log_uid' => $user_id, 'log_content' => '您的'.$category.'审核成功了！']);
            }
            $result = UserAuth::updateAuth($user_id, $auth_type, $update);
            plog('user.auth', '会员-身份-审核', '管理员审核会员：' . $user_id . '审核意见内容：' . $content);
            if($result && $result1)
            {
                User::affairCommit();
                return true;
            }
            throw new \Exception('审核失败！');
        }catch (\Exception $exception){
            User::affairRollback();
            throw new \Exception($exception->getMessage(), 500);
        }
    }

    /**
     * Notes:获取会员体检信息
     * @param int $user_id
     * @return array
     * @throws \Exception
     * User: yym
     * Date: 2022/9/21
     */
    public static function getUserReport(int $user_id)
    {
        try {
            $info = User::getMemberInfo($user_id);
            if(empty($info))
            {
                throw new \Exception('会员信息不存在');
            }
            if(empty($info['user_card_id']))
            {
                throw new \Exception('暂无会员身份证信息');
            }
            //获取体检信息
            [$list, $count] = UserMedicalExaminationReport::getList($user_id);
            if(!empty($list))
            {
                foreach ($list as $k => $item)
                {
                    $list[$k]['report_content'] = json_decode($item['report_content'], true);
                    $list[$k]['report_add_time'] = date("Y-m-d H:i:s", $item['report_add_time']);
                }
            }
            return compact('list', 'count');
        }catch (\Exception $exception){
            throw new \Exception($exception->getMessage(), 500);
        }
    }

    /**
     * Notes:获取会员设备列表
     * @param int $equipment_user_id
     * @param string $equipment_name
     * @return array
     * @throws \Exception
     * User: ZQ
     * Date: 2022/9/23
     */
    public static function getUserEquipment(int $page,int $limit, $equipment_user_id, string $equipment_name, $equipment_class,$equipment_tripartite_sn,$equipment_create_time)
    {
        try {
            [$list,$count] = IntelligenceEquipment::equipmentList($page, $limit, $equipment_user_id, $equipment_name, $equipment_class,$equipment_tripartite_sn,$equipment_create_time);
            if(!empty($list))
            {
                foreach ($list as $k => $item)
                {
                    if (empty($item['user_nickname'])){
                        $list[$k]['username'] = $item['user_account'];
                    }else{
                        $list[$k]['username'] = $item['user_nickname'];
                    }
                    $list[$k]['equipment_create_time'] = date("Y-m-d H:i:s", $item['equipment_create_time']);
                    if (!empty($item['equipment_update_time'])){
                        $list[$k]['equipment_update_time'] = date("Y-m-d H:i:s", $item['equipment_update_time']);
                    }
                    if (!empty($item['equipment_up_end_time'])){
                        $list[$k]['equipment_up_end_time'] = date("Y-m-d H:i:s", $item['equipment_up_end_time']);
                    }
                    if (!empty($item['equipment_down_end_time'])){
                        $list[$k]['equipment_down_end_time'] = date("Y-m-d H:i:s", $item['equipment_down_end_time']);
                    }
                }
            }
            return compact('list', 'count','page','limit');
        }catch (\Exception $exception){
            throw new \Exception($exception->getMessage(), 500);
        }
    }

    /**
     * Notes:获取会员设备详情
     * @param int $equipment_id
     * @return array
     * @throws \Exception
     * User: ZQ
     * Date: 2022/9/23
     */
    public static function userEquipmentInfo($equipment_id)
    {
        try {
            $where = [];
            $where['equipment_id']  = $equipment_id;
            $where['equipment_del'] = 0;
            $data = IntelligenceEquipment::equipmentInfor($where);
            if(!empty($data))
            {
                if (empty($data['user_nickname'])){
                    $data['username'] = $data['user_account'];
                }else{
                    $data['username'] = $data['user_nickname'];
                }
                $data['equipment_create_time'] = date("Y-m-d H:i:s", $data['equipment_create_time']);
                if (!empty($data['equipment_update_time'])){
                    $data['equipment_update_time'] = date("Y-m-d H:i:s", $data['equipment_update_time']);
                }
                if (!empty($data['equipment_up_end_time'])){
                    $data['equipment_up_end_time'] = date("Y-m-d H:i:s", $data['equipment_up_end_time']);
                }
                if (!empty($data['equipment_down_end_time'])){
                    $data['equipment_down_end_time'] = date("Y-m-d H:i:s", $data['equipment_down_end_time']);
                }

            }
            return $data;
        }catch (\Exception $exception){
            throw new \Exception($exception->getMessage(), 500);
        }
    }

    /**
     * Notes:获取设备消息列表
     * @param int $log_user_id
     * @param int $log_equipment_id
     * @return array
     * @throws \Exception
     * User: ZQ
     * Date: 2022/9/23
     */
    public static function getEquipmentLog(int $page,int $limit, $log_user_id, $log_equipment_id)
    {
        try {
            [$list,$count] = IntelligenceLog::equipmentLogList($page, $limit, $log_user_id, $log_equipment_id);
            if(!empty($list))
            {
                foreach ($list as $k => $item)
                {
                    $log_content = json_decode($item['log_content'],true);
                    $content = [];
                    $content[0]['产品id'] = $log_content['productId'] ? $log_content['productId'] : '' ;
                    $content[1]['消息类型'] = $log_content['messageType'] ? $log_content['messageType'] : '';
                    $content[2]['IMEI'] = $log_content['IMEI'] ? $log_content['IMEI'] : '';
                    $content[3]['产品类型'] = $log_content['payload']['serviceData']['devicetype'] ? $log_content['payload']['serviceData']['devicetype'] : '';
                    $content[4]['设备id'] = $log_content['deviceId'] ? $log_content['deviceId'] : '';
                    $list[$k]['log_content'] = $content;
                    $list[$k]['log_create_time'] = date("Y-m-d H:i:s", $item['log_create_time']);
                    if (!empty($item['log_update_time'])){
                        $list[$k]['log_update_time'] = date("Y-m-d H:i:s", $item['log_update_time']);
                    }
                }
            }
            return compact('list', 'count','page','limit');
        }catch (\Exception $exception){
            throw new \Exception($exception->getMessage(), 500);
        }
    }

    /**
     * Notes:获取会员设备详情
     * @param int $log_id
     * @return array
     * @throws \Exception
     * User: ZQ
     * Date: 2022/9/23
     */
    public static function equipmentLogInfo($log_id)
    {
        try {
            $where = [];
            $where['log_id']  = $log_id;
            $data = IntelligenceLog::logInfor($where);
            if(!empty($data))
            {
                $log_content = json_decode($data['log_content'],true);
                $content = [];
                $content[0]['产品id'] = $log_content['productId'] ? $log_content['productId'] : '' ;
                $content[1]['消息类型'] = $log_content['messageType'] ? $log_content['messageType'] : '';
                $content[2]['IMEI'] = $log_content['IMEI'] ? $log_content['IMEI'] : '';
                $content[3]['产品类型'] = $log_content['payload']['serviceData']['devicetype'] ? $log_content['payload']['serviceData']['devicetype'] : '';
                $content[4]['设备id'] = $log_content['deviceId'] ? $log_content['deviceId'] : '';
                $data['log_content'] = $content;
                $data['log_create_time'] = date("Y-m-d H:i:s", $data['log_create_time']);
                if (!empty($data['log_update_time'])){
                    $data['log_update_time'] = date("Y-m-d H:i:s", $data['log_update_time']);
                }
            }
            return $data;
        }catch (\Exception $exception){
            throw new \Exception($exception->getMessage(), 500);
        }
    }

    /**
     * Notes:赠送权益包
     * @param $user_id
     * @param $package_id
     * @param $type
     * @param $admin_id
     * @return bool
     * @throws \Exception
     * User: yym
     * Date: 2022/11/21
     */
    public static function givePackage($user_id, $package_id, $type, $admin_id)
    {
        UserPackageLog::affairBegin();
        try {
            //检测会员是否已赠送或购买此套餐包
            $info = UserPackageLog::getInfo($package_id, $user_id);
            if(!empty($info))
            {
                throw new \Exception('会员该套餐包已存在，无法继续赠送');
            }
            //生成订单记录
            $order_id = PackageServer::givePackage($user_id, $package_id);
            if(empty($order_id))
            {
                throw new \Exception('赠送失败！');
            }
            //生成套餐包记录
            $package_info = Package::getInfo($package_id);
            if(empty($package_info))
            {
                throw new \Exception('套餐包不存在！');
            }
            foreach ($package_info['goods'] as $item)
            {
                $insert = array(
                    'log_user_id' => $user_id,
                    'log_package_id' => $package_id,
                    'log_package_goods_id' => $item['goods_id'],
                    'log_package_status' => UserPackageLog::NORMAL,
                    'log_server_number' => $item['goods_num'],
                    'log_server_type' => $item['goods_num_type'],
                    'log_server_unit' => $item['goods_num_unit'],
                    'log_type' => $type,
                    'log_add_time' => time(),
                    'log_update_time' => time()
                );
                UserPackageLog::insertData($insert);
            }
            User::updateMember($user_id, ['user_package_status' => User::PACKAGE_YES, 'user_package_id' => $package_id, 'user_type' => User::FORMAL]);
            UserPackageLog::affairCommit();
            plog('user.give.package', '会员-赠送-权益包', '管理员：' . $admin_id . '赠送会员：' . $user_id . '权益包：' . $package_id);
            return true;
        }catch (\Exception $exception){
            UserPackageLog::affairRollback();
            throw new \Exception($exception->getMessage(), 500);
        }
    }
    /**
     * Notes:获取会员下亲属关系列表
     * @param int $log_id
     * @return array
     * @throws \Exception
     * User: ZQ
     * Date: 2022/11/15
     */
    public static function relativesList($relatives_user_id)
    {
        try {
            $where = [];
            $where['relatives_user_id']  = $relatives_user_id;
            $where['relatives_del'] = 0;
            $list = UserRelatives::select(['user_relatives.*','user.user_real_name'])
                    ->where($where)
                    ->leftJoin('user','user_id','=','user_relatives.relatives_user_id')
                    ->orderBy('relatives_add_time','DESC')
                    ->get()->toArray();
            if(!empty($list))
            {
                foreach ($list as $k => $item)
                {
                    $list[$k]['relatives_add_time'] = date("Y-m-d H:i:s", $item['relatives_add_time']);
                    if (!empty($item['relatives_update_time'])){
                        $list[$k]['relatives_update_time'] = date("Y-m-d H:i:s", $item['relatives_update_time']);
                    }
                }
            }
            return $list;
        }catch (\Exception $exception){
            throw new \Exception($exception->getMessage(), 500);
        }
    }

    /**
     * Notes:获取会员亲属关系列表
     * @param int $log_id
     * @return array
     * @throws \Exception
     * User: ZQ
     * Date: 2022/11/11
     */
    public static function relativesToList($page,$limit,$keywords)
    {
        try {
            [$list,$count] = UserRelatives::getrelativesList($page,$limit,$keywords);
            if(!empty($list))
            {
                foreach ($list as $k => $item)
                {
                    $list[$k]['relatives_add_time'] = date("Y-m-d H:i:s", $item['relatives_add_time']);
                    if (!empty($item['relatives_update_time'])){
                        $list[$k]['relatives_update_time'] = date("Y-m-d H:i:s", $item['relatives_update_time']);
                    }
                }
            }
            return compact('list', 'page', 'limit', 'count');
        }catch (\Exception $exception){
            throw new \Exception($exception->getMessage(), 500);
        }
    }

    /**
     * Notes:删除会员亲属关系
     * @param int $category_id
     * @return int
     * User: ZQ
     * Date: 2022/9/3
     */
    public static function relativesDel($relatives_id,$admin_id)
    {
        UserRelatives::affairBegin();
        try {
            $where = [];
            $where['relatives_id'] = $relatives_id;
            $data['relatives_del'] = 1;
            $result = UserRelatives::where($where)->update($data);
            if (!empty($result)){
                $msg = '管理员：' . $admin_id . '在：' . date("Y-m-d H:i:s", time()) . '删除会员亲属关系-编号: ' . $relatives_id;
                plog('user-relatives-del', '会员-亲属关系-删除亲属关系', $msg);
                UserRelatives::affairCommit();
                return true;
            }
            throw new \Exception('删除失败！');
        }catch (\Exception $exception){
            UserRelatives::affairRollback();
            throw new \Exception($exception->getMessage(), 500);
        }
    }

    /**
     * Notes:获取会员下亲属关系列表
     * @param int $log_id
     * @return array
     * @throws \Exception
     * User: ZQ
     * Date: 2022/11/15
     */
    public static function equipmentList($equipment_user_id)
    {
        try {
            $where = [];
            $where['equipment_user_id']  = $equipment_user_id;
            $where['equipment_del'] = 0;
            $list = IntelligenceEquipment::select(['user_intelligence_equipment.*','intelligence_products.product_name'])
                ->where($where)
                ->leftJoin('intelligence_products','product_id','=','user_intelligence_equipment.equipment_intelligence_id')
                ->orderBy('equipment_create_time','DESC')
                ->get()->toArray();
            if(!empty($list))
            {
                foreach ($list as $k => $item)
                {
                    $list[$k]['equipment_create_time'] = date("Y-m-d H:i:s", $item['equipment_create_time']);
                    $list[$k]['equipment_up_end_time'] = $list[$k]['equipment_up_end_time'] ? date("Y-m-d H:i:s", $item['equipment_up_end_time']) : '';
                    $list[$k]['equipment_down_end_time'] = $list[$k]['equipment_down_end_time'] ? date("Y-m-d H:i:s", $item['equipment_down_end_time']) : '';
                    $list[$k]['equipment_update_time'] = $list[$k]['equipment_update_time'] ? date("Y-m-d H:i:s", $item['equipment_update_time']) : '';
                }
            }
            return $list;
        }catch (\Exception $exception){
            throw new \Exception($exception->getMessage(), 500);
        }
    }

    /**
     * Notes: 添加设备
     * @return int
     * User: ZQ
     * Date: 2022/11/14
     */
    public static function insertEquipment($admin_id, $equipment_intelligence_id, $equipment_user_id, $equipment_name, $equipment_only,$equipment_type,$equipment_class,$equipment_tripartite_sn,$equipment_status,$equipment_property_id)
    {

        IntelligenceEquipment::affairBegin();
        try {
            $data = [];
            $data['equipment_intelligence_id'] = $equipment_intelligence_id;
            $data['equipment_user_id'] = $equipment_user_id;
            $data['equipment_name'] = $equipment_name;
            $data['equipment_only'] = $equipment_only;
            $data['equipment_type'] = $equipment_type;
            $data['equipment_class'] = $equipment_class;
            $data['equipment_tripartite_sn'] = $equipment_tripartite_sn;
            $data['equipment_status'] = $equipment_status;
            $data['equipment_property_id'] = $equipment_property_id;
            $data['equipment_create_time'] = time();
            $result =  IntelligenceEquipment::insertGetId($data);
            if (!empty($result)){
                $msg = '管理员：' . $admin_id . '在：' . date("Y-m-d H:i:s", time()) . '添加会员智能设备-编号: ' . $result;
                plog('user-equipment-create', '会员-智能设备-添加智能设备', $msg);
                IntelligenceEquipment::affairCommit();
                return $result;
            }
            throw new \Exception('操作失败！');
        }catch (\Exception $exception){
            IntelligenceEquipment::affairRollback();
            throw new \Exception($exception->getMessage(), 500);
        }
    }

    /**
     * Notes:查询会员设备唯一编码
     * @param int $category_id
     * @return int
     * User: ZQ
     * Date: 2022/11/15
     */
    public static function equipmentCheck($equipment_only)
    {
        try {
            $where = [];
            $where['equipment_only'] = $equipment_only;
            $where['equipment_del'] = 0;
            $result = IntelligenceEquipment::where($where)->first();
            if (!empty($result)){
                return $result;
            }else{
                return false;
            }
            throw new \Exception('查询失败！');
        }catch (\Exception $exception){
            throw new \Exception($exception->getMessage(), 500);
        }
    }

    /**
     * Notes:删除会员亲属关系
     * @param int $category_id
     * @return int
     * User: ZQ
     * Date: 2022/11/15
     */
    public static function equipmentDel($equipment_id,$admin_id)
    {
        IntelligenceEquipment::affairBegin();
        try {
            $where = [];
            $where['equipment_id'] = $equipment_id;
            $data['equipment_del'] = 1;
            $result = IntelligenceEquipment::where($where)->update($data);
            if (!empty($result)){
                $msg = '管理员：' . $admin_id . '在：' . date("Y-m-d H:i:s", time()) . '删除会员智能产品设备-编号: ' . $equipment_id;
                plog('user-relatives-del', '会员-智能产品设备-删除智能产品设备', $msg);
                IntelligenceEquipment::affairCommit();
                return true;
            }
            throw new \Exception('删除失败！');
        }catch (\Exception $exception){
            IntelligenceEquipment::affairRollback();
            throw new \Exception($exception->getMessage(), 500);
        }
    }

    /**
     * Notes:获取会员固定资产列表
     * @param int $property_user_id
     * @return array
     * @throws \Exception
     * User: ZQ
     * Date: 2022/11/23
     */
    public static function propertyList($property_user_id)
    {
        try {
            $where = [];
            $where['property_del'] = 0;
            $where['property_status'] = 0;
            $where['property_user_id'] = $property_user_id;
            $list = UserProperty::where($where)->select()->get()->toArray();
            return $list;
        }catch (\Exception $exception){
            throw new \Exception($exception->getMessage(), 500);
        }
    }

    /**
     * Notes:添加医生医嘱
     * @param int $log_user_id
     * @return array
     * @throws \Exception
     * User: ZQ
     * Date: 2022/12/8
     */
    public static function doctorInsert($log_user_id, $log_type, $log_equipment_id, $log_doctor_id, $log_subject_id, $log_message, $log_resolvent, $admin_id)
    {
        UserDoctorsLog::affairBegin();
        try {
            $data = [];
            $data['log_user_id'] = $log_user_id;
            $data['log_type'] = $log_type;
            $data['log_equipment_id'] = $log_equipment_id;
            $data['log_doctor_id'] = $log_doctor_id;
            $data['log_subject_id'] = $log_subject_id;
            $data['log_message'] = $log_message;
            $data['log_resolvent'] = $log_resolvent;
            $data['log_add_time'] = time();
            $result = UserDoctorsLog::insertGetId($data);
            if (!empty($result)){
                $msg = '管理员：' . $admin_id . '在：' . date("Y-m-d H:i:s", time()) . '添加会员医生医嘱-编号: ' . $result;
                plog('user-relatives-del', '会员-医生医嘱-添加会员医生医嘱', $msg);
                UserDoctorsLog::affairCommit();
                return true;
            }
            throw new \Exception('添加失败！');
        }catch (\Exception $exception){
            UserDoctorsLog::affairRollback();
            throw new \Exception($exception->getMessage(), 500);
        }
    }

    /**
     * Notes:会员医生医嘱列表
     * @param int $log_user_id
     * @param int $page
     * @param int $limit
     * @return array
     * @throws \Exception
     * User: ZQ
     * Date: 2022/12/8
     */
    public static function doctorList($log_user_id, $page, $limit)
    {
        [$list,$count] = UserDoctorsLog::doctorLogList($log_user_id, $page, $limit);
        if (!empty($list)){
            foreach ($list as $k => $v){
                $list[$k]['log_add_time'] = date('Y-m-d H:i:s',$v['log_add_time']);
            }
        }
        return compact('list', 'count');
    }

    /**
     * Notes:删除会员医生医嘱
     * @param int $log_user_id
     * @param int $log_id
     * @param int $admin_id
     * @return array
     * @throws \Exception
     * User: ZQ
     * Date: 2022/12/8
     */
    public static function doctorDel($log_user_id, $log_id, $admin_id)
    {
        UserDoctorsLog::affairBegin();
        try {
            $where = [];
            $where['log_id'] = $log_id;
            $where['log_user_id'] = $log_user_id;
            $result = UserDoctorsLog::where($where)->delete();
            if (!empty($result)){
                $msg = '管理员：' . $admin_id . '在：' . date("Y-m-d H:i:s", time()) . '删除会员医生医嘱-编号: ' . $log_id;
                plog('user-relatives-del', '会员-医生医嘱-删除会员医生医嘱', $msg);
                UserDoctorsLog::affairCommit();
                return true;
            }
            throw new \Exception('删除失败！');
        }catch (\Exception $exception){
            UserDoctorsLog::affairRollback();
            throw new \Exception($exception->getMessage(), 500);
        }
    }

    /**
     * Notes:删除会员健康基础数据
     * @param int $data_id
     * @param int $data_user_id
     * @param int $admin_id
     * @return array
     * @throws \Exception
     * User: ZQ
     * Date: 2022/12/8
     */
    public static function healthyDel($data_user_id, $admin_id)
    {
        UserBasicHealthData::affairBegin();
        try {
            $where = [];
            $where['data_user_id'] = $data_user_id;
            $result = UserBasicHealthData::where($where)->delete();
            if (!empty($result)){
                $msg = '管理员：' . $admin_id . '在：' . date("Y-m-d H:i:s", time()) . '删除会员健康基础数据-编号: ' . $data_user_id;
                plog('user-relatives-del', '会员-健康基础数据-删除会员健康基础数据', $msg);
                UserBasicHealthData::affairCommit();
                return true;
            }
            throw new \Exception('删除失败！');
        }catch (\Exception $exception){
            UserBasicHealthData::affairRollback();
            throw new \Exception($exception->getMessage(), 500);
        }
    }

    /**
     * Notes:修改会员健康基础数据
     * @param int $data_id
     * @param string $data_Inspection_suggestions
     * @param string $data_bone_density
     * @param string $data_tcm_testing
     * @param int $admin_id
     * @return array
     * @throws \Exception
     * User: ZQ
     * Date: 2022/12/8
     */
    public static function healthyUpdate($data_user_id, $data_Inspection_suggestions, $data_bone_density, $data_tcm_testing, $admin_id)
    {
        UserBasicHealthData::affairBegin();
        try {
            $where = [];
            $where['data_user_id'] = $data_user_id;
            $data = [];
            $data['data_update_time'] = time();
            $data['data_Inspection_suggestions'] = $data_Inspection_suggestions;
            if (!empty($data_Inspection_suggestions) && empty($data_bone_density) && empty($data_tcm_testing)){
                $result = UserBasicHealthData::where($where)->update($data);
                if (!empty($result)){
                    $msg = '管理员：' . $admin_id . '在：' . date("Y-m-d H:i:s", time()) . '修改会员健康基础数据-编号: ' . $data_user_id;
                    plog('user-relatives-del', '会员-健康基础数据-修改会员健康基础数据', $msg);
                    UserBasicHealthData::affairCommit();
                    return true;
                }
            }elseif (!empty($data_bone_density) && empty($data_tcm_testing)){
                $data['data_bone_density'] = $data_bone_density;
                $data_type = 2;
            }elseif (!empty($data_tcm_testing) && empty($data_bone_density)){
                $data['data_tcm_testing'] = $data_tcm_testing;
                $data_type = 4;
            }elseif(!empty($data_tcm_testing) && !empty($data_bone_density)){
                $data['data_bone_density'] = $data_bone_density;
                $data['data_tcm_testing'] = $data_tcm_testing;
                $data_type = 3;
            }
            $result = UserBasicHealthData::where($where)->update($data);
            if($data_type == 3){
                //插入一条记录
                $log = UserBasicHealthData::where($where)->first();
                $log = json_decode($log,true);
                unset($log['data_id']);
                unset($log['data_update_time']);
                $log['data_type'] = 2;
                $log['data_add_time'] = time();
                unset($log['data_tcm_testing']);
                $id = UserBasicHealthDataLog::insertGetId($log);
                $log['data_type'] = 4;
                unset($log['data_bone_density']);
                $log['data_tcm_testing'] = $data_tcm_testing;
                $ids = UserBasicHealthDataLog::insertGetId($log);
            }elseif($data_type == 2 || $data_type == 4){
                //插入一条记录
                $log = UserBasicHealthData::where($where)->first();
                $log = json_decode($log,true);
                unset($log['data_id']);
                unset($log['data_update_time']);
                $log['data_type'] = $data_type;
                $log['data_add_time'] = time();
                $id = UserBasicHealthDataLog::insertGetId($log);
            }
            if (!empty($result)){
                $msg = '管理员：' . $admin_id . '在：' . date("Y-m-d H:i:s", time()) . '修改会员健康基础数据-编号: ' . $data_user_id;
                plog('user-relatives-del', '会员-健康基础数据-修改会员健康基础数据', $msg);
                if(!empty($id)){
                    $msg = '管理员：' . $admin_id . '在：' . date("Y-m-d H:i:s", time()) . '添加会员健康基础数据记录-编号: ' . $id;
                    plog('user-relatives-del', '会员-健康基础数据记录-添加会员健康基础数据记录', $msg);
                }
                if(!empty($ids)){
                    $msg = '管理员：' . $admin_id . '在：' . date("Y-m-d H:i:s", time()) . '添加会员健康基础数据记录-编号: ' . $ids;
                plog('user-relatives-del', '会员-健康基础数据记录-添加会员健康基础数据记录', $msg);
                }
                UserBasicHealthData::affairCommit();
                return true;
            }
            throw new \Exception('修改失败！');
        }catch (\Exception $exception){
            UserBasicHealthData::affairRollback();
            throw new \Exception($exception->getMessage(), 500);
        }
    }

    /**
     * Notes:查询会员健康基础数据
     * @param int $data_id
     * @param int $data_user_id
     * @return array
     * @throws \Exception
     * User: ZQ
     * Date: 2022/12/8
     */
    public static function healthyInfo($data_user_id)
    {
        $where = [];
        $where['data_user_id'] = $data_user_id;
        $data = UserBasicHealthData::where($where)->first();
        if (!empty($data)){
            $data['data_add_time'] = date('Y-m-d H:i:s',$data['data_add_time']);
            $data['data_update_time'] = $data['data_update_time'] ? date('Y-m-d H:i:s',$data['data_update_time']) : '';
        }
        return $data;
    }

}
