<?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 Jujiao extends Controller{

    protected $shops = [
        0 => [
            'shop_code'=>'JJ001',
            'shop_name'=>'北京聚焦婚纱摄影',
        ],
        // 1 => [
        //     'shop_code'=>'',
        //     'shop_name'=>'天津聚焦婚纱摄影',
        // ],
        // 2 => [
        //     'shop_code'=>'',
        //     'shop_name'=>'沈阳聚焦婚纱摄影',
        // ],
        // 3 => [
        //     'shop_code'=>'',
        //     'shop_name'=>'聚焦baby-三元桥店',
        // ],
        // 4 => [
        //     'shop_code'=>'',
        //     'shop_name'=>'聚焦baby-永旺店',
        // ],
        5 => [
            'shop_code'=>'JJET003',
            'shop_name'=>'聚焦baby-网络店',
        ],
        // 6 => [
        //     'shop_code'=>'',
        //     'shop_name'=>'聚焦baby-杭州店',
        // ],
        // 7 => [
        //     'shop_code'=>'',
        //     'shop_name'=>'聚焦baby-沈阳店',
        // ],
    ];
    
    // 根据事业部获取  店 （电商，网销，渠道）
    public function getShops($brandclass_id){
        return $this->shops;
        // $url = '5a37a1503264d';
        // $data['brandclass_id']= $brandclass_id;
        $url = "5a005e0038270";
        $data= [];
        $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);
        $name = $info['data']['staffname'];
        return $name;
    }

    // 根据员工id，获取员工所属部门及小组
    public function getDGForStaff($staff_id){
        $url = '59f933a395abe';
        $data['staff_id']= $staff_id;
        $info = sx_call($url, $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;
    }
    
    // 根据员工id 获取 事业部 店 部门 列表
    public function getLists($staff_id){
        $staffInfo = getStaffInfoById($staff_id);
        // 判断所属
        switch ($staffInfo['is_belong']) {
            // 集团     事业部列表
            case '1':
                $url = '5a38840b15ba9';
                $data['id'] = '';
                $res = sx_call($url,$data);
                if ($res['code'] == 200) {
                    $brandclassList = $res['data'];
                }else{
                    $brandclassList = '';
                }
                $shopList = '';
                $departmentList = '';
                break;
            // 事业部   店列列表（电商，网销，渠道）
            case '2':
                $brandclassList = [
                    '0' =>[
                        'id'=>$staffInfo['brandclass_id'], 
                        'brandclass'=>$staffInfo['brandclass']
                    ]
                ];
                $url = '5a37a1503264d';
                $data['brandclass_id'] = $staffInfo['brandclass_id'];
                $res = sx_call($url,$data);
                if ($res['code'] == 200) {
                    $shopList = $res['data'];
                }else{
                    $shopList = '';
                }
                $departmentList = '';
                break;
            // 店   部门列表
            case '3':
                $brandclassList = [
                    '0' =>[
                        'id'=>$staffInfo['brandclass_id'], 
                        'brandclass'=>$staffInfo['brandclass']
                    ]
                ];
                $shopList = [
                    '0' =>[
                        'shop_code'=>$staffInfo['shop_code'],
                        'shop_name'=>$staffInfo['shop_name']
                    ]
                ];
                $url = '5a0aef152b750';
                $data['shop_code'] = $staffInfo['shop_code'];
                $res = sx_call($url, $data);
                if ($res['code'] == 200) {
                    $departmentList = $res['data'];
                }else{
                    $departmentList = '';
                }
                break;
            default:
                $brandclassList = [
                    '0' =>[
                        'id'=>$staffInfo['brandclass_id'], 
                        'brandclass'=>$staffInfo['brandclass']
                    ]
                ];
                $shopList = [
                    '0' =>[
                        'shop_code'=>$staffInfo['shop_code'],
                        'shop_name'=>$staffInfo['shop_name']
                    ]
                ];
                $url = '5a0aef152b750';
                $data['shop_code'] = $staffInfo['shop_code'];
                $res = sx_call($url, $data);
                if ($res['code'] == 200) {
                    $departmentList = $res['data'];
                }else{
                    $departmentList = '';
                }
                break;
        }

        $lists = [
            'brandclassList' => $brandclassList,
            'shopList'       => $shopList,
            'departmentList' => $departmentList,
        ];
        return $lists;
    }

    // 大屏专用  判断  该员工是否有权限查看大屏数据
    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) {
            // controller('crm/Index','controller')->index();
            // exit;
            return false;
        }else{
            return true;
        }
    }

    // 获取毛客资 量
    public function getCustomerNum($data){
        // 有效客资定义：毛客资中，标记有效的，消费类型为婚纱
        $where['is_status'] = 1;
        // $where['c_from'] = 1;
        $where['customer_type'] = 1;
        // $where['is_valid'] = 1;
        $num = db('c_customerinfo force index(dj)')
            ->where($where)
            ->where('add_shop_code', 'in', $data['add_shop_code'])
            ->where('dj_day', 'between time', [$data['start'], $data['end']])
            ->count();
        // echo db()->getLastSql();
        // exit;
        return $num;
    }

    // 获取有效客资 量
    public function getInvCustomerNum($data){
        // 有效客资定义：毛客资中，标记有效的 聚焦  按照登记时间查
        $where['is_status'] = 1;
        // $where['c_from'] = 1;
        $where['customer_type'] = 1;
        $where['is_valid'] = 1;
        $num = db('c_customerinfo force index(dj)')
            ->where($where)
            ->where('add_shop_code', 'in', $data['add_shop_code'])
            ->where('dj_day', 'between time', [$data['start'], $data['end']])
            ->count();
        return $num;
    }

    // 进店/邀约 量
    // public function getIntoCustomerNum($data){
    //     // 进店/邀约定义：电商、网销录入的新客资  且实际进店，标记为进店进客 
    //     // $where['c_from']        = 1;
    //     $where['is_status']     = 1;
    //     $where['is_intostore']  = 2;
    //     $where['customer_type'] = 1;

    //     $num = db('c_customerinfo')
    //         ->where($where)
    //         ->where('shop_code', 'in', $data['add_shop_code'])
    //         ->where('syjd_day', 'between time', [$data['start'], $data['end']])
    //         ->count();
    //     return $num;
    // }

    // 自然进店  渠道标记为 ‘自然进店’
    public function getIntoCustomerNum($data){
        $where['is_status']     = 1;
        $where['customer_channel'] = '自然进店';

        $num = db('c_customerinfo')
            ->where($where)
            ->where('shop_code', 'in', $data['add_shop_code'])
            ->where('dj_day', 'between time', [$data['start'], $data['end']])
            ->count();
        return $num;
    }

    // 新单 量
    public function getOrderNumberNum($data){
        $start = date('Ymd',strtotime($data['start']));
        $end = date('Ymd',strtotime($data['end']));
        
        $num = db('c_customerorder', 'sx_erp_hs')
            ->where('shop_code', 'in', $data['add_shop_code'])
            ->where('payment_money', '>', 0)
            ->where('targetdate', 'between', [$start, $end])
            ->count();
        // echo db('c_customerorder', 'sx_erp_hs')->getLastSql();
        // exit;
        // $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.shop_code', 'in', $data['add_shop_code'])
        //     //->where('o.order_amount', '>', '0')
        //     ->where('o.target_time', 'between time', [$data['start'], $data['end']])
        //     ->count();
        // echo db()->getLastSql();
        // exit;
        return $num;
    }

    //其它费用统计
    public function anotherCost($param){
        $start = $param['start'] ? $param['start'] : date('Y-m-d 00:00:00');
        $end   = $param['end'] ? $param['end'] : date('Y-m-d 23:59:59');
        $sql = ' 1=1 ';
        if($param['brandclass_id']){
            $sql .= " and brandclass_id=".intval($param['brandclass_id']);
        }
        // if($param['add_shop_code']){
        //     $add_shop_code = explode(',',$param['add_shop_code']);
        // }
        $info = db('s_another_cost_detail')
            ->where($sql)
            // ->where('shop_code','in',$add_shop_code)
            ->where('cost_date','between time',[$start,$end])
            ->sum('cost_avg');
        return$info;
    }

    // 花费 
    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;
        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 dealMoney($data){
        // 新单 定义：电商、网销录入的新客资转化为订单，消费类型为婚纱，的有效订单 的 一销套系金额  只能查 customer_order表
        // 根据customerinfo 表查 电商、网销 录入的新客资，消费类型为婚纱，已经有效的订单，order_day 为条件时间，根据customer_id，join customer_order表，sum('order_amount')

        // $where['c.is_status'] = 1;
        // // $where['c.c_from'] = 1;
        // $where['c.customer_type'] = 1;
        // $where['c.consultation_type_id'] = HS_TYPE;
        // $where['c.is_success'] = 1;

        // $deal = db('c_customer_order')->alias('o')
        //     ->join('c_customerinfo c ','c.id = o.customer_id')
        //     ->where($where)
        //     ->where('o.order_valid', 2)
        //     ->where('c.add_shop_code', 'in', $data['add_shop_code'])
        //     ->where('o.create_time', 'between time', [$data['start'], $data['end']])
        //     ->sum('o.order_amount');

        // $deal = db('c_customer_order')->alias('o')
        //     ->join('c_customerinfo c', 'c.id=o.customer_id', 'LEFT')
        //     ->where('o.is_delete', 2)
        //     ->where('o.shop_code', 'in',$data['add_shop_code'])
        //     ->where('o.create_time', 'between time', [$data['start'], $data['end']])
        //     ->sum('o.order_amount');

        $start = date('Ymd',strtotime($data['start']));
        $end = date('Ymd',strtotime($data['end']));

        $deal = db('c_customerorder', 'sx_erp_hs')
            ->where('shop_code', 'in', $data['add_shop_code'])
            ->where('targetdate', 'between', [$start, $end])
            ->sum('bargain_money');

        // echo db('c_customerorder', 'sx_erp_hs')->getLastSql();
        // exit;
        return $deal;
    }


    // 营收 / 实收
    public function incomeMoney($data){
        // 新单 定义：实际收入，不限 电商还是网销、消费类型、订单状态是否有效 
        $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('c.shop_code', 'in', $data['add_shop_code'])
            ->where('d.pay_time', 'between time', [$data['start'], $data['end']])
            ->sum('d.order_fact');
        return $income;
    }


}