<?php

namespace app\user\controller;

use app\user\model\User as UserModel;
use app\user\model\AgentUser as AgentUser;
use app\user\model\UserScore as UserScore;
use app\user\model\SellCouponUserOrgin;
use app\user\model\ProductPriceScheme;
use fastphp\base\Controller;

class User extends Controller
{
    //获取列表
    public function getList ()
    {
        $page = 0;
        if (isset($_GET['PageIndex'])) {
            $page = ($_GET['PageIndex'] - 1) * 50;
        }
        $where = '';
        if(!empty($_GET['keyWord'])){

            $where = "LoginCode like '%".$_GET['keyWord']."%' or Phone like '%".$_GET['keyWord']."%' or TaoBao like '%".$_GET['keyWord']."%' or Wx like '%".$_GET['keyWord']."%' or QQ like '%".$_GET['keyWord']."%'";
        }

        if(!empty($_GET['schemeId'])){
            $where = "discount_id=".$_GET['schemeId'];
        }

        $user_model = new UserModel;
        $discount_model = new ProductPriceScheme;
        $user_list = $user_model->getUserListPage($where, '*', '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){
            $info['Password'] = '';
            if(empty($info['id_code'])){
                $info['is_verify'] = '未认证';
            } else {
                $info['id_code'] = substr($info['id_code'], 0, 6) . '***';
                if ($info['is_verify']==2) {
                    $info['is_verify'] = '禁用';
                } else {
                    $info['is_verify'] = $info['is_verify']?'认证成功':'认证失败';
                }
            }
            if ($info['is_agent']==1) {
                $info['LoginCode'] = '经销商'.$info['LoginCode'];
            }

            $info['discount'] = $discount_list[$info['discount_id']];

            if($info['CreateType'] == 4){
                $agent = new AgentUser;
                $agent_info = $agent->getOne(['id'=>$info['agent_id']]);
                $info['CreateType'] = '代理商推广：'.$agent_info['realname'].$agent_info['qq'];
            }
            
        }
        $data = [
            'Code' => 10000,
            'Data' => $user_list,
            'Message' => '',
            'TotalCount' => (int)$user_model->getCount($where)['count'],
        ];
        echo json_encode($data);
    }

    //添加会员
    public function addUser()
    {
        $data = json_decode(file_get_contents("php://input"), true);
        $data['LoginCode'] = trim($data['LoginCode']);

        if(empty($data['LoginCode'])){
            $info = [
                'Code' => 10003,
                'Data' => '',
                'Message' => '账号为空',
            ];
            echo json_encode($info);
            die;
        }

        $data['TenantId'] = 0;
        $data['Enabled'] = 1;
        $data['UpdateTime'] = date('Y-m-d H:i:s',time());
        $data['CreateTime'] = date('Y-m-d H:i:s',time());
        $data['CreateType'] = 1;
        $data['ProductAccountCount'] = 0;
        $data['ExpiredProductAccountCount'] = 0;
        $data['RestAmount'] = 0;
        $data['ConsumeAmount'] = 0;
        $data['DeleteTag'] = 0;
        $data['UseTestCount'] = 0;
        $data['Sex'] = 0;
        $data['LastLoginDate'] = date('Y-m-d H:i:s',time());
        $data['Password'] = empty($data['Password'])?cToMd5('1234'):cToMd5(trim($data['Password']));

        $user_model = new UserModel;
        $data['ManagerId'] = 0;

        $has_user = $user_model->isExit("LoginCode='".$data['LoginCode']."' or Phone='".$data['Phone']."' or TaoBao='".$data['Phone']."'");
        if ($has_user){
            $info = [
                'Code' => 10007,
                'Data' => '',
                'Message' => '该账号或者手机号被注册了',
            ];
            echo json_encode($info);
            die;
        }

        if ($user_model->add($data)) {
            $info = [
                'Code' => 10000,
                'Data' => '',
                'Message' => '',
            ];
            echo json_encode($info);
            die;
        }
        die;
    }

