<?php
/**
 * 大屏专用lib
 *
 * ============================================================================
 * 版权所有 2017北京素玄科技，并保留所有权利。
 *
 * 网站地址: http://www.suxuantech.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！未经允许的情况下，您不能对本系统代码做任何修改 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * 如有修改需求，请联系素玄科技有限公司：contact@suxuantech.cn
 * ============================================================================
 * $Author: lilong<lilong@suxuantech.cn> 2017-10-27 $
 */
namespace app\crm\lib;
use think\Controller;

class Bigscreen extends Controller{
    // 获取集团信息
    public function getGName($param){
        $gInfo = cache('company_'.$param['group_company_name']);
        if (empty($gInfo)) {
            $url = '5a6978bb82027';
            $data=[];
            $res = sx_call($url, $data);
            if ($res['code'] == 200) {
                $gInfo = $res['data'][0];
                cache('company_'.$gInfo['group_company_name']);
            }
            unset($res);
        }
        return $gInfo;
    }

    // 根据事业部id获取事业部信息
    public function getBrandInfo($id){
        if (!$id || $id==0) {
            $mark = 'all';
        }else{
            $mark = $id;
        }
        $brandclassInfo = cache('brandclassInfo_'.$mark);
        if(empty($brandclassInfo)){
            $url = '5a38840b15ba9';
            $data['id'] = $id;
            $res = sx_call($url, $data);
            if($res['code'] == 200){
                // var_dump($res['data']);
                if ($mark == 'all') {
                    $brandclassInfo = $res['data'];
                }else{
                    $brandclassInfo = $res['data'][0];
                }
                cache('brandclassInfo_'.$mark,$brandclassInfo);
            }
        }
        return $brandclassInfo;
    }

    // 根据事业部获取  店 （电商，网销，渠道）
    public function getShops($brandclass_id){
        $url = '5a37a1503264d';
        $data['brandclass_id']= $brandclass_id;
        $data['is_marketing'] = 2;
        $res = sx_call($url, $data);
        if ($res['code'] == 200) {
            $shopList = $res['data'];
        }else{
            $shopList = '';
        }
        return $shopList;
    }

    // 获取所有部门信息
    public function getdeparments($shop_code = ''){
        $url = '5a0aef152b750';
        $data['shop_code'] = $shop_code;
        $res = sx_call($url, $data);
        $return = $res['data'];
        return $return;
    }

    // 根据部门id获取所有  小组  信息
    public function getGroups($deparment_id){
        $where = [
            'department_id' => $deparment_id,
        ];
        $groups = db('c_staff_group')->where($where)->select();
        return $groups;
    }

    // 根据部门id获取所有  员工  信息
    public function getDepartmentStaffs($department_id){
        $url = '5a0e6f272bb38';
        $data['department_id'] = $department_id;
        $data['get_leave'] = 2;
        $res = sx_call($url, $data);
        return $res['data'];
    }
    // 根据岗位id获取所有  员工  信息
    public function getStaffInfoByPositon($position_id,$shop_code){
        $url = '5a0a624728618';
        $data['position_id']= $position_id;
        $data['shop_code']  = $shop_code;
        $res = sx_call($url, $data);
        if ($res['code'] == 200) {
            $return = $res['data'];
        }else{
            $return = [];
        }
        return $return;
    }

    // 根据shop_code  获取该店下所有的员工信息
    public function getStaffInfoByShop($shop_code){
        $url = '5a19201a33c20';
        $data['shop_code']  = $shop_code;
        $data['get_leave']  = 2;
        $res = sx_call($url, $data);
        if ($res['code'] == 200) {
            $return = $res['data'];
        }else{
            $return = [];
        }
        return $return;
    }
    // 根据 组id 获取所有 小组成员 信息
    public function getStaffs($group_id){
        $where = [
            'group_id' => $group_id,
        ];
        $staffs = db('c_staff_group_relation')->where($where)->column('staff_id');
        $staffs = implode(',', $staffs);
        $url = '5a18e3fa516a1';
        $data['staff_id'] = $staffs;
        $res = sx_call($url, $data);

        return $res['data'];
    }

