<?php

namespace app\common\logic;

use app\common\api\RedisApi;
use app\common\model\Manager as mManager;
use app\common\model\Recharge;
use app\common\model\Register;

class Stat extends Base
{


    /**
     * @获取所有下级员工id (包含自身)
     *
     * @author: zsl
     * @since: 2021/3/5 14:01
     */
    public function getSubManagerIds($manager_id)
    {
        //获取所有员工数据
        $mManager = new mManager();
        $field = "id,pid,name";
        $where = [];
        $where[] = ['status', 'in', [0, 1]];
        $managerLists = $mManager -> field($field) -> where($where) -> select();
        $ids = get_sub_manager_ids($managerLists, $manager_id);
        return array_merge($ids, [$manager_id]);
    }


    /**
     * @员工业绩数据
     *
     * @author: zsl
     * @since: 2021/3/8 13:56
     */
    public function data($manager_id, $start_date = 0, $end_date = 0, $recursion = true)
    {

        $redis = new RedisApi();
        $key = 'achievements_data_' . $manager_id . '_' . $start_date . '_' . $end_date . '_' . ($recursion ? 1 : 0);
        if ($data = $redis -> get($key)) {
            return json_decode($data, true);
        }
        $mRegister = new Register();
        $mRecharge = new Recharge();
        //数据所属员工
        $where = [];
        $where2 = [];
        if ($manager_id != config('administrators_id')) {
            if (true == $recursion) {
                // 包含下级
                $where[] = ['manager_id', 'in', $this -> getSubManagerIds($manager_id)];
                $where2[] = ['manager_id', 'in', $this -> getSubManagerIds($manager_id)];
            } else {
                // 不包含下级
                $where[] = ['manager_id', '=', $manager_id];
                $where2[] = ['manager_id', '=', $manager_id];
            }
        } else {
            //超级管理员 查看全部数据,不构建查询条件
        }
        if (!empty($start_date) && !empty($end_date)) {
            $where[] = ['register_time', 'between', [$start_date, $end_date]];
            $where2[] = ['pay_time', 'between', [$start_date, $end_date]];
        }
        //获取注册数据
        $field = "id,register_ip";
        $registerData = $mRegister -> field($field) -> where($where) -> select() -> toArray();
        //获取充值数据
        $field = "id,user_account,cost_amount";
        $rechargeData = $mRecharge -> field($field) -> where($where2) -> select() -> toArray();
        $data['register_count'] = count($registerData);
        $data['register_ip_count'] = count(array_flip(array_column($registerData, 'register_ip')));
        $data['recharge_count'] = count(array_unique(array_column($rechargeData, 'user_account')));
        $data['recharge_pay_sum'] = round(array_sum(array_column($rechargeData, 'cost_amount')) / 100, 2);
        //写入缓存
        $redis -> set($key, json_encode($data));
        $redis -> expire($key, 3600 * 24);
        return $data;
    }


}