<?php
/*
 * @Author: taowj 965042433@qq.com
 * @Date: 2023-06-06 16:07:57
 * @LastEditors: taowj 965042433@qq.com
 * @LastEditTime: 2023-06-08 15:15:08
 * @FilePath: \introducer\application\api\controller\Commission.php
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

/**
 * Created by PhpStorm.
 * 分销相关接口
 * User: pc
 * Date: 2022/11/4
 * Time: 13:55
 */

namespace app\api\controller\shopro;

use app\admin\controller\users\Agent;
use app\common\controller\Api;
use app\admin\model\users\Users as UsersModel;
use app\admin\model\UserMoneyLog;
use app\admin\model\shopro\order\Goodsorder as GoodsorderModel;
use app\admin\model\shopro\order\Rechargeorder as RechargeorderModel;
use app\admin\model\users\Agent as AgentModel;
use app\admin\model\shopro\goods\Goods as GoodsModel;
use app\api\model\PaymentLogModel;
use think\config;
use think\Db;
use think\Exception;
use think\Log;

class Commission extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    /**
     * 扫充值码绑定关系
     */
    public function scanRechargeCode()
    {
        $user_id = $this->auth->id;
        //邀请人
        $pid = $this->request->post('user_id', 0);
        //绑定关系
        UsersModel::where(['id' => $user_id])->update(['pid' => $pid, 'pid_time' => time()]);
        $this->success('扫码成功');
    }
    /**
     * 展示邀请码
     */
    public function displayInviteCode()
    {
        $user_id = $this->auth->id;
        $agentInfo = AgentModel::where(['agent_user_id' => $user_id, 'status' => 1, 'level' => ['>', 0]])->find();
        if (!$agentInfo) {
            $this->error('您还不是团长，无法邀请他人');
        }
        $data['type'] = 2; //二维码类型 1=邀请锁客,2=商城分销专用二维码
        $data['user_id'] = $user_id;
        if (!$agentInfo['invite_code']) {
            $url = createQrcode($data, $data['type']);
            AgentModel::where(['agent_user_id' => $user_id])->update(['invite_code' => $url]);
        } else {
            $url = $agentInfo['invite_code'];
        }
        $this->success('获取邀请码成功', ['url' => $url]);
    }
    /**
     * 通过核销码查询订单信息
     */
    public function findOrderByCode()
    {
        //核销码
        $code = $this->request->post('verification_code', '');
        //通过核销码查询订单信息
        $orderInfo = GoodsorderModel::where(['verification_code' => $code])->find();
        if (!$orderInfo) {
            $this->error('核销码输入错误!');
        }
        if ($orderInfo['status'] == 3) {
            $this->error('该核销码已使用过!');
        }
        $goodsList = GoodsModel::where(['goods_id' => $orderInfo['goods_id']])->select();
        $this->success('订单查询成功', ['orderInfo' => $orderInfo, 'goodsInfo' => $goodsList]);
    }
    /**
     * 自提订单核销
     */
    public function checkCode()
    {
        $user_id = $this->auth->id;
        $code = $this->request->post('verification_code', ''); //核销码
        //查看当前核销人员是否有核销资格
        $agentInfo = AgentModel::where(['agent_user_id' => $user_id, 'status' => 1, 'level' => ['>', 0]])->find();
        if (!$agentInfo) {
            $this->error('您不是团长，无法核销订单');
        }
        //查看核销码对应的订单是否存在
        $orderInfo = GoodsorderModel::where(['verification_code' => $code, 'delivery_type' => 1, 'status' => 2])->find();
        if (!$orderInfo) {
            $this->error('核销码错误');
        }
        //更新订单状态为已完成
        GoodsorderModel::where(['verification_code' => $code, 'delivery_type' => 1, 'status' => 2])->update(['status' => 3, 'updatetime' => time()]);
        //核销记录
        $data = [
            'user_id' => $user_id,
            'money' => 0,
            'before' => 0,
            'after' => 0,
            'memo' => $code,
            'type' => 12,
            'createtime' => time(),
            'transfer_user_id' => $orderInfo['user_id'],
            'order_id' => $orderInfo['id']
        ];
        UserMoneyLog::create($data);
        $this->success('订单核销成功');
    }
    /**
     * 核销记录查询,团长核销过的订单
     */
    public function checkCodeLog()
    {
        //团长ID
        $user_id = $this->auth->id;
        $page = $this->request->post('page', 1);
        $checkCodeLog = UserMoneyLog::field("id,user_id,memo as verification_code,FROM_UNIXTIME(createtime,'%Y-%m-%d %T') as createtime,transfer_user_id,order_id")
            ->where(['user_id' => $user_id, 'type' => 12])
            ->order('createtime desc')
            ->page($page)
            ->limit($this->pageSize)
            ->select();
        $this->success('核销记录查询成功', ['checkCodeLog' => $checkCodeLog]);
    }
    /**
     * 邀请记录
     */
    public function shareList()
    {
        $page = $this->request->post('page', 1);
        $user_id = $this->auth->id;
        $shareList = UsersModel::field("id,nickname,avatar,FROM_UNIXTIME(pid_time,'%Y-%m-%d %T') as pid_time")
            ->where(['pid' => $user_id])
            ->order('pid_time desc')
            ->page($page)
            ->limit($this->pageSize)
            ->select();
        $this->success('查询邀请记录成功', ['shareList' => $shareList]);
    }
    /**
     * 团长收益明细
     */
    public function commissionDetail()
    {
        $page = $this->request->post('page', 1);
        //用户id
        $user_id = $this->auth->id;
        //查询商城分销奖励明细
        $userMoneyLog = UserMoneyLog::field("id,user_id,money,memo,type,FROM_UNIXTIME(createtime,'%Y-%m-%d %T') as createtime,order_id")
            ->where(['user_id' => $user_id, 'type' => ['in', [10, 11]]])
            ->order('createtime desc')
            ->page($page)
            ->limit($this->pageSize)
            ->select();
        $this->success('查询收益明细成功', ['moneyLog' => $userMoneyLog]);
    }
    /**
     * 订单分佣,充值订单在生成充值订单后立即分佣，购物订单在已完成后进行分佣
     */
    public static function divideCommission($order_sn = 0)
    {
        //查询支付信息
        $payLog = PaymentLogModel::where(['order_sn' => $order_sn, 'status' => 2, 'pay_way' => ['in', ['weixin', 'alipay']]])->find();
        if ($payLog) {
            try {
                Db::startTrans();
                //判断订单类型为充值订单
                if ($payLog['order_type'] == 'recharge') {
                    //判断充值订单是否已支付
                    $orderInfo = RechargeorderModel::where(['id' => $payLog['order_id']])->find();
                    if ($orderInfo['status'] == 'paid') {
                        //判断充值订单是否已进行过分佣
                        $moneyLog = UserMoneyLog::where(['order_id' => $payLog['order_id'], 'type' => 10])->find();
                        //查找上级团长
                        $userInfo = UsersModel::where(['id' => $payLog['user_id']])->find();
                        if (!$moneyLog) {
                            $pAgentInfo = AgentModel::where(['agent_user_id' => $userInfo['pid'], 'status' => 1])->find();
                            if ($pAgentInfo) {
                                //获取分佣比例
                                $commissionRate = Config::get('site.recharge_commission_rate');
                                //获取团长资金情况
                                $puserInfo = UsersModel::where(['id' => $userInfo['pid']])->find();
                                //判断团长身份等级
                                if ($pAgentInfo['level'] == 3) {
                                    //上级团长是市级代理，则获得所有层级分佣
                                    $money = sprintf("%.2f", 100 * ($commissionRate['maker'] + $commissionRate['area'] + $commissionRate['city']));
                                    //分佣记录
                                    $data = [
                                        'user_id' => $userInfo['pid'],
                                        'money' => $money,
                                        'before' => $puserInfo['total_money'],
                                        'after' => $puserInfo['total_money'] + $money,
                                        'memo' => '充值订单(ID:' . $payLog['order_id'] . ')市级代理分佣',
                                        'type' => 10,
                                        'createtime' => time(),
                                        'order_id' => $payLog['order_id'],
                                        'logs_id' => $payLog['id']
                                    ];
                                    UserMoneyLog::create($data);
                                    //钱包加钱
                                    UsersModel::where(['id' => $userInfo['pid']])->setInc('total_money', $money);
                                } elseif ($pAgentInfo['level'] == 2) {
                                    //上级团长是区县级代理，则获得区县级和团长分佣
                                    $money = sprintf("%.2f", 100 * ($commissionRate['maker'] + $commissionRate['area']));
                                    //分佣记录
                                    $data = [
                                        'user_id' => $userInfo['pid'],
                                        'money' => $money,
                                        'before' => $puserInfo['total_money'],
                                        'after' => $puserInfo['total_money'] + $money,
                                        'memo' => '充值订单(ID:' . $payLog['order_id'] . ')区县代理分佣',
                                        'type' => 10,
                                        'createtime' => time(),
                                        'order_id' => $payLog['order_id'],
                                        'logs_id' => $payLog['id']
                                    ];
                                    UserMoneyLog::create($data);
                                    //钱包加钱
                                    UsersModel::where(['id' => $userInfo['pid']])->setInc('total_money', $money);
                                    //市级分佣，查找市级代理商
                                    $cityAgent = AgentModel::where(['city_id' => $pAgentInfo['city_id'], 'status' => 1, 'level' => 3])->find();
                                    if ($cityAgent) {
                                        $money = sprintf("%.2f", 100 * $commissionRate['city']);
                                        //查找市级代理用户信息
                                        $cityAgentUserInfo = UsersModel::where(['id' => $cityAgent['agent_user_id']])->find();
                                        if ($cityAgentUserInfo) {
                                            //分佣记录
                                            $data = [
                                                'user_id' => $cityAgent['agent_user_id'],
                                                'money' => $money,
                                                'before' => $cityAgentUserInfo['total_money'],
                                                'after' => $cityAgentUserInfo['total_money'] + $money,
                                                'memo' => '充值订单(ID:' . $payLog['order_id'] . ')市级代理分佣',
                                                'type' => 10,
                                                'createtime' => time(),
                                                'order_id' => $payLog['order_id'],
                                                'logs_id' => $payLog['id']
                                            ];
                                            UserMoneyLog::create($data);
                                            //钱包加钱
                                            UsersModel::where(['id' => $cityAgent['agent_user_id']])->setInc('total_money', $money);
                                        }
                                    }
                                } elseif ($pAgentInfo['level'] == 1) {
                                    //上级团长只是团长，则只获得团长分佣
                                    $money = sprintf("%.2f", 100 * $commissionRate['maker']);
                                    //分佣记录
                                    $data = [
                                        'user_id' => $userInfo['pid'],
                                        'money' => $money,
                                        'before' => $puserInfo['total_money'],
                                        'after' => $puserInfo['total_money'] + $money,
                                        'memo' => '充值订单(ID:' . $payLog['order_id'] . ')团长分佣',
                                        'type' => 10,
                                        'createtime' => time(),
                                        'order_id' => $payLog['order_id'],
                                        'logs_id' => $payLog['id']
                                    ];
                                    UserMoneyLog::create($data);
                                    //钱包加钱
                                    UsersModel::where(['id' => $userInfo['pid']])->setInc('total_money', $money);
                                    //区县分佣,查找区县代理
                                    $areaAgent = AgentModel::where(['area_id' => $pAgentInfo['area_id'], 'status' => 1, 'level' => 2])->find();
                                    if ($areaAgent) {
                                        //获取区县代理用户信息
                                        $areaAgentUserInfo = UsersModel::where(['id' => $areaAgent['agent_user_id']])->find();
                                        $money = sprintf("%.2f", 100 * $commissionRate['area']);
                                        //分佣记录
                                        $data = [
                                            'user_id' => $areaAgent['agent_user_id'],
                                            'money' => $money,
                                            'before' => $areaAgentUserInfo['total_money'],
                                            'after' => $areaAgentUserInfo['total_money'] + $money,
                                            'memo' => '充值订单(ID:' . $payLog['order_id'] . ')区县代理分佣',
                                            'type' => 10,
                                            'createtime' => time(),
                                            'order_id' => $payLog['order_id'],
                                            'logs_id' => $payLog['id']
                                        ];
                                        UserMoneyLog::create($data);
                                        //钱包加钱
                                        UsersModel::where(['id' => $areaAgent['agent_user_id']])->setInc('total_money', $money);
                                    } else {
                                        //没有区县代理，则查找市级代理商
                                        $cityAgent = AgentModel::where(['city_id' => $pAgentInfo['city_id'], 'status' => 1, 'level' => 3])->find();
                                        if ($cityAgent) {
                                            $money = sprintf("%.2f", 100 * ($commissionRate['area'] + $commissionRate['city']));
                                            //查找市级代理用户信息
                                            $cityAgentUserInfo = UsersModel::where(['id' => $cityAgent['agent_user_id']])->find();
                                            if ($cityAgentUserInfo) {
                                                //分佣记录
                                                $data = [
                                                    'user_id' => $cityAgent['agent_user_id'],
                                                    'money' => $money,
                                                    'before' => $cityAgentUserInfo['total_money'],
                                                    'after' => $cityAgentUserInfo['total_money'] + $money,
                                                    'memo' => '充值订单(ID:' . $payLog['order_id'] . ')市级代理分佣',
                                                    'type' => 10,
                                                    'createtime' => time(),
                                                    'order_id' => $payLog['order_id'],
                                                    'logs_id' => $payLog['id']
                                                ];
                                                UserMoneyLog::create($data);
                                                //钱包加钱
                                                UsersModel::where(['id' => $cityAgent['agent_user_id']])->setInc('total_money', $money);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                } elseif ($payLog['order_type'] == 'goods') { //判断订单类型为商品订单
                    $orderInfo = GoodsorderModel::where(['id' => $payLog['order_id'], 'status' => 3])->find();
                    if ($orderInfo) {
                        //判断充值订单是否已进行过分佣
                        $moneyLog = UserMoneyLog::where(['order_id' => $payLog['order_id'], 'type' => 11])->find();
                        //查找上级团长
                        $userInfo = UsersModel::where(['id' => $payLog['user_id']])->find();
                        if (!$moneyLog) {
                            $pAgentInfo = AgentModel::where(['agent_user_id' => $userInfo['pid'], 'status' => 1])->find();
                            if ($pAgentInfo) {
                                //获取分佣比例
                                $commissionRate = Config::get('site.shop_commission_rate');
                                //获取团长资金情况
                                $puserInfo = UsersModel::where(['id' => $userInfo['pid']])->find();
                                //判断团长身份等级
                                if ($pAgentInfo['level'] == 3) {
                                    //上级团长是市级代理，则获得所有层级分佣
                                    $money = sprintf("%.2f", 100 * ($commissionRate['maker'] + $commissionRate['area'] + $commissionRate['city']));
                                    //分佣记录
                                    $data = [
                                        'user_id' => $userInfo['pid'],
                                        'money' => $money,
                                        'before' => $puserInfo['total_money'],
                                        'after' => $puserInfo['total_money'] + $money,
                                        'memo' => '购物订单(ID:' . $payLog['order_id'] . ')市级代理分佣',
                                        'type' => 11,
                                        'createtime' => time(),
                                        'order_id' => $payLog['order_id'],
                                        'logs_id' => $payLog['id']
                                    ];
                                    UserMoneyLog::create($data);
                                    //钱包加钱
                                    UsersModel::where(['id' => $userInfo['pid']])->setInc('total_money', $money);
                                } elseif ($pAgentInfo['level'] == 2) {
                                    //上级团长是区县级代理，则获得区县级和团长分佣
                                    $money = sprintf("%.2f", 100 * ($commissionRate['maker'] + $commissionRate['area']));
                                    //分佣记录
                                    $data = [
                                        'user_id' => $userInfo['pid'],
                                        'money' => $money,
                                        'before' => $puserInfo['total_money'],
                                        'after' => $puserInfo['total_money'] + $money,
                                        'memo' => '购物订单(ID:' . $payLog['order_id'] . ')区县代理分佣',
                                        'type' => 11,
                                        'createtime' => time(),
                                        'order_id' => $payLog['order_id'],
                                        'logs_id' => $payLog['id']
                                    ];
                                    UserMoneyLog::create($data);
                                    //钱包加钱
                                    UsersModel::where(['id' => $userInfo['pid']])->setInc('total_money', $money);
                                    //市级分佣，查找市级代理商
                                    $cityAgent = AgentModel::where(['city_id' => $pAgentInfo['city_id'], 'status' => 1, 'level' => 3])->find();
                                    if ($cityAgent) {
                                        $money = sprintf("%.2f", 100 * $commissionRate['city']);
                                        //查找市级代理用户信息
                                        $cityAgentUserInfo = UsersModel::where(['id' => $cityAgent['agent_user_id']])->find();
                                        if ($cityAgentUserInfo) {
                                            //分佣记录
                                            $data = [
                                                'user_id' => $cityAgent['agent_user_id'],
                                                'money' => $money,
                                                'before' => $cityAgentUserInfo['total_money'],
                                                'after' => $cityAgentUserInfo['total_money'] + $money,
                                                'memo' => '购物订单(ID:' . $payLog['order_id'] . ')市级代理分佣',
                                                'type' => 11,
                                                'createtime' => time(),
                                                'order_id' => $payLog['order_id'],
                                                'logs_id' => $payLog['id']
                                            ];
                                            UserMoneyLog::create($data);
                                            //钱包加钱
                                            UsersModel::where(['id' => $cityAgent['agent_user_id']])->setInc('total_money', $money);
                                        }
                                    }
                                } elseif ($pAgentInfo['level'] == 1) {
                                    //上级团长只是团长，则只获得团长分佣
                                    $money = sprintf("%.2f", 100 * $commissionRate['maker']);
                                    //分佣记录
                                    $data = [
                                        'user_id' => $userInfo['pid'],
                                        'money' => $money,
                                        'before' => $puserInfo['total_money'],
                                        'after' => $puserInfo['total_money'] + $money,
                                        'memo' => '购物订单(ID:' . $payLog['order_id'] . ')团长分佣',
                                        'type' => 11,
                                        'createtime' => time(),
                                        'order_id' => $payLog['order_id'],
                                        'logs_id' => $payLog['id']
                                    ];
                                    UserMoneyLog::create($data);
                                    //钱包加钱
                                    UsersModel::where(['id' => $userInfo['pid']])->setInc('total_money', $money);
                                    //区县分佣,查找区县代理
                                    $areaAgent = AgentModel::where(['area_id' => $pAgentInfo['area_id'], 'status' => 1, 'level' => 2])->find();
                                    if ($areaAgent) {
                                        //获取区县代理用户信息
                                        $areaAgentUserInfo = UsersModel::where(['id' => $areaAgent['agent_user_id']])->find();
                                        $money = sprintf("%.2f", 100 * $commissionRate['area']);
                                        //分佣记录
                                        $data = [
                                            'user_id' => $areaAgent['agent_user_id'],
                                            'money' => $money,
                                            'before' => $areaAgentUserInfo['total_money'],
                                            'after' => $areaAgentUserInfo['total_money'] + $money,
                                            'memo' => '购物订单(ID:' . $payLog['order_id'] . ')区县代理分佣',
                                            'type' => 11,
                                            'createtime' => time(),
                                            'order_id' => $payLog['order_id'],
                                            'logs_id' => $payLog['id']
                                        ];
                                        UserMoneyLog::create($data);
                                        //钱包加钱
                                        UsersModel::where(['id' => $areaAgent['agent_user_id']])->setInc('total_money', $money);
                                    } else {
                                        //没有区县代理，则查找市级代理商
                                        $cityAgent = AgentModel::where(['city_id' => $pAgentInfo['city_id'], 'status' => 1, 'level' => 3])->find();
                                        if ($cityAgent) {
                                            $money = sprintf("%.2f", 100 * ($commissionRate['area'] + $commissionRate['city']));
                                            //查找市级代理用户信息
                                            $cityAgentUserInfo = UsersModel::where(['id' => $cityAgent['agent_user_id']])->find();
                                            if ($cityAgentUserInfo) {
                                                //分佣记录
                                                $data = [
                                                    'user_id' => $cityAgent['agent_user_id'],
                                                    'money' => $money,
                                                    'before' => $cityAgentUserInfo['total_money'],
                                                    'after' => $cityAgentUserInfo['total_money'] + $money,
                                                    'memo' => '购物订单(ID:' . $payLog['order_id'] . ')市级代理分佣',
                                                    'type' => 11,
                                                    'createtime' => time(),
                                                    'order_id' => $payLog['order_id'],
                                                    'logs_id' => $payLog['id']
                                                ];
                                                UserMoneyLog::create($data);
                                                //钱包加钱
                                                UsersModel::where(['id' => $cityAgent['agent_user_id']])->setInc('total_money', $money);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                Log::record($order_sn . '分佣失败' . $e->getMessage(), 'debug');
            }
        }
    }
}