    // 根据员工  id  获取   员工名字
    public function getStaffInfo($staff_id){
        /*$url = '59f933a395abe';
        $data['staff_id']= $staff_id;
        $info = sx_call($url, $data);*/
        $data['staff_id']= $staff_id;
        $mc = new \app\common\lib\mcInterface();
        $info = $mc->getOneStaff($data);
        $name = $info['data']['staffname'];
        return $name;
    }

    // 根据员工id，获取员工所属部门及小组
    public function getDGForStaff($staff_id){
        /*$url = '59f933a395abe';
        $data['staff_id']= $staff_id;
        $info = sx_call($url, $data);*/
        $data['staff_id']= $staff_id;
        $mc = new \app\common\lib\mcInterface();
        $info = $mc->getOneStaff($data);
        
        $res = db('c_staff_group')->where('department_id', $info['data']['department_id'])->find();
        
        $return['dname'] = $info['data']['department_name'];
        $return['gname'] = $res['group_name'];
        return $return;
    }
    // 根据shop_code 获取该店加权系数
    public function getShopWeight($shop_code){
        $weight = cache('shopWeight_'.$shop_code);
        if (!$weight) {
            $url = '5a005e0038270';
            $data['shop_code'] = $shop_code;
            $info = sx_call($url, $data);
            if ($info['code'] == 200) {
                $weight = $info['data'][0]['weight'];
                if ($weight == 0) {
                    $weight = 1;
                }
                cache('shopWeight_'.$shop_code, $weight);
            }else{
                $weight = '1';
            }
        }
        return $weight;
    }

    // 大屏专用  判断  该员工是否有权限查看大屏数据
    public function checkBigScreenAuth(){
        // 获取配置文件中的信息，根据,分割成数组，如果staff_id不存在，则跳转到登录或首页
        $staff_id = session('staff_id');
        $str_id = config('bigScreen_id');
        $bigScreen_id = explode(',', $str_id);
        $is_in = in_array($staff_id, $bigScreen_id);
        if ($is_in === false) {
            ///查看有无查看大屏权限
            if(check_right('menu1556162726')){
                return true;
            }
            return false;
        }else{
            return true;
        }
    }

    // 花费 
    public function costMoney($data){
        // 新单 定义：电商的花费（不包含返点） s_channel_cost 表
        $allCost = db('s_channel_cost')
            ->where('shop_code', 'in', $data['add_shop_code'])
            ->where('cost_date', 'between time', [$data['start'], $data['end']])
            ->field('id,channel_id,sum(cost) as cost')
            ->group('channel_id')
            ->select();
        // $cost = 0;
        $cost = 0;
        foreach ($allCost as $key => $value) {
            $returnCost = db('s_shop_return_rule')->where('channel_id', $value['channel_id'])->field('return_rule,return_value')->find();
            if ($returnCost) {
                // 占比
                if ($returnCost['return_rule'] == 1) {
                    $cost += $value['cost'] * ((100-$returnCost['return_value'])/100);
                }
                // 定额
                else if ($returnCost['return_rule'] == 2) {
                    $cost += $value['cost'] - $returnCost['return_value'];
                }
            }else{
                $cost += $value['cost'];
            }
        }
        return $cost;
    }

    // 获取毛客资量 
    public function getCustomerNum($data){
        // 毛客资定义：电商录入的新客资，不包括网销，渠道录入的客资
        $where['is_status'] = 1;
        $where['c_from'] = 1;
        if ($data['brandclass_id']) {
            $where['brandclass_id'] = $data['brandclass_id'];
        }
        if ($data['add_shop_code']) {
            $shop_code = '';
            foreach ($data['add_shop_code'] as $key => $value) {
                $shop_code .= '"'.$value.'",';
            }
            $shop_code = trim($shop_code,',');
            $sql = 'add_shop_code IN ('.$shop_code.')';
        }
        $num = db('c_customerinfo force index(all_time)')
            ->where($where)
            ->where($sql)
            ->where('dj_day', 'between time', [$data['start'], $data['end']])
            ->count();
        return $num;
    }

