<?php

namespace app\agent\controller;

use fastphp\base\Controller;
use app\agent\model\AgentUser;
use app\agent\model\ProductUserPrice;
use app\agent\model\ProductPackage;
use app\agent\model\Product as ProductModel;
use app\agent\model\AgentPrice as AgentPriceModel;
use app\agent\model\User as UserModel;
use app\agent\model\AgentScore as AgentScoreModel;
use app\user\model\ProductPriceScheme;
use app\agent\model\CashOut as CashOutModel;
use app\order\model\UserScore as ScoreModel;

class Userinfo extends Controller
{
    //代理商首页
    public function index() 
    {

        $agent_user_model = new AgentUser;
        $discount_model = new ProductPriceScheme;
        $userinfo = $agent_user_model->getOne(['id'=>$this->userinfo['OperaterID']]);
        $userinfo['id'] = base64_encode($userinfo['id']);
        $userinfo['discount'] = $discount_model->getOne(['Id'=>$userinfo['discount_id']])['Name'];

        $info = [
            'Code'=>10000,
            'data'=>$userinfo
        ];
        echo  json_encode($info);
    }

    //代理商修改密码
    public function updatePass()
    {
        $data = json_decode(file_get_contents("php://input"), true);
        $agent_user_model = new AgentUser;
        $userinfo = $agent_user_model->getOne(['id'=>$this->userinfo['OperaterID']]);
        if($userinfo['password'] != cToMd5($data['old_pass'])){
            $info = [
                'Code' => -10000,
                'Message' => '旧密码错误',
            ];
            echo json_encode($info);
            die;
        }
        $update = [
            'password' => cToMd5($data['new_pass'])
        ];
        if($agent_user_model->updateOne(['id'=>$this->userinfo['OperaterID']],$update)){
            $info = [
                'Code' => 10000,
                'Message' => '更新成功',
            ];
            echo json_encode($info);
            die;
        } else {
            $info = [
                'Code' => -10000,
                'Message' => '更新失败',
            ];
            echo json_encode($info);
        }
    }

    

    //提现
    public function cashOut()
    {
        $post = json_decode(file_get_contents("php://input"), true);
        $data = [];
        $post['cash_out_money'] = abs($post['cash_out_money']);
        $data['userid'] = $this->userinfo['OperaterID'];
        $data['username'] = $this->userinfo['LoginName'];
        $data['money'] = $post['cash_out_money'];
        $data['apply_reason'] = $post['reason'];
        $data['alipay_account'] = $post['alipay_account'];
        $data['real_name'] = $post['real_name'];
        $data['is_agent'] = 1;
        $agent_user_model = new AgentUser;
        $agent_info = $agent_user_model->getOne(['id'=>$data['userid']]);
        $user_rest = $agent_info['account'];
        $rest = $user_rest - $post['cash_out_money'];
        if ($rest < 0){
            echo  json_encode(['Code'=>-10000,]);
            die;
        } else {
            if($agent_user_model->where(['id'=>$data['userid'],'account'=>$user_rest])->update(['account'=>$rest])){
                $cash = new CashOutModel;
                $status = $cash->add($data);
                $score_model = new AgentScoreModel;
                $score['agent_id'] = $data['userid'];
                $score['order_id'] = 0;
                $score['score_type'] = 4;
                $score['score_value'] = $data['money'];
                $score['agent_name'] = $this->userinfo['LoginName'];
                $score['op_user'] = $this->userinfo['LoginName'];
                $score['rest_amount1'] = $agent_info['account'];
                $score['rest_amount2'] = $rest;
                $score['remark'] = '提现扣除';
                $score_model->add($score);
            }
        }
        echo  json_encode(['Code'=>10000,]);
    }

    //验证是否是该代理的用户
    public function verify()
    {
        $data = json_decode(file_get_contents("php://input"), true);
        $user_id = $data['user_id'];
        $agent_id = $this->userinfo['OperaterID'];
        $user_model = new UserModel;
        $userinfo = $user_model->getOne(['Id'=>$user_id]);
        if($userinfo['agent_id'] != $agent_id){
            die;
        }
        $info = [
            'Code' => 20000,
            'Message' => '请正确操作',
        ];
        echo json_encode($info);
    }

