<?php
/*
 * description：
 * author：wh
 * email：
 * createTime：{2022/01/18} {16:24} 
 */


namespace app\index\model;

use app\apidata\Config;
use app\common\model\TabConf;
use think\Db;

class WechatUserModel extends \app\index\model\BaseModel
{

    /**
     * desc：
     * author：wh
     * @param $wx_user_info \app\index\model\微信用户
     *
     * {
     * "openid":"or9D2vs863Ky5Py2ovkAiu9XFLO4",
     * "nickname":"起源果蔬副食大华",
     * "sex":0,
     * "language":"",
     * "city":"",
     * "province":"",
     * "country":"",
     * "headimgurl":"https://thirdwx.qlogo.cn/mmopen/vi_32/joiaA475nx3fJiaqx0ibdnWo4A7Q3uCgu2hsribI0ATLItORjuUgCSP8mCaBkqL61ibGojib4pQYX1djUhZpF5zoqpSg/132",
     * "privilege":[]
     * }
     */
    static function insertInfo(array $wx_user_info)
    {

        if (isset($wx_user_info['privilege'])) {
            $wx_user_info['privilege'] = json_encode($wx_user_info['privilege']);
        }
        $data = [
            'nickname' => $wx_user_info['nickname'],
            'country' => $wx_user_info['country'],
            'province' => $wx_user_info['province'],
            'city' => $wx_user_info['city'],
            'headimage' => $wx_user_info['headimgurl'],
            'language' => $wx_user_info['language'],
            'openid' => $wx_user_info['openid'],
            'unionid' => isset($wx_user_info['unionid']) ? $wx_user_info['unionid'] : '',
            'privilege' => $wx_user_info['privilege'],
            'sex' => $wx_user_info['sex'],
            'arm_group' => '',
            'score' => 0,//积分
            'group_buy_earnings' => 0,//拼团收益
            'water_drop_balance' => 0,//水滴
        ];
        self::tab(TabConf::$fa_wechatuser)
            ->data($data)
            ->insert();
    }

    /**
     * desc：更新用户信息
     *
     * author：wh
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    static function updateUser($wx_user_info)
    {
        $data = [
            'nickname' => $wx_user_info['nickname'],
            'headimage' => $wx_user_info['headimgurl'],
            'unionid' => isset($wx_user_info['unionid']) ? $wx_user_info['unionid'] : '',
        ];
        self::tab(TabConf::$fa_wechatuser)
            ->data($data)
            ->where('openid', index_user_openid())
            ->update();
    }

    /**
     * desc：
     * author：wh
     * @param string $unionid
     * @return array|bool|\PDOStatement|string|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    static function getWxUserByUnionid(string $unionid)
    {
        return Db::table(TabConf::$fa_wechatuser)
            ->field('id')
            ->where('unionid', $unionid)
            ->find();
    }

    /**
     * desc：
     * author：wh
     * @param string $openid
     * @return array|bool|\PDOStatement|string|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    static function getWxUserByOpenid(string $openid)
    {
        return Db::table(TabConf::$fa_wechatuser)
            //->field('id')
            ->where('openid', $openid)
            ->find();
    }

    /**
     * desc：
     * author：wh
     * @param string $openid
     * @return array|bool|\PDOStatement|string|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    static function getNicknameByOpenid(string $openid)
    {
        return Db::table(TabConf::$fa_wechatuser)
            ->where('openid', $openid)
            ->value('nickname');
    }


    /**
     * desc：增加店铺会员积分
     *
     * author：wh
     */
    static function addShopMemberScore(string $openid, $shop_member_score)
    {
        Db::table(TabConf::$fa_wechatuser)
            ->where('openid', $openid)
            ->setInc('shop_member_score', $shop_member_score);
    }


    /**
     * desc：增加积分、积分变动记录
     * author：wh
     */
    static function addScore(string $openid, $order_real_amount)
    {
        $score = $order_real_amount * 100;
        //用户
        $user = Db::table(TabConf::$fa_wechatuser)
            ->where('openid', $openid)
            ->find();
        //增加积分变动记录
        Db::table(TabConf::$fa_score_change_record)
            ->data([
                'nickname' => $user['nickname'],
                'openid' => $user['openid'],
                'score' => $score,
                'score_before' => $user['score'],
                'score_after' => $user['score'] + $score,
                'from' => 'main_store_goods_buy_order',
            ])
            ->insert();
        //增加积分
        return self::tab(TabConf::$fa_wechatuser)
            ->where('openid', $openid)
            ->setInc('score', $score);//分为单位

    }