    // 获取有效客资 量
    public function getInvCustomerNum($data){
        // 有效客资定义：毛客资中，标记有效的
        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['is_valid'] = 1;
        $num = db('c_customerinfo force index(all_time)')
            ->where($where)
            ->where('shop_code', 'in', $data['add_shop_code'])
            ->where('yx_day', 'between time', [$data['start'], $data['end']])
            ->count();
        return $num;
    }

    // 进店 量
    public function getIntoCustomerNum($data){
        $where['is_status'] = 1;
        $where['c_from'] = 1;

        $num = db('c_customerinfo force index(all_time)')
            ->where($where)
            ->where('is_intostore', 'in', [2,3,5])
            ->where('shop_code', 'in', $data['add_shop_code'])
            ->where('syjd_day', 'between time', [$data['start'], $data['end']])
            ->count();
        return $num;
    }

    // 新单 量
    public function getOrderNumberNum($data){
        // 如果是查店的数据
        if ($data['type'] == 'shop') {
            $shop_code = '';
            foreach ($data['add_shop_code'] as $key => $value) {
                $shop_code .= '"'.$value.'",';
            }
            $shop_code = trim($shop_code,',');
            $sql = 'c.shop_code IN ('.$shop_code.')';
        }
        // 如果是查部门或者小组客资
        else if ($data['type'] == 'department' || $data['type'] == 'group') {
            $sql = 'c.sales_staff_id in ('.$data['ids'].')';
        }
        $num = db('c_customer_order')->alias('o')
            ->join('c_customerinfo c', 'c.id=o.customer_id', 'LEFT')
            ->where('o.order_valid', 2)
            ->where('o.is_delete', 2)
            ->where('o.valid_time', 'between time', [$data['start'], $data['end']])
            ->where($sql)
            ->where('c.is_status', 1)
            ->where('c.c_from', 1)
            ->count();
        // echo db()->getLastSql().'<br />';
        // exit;
        return $num;
    }

    // 套系总额
    public function dealMoney($data){
        // 如果是查店的数据
        if ($data['type'] == 'shop') {
            $shop_code = '';
            foreach ($data['add_shop_code'] as $key => $value) {
                $shop_code .= $value.',';
            }
            $shop_code = trim($shop_code,',');
            $sql = 'o.shop IN ('.$shop_code.')';
        }
        // 如果是查部门或者小组客资
        else if ($data['type'] == 'department' || $data['type'] == 'group') {
            $sql = 'c.sales_staff_id in ('.$data['ids'].')';
        }
        $where['c.is_status'] = 1;
        $where['c.c_from'] = 1;
        $deal = db('c_customer_order')->alias('o')
            ->join('c_customerinfo c ','c.id = o.customer_id')
            ->where($where)
            ->where($sql)
            ->where('o.order_valid', 2)
            ->where('o.valid_time', 'between time', [$data['start'], $data['end']])
            ->sum('o.order_amount');
        return $deal;
    }

    // 营收 / 实收  当日的实际收款金额 不区分客资类型，不区分crm/erp 
    public function incomeMoney($data){
        // 如果是查店的数据
        if ($data['type'] == 'shop') {
            $shop_code = '';
            foreach ($data['add_shop_code'] as $key => $value) {
                $shop_code .= $value.',';
            }
            $shop_code = trim($shop_code,',');
            $sql = 'o.shop IN ('.$shop_code.')';
        }
        // 如果是查部门或者小组客资
        else if ($data['type'] == 'department' || $data['type'] == 'group') {
            $sql = 'c.sales_staff_id in ('.$data['ids'].')';
        }
        $income = db('c_order_detail')->alias('d')
            ->join('c_customer_order o', 'd.order_sn=o.order_sn', 'LEFT')
            ->join('c_customerinfo c', 'c.id=o.customer_id', 'LEFT')
            ->where($sql)
            ->where('d.pay_time', 'between time', [$data['start'], $data['end']])
            ->sum('d.order_fact');
        return $income;
    }

}