    //设置测试数
    public function testCount()
    {
        $data = json_decode(file_get_contents("php://input"), true);
        $user_model = new UserModel;
        $user_update['TestCountLimit'] = $data['limit'];
        $user_model->updateOne(['Id'=>$data['UserId']],$user_update);
        $info = [
            'Code' => 10000,
            'Data' => '',
            'Message' => '',
        ];
        echo json_encode($info);
        die;
    }

     //充值
//      UserId: "112984"
// amount: "1"
// attchInfo: "测试"
// opAmountType: 1
// rest: "0.00"
// showAmountDialog: true
     public function updateRestAmount()
     {
         $data = json_decode(file_get_contents("php://input"), true);
         $user_model = new UserModel;

        

         $user_update['OperateUserName'] = $this->userinfo['LoginName'];
        //  $user_model->updateOne(['Id'=>$data['UserId']],$user_update);
         $info = [
             'Code' => 10000,
             'Data' => '',
             'Message' => '',
         ];
         die;
         echo json_encode($info);
         die;
     }

     //一毛钱天卡
    public function setDay()
    {
        $data = json_decode(file_get_contents("php://input"), true);
        $id = $data['Id'];
        $user_model = new UserModel;

        

         $user_update['ProductAccountCount'] = $data['ProductAccountCount'];
         $user_model->updateOne(['Id'=>$id],$user_update);
         $info = [
             'Code' => 10000,
             'Data' => '',
             'Message' => '',
         ];
         echo json_encode($info);
    }
    //一毛钱天卡
   public function isagent()
   {
       $data = json_decode(file_get_contents("php://input"), true);
       $id = $data['Id'];
       $user_model = new UserModel;

       

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

    //资金转移
    public function moneyChange()
    {
        $data = json_decode(file_get_contents("php://input"), true);


        $user_model = new UserModel;
        $score_model = new UserScore;
        $coupon = new SellCouponUserOrgin;

        //被转移
        $where1 = ['LoginCode'=>$data['luser']];
        //转移
        $where2 = ['LoginCode'=>$data['ruser']];

        $luser = $user_model->getOne($where1);
        $ruser = $user_model->getOne($where2);

        if(empty($luser) || empty($ruser)){
            $info = [
                'Code' => 20000,
                'Data' => '用户不存在',
                'Message' => '',
            ];
            echo json_encode($info);
            die;
        }

        $updata1=[
            'RestAmount'=>$luser['RestAmount']-$data['money'],
            'TaoBao' => null
        ];
        if($updata1['RestAmount']<0 || $data['money']<0){
            $info = [
                'Code' => 20000,
                'Data' => '金额不足或金额小于0',
                'Message' => '',
            ];
            echo json_encode($info);
            die;
        }

        //优惠券转移
        $coupon_update = [
            'ToUser' => $ruser['Id']
        ];
        $coupon_where = [
            'ToUser' => $luser['Id']
        ];
        $coupon->updateOne($coupon_where,$coupon_update);

        $updata2=[
            'RestAmount'=>$ruser['RestAmount']+$data['money'],
            'TaoBao' => ($data['luser'] == 'zengsong')?$ruser['TaoBao']:$data['luser']
        ];

        $score_update1 = [
            'TenantId'=>0,
            'UserId'=>$luser['Id'],
            'ScoreType'=>2,
            'ScoreTypeName'=>'资金转移扣除'.$data['luser'].'->'.$data['ruser'],
            'ScoreValue'=>$data['money'],
            'CreateTime'=>date('Y-m-d H:m:s'),
            'UpdateTime'=>date('Y-m-d H:m:s'),
            'DeleteTag'=>0,
            'UserName'=> $data['luser'],
            'OperateUserName'=> $this->userinfo['LoginName'],
            'RestAmount1'=>$luser['RestAmount'],
            'RestAmount2'=>$updata1['RestAmount'],
        ];

        $score_update2 = [
            'TenantId'=>0,
            'UserId'=>$ruser['Id'],
            'ScoreType'=>2,
            'ScoreTypeName'=>'资金转移充值'.$data['luser'].'->'.$data['ruser'],
            'ScoreValue'=>$data['money'],
            'CreateTime'=>date('Y-m-d H:m:s'),
            'UpdateTime'=>date('Y-m-d H:m:s'),
            'DeleteTag'=>0,
            'UserName'=> $data['ruser'],
            'OperateUserName'=> $this->userinfo['LoginName'],
            'RestAmount1'=>$ruser['RestAmount'],
            'RestAmount2'=>$updata2['RestAmount'],
        ];

        $user_model->updateOne($where1,$updata1);
        $user_model->updateOne($where2,$updata2);

        $score_model->add($score_update1);
        $score_model->add($score_update2);

        $info = [
            'Code' => 10000,
            'Data' => '',
            'Message' => '',
        ];
        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;
        $discount_model = new ProductPriceScheme;

        $user_info = $user_model->getOne(['Id'=>$data['userId']]);
        //原始折扣
        $discount_old = $discount_model->getList(['Id'=>['in',[$data['schemeId'],$user_info['discount_id']]]],'Id,discount');
        
        $discount_list = [];
        foreach($discount_old as $info){
            $discount_list[$info['Id']] = $info["discount"];
        }

        if($user_info['discount_id'] != 0 &&$user_info['discount_id'] != -1){
            if($discount_list[$data['schemeId']]>$discount_list[$user_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 useDanPrice()
    {
        $data = json_decode(file_get_contents("php://input"), true);
        // dump($data);

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

        $user_model = new UserModel;

        if ($user_model->updateOne(['Id'=>$data['userid']],['discount_id'=>-1])){
            $info = [
                'Code' => 10000,
                'Data' => '',
                'Message' => '',
            ];
            echo json_encode($info);
        } else {
            die;
        }
    }

    //获取新注册的用户
    public function getRegisterList ()
    {
        $where = '';
        $where = "`ManagerId`=0 AND `agent_id` = 0";

        $user_model = new UserModel;
        $user_list = $user_model->getUserListPage($where, 'Id,LoginCode,CreateTime,Name,TestCountLimit,UseTestCount,ManagerId,id_code,is_verify', 'id desc', "50");


        foreach ($user_list as &$info){
            if(empty($info['id_code'])){
                $info['is_verify'] = '未认证';
            } else {
                $info['id_code'] = substr($info['id_code'], 0, 6) . '***';
                if ($info['is_verify']==2) {
                    $info['is_verify'] = '禁用';
                } else {
                    $info['is_verify'] = $info['is_verify']?'认证成功':'认证失败';
                }
            }
        }
        $data = [
            'Code' => 10000,
            'Data' => $user_list,
            'Message' => '',
            'TotalCount' => (int)$user_model->getCount($where)['count'],
        ];
        echo json_encode($data);
    }

    //管理员领取新注册的用户
    public function getNewUser ()
    {
        $uid = json_decode(file_get_contents("php://input"), true);
        if (empty($uid)) {
            $data = [
                'Code' => -30000,
                'Message' => '非法操作',
            ];
            echo json_encode($data);
            die;
        }

        $where = ['Id' => $uid];
        
        $user_model = new UserModel;
        $user_info = $user_model->getOne($where,'ManagerId');
        if (!empty($user_info['ManagerId'])) {

            $data = [
                'Code' => -20000,
                'Message' => '已经被其他人领取',
            ];
            echo json_encode($data);
            die;
        } else {

            $updata = [
                'ManagerId' => $this->userinfo['OperaterID'],
                'ManagerName' => $this->userinfo['RealName'],
            ];

            $user_model->updateOne($where, $updata);

            $data = [
                'Code' => 10000,
                'Message' => '领取成功',
            ];
            echo json_encode($data);
        }
    }


}