    //代理商下的用户
    public function getList ()
    {
        $page = 0;
        if (isset($_GET['PageIndex'])) {
            $page = ($_GET['PageIndex'] - 1) * 50;
        }
        $where = [];
        if(!empty($_GET['keyWord'])){
            $where['LoginCode'] = $_GET['keyWord'];
        }
        $where['agent_id'] = $this->userinfo['OperaterID'];
        $user_model = new UserModel;
        $discount_model = new ProductPriceScheme;
        $user_list = $user_model->getListPage($where, '`LoginCode`,`RestAmount`,`discount_id`,`CreateTime`,`QQ`,`Wx`,`TaoBao`,`Email`,`Id`,`id_code`,`is_verify`', 'id desc', "$page,50");
        
        //折扣列表
        $discount_data = $discount_model->getList();
        $discount_list = [];
        $discount_list[0] = '原价';
        $discount_list[-1] = '专项优惠';
        foreach($discount_data as $info) {
            $discount_list[$info['Id']] = $info['Name'];
        }

        foreach ($user_list as &$info){
            if(empty($info['id_code'])){
                $info['is_verify'] = '未认证';
            } else {
                $info['id_code'] = substr($info['id_code'], 0, 6) . '***';
                $info['is_verify'] = $info['is_verify']?'认证成功':'认证失败';
            }
            $info['discount'] = $discount_list[$info['discount_id']];

        }
        $data = [
            'Code' => 10000,
            'Data' => $user_list,
            'Message' => '',
            'TotalCount' => (int)$user_model->getCount($where)['count'],
        ];
        echo json_encode($data);
    }

    //获取代理最低价
    public function getAgentPrice()
    {
        
        $data = json_decode(file_get_contents("php://input"), true);
        
       
        $agent_user_model = new AgentUser;
        $package_model = new ProductPackage;
        $product_model = new ProductModel;
        $discount_model = new ProductPriceScheme;

        $agent_id = $this->userinfo['OperaterID'];

        $agent_info = $agent_user_model->getOne(['id'=>$agent_id]);

        //套餐价
        $package_price = $package_model->getOne(['Id' => $data['Id']]);

        //退款价
        $refund_price = $product_model->getOne(['Id' => $data['ProductId']]);

        $discount = $discount_model->getOne(['Id'=>$agent_info['discount_id']]); 
        if (empty($discount)){
            $retuen_data = [
                'Code' => -10000,
                'Message' => '请联系管理员设置您的代理价！',
            ];
            echo json_encode($retuen_data);
            die;
        }

        $user_set_price = $package_price['LinePrice'] * $discount['discount'] / 100;
        $user_refund_price = $refund_price['RefundDayPrice'] * $discount['discount'] / 100;

        $price = [
            'price' => $user_set_price,
            'refund' => $user_refund_price
        ];

        $retuen_data = [
            'Code' => 30000,
            'Data' => $price,
            'Message' => '',
        ];
        echo json_encode($retuen_data);
    }

    //设置价格
    public function setPrice()
    {
        $data = json_decode(file_get_contents("php://input"), true);
        $price_model = new ProductUserPrice;
        $discount_model = new ProductPriceScheme;
        $agent_user_model = new AgentUser;
        $package_model = new ProductPackage;
        $product_model = new ProductModel;
        $user_model = new UserModel;

        $agent_id = $this->userinfo['OperaterID'];

        $where = [
            'agent_id' => $agent_id,
            'package_id' => $data['PackageId']
        ];

        $agent_info = $agent_user_model->getOne(['id'=>$agent_id]);

        $discount = $discount_model->getOne(['Id'=>$agent_info['discount_id']]); 
        if (empty($discount)){
            $retuen_data = [
                'Code' => -10000,
                'Message' => '请联系管理员设置您的代理价！',
            ];
            echo json_encode($retuen_data);
            die;
        }

        //套餐价
        $package_price = $package_model->getOne(['Id' => $data['PackageId']]);

        //退款价
        $refund_price = $product_model->getOne(['Id' => $data['ProductId']]);

        $user_set_price = $package_price['LinePrice'] * $discount['discount'] / 100;
        $user_refund_price = $refund_price['RefundDayPrice'] * $discount['discount'] / 100;


        if($data['UserPrice']<$user_set_price || $data['RefundDayPrice']<$user_refund_price){
            $retuen_data = [
                'Code' => -10000,
                'Message' => '低于您的代理价',
            ];
            echo json_encode($retuen_data);
            die;
        }

        $update_data = [
            'TenantId' => 0,
            'ProductId' => $data['ProductId'],
            'PackageId' => $data['PackageId'],
            'UserId' => $data['UserId'],
            'UserPrice' => abs($data['UserPrice']),
            'RefundDayPrice' => abs($data['RefundDayPrice']),
            'Status' => 1,
            'DeleteTag' => 0
        ];

        $where = [
            'PackageId' => $data['PackageId'],
            'UserId' => $data['UserId']
        ];

        $user_price = $price_model->getOne($where);

        if(empty($user_price)){
            $price_model->add($update_data);
        } else {
            $price_model->updateOne($where,$update_data);
        }

        $user_model->updateOne(['Id'=>$data['UserId']],['discount_id'=>-1]);

        $retuen_data = [
            'Code' => 10000,
            'Message' => '',
        ];
        echo json_encode($retuen_data);
    }

