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

class Logs extends Base{
    public function index(){
        $control = 'Setting';
        $actions = $this->getActions('app\crm\controller' . '\\' . $control);
        $arr = [];
        foreach($actions as $k=>$v){
            $info = $this->get_cc_desc('crm','Setting',$v);
            if($info != ''){
                $arr[strtolower($v)] = $info;
            }
        }
        print_r($arr);
    }
    function getActions($className, $base='\app\crm\controller\Setting') {
        $methods = get_class_methods(new $className());
        $baseMethods = get_class_methods(new $base());
        $res = array_diff($methods, $baseMethods);
        return $baseMethods;
    }
    /**
     * @cc 获取函数的注释
     *
     * @param $module Home
     * @param $controller Auth
     * @param $action index
     *
     * @return string 注释
     *
     */
    protected function get_cc_desc($module,$controller,$action){
        $desc='app\crm\controller\Setting';
        $func  = new \ReflectionMethod(new $desc(),$action);
        $tmp   = $func->getDocComment();
        $flag  = preg_match_all('/@cc(.*?)\n/',$tmp,$tmp);
        $tmp   = trim($tmp[1][0]);
        $tmp   = $tmp !='' ? $tmp:'';
        return $tmp;
    }
    // 查看在线网销 页面
    public function checkOnlineStaff(){
        // 权限
        $auth = check_right('menu1538119117');
        if (!$auth) {
            return $this->redirect('/');
        }
        $shopList = [];
        // 当前店和客资提报归属店 是同一个店
        if (session('shop_code') == session('belong_shop_code')) {
            $shopList[0] = [
                'shop_code'=>session('shop_code'),
                'shop_name'=>session('shop_name'),
            ];
        }else{
            $shopList[0] = [
                'shop_code'=>session('belong_shop_code'),
                'shop_name'=>session('belong_shop_name'),
            ];
        }

        $this->assign('shopList',$shopList);
        // 是否开启自动分配
        $fpStatus = db_config('fp_switch_'.$shopList[0]['shop_code']);

        if($fpStatus==1){
            $this->assign('fpStatus', 1);
            // 当前店面下的规则
            $temp_rule = db('s_allocation_rule')->where('shop_code', $shopList[0]['shop_code'])->where('isopen',1)->order('order_sort asc')->field('id,customer_condition,staff_type,staff_value,order_sort')->select();
            $rule = [];
            foreach ($temp_rule as $key => $value) {
                $rule[$key]['id'] = $value['id'];
                $rule[$key]['order_sort'] = $value['order_sort'];
                switch ($value['customer_condition']) {
                    case 'customer_channel':
                        $rule[$key]['customer_condition'] = '来源渠道';
                        $rule[$key]['staffs'] = [];
                        break;
                    case 'customer_region':
                        $rule[$key]['customer_condition'] = '地域';
                        $rule[$key]['staffs'] = [];
                        break;
                    case 'add_organize':
                        $rule[$key]['customer_condition'] = '提报人';
                        $rule[$key]['staffs'] = [];
                        break;
                    case 'default':
                        $rule[$key]['customer_condition'] = '默认规则';
                        switch ($value['staff_type']) {
                            case 'department_name':
                                $dInfo = json_decode($value['staff_value'], true);
                                // 取部门下的员工 工作类型是话务
                                $param['shop_code']     = $shopList[0]['shop_code'];
                                $param['department_id'] = $dInfo[0]['department_id'];
                                $param['work_type']     = RECEIVE_WORK_TYPE;
                                $temp_staff = controller('crm/Customer')->getDepartmentStaffs($param);
                                break;
                            case 'position_name':
                                $pInfo = json_decode($value['staff_value'], true);
                                // 岗位下的员工  工作类型是话务
                                $param['shop_code']   = $shopList[0]['shop_code'];
                                $param['position_id'] = $pInfo[0]['position_id'];
                                $param['work_type']   = RECEIVE_WORK_TYPE;
                                $temp_staff = getPositionStaffs($param);
                                // var_dump($temp_staff);
                                // exit;
                                break;
                            case 'group_name':
                                $gInfo = json_decode($value['staff_value'], true);
                                // 小组下的员工
                                $param['group_id'] = $gInfo[0]['group_id'];
                                $temp_staff = getGroupStaffs($param);
                                break;
                            case 'staff_name':
                                $temp_staff = json_decode($value['staff_value'], true);
                                break;
                        }

                        $staffList = [];
                        $sids = '';
                        $next = cache('fpCustomerP'.$value['id']);
                        if ($next) {
                            $last = $next-1;
                        }else{
                            $next = 0;
                            $last = count($temp_staff)-1;
                        }

                        // var_dump($temp_staff);
                        // exit;
                        foreach ($temp_staff as $k => $v) {
                            // 排队状态
                            if ($k == $next) {
                                $staffList[$v['staff_id']]['jr_status'] = '<span style="color: #01b88a;font-size: larger">排队中</span>';
                            }else if ($k == $last){
                                $last_status = db('l_fp_logs')
                                    ->where('jr_staff_id', $v['staff_id'])
                                    ->where('fp_model', 1)
                                    ->where('fp_brandclass_id', session('brandclass_id'))
                                    ->whereTime('jr_time', 'today')
                                    ->order('fp_time desc')
                                    ->value('fp_status');
                                // 分配状态（1：已分配；2：未分配；3：待接收；4：分配失败；5：放弃）
                                switch ($last_status) {
                                    case '1':
                                        $str = '已分配';
                                        break;
                                    case '2':
                                        $str = '未分配';
                                        break;
                                    case '3':
                                        $str = '待接收';
                                        break;
                                    case '4':
                                        $str = '分配失败';
                                        break;
                                    case '5':
                                        $str = '已放弃';
                                        break;
                                    default:
                                        $str = '未分配';
                                        break;
                                }
                                $staffList[$v['staff_id']]['jr_status'] = '<span style="color: #01b88a;font-size: larger">'.$str.'</span>';
                            }else{
                                $staffList[$v['staff_id']]['jr_status'] = '<span style="color:#cccccc;font-size: larger"">等待中</span>';
                            }
                            // 判断在线 不在线
                            $status = controller('crm/Customer','lib')->getStaffOnlineStatus($v['staff_id']);
                            if ($status) {
                                $staffList[$v['staff_id']]['status'] = '<span style="color: #01b88a;font-size: larger">在线</span>';
                            }
                            // 不在线
                            else{
                                // 是否开启离线接收客资
                                if (db_config('not_online_is_fp_'.$v['staff_id']) == 1) {
                                    // $staffList[$v['staff_id']]['not_online_is_fp'] = '开启，离线接收';
                                    $staffList[$v['staff_id']]['status'] = '<span style="color:#cccccc;font-size: larger">'.'不在线'.'</span>|开启，离线接收';
                                }else{
                                    // $staffList[$v['staff_id']]['not_online_is_fp'] = '';
                                    $staffList[$v['staff_id']]['status'] = '<span style="color:#cccccc;font-size: larger">'.'不在线'.'</span>';
                                }
                            }
                            $staffList[$v['staff_id']]['id'] = $v['staff_id'];
                            $staffList[$v['staff_id']]['staff_name'] = $v['staff_name'];

                            $sids .= $v['staff_id'].',';
                        }
                        $sids = trim($sids, ',');
                        // 登录信息
                        $loginData = db('s_session')->where('staff_id', 'in', $sids)->column('login_time,login_type,status,ip', 'staff_id');

                        foreach ($staffList as $k => $v) {
                            $staffList[$k]['login_time'] = $loginData[$k]['login_time'] ? date('Y-m-d H:i', strtotime($loginData[$k]['login_time'])) : '';
                        }
                        // var_dump($staffList);
                        $rule[$key]['staffs'] = $staffList;
                        break;
                }
            }
            // exit;
            $this->assign('rule', $rule);
        }else{
            $this->assign('fpStatus', 0);
        }

        $this->assign('today', date('Y-m-d'));
        $this->assign('title','签到信息表');
        return $this->fetch();
    }
    // 在线员工数据
    public function onlineStaffList(){
        $data = input();
        $shop_code = trim($data['shop_code']);

        if (!$shop_code) {
            if (session('shop_code') == session('belong_shop_code')) {
                $shop_code = session('shop_code');
            }else{
                $shop_code = session('belong_shop_code');
            }
        }

        $url = '5b75341456d18';
        $param['shop_code'] = $shop_code;
        $param['work_type'] = RECEIVE_WORK_TYPE;
        $temp_staff = sx_call($url, $param);

        $staffList = [];
        if ($temp_staff['code'] == 200) {
            // $staffList = $temp_staff['data'];
            $sids = '';
            foreach ($temp_staff['data'] as $key => $value) {
                // 判断在线 不在线
                $status = controller('crm/Customer','lib')->getStaffOnlineStatus($value['id']);
                // 在线
                if ($status) {
                    $staffList[$value['id']]['online'] = '1';
                    $staffList[$value['id']]['id']     = $value['id'];
                    $staffList[$value['id']]['staff']  = $value['staffname'];
                    $staffList[$value['id']]['status'] = '<span style="color: #01b88a;font-size: larger">在线</span>';
                    $staffList[$value['id']]['operation'] = 200;
                }
                // 不在线
                else{
                    $staffList[$value['id']]['online'] = '2';
                    $staffList[$value['id']]['id']     = $value['id'];
                    $staffList[$value['id']]['staff']  = $value['staffname'];
                    $staffList[$value['id']]['status'] = '<span style="color:#cccccc;font-size: larger">'.'不在线'.'</span>';
                    $staffList[$value['id']]['operation'] = 0;
                }
                $sids .= $value['id'].',';
            }
            $sids = trim($sids, ',');
            $where['is_fp'] = 1;
            $where['c_from'] = 1;
            $where['is_status'] = 1;

            // 分配的客资数量 (自动分配)
            $sysData = db('l_fp_logs')
                ->where('fp_status', 1)
                ->where('fp_model', 1)
                ->where('jr_staff_id', 'in', $sids)
                ->where('fp_brandclass_id', session('brandclass_id'))
                ->whereTime('jr_time', 'today')
                ->group('jr_staff_id')
                ->order('cid desc')
                ->column('count(*)', 'jr_staff_id');

            // 分配的客资数量 (其他)
            $otherData = db('l_fp_logs')
                ->where('fp_status', 1)
                ->where('fp_model', '>', 1)
                ->where('jr_staff_id', 'in', $sids)
                ->where('fp_brandclass_id', session('brandclass_id'))
                ->whereTime('jr_time', 'today')
                ->group('jr_staff_id')
                ->order('cid desc')
                ->column('count(*)', 'jr_staff_id');

            foreach ($staffList as $key => $value) {
                $staffList[$key]['sysData']  = $sysData[$key] ? $sysData[$key] : 0;
                $staffList[$key]['otherData']= $otherData[$key] ? $otherData[$key] : 0;
                $staffList[$key]['allNum']   = $staffList[$key]['sysData']+$staffList[$key]['otherData'];
            }

            // 登录信息
            $loginData = db('s_session')->where('staff_id', 'in', $sids)->column('login_time,login_type,status,ip', 'staff_id');
            foreach ($staffList as $key => $value) {
                $staffList[$key]['login_time'] = $loginData[$key]['login_time'] ? date('Y-m-d H:i', strtotime($loginData[$key]['login_time'])) : '';
                $staffList[$key]['login_type'] = $loginData[$key]['login_type'] ? $loginData[$key]['login_type'] : '';
                $staffList[$key]['ip']         = $loginData[$key]['ip'] ? $loginData[$key]['ip'] : '';
            }
        }else{
            $staffList = [];
        }

        $staffList = my_sort($staffList, 'online');

        $returnData['code'] = 0;
        $returnData['msg']  = '';
        $returnData['count']= count($staffList);
        $returnData['data'] = $staffList;
        // var_dump($returnData);
        // exit;
        return json($returnData);
    }
    // 签到详情独立页面
    public function getRuleStaff(){
        // 权限
        $auth = check_right('menu1571127958');
        if (!$auth) {
            return $this->redirect('/');
        }
        // 当前店和客资提报归属店 是同一个店
        if (session('shop_code') == session('belong_shop_code')) {
            $shopList[0] = [
                'shop_code'=>session('shop_code'),
                'shop_name'=>session('shop_name'),
            ];
        }else{
            $shopList[0] = [
                'shop_code'=>session('belong_shop_code'),
                'shop_name'=>session('belong_shop_name'),
            ];
        }

        $this->assign('shopList',$shopList);
        // 是否开启自动分配
        $fpStatus = db_config('fp_switch_'.$shopList[0]['shop_code']);
        if($fpStatus==1){
            $this->assign('fpStatus', 1);
            // 当前店面下的规则
            $temp_rule = db('s_allocation_rule')->where('shop_code', $shopList[0]['shop_code'])->where('isopen',1)->order('order_sort asc')->field('id,customer_condition,staff_type,staff_value,order_sort')->select();
            $rule = [];
            foreach ($temp_rule as $key => $value) {
                $rule[$key]['id'] = $value['id'];
                $rule[$key]['order_sort'] = $value['order_sort'];
                switch ($value['customer_condition']) {
                    case 'customer_channel':
                        $rule[$key]['customer_condition'] = '来源渠道';
                        $rule[$key]['staffs'] = [];
                        break;
                    case 'customer_region':
                        $rule[$key]['customer_condition'] = '地域';
                        $rule[$key]['staffs'] = [];
                        break;
                    case 'add_organize':
                        $rule[$key]['customer_condition'] = '提报人';
                        $rule[$key]['staffs'] = [];
                        break;
                    case 'default':
                        $rule[$key]['customer_condition'] = '默认规则';
                        switch ($value['staff_type']) {
                            case 'department_name':
                                $dInfo = json_decode($value['staff_value'], true);
                                // 取部门下的员工 工作类型是话务
                                $param['shop_code']     = $shopList[0]['shop_code'];
                                $param['department_id'] = $dInfo[0]['department_id'];
                                $param['work_type']     = RECEIVE_WORK_TYPE;
                                $temp_staff = controller('crm/Customer')->getDepartmentStaffs($param);
                                break;
                            case 'position_name':
                                $pInfo = json_decode($value['staff_value'], true);
                                // 岗位下的员工  工作类型是话务
                                $param['shop_code']   = $shopList[0]['shop_code'];
                                $param['position_id'] = $pInfo[0]['position_id'];
                                $param['work_type']   = RECEIVE_WORK_TYPE;
                                $temp_staff = getPositionStaffs($param);
                                // var_dump($temp_staff);
                                // exit;
                                break;
                            case 'group_name':
                                $gInfo = json_decode($value['staff_value'], true);
                                // 小组下的员工
                                $param['group_id'] = $gInfo[0]['group_id'];
                                $temp_staff = getGroupStaffs($param);
                                break;
                            case 'staff_name':
                                $temp_staff = json_decode($value['staff_value'], true);
                                break;
                        }

                        $staffList = [];
                        $sids = '';
                        $next = cache('fpCustomerP'.$value['id']);
                        if ($next) {
                            $last = $next-1;
                        }else{
                            $next = 0;
                            $last = count($temp_staff)-1;
                        }
                        // var_dump($temp_staff);
                        // exit;
                        foreach ($temp_staff as $k => $v) {
                            // 排队状态
                            if ($k == $next) {
                                $staffList[$v['staff_id']]['jr_status'] = '<span style="color: #01b88a;font-size: larger">排队中</span>';
                            }else if ($k == $last){
                                $last_status = db('l_fp_logs')
                                    ->where('jr_staff_id', $v['staff_id'])
                                    ->where('fp_model', 1)
                                    ->where('fp_brandclass_id', session('brandclass_id'))
                                    ->whereTime('jr_time', 'today')
                                    ->order('fp_time desc')
                                    ->value('fp_status');
                                // 分配状态（1：已分配；2：未分配；3：待接收；4：分配失败；5：放弃）
                                switch ($last_status) {
                                    case '1':
                                        $str = '已分配';
                                        break;
                                    case '2':
                                        $str = '未分配';
                                        break;
                                    case '3':
                                        $str = '待接收';
                                        break;
                                    case '4':
                                        $str = '分配失败';
                                        break;
                                    case '5':
                                        $str = '已放弃';
                                        break;
                                    default:
                                        $str = '未分配';
                                        break;
                                }
                                $staffList[$v['staff_id']]['jr_status'] = '<span style="color: #01b88a;font-size: larger">'.$str.'</span>';
                            }else{
                                $staffList[$v['staff_id']]['jr_status'] = '<span style="color:#cccccc;font-size: larger"">等待中</span>';
                            }
                            // 判断在线 不在线
                            $status = controller('crm/Customer','lib')->getStaffOnlineStatus($v['staff_id']);
                            if ($status) {
                                $staffList[$v['staff_id']]['status'] = '<span style="color: #01b88a;font-size: larger">在线</span>';
                            }
                            // 不在线
                            else{
                                // 是否开启离线接收客资
                                if (db_config('not_online_is_fp_'.$v['staff_id']) == 1) {
                                    // $staffList[$v['staff_id']]['not_online_is_fp'] = '开启，离线接收';
                                    $staffList[$v['staff_id']]['status'] = '<span style="color:#cccccc;font-size: larger">'.'不在线'.'</span>|开启，离线接收';
                                }else{
                                    // $staffList[$v['staff_id']]['not_online_is_fp'] = '';
                                    $staffList[$v['staff_id']]['status'] = '<span style="color:#cccccc;font-size: larger">'.'不在线'.'</span>';
                                }
                            }
                            $staffList[$v['staff_id']]['id'] = $v['staff_id'];
                            $staffList[$v['staff_id']]['staff_name'] = $v['staff_name'];

                            $sids .= $v['staff_id'].',';
                        }
                        $sids = trim($sids, ',');
                        // 登录信息
                        $loginData = db('s_session')->where('staff_id', 'in', $sids)->column('login_time,login_type,status,ip', 'staff_id');

                        foreach ($staffList as $k => $v) {

                            $staffList[$k]['login_time'] = $loginData[$k]['login_time'] ? date('Y-m-d H:i', strtotime($loginData[$k]['login_time'])) : '';
                        }
                        // var_dump($staffList);
                        $rule[$key]['staffs'] = $staffList;
                        break;
                }
            }
            // exit;
            $this->assign('rule', $rule);
        }else{
            $this->assign('fpStatus', 0);
        }

        $this->assign('today', date('Y-m-d'));
        $this->assign('title','签到信息表');
        return $this->fetch();
    }
    // 规则切换
    public function ruleData(){
        $rid = (int)input('post.rid');
        if (!$rid) {
            return array('code'=>100,'msg'=>'没有获取规则id。');
        }

        // 当前规则
        $this_rule = db('s_allocation_rule')->where('id', $rid)->field('id,customer_condition,staff_value')->select();
        $temp_staff = json_decode($this_rule[0]['staff_value'], true);
        $staffList = [];
        $sids = '';
        $next = cache('fpCustomerP'.$rid);
        if ($next) {
            $last = $next-1;
        }else{
            $next = 0;
            $last = count($temp_staff)-1;
        }
        foreach ($temp_staff as $k => $v) {
            // 排队状态
            if ($k == $next) {
                $staffList[$v['staff_id']]['jr_status'] = '<span style="color: #01b88a;font-size: larger">排队中</span>';
            }else if ($k == $last){
                $last_status = db('l_fp_logs')
                    ->where('jr_staff_id', $v['staff_id'])
                    ->where('fp_model', 1)
                    ->where('fp_brandclass_id', session('brandclass_id'))
                    ->whereTime('jr_time', 'today')
                    ->order('fp_time desc')
                    ->value('fp_status');
                // 分配状态（1：已分配；2：未分配；3：待接收；4：分配失败；5：放弃）
                switch ($last_status) {
                    case '1':
                        $str = '已分配';
                        break;
                    case '2':
                        $str = '未分配';
                        break;
                    case '3':
                        $str = '待接收';
                        break;
                    case '4':
                        $str = '分配失败';
                        break;
                    case '5':
                        $str = '已放弃';
                        break;
                    default:
                        $str = '已分配';
                        break;
                }
                $staffList[$v['staff_id']]['jr_status'] = '<span style="color: #01b88a;font-size: larger">'.$str.'</span>';
            }else{
                $staffList[$v['staff_id']]['jr_status'] = '<span style="color:#cccccc;font-size: larger"">等待中</span>';
            }
            // 判断在线 不在线
            $status = controller('crm/Customer','lib')->getStaffOnlineStatus($v['staff_id']);
            if ($status) {
                $staffList[$v['staff_id']]['status'] = '<span style="color: #01b88a;font-size: larger">在线</span>';
            }
            // 不在线
            else{
                // 是否开启离线接收客资
                if (db_config('not_online_is_fp_'.$v['staff_id']) == 1) {
                    // $staffList[$v['staff_id']]['not_online_is_fp'] = '开启，离线接收';
                    $staffList[$v['staff_id']]['status'] = '<span style="color:#cccccc;font-size: larger">不在线</span>|开启，离线接收';
                }else{
                    $staffList[$v['staff_id']]['status'] = '<span style="color:#cccccc;font-size: larger">不在线</span>';
                    // $staffList[$v['staff_id']]['not_online_is_fp'] = '';
                }
            }
            $staffList[$v['staff_id']]['id'] = $v['staff_id'];
            $staffList[$v['staff_id']]['staff_name'] = $v['staff_name'];

            $sids .= $v['staff_id'].',';
        }
        $sids = trim($sids, ',');
        // 登录信息
        $loginData = db('s_session')->where('staff_id', 'in', $sids)->column('login_time,login_type,status,ip', 'staff_id');

        foreach ($staffList as $k => $v) {
            $staffList[$k]['login_time'] = $loginData[$k]['login_time'] ? date('Y-m-d H:i', strtotime($loginData[$k]['login_time'])) : '';
        }
        $return = [];
        foreach ($staffList as $key => $value) {
            array_push($return, $value);
        }
        return $return;
    }
    // 签出
    public function staffQc(){
        $id = (int)input('post.id');
        $status = 3;
        // 取出员工信息
        $info = cache('staffInfo_'.$id);
        $param['status'] = $status;
        db()->startTrans();
        try{
            db('s_session')->where(array('staff_id' => session('staff_id')))->update($param);
            cookie('status',$status);
            db()->commit();
            // 赋值状态
            $info['status'] = $status;
            $info['active'] = time()-60;
            if($info['keep_login'] == 1){
                cache('staffInfo_'.$id, json_encode($info),432000);
            }else{
                cache('staffInfo_'.$id, json_encode($info));
            }
            cookie('status',$status);
            action_log(session('staff_name').' 于 '.date('Y-m-d H:i:s').' 签出',[]);
            return array('code'=>200,'msg'=>'操作成功。');
        }catch (\Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'操作失败，请重试。','error'=>$e->getMessage());
        }
    }

    // 查看分配日志
    public function fpLogs(){
        // 权限
        $auth = check_right('menu1537322380');
        if (!$auth) {
            return $this->redirect('/');
        }
        // 如果当前登录人属于电商 分配人查电商 接收人查网销
        if (session('is_marketing') == 1) {
            $jr_staff_list=controller("Customer","lib")->get_staff_lists(array('shop_code'=>session('belong_shop_code')));
        }
        // 如果当前登录人属于网销 分配人查电商 接收人查网销
        elseif (session('is_marketing') == 3) {
            $jr_staff_list=controller("Customer","lib")->get_staff_lists(array('shop_code'=>session('shop_code')));
        }
        // 如果当前登录人属于渠道 分配人查各实体店 接收人查渠道
        elseif (session('is_marketing') == 4) {
            $jr_staff_list=controller("Customer","lib")->get_staff_lists(array('shop_code'=>session('shop_code')));
        }else{
            $jr_staff_list=controller("Customer","lib")->get_staff_lists(array('shop_code'=>session('shop_code')));
        }

        // 店面类型 （is_marketing 1:电商；2:实体；3:网销；4:渠道）
        $this->assign('is_marketing', session('is_marketing'));
        // 分配人集合
        // $this->assign('fp_staff', $fp_staff);
        // 录入人集合
        $this->assign('jr_staff', $jr_staff_list);

        $this->assign('brandclass_id', session('brandclass_id'));
        $this->assign('brandclass', session('brandclass'));
        $this->assign('title', '客资分配日志');
        return $this->fetch();
    }

    // 搜索分配日志
    public function searchFplogs(){
        // 权限
        $auth = check_right('menu1537322380');
        if (!$auth) {
            return $this->redirect('/');
        }
        $result['code'] = 0;
        $result['msg'] = '';
        $data = input();
        $limit = $data['limit'] ? intval($data['limit']) : 20;
        $page = $data['page'] ? intval($data['page']) : 1;
        // 如果当前登录人属于电商 分配人查电商 接收人查网销
        // if (session('is_marketing') == 1) {
        //     $where['jr_shop_code'] = session('belong_shop_code');
        // }
        // // 如果当前登录人属于网销 分配人查电商 接收人查网销
        // elseif (session('is_marketing') == 3) {
        //     $where['jr_shop_code'] = session('shop_code');
        // }
        // // 如果当前登录人属于渠道 分配人查各实体店 接收人查渠道
        // elseif (session('is_marketing') == 4) {
        //     $where['jr_shop_code'] = session('shop_code');
        // }
        // // 其他
        // else{
        $where['fp_brandclass_id'] = session('brandclass_id');
        $where['jr_shop_code'] = session('shop_code');
        // }
        // 时间判断
        if($data['start'] && $data['end']){
            $start = date('Y-m-d 00:00:00', strtotime($data['start']));
            $end = date('Y-m-d 23:59:59', strtotime($data['end']));
            $sql_time = ' fp_time BETWEEN "'.$start.'" AND "'.$end.'" ';
        }elseif($data['start'] && !$data['end']){
            $start = date('Y-m-d 00:00:00', strtotime($data['start']));
            $sql_time = ' fp_time > "'.$start.'" ';
        }elseif(!$data['start'] && $data['end']){
            $end = date('Y-m-d 23:59:59', strtotime($data['end']));
            $sql_time = ' fp_time < "'.$end.'" ';
        }else{
            $start = date('Y-m-d 00:00:00');
            $end = date('Y-m-d 23:59:59');
            $sql_time = ' fp_time BETWEEN "'.$start.'" AND "'.$end.'" ';
        }

        // 如果通过id查询，其他条件全部忽略
        if($data['cid']) {
            $whereC['c_from'] = 1;
            $whereC['is_status'] = 1;
            $whereC['brandclass_id'] = session('brandclass_id');
            $sql = ' id="'.(int)$data['cid'].'" OR customer_tel LIKE "%'.trim($data['cid']).'%" OR customer_wechat LIKE "%'.trim($data['cid']).'%" OR customer_qq LIKE "%'.trim($data['cid']).'%" ';
            $cInfo = db('c_customerinfo')->where($whereC)->where($sql)->field('id')->select();
            // echo db()->getLastSql();
            $cids = '';
            foreach ($cInfo as $key => $value) {
                $cids .= $value['id'].',';
            }
            $cids = trim($cids, ',');
            $res = db('l_fp_logs')->where('cid', 'in', $cids)->limit($limit)->page($page)->order('fp_time desc')->select();
            // echo db()->getLastSql();
            // exit;
            $count = db('l_fp_logs')->where($where)->where('cid', 'in', $cids)->count();
        }else{
            if($data['jr_staff_id']) $where['jr_staff_id'] = intval($data['jr_staff_id']);
            if($data['fp_status']) $where['fp_status'] = intval($data['fp_status']);
            if($data['fp_model']) $where['fp_model'] = intval($data['fp_model']);
            $res = db('l_fp_logs')->where($where)->limit($limit)->page($page)->where($sql_time)->order('fp_time desc')->select();
            $count = db('l_fp_logs')->where($where)->where($sql_time)->count();
        }

        // echo db()->getLastSql();
        // exit;
        if($res){
            $result['data'] = $res;
            $result['count'] = $count;
        }else{
            $result['data'] = array();
        }
        return ($result);
    }

    // 测试
    public function test()
    {
        $res = controller('crm/ListenCron', 'lib')->runcronhour();
    }

    /*************************客资操作日志*******start**********************************/
    //日志
    public function customerLogs(){
        $staff = controller('crm/Customer','lib')->getShopAllStaff(['shop_code'=>session('shop_code')]);
        $this->assign('staff',$staff);
        $this->assign('title','客资操作日志');
        return $this->fetch();
    }
    public function customerLogJSON(){
        set_time_limit(0);
        $param = input();
        $result = [];
        $result['code'] = 0;
        $result['msg'] = '';
        $page = $param['page'] ? $param['page'] : 1;
        $limit = $param['limit'] ? $param['limit'] : 50;
        $where = [];
        if($param['staff_id']){
            $where['staff_id'] = intval($param['staff_id']);
        }
        $sql = ' 1=1 ';
        if(!$param['customer_id'] && !$param['customer_tel']){
            $staff = controller('crm/Customer','lib')->getShopAllStaff(['shop_code'=>session('shop_code')]);
            $staffIds = array_column($staff,'id');
            if ($staffIds) {
                $sql .= ' and staff_id in ('.implode(',',$staffIds).') ';
            }
        }
        if($param['customer_id']){
            $where['customer_id'] = intval($param['customer_id']);
        }
        $start = $param['start'] ? date('Y-m-d 00:00:00',strtotime($param['start'])) :  date('Y-m-d 00:00:00');
        $end = $param['end'] ? date('Y-m-d 23:59:59',strtotime($param['end'])) :  date('Y-m-d 23:59:59');
        if($param['customer_tel']){
            $info = db('action_log','db_logs')->where($sql)->where('controller','in',['Customer','App'])->where('action','<>','editCustomerTel')->where('old_data|data','like','%'.trim($param['customer_tel']).'%')->where($where)->where('create_time','between',[$start,$end])->order('id desc')->page($page)->limit($limit)->select();
            $count = db('action_log','db_logs')->where($sql)->where('controller','in',['Customer','App'])->where('action','<>','editCustomerTel')->where('old_data|data','like','%'.trim($param['customer_tel']).'%')->where($where)->where('create_time','between',[$start,$end])->count('id');
        }else{
            $info = db('action_log','db_logs')->where($sql)->where('controller','in',['Customer','App'])->where('action','<>','editCustomerTel')->where($where)->where('create_time','between',[$start,$end])->order('id desc')->page($page)->limit($limit)->select();
            $count = db('action_log','db_logs')->where($sql)->where('controller','in',['Customer','App'])->where('action','<>','editCustomerTel')->where($where)->where('create_time','between',[$start,$end])->count('id');
        }

        if(!empty($info)){
            foreach($info as $k=>$v){
                $info[$k]['action'] = getLogsName($v['action']);

                if(is_json($v['data'])){
                    $oldDate = json_decode($v['old_data'], true);
                    $oldDateStr = '';
                    foreach ($oldDate as $kk => $vv) {
                        $key = translate('c_customerinfo',$kk);
                        if($kk == 'is_valid'){
                            $vv = getIsValid($vv);
                        }
                        if($kk == 'is_intostore'){
                            $vv = getIsIntostore($vv);
                        }
                        if($kk == 'is_loss'){
                            $vv = getIsLoss($vv);
                        }
                        if($kk == 'is_status'){
                            $vv = getIsStatusAttr($vv);
                        }
                        if($key){
                            $oldDateStr .= $key.'：'.$vv.'；<br>';
                        }
                    }
                    $newDate = json_decode($v['data'], true);
                    $newDateStr = '';
                    foreach ($newDate as $kkk => $vvv) {
                        if($kkk == 'is_valid'){
                            $vvv = getIsValid($vvv);
                        }
                        if($kkk == 'is_intostore'){
                            $vvv = getIsIntostore($vvv);
                        }
                        if($kkk == 'is_loss'){
                            $vvv = getIsLoss($vvv);
                        }
                        $key1 = translate('c_customerinfo',$kkk);
                        if($key1){
                            $newDateStr .= $key1.'：'.$vvv.'；<br>';
                        }
                    }
                    $info[$k]['old'] = $oldDateStr;
                    $info[$k]['new'] = $newDateStr;
                }else{

                    if(strpos(';<br />', $v['old_data']) === false){
                        $info[$k]['old'] = $v['old_data'];
                    }else{
                        $oldDate = explode(';<br />',$v['old_data']);
                        $oldDateStr = $v['old_data'];
                        foreach ($oldDate as $kk => $vv) {
                            $key1 = translate('c_customerinfo',substr($vv,0,strpos($vv, ':')));
                            if($key1 && substr($vv,strpos($vv,':')+1)){
                                $oldDateStr .= $key1.'：'.substr($vv,strpos($vv,':')+1).'<br>';
                            }
                        }
                        $info[$k]['old'] = $oldDateStr;

                    }
                    if(strpos(';<br />', $v['data']) === false){
                        $info[$k]['new'] = $v['data'];
                    }else{
                        $newDate = explode(';<br />',$v['data']);
                        $newDateStr = '';
                        foreach ($newDate as $kk => $vv) {
                            $key1 = translate('c_customerinfo',substr($vv,0,strpos($vv, ':')));
                            if($key1 && substr($vv,strpos($vv,':')+1)){
                                $newDateStr .= $key1.'：'.substr($vv,strpos($vv,':')+1).'<br>';
                            }
                        }
                        $info[$k]['new'] = $newDateStr;
                    }
                }
            }
            $result['data'] = $info;
            $result['count'] = $count;

        }else{
            $result['data'] = array();
        }
        return json($result);
    }
    /*************************客资操作日志*******end**********************************/

    /*************************手机修改日志*******start**********************************/
    public function telLogs(){
        $staff = controller('crm/Customer','lib')->getShopAllStaff(['shop_code'=>session('shop_code')]);
        $this->assign('staff',$staff);
        $this->assign('title','手机修改日志');
        return $this->fetch();
    }
    public function telLogsJSON(){
        set_time_limit(0);
        $param = input();
        $result = [];
        $result['code'] = 0;
        $result['msg'] = '';
        $page = $param['page'] ? $param['page'] : 1;
        $limit = $param['limit'] ? $param['limit'] : 50;
        $where = [];
        if($param['staff_id']){
            $where['staff_id'] = intval($param['staff_id']);
        }
        $sql = ' 1=1 ';
        if(!$param['customer_id'] && !$param['customer_tel']){
            $staff = controller('crm/Customer','lib')->getShopAllStaff(['shop_code'=>session('shop_code')]);
            $staffIds = array_column($staff,'id');
            if ($staffIds) {
                $sql .= ' and staff_id in ('.implode(',',$staffIds).') ';
            }
        }
        if($param['customer_id']){
            $where['customer_id'] = intval($param['customer_id']);
        }
        $start = $param['start'] ? date('Y-m-d 00:00:00',strtotime($param['start'])) :  date('Y-m-d 00:00:00');
        $end = $param['end'] ? date('Y-m-d 23:59:59',strtotime($param['end'])) :  date('Y-m-d 23:59:59');
        if($param['customer_tel']){
            $info = db('action_log','db_logs')->where($sql)->where('controller','Customer')->where('action','editCustomerTel')->where('old_data|data','like','%'.trim($param['customer_tel']).'%')->where($where)->where('create_time','between',[$start,$end])->order('id desc')->page($page)->limit($limit)->select();
            $count = db('action_log','db_logs')->where($sql)->where('controller','Customer')->where('action','editCustomerTel')->where('old_data|data','like','%'.trim($param['customer_tel']).'%')->where($where)->where('create_time','between',[$start,$end])->count('id');
        }else{
            $info = db('action_log','db_logs')->where($sql)->where('controller','Customer')->where('action','editCustomerTel')->where($where)->where('create_time','between',[$start,$end])->order('id desc')->page($page)->limit($limit)->select();
            $count = db('action_log','db_logs')->where($sql)->where('controller','Customer')->where('action','editCustomerTel')->where($where)->where('create_time','between',[$start,$end])->count('id');
        }

        foreach($info as $k=>$v){
            $info[$k]['action'] = '修改客资手机号';
            $resOld = json_decode($v['old_data'],true);
            $res = json_decode($v['data'],true);
            $key = array_keys($res);
            if($key[0] == 'customer_tel'){
                $info[$k]['old_data'] = '手机号:'.$resOld['customer_tel'];
                $info[$k]['data'] = '手机号:'.$res['customer_tel'];
            }
            if($key[0] == 'mate_tel'){
                $info[$k]['old_data'] = '配偶手机号:'.$resOld['mate_tel'];
                $info[$k]['data'] = '配偶手机号:'.$res['mate_tel'];
            }
        }
        $result['data'] = $info;
        $result['count'] = $count;

        return json($result);
    }
    /*************************手机修改日志*******end**********************************/
    /*************************设定日志*******start**********************************/
    public function settingLogs(){
        $staff = controller('crm/Customer','lib')->getShopAllStaff(['shop_code'=>session('shop_code')]);
        $this->assign('staff',$staff);
        $list = cache('setting_list');
        if(empty($list)){
            $control = 'Setting';
            $actions = $this->getActions('app\crm\controller' . '\\' . $control);
            $list = [];
            foreach($actions as $k=>$v){
                $info = $this->get_cc_desc('crm','Setting',$v);
                if($info != ''){
                    $list[strtolower($v)] = $info;
                }
            }
            cache('setting_list',$list);
        }

        $this->assign('list',$list);
        $this->assign('title','设定日志');
        return $this->fetch();
    }
    public function settingLogsJSON(){
        set_time_limit(0);
        $param = input();
        $result = [];
        $result['code'] = 0;
        $result['msg'] = '';
        $page = $param['page'] ? $param['page'] : 1;
        $limit = $param['limit'] ? $param['limit'] : 50;
        if($param['staff_id']){
            $staffIds = [intval($param['staff_id'])];
        }else{
            $staff = controller('crm/Customer','lib')->getShopAllStaff(['shop_code'=>session('shop_code')]);
            $staffIds = array_column($staff,'id');
        }
        $where = [];
        if($param['action']){
            $where['action'] = $param['action'];
        }
        $start = $param['start'] ? date('Y-m-d 00:00:00',strtotime($param['start'])) :  date('Y-m-d 00:00:00');
        $end = $param['end'] ? date('Y-m-d 23:59:59',strtotime($param['end'])) :  date('Y-m-d 23:59:59');

        $info = db('action_log','db_logs')->where('staff_id','in',$staffIds)->where('controller','Setting')->where($where)->where('create_time','between',[$start,$end])->order('id desc')->page($page)->limit($limit)->select();
        $result['sql'] = db('action_log','db_logs')->getLastSql();
        $count = db('action_log','db_logs')->where('staff_id','in',$staffIds)->where('controller','Setting')->where($where)->where('create_time','between',[$start,$end])->count('id');
        if(!empty($info)) {
            foreach ($info as $k => $v) {
                $info[$k]['action'] = getLogsName($v['action']);
                $info[$k]['old'] = $v['old_data'];
                $info[$k]['new'] = $v['data'];
            }
        }
        $result['data'] = $info;
        $result['count'] = $count;

        return json($result);
    }
    /*************************设定日志*******end**********************************/



    /*************************客资提醒查询*******start**********************************/
    public function remindLogs(){

        return $this->fetch();
    }
    public function remindJSON(){
        $data = input();
        $result = [];
        $result['code'] = 0;
        $result['msg'] = '';
        $page = $data['page'] ? $data['page'] : 1;
        $limit = $data['limit'] ? $data['limit'] : 100;
        $start = $data['start'] ? date('Y-m-d 00:00:00',strtotime($data['start'])) :  date('Y-m-d');
        $end = $data['end'] ? date('Y-m-d 23:59:59',strtotime($data['end'])) :  date('Y-m-d 23:59:59');
        $key = '';
        switch($data['remind_type']){
            case 'baby_birthday':
                $key = 'baby_birthday';
                break;
            case 'ready_baby_day':
                $key = 'ready_baby_day';
                break;
            case 'customer_birthday':
                $key = 'customer_birthday';
                break;
            case 'mate_birthday':
                $key = 'mate_birthday';
                break;
            case 'marry_day':
                $key = 'marry_day';
                break;
            case 'next_day':
                $key = 'next_time';
                break;
            case 'yjd_day':
                $key = 'yjd_day';
                break;
            case 'syjd_day':
                $key = 'syjd_day';
                break;
            case 'order_day':
                $key = 'order_day';
                break;
            default :
                $key = 'customer_birthday';
                break;
        }
        $sql = ' 1=1 ';
        if($data['customer_id']){
            $sql .= ' and id='.intval($data['customer_id']);
        }
        if($data['customer_tel']){
            $sql .= ' and (customer_tel ="'.trim($data['customer_tel']).'" or mate_tel="'.trim($data['customer_tel']).'")';
        }
        $where = [];
        $where['is_status'] = 1;
        $where['is_loss'] = 2;
        $where['is_examine'] = 1;
        if(session('shop_type') == 2){
            $field = 'id,dj_staff,sales_staff,reception_name,baby_name,baby_birthday,ready_baby_day,customer_name,customer_tel,customer_birthday,mate_name,mate_tel,mate_birthday,marry_day,next_time,yjd_day,syjd_day,order_day,dj_day';
        }else{
            $field = 'id,dj_staff,sales_staff,reception_name,customer_name,customer_tel,customer_birthday,mate_name,mate_tel,mate_birthday,marry_day,next_time,yjd_day,syjd_day,order_day,dj_day';
        }
        $info = db('c_customerinfo')->where($where)->where('shop_code|add_shop_code',session('shop_code'))->where($sql)->where($key,'between',[$start,$end])->field($field)->order($key.' desc')->limit($limit)->page($page)->select();
        $count = db('c_customerinfo')->where($where)->where('shop_code|add_shop_code',session('shop_code'))->where($sql)->where($key,'between',[$start,$end])->count();
        $result['data'] = $info;
        $result['count'] = $count;

        return json($result);
    }
    /*************************客资提醒查询*******end**********************************/

    /**
     * 查询当前店下今天 追踪记录里 存在 拦截的数据
     * @return array
     * @author lilong<lilong@suxuantech.cn>
     */
    public function getLanjieList(){
        # code...
    }
}  