<?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 Tcdj extends Controller{
    // 大屏专用  判断  该员工是否有权限查看大屏数据
    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 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 getShopCode($brandclass_id=0) {
        $mc = new \app\common\lib\mcInterface();
        $param['brandclass_id'] = (int)$brandclass_id;
        $brandShops = $mc->getShops($param);

        $no_shops = config('no_bigScreen_shops');
        $no_shops = explode(',', $no_shops);

        $hsAllShops = [];
        $etAllShops = [];
        foreach ($brandShops as $key => $value) {
            if (in_array($value['shop_code'], $no_shops)) {
                continue;
            }else{
                if ($value['shop_type']==2) {
                    $temp['shop_type'] = $value['shop_type'];
                    $temp['shop_code'] = $value['shop_code'];
                    $temp['shop_name'] = $value['shop_name'];
                    $temp['belong_shop_code'] = $value['belong_shop_code'];
                    $temp['belong_shop_name'] = $value['belong_shop_name'];
                    $temp['brandclass_id'] = $value['brandclass_id'];
                    $temp['brandclass']    = $value['brandclass'];
                    array_push($etAllShops, $temp);
                }else{
                    $temp['shop_type'] = $value['shop_type'];
                    $temp['shop_code'] = $value['shop_code'];
                    $temp['shop_name'] = $value['shop_name'];
                    $temp['belong_shop_code'] = $value['belong_shop_code'];
                    $temp['belong_shop_name'] = $value['belong_shop_name'];
                    $temp['brandclass_id'] = $value['brandclass_id'];
                    $temp['brandclass']    = $value['brandclass'];
                    array_push($hsAllShops, $temp);
                }
            }
        }
        return array('hs'=>$hsAllShops, 'et'=>$etAllShops);
    }

    // 花费
    public function costMoney($data){
        if ($data['add_shop_code']) {
            $shop_code = '';
            if ($data['add_shop_code']['hs']) {
                foreach ($data['add_shop_code']['hs'] as $key => $value) {
                    $shop_code .= $value['shop_code'].',';
                }
            }
            if ($data['add_shop_code']['et']) {
                foreach ($data['add_shop_code']['et'] as $key => $value) {
                    $shop_code .= $value['shop_code'].',';
                }
            }
            $shop_code = trim($shop_code,',');
            $where['shop_code'] = ['in',explode(',',$shop_code)];
        }
        // 新单 定义：电商的花费（不包含返点） s_channel_cost 表
        $allCost = db('s_channel_cost')
            ->where($where)
            ->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;
    }

    // 获取毛客资量 crm录入的客资
    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 = '';
            if ($data['add_shop_code']['hs']) {
                foreach ($data['add_shop_code']['hs'] as $key => $value) {
                    $shop_code .= $value['shop_code'].',';
                }
            }
            if ($data['add_shop_code']['et']) {
                foreach ($data['add_shop_code']['et'] as $key => $value) {
                    $shop_code .= $value['shop_code'].',';
                }
            }
            $shop_code = trim($shop_code,',');
            $where['add_shop_code'] = ['in',explode(',',$shop_code)];
        }
        // var_dump($shop_code);die;
        $num = db('c_customerinfo force index(all_time)')
            ->where($where)
            ->where('dj_day', 'between time', [$data['start'], $data['end']])
            ->count();
        // echo db()->getLastSql();die;
        return $num;
    }

    // 获取有效客资 量
    public function getInvCustomerNum($data){
        if ($data['add_shop_code']) {
            $shop_code = '';
            if ($data['add_shop_code']['hs']) {
                foreach ($data['add_shop_code']['hs'] as $key => $value) {
                    $shop_code .= $value['shop_code'].',';
                }
            }
            if ($data['add_shop_code']['et']) {
                foreach ($data['add_shop_code']['et'] as $key => $value) {
                    $shop_code .= $value['shop_code'].',';
                }
            }
            $shop_code = trim($shop_code,',');
            $where['shop_code'] = ['in',explode(',',$shop_code)];
        }
        // 有效客资定义：毛客资中，标记有效的
        $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', $shop_code)
            ->where('yx_day', 'between time', [$data['start'], $data['end']])
            ->where('dj_day', 'between time', [$data['start'], $data['end']])
            ->count();
        return $num;
    }

    // 进店 量
    public function getIntoCustomerNum($data){
        if ($data['add_shop_code']) {
            $shop_code = '';
            if ($data['add_shop_code']['hs']) {
                foreach ($data['add_shop_code']['hs'] as $key => $value) {
                    $shop_code .= $value['shop_code'].',';
                }
            }
            if ($data['add_shop_code']['et']) {
                foreach ($data['add_shop_code']['et'] as $key => $value) {
                    $shop_code .= $value['shop_code'].',';
                }
            }
            $shop_code = trim($shop_code,',');
            $where['shop_code'] = ['in',explode(',',$shop_code)];
        }

        $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('syjd_day', 'between time', [$data['start'], $data['end']])
            ->count();
        return $num;
    }

    // 新单 量
    public function getOrderNumberNum($data){
        // 如果是查店的数据
        $where = [];
        if ($data['type'] == 'shop') {
            $shop_code = '';
            if ($data['add_shop_code']['hs']) {
                foreach ($data['add_shop_code']['hs'] as $key => $value) {
                    $shop_code .= $value['shop_code'].',';
                }
            }
            if ($data['add_shop_code']['et']) {
                foreach ($data['add_shop_code']['et'] as $key => $value) {
                    $shop_code .= $value['shop_code'].',';
                }
            }
            $shop_code = trim($shop_code,',');
            $where['c.shop_code'] = ['in',explode(',',$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('c.order_day', 'between time', [$data['start'], $data['end']])
            ->where($where)
            ->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 = '';
            if ($data['add_shop_code']['hs']) {
                foreach ($data['add_shop_code']['hs'] as $key => $value) {
                    $shop_code .= $value['shop_code'].',';
                }
            }
            if ($data['add_shop_code']['et']) {
                foreach ($data['add_shop_code']['et'] as $key => $value) {
                    $shop_code .= $value['shop_code'].',';
                }
            }
            $shop_code = trim($shop_code,',');
            $where['o.shop_code'] = ['in',explode(',',$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('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 = '';
            if ($data['add_shop_code']['hs']) {
                foreach ($data['add_shop_code']['hs'] as $key => $value) {
                    $shop_code .= $value['shop_code'].',';
                }
            }
            if ($data['add_shop_code']['et']) {
                foreach ($data['add_shop_code']['et'] as $key => $value) {
                    $shop_code .= $value['shop_code'].',';
                }
            }
            $shop_code = trim($shop_code,',');
            $where['o.shop_code'] = ['in',explode(',',$shop_code)];
        }
        // 如果是查部门或者小组客资
        else if ($data['type'] == 'department' || $data['type'] == 'group') {
            $sql = 'c.sales_staff_id in ('.$data['ids'].')';
        }elseif($data['brandclass_id']){
            $sql = ' c.brandclass_id='.$data['brandclass_id'];
        }
        $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($where)
            ->where('d.pay_time', 'between time', [$data['start'], $data['end']])
            ->sum('d.order_fact');
        return $income;
    }
    // 电商 营收
    public function getOrderMoney($param) {
        if ($param['brandclass_id']) {
            $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('o.brandclass_id', $param['brandclass_id'])
                ->where('c.add_shop_code', 'in', $param['add_shop_code'])
                ->where('d.pay_time', 'between time', [$param['start'], $param['end']])
                ->sum('d.order_fact');
        }else{
            $income = db('c_order_detail')
                ->where('pay_time', 'between time', [$param['start'], $param['end']])
                ->sum('order_fact');
        }
        return $income;
    }

    // -------------------- //
    /*
     * 根据报表设定，取有效客资数量
     *
     * @param string  $param['start']/['end']时间 (开始，结束)
     * @param string  $param['shop_code']shop_code
     * @param string  $param['valid_customer_consumptiontype']有效客资条件
     * @param string  $param['branclass_id']事业部id
     *
     * @return string
     */
    public function getValidCustomer($param){
        $where['c_from'] = 1;
        $where['is_valid'] = 1;
        $where['is_status'] = 1;
        $where['add_shop_code'] = $param['shop_code'];
        $where['brandclass_id'] = $param['brandclass_id'];

        if ($param['valid_customer_consumptiontype']) {
            $where['consultation_type_id'] = $param['valid_customer_consumptiontype'];
        }

        $validCustomer = db('c_customerinfo')
            ->where($where)
            ->where('yx_day', 'between', [$param['start'], $param['end']])
            ->count();

        return $validCustomer;
    }

    /*
     * 没有接收的客资
     *
     * @param string  $param['start']/['end']时间 (开始，结束)
     * @param string  $param['shop_code']shop_code
     * @param string  $param['branclass_id']事业部id
     *
     * @return string
     */
    public function getNoReceiveCustomer($param){
        $where['c_from'] = 1;
        $where['is_status'] = 1;
        $where['add_shop_code'] = $param['shop_code'];
        $where['brandclass_id'] = $param['brandclass_id'];

        $noReceiveCustomer = db('c_customerinfo')
            ->where($where)
            ->where('is_fp', '<>', 1)
            ->where('dj_day', 'between', [$param['start'], $param['end']])
            ->count();

        return $noReceiveCustomer;
    }

    /*
     * 在线员工数量
     *
     * @param string  $param['shop_code']shop_code
     *
     * @return string
     */
    public function getOnlineStaffs($param){
        $staffs = cache('staffs_hw_'.$param['shop_code']);
        if (!$staffs) {
            $url = '5a1510583e3a5';
            $data['shop_code'] = $param['shop_code'];
            $data['work_type'] = RECEIVE_WORK_TYPE;
            $data['get_leave'] = 2;
            $info = sx_call($url, $data);
            if ($info['code'] == 200) {
                $staffs = $info['data'];
                cache('staffs_hw_'.$param['shop_code'], $staffs);
            }
        }

        $onlineStaffs = 0;
        foreach ($staffs as $key => $value) {
            $status = controller('Customer','lib')->getStaffOnlineStatus($value['id']);
            if ($status) {
                $onlineStaffs++;
            }
        }

        return $onlineStaffs;
    }

    /*
     * 获取各电商渠道客资数量 (毛客资)
     *
     * @param string  $param['start']/['end']时间 (开始，结束)
     * @param string  $param['shop_code']shop_code
     * @param string  $param['branclass_id']事业部id
     *
     * @return string
     */
    public function getChannelCustomerNum($param){
        $where['c_from'] = 1;
        $where['is_status'] = 1;
        $where['brandclass_id'] = $param['brandclass_id'];

        $channelCustomerNum = db('c_customerinfo')
            ->where($where)
            ->where('add_shop_code', 'in', $param['shop_codes'])
            ->where('dj_day', 'between', [$param['start'], $param['end']])
            ->group('customer_channel')
            ->column('count(*) as num, customer_channel','customer_channel');

        // 获取店下所有渠道
        $channels = db('s_channel')->where('shop_code', 'in', $param['shop_codes'])->group('channel_name')->field('channel_name')->select();

        $returnData = [];
        foreach ($channels as $key => $value) {
            $returnData[$key]['channel_name']=$value['channel_name'];

            if ($channelCustomerNum[$value['channel_name']]) {
                $num = $channelCustomerNum[$value['channel_name']];
            }else{
                $num = 0;
            }
            $returnData[$key]['num']= $num;
        }
        foreach ($returnData as $key => $value) {
            if ($value['num']==0) {
                unset($returnData[$key]);
            }
        }
        // var_dump($returnData);
        // exit;
        $sort_order = 'SORT_DESC';
        $returnData = my_sort($returnData, 'num', $sort_order);

        return $returnData;
    }

    /*
     * 无效客资原因统计
     *
     * @param string  $param['start']/['end']时间 (开始，结束)
     * @param string  $param['shop_code']shop_code
     * @param string  $param['branclass_id']事业部id
     *
     * @return string
     */
    public function getUnvalidCustomer($param){
        $where['c_from'] = 1;
        $where['is_status'] = 1;
        $where['brandclass_id'] = $param['brandclass_id'];

        $unvalidCustomerNum = db('c_customerinfo')
            ->where($where)
            ->where('add_shop_code', 'in', $param['shop_codes'])
            ->where('dj_day', 'between', [$param['start'], $param['end']])
            ->where('unvalid_reason', 'not null')
            ->group('unvalid_reason')
            ->column('count(*) as num, unvalid_reason','unvalid_id');
        // echo db()->getLastSql();
        // exit;
        // 获取所有无效原因
        $unValidReason = cache('unValidReason');
        if(empty($unValidReason)){
            $url = '5af3fe7a0a668';
            $data= [];
            $res = sx_call($url,$data);
            if($res['code'] == 200){
                $unValidReason = $res['data'];
                cache('unValidReason'.$unValidReason);
            }
        }

        $returnData = [];
        foreach ($unValidReason as $key => $value) {
            $returnData[$value['id']]['reason']=$value['reason'];
            if ($unvalidCustomerNum[$value['id']]['num']) {
                $num = $unvalidCustomerNum[$value['id']]['num'];
            }else{
                $num = 0;
            }
            $returnData[$value['id']]['num']= $num;
        }
        foreach ($returnData as $key => $value) {
            if ($value['num'] ==0) {
                unset($returnData[$key]);
            }
        }
        // var_dump($returnData);
        // exit;
        $sort_order = 'SORT_DESC';
        $returnData = my_sort($returnData, 'num', $sort_order);

        return $returnData;
    }

    /*
     * 取无效客资数量
     *
     * @param string  $param['start']/['end']时间 (开始，结束)
     * @param string  $param['shop_code']shop_code
     * @param string  $param['branclass_id']事业部id
     *
     * @return string
     */
    public function getUnvalidCustomerNum($param){
        $where['c_from'] = 1;
        $where['is_valid'] = 3;
        $where['is_status'] = 1;
        $where['add_shop_code'] = $param['shop_code'];
        $where['brandclass_id'] = $param['brandclass_id'];

        // if ($param['valid_customer_consumptiontype']) {
        //     $where['consultation_type_id'] = $param['valid_customer_consumptiontype'];
        // }

        $unvalidCustomer = db('c_customerinfo')
            ->where($where)
            ->where('yx_day', 'between', [$param['start'], $param['end']])
            ->count();

        return $unvalidCustomer;
    }
    // 婚纱营收
    public function getHSFact($data){
        $num = db('c_paymentcontent', 'sx_erp_hs')
            ->where('shop_code','in',$data['shop_code'])
            ->where('paymentdate', 'between', [$data['start'], $data['end']])
            ->sum('payment_money');
        return $num;
    }
    // 儿童营收
    public function getETFact($data){
        $num = db('c_paymentcontent', 'sx_erp_et')
            ->where('shop_code','in',$data['shop_code'])
            ->where('paymentdate', 'between', [$data['start'], $data['end']])
            ->sum('payment_money');
        return $num;
    }
}