    //获取折扣
    public function getDiscount()
    {
        $discount_model = new ProductPriceScheme;
        $user_model = new UserModel;
        $agent_user_model = new AgentUser;

        $agent_id = $this->userinfo['OperaterID'];
        $agent_info = $agent_user_model->getOne(['id'=>$agent_id]);

        $list = $discount_model->getList(['Id'=>['<',$agent_info['discount_id']]],'*','id asc');
        $info = [
            'Code' => 10000,
            'Data' => $list,
            'Message' => '',
            'TotalCount' => 8
        ];
        echo json_encode($info);
    }

    //代理折扣
    public function setUserDiscount()
    {
        $data = json_decode(file_get_contents("php://input"), true);
        // dump($data);

        if(!isset($data['schemeId'])){
            die;
        }

        $user_model = new UserModel;
        $agent_user_model = new AgentUser;
        $discount_model = new ProductPriceScheme;

        $agent_id = $this->userinfo['OperaterID'];
        $agent_info = $agent_user_model->getOne(['id'=>$agent_id]);
        //原始折扣
        $discount_old = $discount_model->getList(['Id'=>['in',[$data['schemeId'],$agent_info['discount_id']]]],'Id,discount');
        
        $discount_list = [];
        foreach($discount_old as $info){
            $discount_list[$info['Id']] = $info["discount"];
        }

        if($discount_list[$data['schemeId']]<=$discount_list[$agent_info['discount_id']]){
            $info = [
                'Code' => -10000,
                'Data' => '',
                'Message' => '不能低于您的折扣！',
            ];
            echo json_encode($info);
            die;
        }
            

        $discount_data = [
            'discount_id' => $data['schemeId']
        ];

        $user_model->updateOne(['Id'=>$data['userId']],$discount_data);
        $info = [
            'Code' => 10000,
            'Data' => '',
            'Message' => '',
        ];
        echo json_encode($info);
    }

    //代理给用户充值
    public function chongzhi() {
        $data = json_decode(file_get_contents("php://input"), true);
        $data['money'] = abs($data['money']);
        $agent_id = $this->userinfo['OperaterID'];
        //获取代理信息
        $agent_user_model = new AgentUser;
        $agent_info = $agent_user_model->getOne(['id'=>$agent_id]);
        $agent_balance = $agent_info['account'];
        $rest = $agent_balance - $data['money'];
        
        if ($rest<0) {
            $info = [
                'Code' => -30000,
                'Data' => '',
                'Message' => '余额不足！',
            ];
            echo json_encode($info);
            die;
        } else {
            $user_model = new UserModel;   
            $user_info = $user_model->getOne(['Id' => $data['user_id']]);
            $user_balance = $user_info['RestAmount'];
            $agent_update_data = [
                'account' => $rest
            ];

            if ($agent_user_model->updateOne(['id' => $agent_id,'account' => $agent_balance],$agent_update_data)) {
                $score_model = new AgentScoreModel;
                $score['agent_id'] = $agent_id;
                $score['order_id'] = 0;
                $score['score_type'] = 4;
                $score['score_value'] = $data['money'];
                $score['agent_name'] = $this->userinfo['LoginName'];
                $score['op_user'] = $this->userinfo['LoginName'];
                $score['rest_amount1'] = $agent_balance;
                $score['rest_amount2'] = $rest;
                $score['remark'] = '给旗下用户充值扣除'.$data['username'];
                $score_model->add($score);

                $user_balance_rest = $user_balance + $data['money'];

                if ($user_model->updateOne(['Id' => $data['user_id'],'RestAmount' => $user_balance],['RestAmount' => $user_balance_rest])) {

                    $score_user_model = new ScoreModel;
                    $score_user_data = [
                        'UserId' => $data['user_id'],
                        'ScoreType' => 1,
                        'ScoreTypeName' => '充值',
                        'ScoreValue' => $data['money'],
                        'UserName' => $data['username'],
                        'OperateUserName' => $this->userinfo['LoginName'],
                        'RestAmount1' => $user_balance,
                        'RestAmount2' => $user_balance_rest,
                        'CreateTime' => date('Y-m-d H:i:s', time()),
                        'UpdateTime' => date('Y-m-d H:i:s', time()),
                        'TenantId' => 0,
                        'Remark' => '充值',
                        'DeleteTag' => 0,
                    ];
                    $score_user_model->add($score_user_data);

                    $info = [
                        'Code' => 10000,
                        'Data' => '',
                        'Message' => '',
                    ];
                    echo json_encode($info);
                    die;
                }


            }
        }
    }
}