    /**
     * desc：减去积分 扣除积分、积分变动记录
     * author：wh
     */
    static function deductScore(string $openid, $order_real_amount, $remark = '')
    {
        $score = $order_real_amount * 100;
        //用户
        $user = Db::table(TabConf::$fa_wechatuser)
            ->where('openid', $openid)
            ->find();
        //增加积分变动记录
        Db::table(TabConf::$fa_score_change_record)
            ->data([
                'nickname' => $user['nickname'],
                'openid' => $user['openid'],
                'score' => -$score,
                'score_before' => $user['score'],
                'score_after' => $user['score'] - $score,
                'from' => 'system_deduct_score',//系统冲扣积分
                'remark' => $remark,
            ])
            ->insert();
        //增加积分
        return self::tab(TabConf::$fa_wechatuser)
            ->where('openid', $openid)
            ->setDec('score', $score);//分为单位

    }

    /**
     * desc：积分冲补
     *
     * author：wh
     * @param string $openid
     * @param $order_real_amount
     * @param string $remark
     * @return bool|int|string|true
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    static function repairScore(string $openid, $order_real_amount, $remark = '')
    {
        $score = $order_real_amount * 100;
        //用户
        $user = Db::table(TabConf::$fa_wechatuser)
            ->where('openid', $openid)
            ->find();
        //增加积分变动记录
        Db::table(TabConf::$fa_score_change_record)
            ->data([
                'nickname' => $user['nickname'],
                'openid' => $user['openid'],
                'score' => $score,
                'score_before' => $user['score'],
                'score_after' => $user['score'] + $score,
                'from' => 'system_repair_score',//系统冲补积分
                'remark' => $remark,
            ])
            ->insert();
        //增加积分
        return self::tab(TabConf::$fa_wechatuser)
            ->where('openid', $openid)
            ->setInc('score', $score);//分为单位

    }

    /**
     * desc：每笔订单成功之后增加水滴
     *
     * author：wh
     * @param string $openid
     * @param $order_real_amount
     * @return bool|int|string|true
     * @throws \think\Exception
     */
    static function addWaterDropBalance(string $openid, $order_real_amount)
    {
        $water_drop_basic_num = (int)Config::sundryConfigVal('water_drop_basic_num');

        $water = 0;
        if ($order_real_amount < 1) {
            $water = 1;//小于1积累1滴水滴
        } else if ($order_real_amount >= 1 && $order_real_amount < 10) {
            $water = 2;
        } else if ($order_real_amount >= 10 && $order_real_amount < 50) {
            $water = 3;
        } else if ($order_real_amount >= 50 && $order_real_amount < 100) {
            $water = 4;
        } else if ($order_real_amount >= 100 && $order_real_amount < 500) {
            $water = 5;
        } else if ($order_real_amount >= 500 && $order_real_amount < 2000) {
            $water = 6;
        } else if ($order_real_amount >= 2000) {
            $water = 7;
        }
        return self::tab(TabConf::$fa_wechatuser)
            ->where('openid', $openid)
            ->setInc('water_drop_balance', $water * $water_drop_basic_num);
    }

    /**
     * desc：实时获取用户身上的微信拼团收益
     * author：wh
     */
    static function getUserEarnings()
    {
        $val = self::tab(TabConf::$fa_wechatuser)
            ->where('openid', index_user_openid())
            ->value('group_buy_earnings');

        return 1 * $val;
    }

    static function getUserTypeByOpenid(string $openid)
    {
        return self::tab(TabConf::$fa_wechatuser)
            ->where('openid', $openid)
            ->value('user_type');
    }

    /**
     * desc：实时获取用户身上的积分
     * author：wh
     */
    static function getUserScore()
    {
        return self::tab(TabConf::$fa_wechatuser)
            ->where('openid', index_user_openid())
            ->value('score');
    }

    /**
     * desc：实时获取用户身上的水滴
     * author：wh
     */
    static function getUserWater()
    {
        return self::tab(TabConf::$fa_wechatuser)
            ->where('openid', index_user_openid())
            ->value('water_drop_balance');
    }
}