<?php

namespace app\agent\controller;

use fastphp\base\Controller;
use app\agent\model\AgentUser;
use app\agent\model\User as UserModel;
use app\agent\model\Product as PoductModel;
use app\agent\model\ProductPackage as PoductPackageModel;
use app\agent\model\AgentPrice as AgentPriceModel;
use app\agent\model\AgentScore as AgentScoreModel;
use app\agent\model\ProductPriceDiscount as ProductPriceDiscountModel;
use app\agent\model\ProductOrder as ProductOrderModel;
use app\agent\model\ProductPriceScheme;

class Agent extends Controller
{
    //代理商列表
    public function getList ()
    {
        $page = 0;
        if (isset($_GET['PageIndex'])) {
            $page = ($_GET['PageIndex'] - 1) * 50;
        }
        $where = [];
        if(!empty($_GET['keyWord'])){
            $where = "username ='".$_GET['keyWord']."' OR phone='".$_GET['keyWord']."'";
        }
        
        $agent_user_model = new AgentUser;
        $user_model = new UserModel;
        $order_model = new ProductOrderModel;
        $discount_model = new ProductPriceScheme;

        $user_list = $agent_user_model->getListPage($where, '*', 'id desc', "$page,50");

        if (count($user_list) == 0) {
            $data = [
                'Code' => 20000,
                'Message' => '用户不存在'
            ];
            echo json_encode($data);
            die;
        }
 
        //折扣列表
        $discount_data = $discount_model->getList();
        $discount_list = [];
        $discount_list[0] = '原价';
        foreach($discount_data as $info) {
            $discount_list[$info['Id']] = $info['Name'];
        }

        //获取代理商下的用户数
        $agent_ids = [];
        $list = [];
        foreach ($user_list as &$info){
            $info['password'] = '';
            $agent_ids[] = $info['id'];
            $info['discount'] = $discount_list[$info['discount_id']];
            $list[$info['id']] = $info;

        }
        
        $last_month_cost_money = $order_model->getLastMonthCost($agent_ids);
        $last_month_refund_money = $order_model->getLastMonthRefund($agent_ids);
        $month_cost_money = $order_model->getMonthCost($agent_ids);
        $month_refund_money = $order_model->getMonthRefund($agent_ids);

        $last_cost_list = $last_refund_list = $cost_list = $refund_list = [];

        foreach ($last_month_cost_money as $info){
            $last_cost_list[$info['agent_id']] = $info['pay_money'];
        }
        foreach ($last_month_refund_money as $info){
            $last_refund_list[$info['agent_id']] = $info['pay_money'];
        }
        foreach ($month_cost_money as $info){
            $cost_list[$info['agent_id']] = $info['pay_money'];
        }
        foreach ($month_refund_money as $info){
            $refund_list[$info['agent_id']] = $info['pay_money'];
        }



        $agent_user_num = $user_model->getAgentUser(['agent_id'=>['in',$agent_ids]]);
        foreach ($agent_user_num as $info){
            $list[$info['agent_id']]['user_num'] = $info['num'];
            if (!isset($last_cost_list[$info['agent_id']])){
                $last_cost_list[$info['agent_id']] = 0;
            }
            if (!isset($cost_list[$info['agent_id']])){
                $cost_list[$info['agent_id']] = 0;
            }
            if (!isset($last_refund_list[$info['agent_id']])){
                $last_refund_list[$info['agent_id']] = 0;
            }
            if (!isset($refund_list[$info['agent_id']])){
                $refund_list[$info['agent_id']] = 0;
            }
            $list[$info['agent_id']]['last_cost'] = round($last_cost_list[$info['agent_id']] - $last_refund_list[$info['agent_id']],2);
            $list[$info['agent_id']]['cost'] = round($cost_list[$info['agent_id']] - $refund_list[$info['agent_id']],2);
        }
        // dump($list);die;
        $list = array_merge($list);

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

    //设置代理商最低价格价格表
    public function price()
    {
        $id = $_GET['userId'];
        $list = [];
        $product_model = new PoductModel;
        $package_model = new PoductPackageModel;
        $price_model = new AgentPriceModel;
        $product = $product_model->getList(['OnLine'=>1,'Id'=>['<>',11]], '*', 'Sort asc');
        $package = $package_model->getList([], '*', 'TenantId asc');
        $price = $price_model->getList(['agent_id'=>$id], '*');

        //按照套餐整理价格
        $price_list = [];
        foreach($price as $info){
            $price_list[$info['package_id']] = $info;
        }


        //按照产品整理价格
        $package_list = [];
        foreach($package as $info){
            $package_list[$info['ProductId']][] = $info;
        }

        //处理数据
        foreach ($product as $p_info){
            $temp = [];
            $temp['Product'] = $p_info;
            $package_temp = [];

            //套餐分离
            foreach ($package_list[$p_info['Id']] as $pack_info){
                $pack_temp = [];
                $pack_temp['Package'] = $pack_info;
                //若没有价格 默认价格
                if(empty($price_list[$pack_info['Id']])){
                    $price_list[$pack_info['Id']]['refund'] = $p_info['RefundDayPrice'];
                    $price_list[$pack_info['Id']]['price'] = $pack_info['Price'];
                }
                $pack_temp['UserPrice'] = $price_list[$pack_info['Id']];
                $package_temp[] = $pack_temp;
            }
            $temp['PackageUserPrices'] = $package_temp;

            $list[] = $temp;
        }

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

    //设置最低价
    public function setPrice()
    {
        $data = json_decode(file_get_contents("php://input"), true);
        $price_model = new AgentPriceModel;

        $update_data = [
            'product_id' => $data['ProductId'],
            'package_id' => $data['PackageId'],
            'agent_id' => $data['UserId'],
            'price' => $data['UserPrice'],
            'refund' => $data['RefundDayPrice'],
        ];

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

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

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

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

    //按照折扣设置最低价
    public function setPriceDiscount()
    {
        $data = json_decode(file_get_contents("php://input"), true);
        $price_model = new AgentPriceModel;
        $discount = new ProductPriceDiscountModel;
        $package_model = new PoductPackageModel;
        $product_model = new PoductModel;

        $discount_list = $discount->getList(['SchemeId'=>$data['schemeId']]);
        $package_list = [];
        $pack_list = $package_model->getList();
        foreach ($pack_list as $info){
            $package_list[$info['Id']] = $info;
        }

        $product_list = [];
        $p_list = $product_model->getList();
        foreach ($p_list as $info){
            $product_list[$info['Id']] = $info;
        }

        foreach ($discount_list as $info){
            $update_data = [
                'product_id' => $info['ProductId'],
                'package_id' => $info['PackageId'],
                'agent_id' => $data['userId'],
                'price' => $package_list[$info['PackageId']]['LinePrice'] * $info['BuyPriceDiscount']/100,
                'refund' => $product_list[$info['ProductId']]['RefundDayPrice'] * $info['RefundDayPriceDiscount']/100,
            ];

            if ($update_data['price'] < $package_list[$info['PackageId']]['MinPrice']){
                $update_data['price'] = $package_list[$info['PackageId']]['MinPrice'];
            }

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

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

            // die;

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

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

    //是否启用修改后的价格
    public function setPriceStatus()
    {
        $data = json_decode(file_get_contents("php://input"), true);
        $price_model = new AgentPriceModel;
        $id = $data['id'];
        $update_data['status'] = $data['status'];

        $where = ['id'=>$id];
        if($price_model->updateOne($where,$update_data)){
            $retuen_data = [
                'Code' => 10000,
                'Message' => '',
            ];
            echo json_encode($retuen_data);
            die;
        } else {
            $retuen_data = [
                'Code' => -10000,
                'Message' => '操作失败',
            ];
            echo json_encode($retuen_data);
            die;
        }
    }

    //添加代理商
    public function addAgent()
    {
        $data = json_decode(file_get_contents("php://input"), true);
        $data['password'] = cToMd5($data['password']);
        $agent_user_model = new AgentUser;

        $agent_user_model->add($data);

        $retuen_data = [
            'Code' => 10000,
            'Message' => '操作成功',
        ];
        echo json_encode($retuen_data);
        die;
    }

    //修改代理商
    public function updateAgent()
    {
        $data = json_decode(file_get_contents("php://input"), true);
        
        $agent_user_model = new AgentUser;

        $update_data = [
            'phone'=>$data['phone'],
            'qq'=>$data['qq'],
            'realname'=>$data['realname'],
        ];
        if(!empty($data['password'])){
            $data['password'] = cToMd5($data['password']);
            $update_data['password'] = $data['password'];
        }

        $agent_user_model->updateOne(['id'=>$data['id']],$update_data);

        $retuen_data = [
            'Code' => 10000,
            'Message' => '操作成功',
        ];
        echo json_encode($retuen_data);
        die;
    }

    //代理商充值扣款
    public function account()
    {
        $data = json_decode(file_get_contents("php://input"), true);
        
        $agent_user_model = new AgentUser;
        $score_model = new AgentScoreModel;

        $update_data = [];
        $score = [];
        $id = $data['id'];

        $agent = $agent_user_model->getOne(['id'=>$id]);
        if($data['opAmountType'] == 1){
            $update_data['account'] = $data['rest'] + $data['amount'];
            $score['agent_id'] = $id;
            $score['order_id'] = 0;
            $score['score_type'] = 3;
            $score['score_value'] = $data['amount'];
            $score['agent_name'] = $agent['username'];
            $score['op_user'] = $this->userinfo['LoginName'];
            $score['rest_amount1'] = $agent['account'];
            $score['rest_amount2'] = $update_data['account'];
            $score['remark'] = $data['attchInfo'];
        } else {
            $update_data['account'] = $data['rest'] - $data['amount'];
            $score['agent_id'] = $id;
            $score['order_id'] = 0;
            $score['score_type'] = 4;
            $score['score_value'] = $data['amount'];
            $score['agent_name'] = $agent['username'];
            $score['op_user'] = $this->userinfo['LoginName'];
            $score['rest_amount1'] = $agent['account'];
            $score['rest_amount2'] = $update_data['account'];
            $score['remark'] = $data['attchInfo'];
        }


        if($agent_user_model->updateOne(['id'=>$id],$update_data)){

            $score_model->add($score);

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

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

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

        $agent_user_model = new AgentUser;

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

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