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

class Setting extends Controller{
    function remindList1(){
        $res = db('crm_s_reminditemset')->where('brandclass_id',session('brandclass_id'))->where('id','remind1')->find();
        if($res){
            return $res;
        }else{
            return false;
        }
    }
    function remindList2(){
        $res = db('crm_s_reminditemset')->where('brandclass_id',session('brandclass_id'))->where('id','remind2')->find();
        if($res){
            return $res;
        }else{
            return false;
        }
    }
    function remindList3(){
        $res = db('crm_s_reminditemset')->where('brandclass_id',session('brandclass_id'))->where('id','remind3')->find();
        if($res){
            return $res;
        }else{
            return false;
        }
    }
    function editRemind($param){
        db()->startTrans();

        for($i=1;$i<=2;$i++){
            if($param['isopen'.$i] == '' || $param['isopen'.$i] == null){
                $param['isopen'.$i] = 0;
            }
            $info = db('crm_s_reminditemset')->where('id',$param['id'.$i])->where('brandclass_id',session('brandclass_id'))->find();
            if($info['id']){
                $data = array(
                    'isopen' => $param['isopen'.$i],
                    'remind_type' => $param['remind_type'.$i],
                    'advancehour' => $param['advancehour'.$i],
                );
                $up = db('crm_s_reminditemset')->where('id',$param['id'.$i])->where('brandclass_id',session('brandclass_id'))->update($data);
                if($up === false){
                    db()->rollback();
                }else{
                    action_log($param,$info,0,session('staff_id'),session('staff_name'));

                    db()->commit();
                }
            }else{
                $data = array(
                    'id' => $param['id'.$i],
                    'isopen' => $param['isopen'.$i],
                    'remind_type' => $param['remind_type'.$i],
                    'advancehour' => $param['advancehour'.$i],
                    'brandclass_id' => session('brandclass_id'),
                    'brandclass' => session('brandclass'),
                );
                $res = db('crm_s_reminditemset')->insert($data);
                if($res){
                    action_log($data,'',0,session('staff_id'),session('staff_name'));
                    db()->commit();
                }else{
                    db()->rollback();
                }
            }

        }
        return true;
    }
    function delRemind($id){
        db()->startTrans();
        $res = db('crm_s_reminditemset')->where('id',$id)->delete();
        if($res){
            action_log($id,'',0,session('staff_id'),session('staff_name'));
            db()->commit();
            return $res;
        }else{
            return false;
        }
    }
    function remindAdd($param){
        $param['brandclass_id'] = session('brandclass_id');
        $param['brandclass'] = session('brandclass');
        $db = db('crm_s_reminditemset');
        if($param['id']){
            $res = $db->where('id',$param['id'])->update($param);
        }else{
            $db->insert($param);
            $res = $db->getLastInsID();
        }
        $db->startTrans();
        if($res){
            action_log($param,'',0,session('staff_id'),session('staff_name'));
            $db->commit();
            return true;
        }else{
            $db->rollback();
            return false;
        }
    }
    
    function getKPIList(){
        $tar = new \app\crm\lib\Target();
        return $tar->getAllTarget();
    }
    function setGoal($param){
        if($param['staff_id']>0){
            $auth = check_right('menu1529653231');
            if(empty($auth)){
                return array('code'=>110,'msg'=>'没有小组权限,不能创建人员目标');
            }
        }elseif($param['position_code']){
            $auth = check_right('menu1529653231');
            if(empty($auth)){
                return array('code'=>110,'msg'=>'没有小组权限,不能创建岗位目标');
            }
        }elseif($param['group_id'] && empty($param['staff_id']) && empty($param['position_code'])){
            $auth = check_right('menu1531471639');
            if(empty($auth)){
                return array('code'=>110,'msg'=>'没有部门权限,不能创建小组目标');
            }
        }elseif($param['department_id'] && empty($param['group_id']) && empty($param['staff_id']) && empty($param['position_code'])){
            $auth = check_right('menu1512637269');
            if(empty($auth)){
                return array('code'=>110,'msg'=>'没有店面权限,不能创建部门目标');
            }
        }
        if(!empty($param['province_id'])){//根据省获取地域
            $region = controller("Customer","lib")->getRegionByProvinceId(['id'=>$param['province_id']]);
            $param['region_id'] = $region['id'];
            $param['region_name'] = $region['region_name'];
        }
        if($param['month']) $month = date('Y-m',strtotime($param['month']));
           /* //大于5条后不让设置
            $count = db('crm_s_kpi_staffgoal')
                ->where('shop_code',session('shop_code'))
                ->where('position_id',$param['position_id'])
                ->where('department_id',$param['department_id'])
                ->where('staff_id',$param['staff_id'])
                ->where('province_id',$param['province_id'])
                ->where('city_id',$param['city_id'])
                ->where('channel_id',$param['channel_id'])
                ->where('month',$month)
                ->count();*/
            $start = date('Y-m-01',strtotime($month));
            $end = date('Y-m-d',strtotime("$month +1 month -1 day"));

           /* if($count >= 5) {
                $arr = array(
                    'code' => 120,
                    'msg' => '目标数量已到5条最大值，不能设置',
                    'data' => array()
                );
                return $arr;
            }*/
            $res = db('crm_s_kpi_staffgoal')
                ->where('shop_code',session('shop_code'))
                ->where('kpi_id',$param['kpi_id'])
                ->where('position_id',$param['position_id'])
                ->where('department_id',$param['department_id'])
                ->where('group_id',$param['group_id'])
                ->where('staff_id',$param['staff_id'])
                ->where('province_id',$param['province_id'])
                ->where('city_id',$param['city_id'])
                ->where('channel_id',$param['channel_id'])
                ->where('month',$month)
                ->where('flag',$param['flag'])
                ->find();
        if(!empty($res)){
            $arr = array(
                'code'=>150,
                'msg'=>'本时间段已存在此目标，不能设置',
                'data'=>array()
            );
            return $arr;
        }
        $day_number = diffBetweenTwoDays($start,$end);
        $day_number = $day_number+1;
        $data = array(
            'position_name'  =>  $param['position_name'],
            'position_id'  =>  $param['position_id'],
            'position_code'  =>  $param['position_code'],
            'region_id'  =>  $param['region_id'],
            'region_name'  =>  $param['region_name'],
            'channel_id'  =>  $param['channel_id'],
            'channel_name'  =>  $param['channel_name'],
            'province_id'  =>  $param['province_id'],
            'province_name'  =>  $param['province_name'],
            'city_id'  =>  $param['city_id'],
            'city_name'  =>  $param['city_name'],
            'department_id'  =>  $param['department_id'],
            'department_name'  =>  $param['department_name'],
            'group_id'  =>  $param['group_id'],
            'group_name'  =>  $param['group_name'],
            'staff_id'  =>  $param['staff_id'],
            'staff_name'  =>  $param['staff_name'],
            'month' => $month,
            'flag' => $param['flag'],
            'start' =>  $start,
            'end' =>  $end,
            'day_number' =>  $day_number,
            'avg_value' =>  sprintf('%.2f',$param['kpi_value']/$day_number),
            'kpi_id' =>  $param['kpi_id'],
            'kpi_name' =>  $param['kpi_name'],
            'kpi_value' =>  $param['kpi_value'],
            'kpi_unit' =>  $param['kpi_unit'],
            'order_sort' =>  $param['order_sort'],
            'create_time' =>  date('Y-m-d H:i:s',time()),
            'shop_name' =>  $param['shop_name'] ? : session('shop_name'),
            'shop_code' =>  $param['shop_code'] ? : session('shop_code'),
            'setkey' =>  session('setkey'),
            'brandclass_id' =>  session('brandclass_id'),
            'brandclass' =>  session('brandclass'),
        );
        db()->startTrans();
        db('crm_s_kpi_staffgoal')->insert($data);
        $res = db('crm_s_kpi_staffgoal')->getLastInsID();
        if($res){
            action_log($param,'',0,session('staff_id'),session('staff_name'));
            $arr = array(
                'code'=>200,
                'msg'=>'设置成功',
                'data'=>$data
            );
            db()->commit();
            return $arr;
        }else{
            $arr = array(
                'code'=>100,
                'msg'=>'设置失败',
                'data'=>array()
            );
            db()->rollback();
            return $arr;
        }

    }
    function getGoalJSON($param){
        $result['code'] = 0;
        $result['msg'] = '';
        $limit = $param['limit'] ? $param['limit'] : 10;
        $page = $param['page'] ? $param['page'] : 1;
        if($param['search_month']){
            $where['month'] = trim($param['search_month']);
        }else{
            $where['month'] = date('Y-m');
        }
        if($param['kpi_id']) $where['kpi_id'] = $param['kpi_id'];
        if($param['shop_code']) $where['shop_code'] = $param['shop_code'];
        //店权限
        if(check_right('menu1512637269')){
                $result['data'] = db('crm_s_kpi_staffgoal')->where($where)->page($page,$limit)->order('order_sort')->select();
                $result['count'] = db('crm_s_kpi_staffgoal')->where($where)->count();
        }elseif(check_right('menu1531471639')){//部门权限
                $result['data'] = db('crm_s_kpi_staffgoal')->where($where)->page($page,$limit)->order('order_sort')->select();
                $result['count'] = db('crm_s_kpi_staffgoal')->where($where)->count();
        }elseif(check_right('menu1529653231')){
                $result['data'] = db('crm_s_kpi_staffgoal')->where($where)->where('group_id','>',0)->page($page,$limit)->order('order_sort')->select();
                $result['count'] = db('crm_s_kpi_staffgoal')->where($where)->where('group_id','>',0)->count();
        }else{
                $result['data'] = db('crm_s_kpi_staffgoal')->where($where)->where('staff_id > 0 or (position_code is not null or position_code<>"")')->page($page,$limit)->order('order_sort')->select();
                $result['count'] = db('crm_s_kpi_staffgoal')->where($where)->where('staff_id > 0 position_code<>""')->count();
        }
        return ($result);
    }
    function updateGoal($param){
        if($param['staff_id']>0){
            $auth = check_right('menu1529653231');
            if(empty($auth)){
                return array('code'=>110,'msg'=>'没有小组权限,不能修改员工目标');
            }
        }elseif($param['position_code']){
            $auth = check_right('menu1529653231');
            if(empty($auth)){
                return array('code'=>110,'msg'=>'没有小组权限,不能修改岗位目标');
            }
        }elseif($param['group_id'] && empty($param['staff_id']) && empty($param['position_code'])){
            $auth = check_right('menu1531471639');
            if(empty($auth)){
                return array('code'=>110,'msg'=>'没有部门权限,不能修改小组目标');
            }
        }elseif($param['department_id'] && empty($param['group_id']) && empty($param['staff_id']) && empty($param['position_code'])){
            $auth = check_right('menu1512637269');
            if(empty($auth)){
                return array('code'=>110,'msg'=>'没有店面权限,不能修改部门目标');
            }
        }
        if(!empty($param['province_id'])){//根据省获取地域
            $region = controller("Customer","lib")->getRegionByProvinceId(['id'=>$param['province_id']]);
            $param['region_id'] = $region['id'];
            $param['region_name'] = $region['region_name'];
        }
        if($param['month']) $month = date('Y-m',strtotime($param['month']));
        $start = date('Y-m-01',strtotime($month));
        $end = date('Y-m-d',strtotime("$month +1 month -1 day"));
        $res = db('crm_s_kpi_staffgoal')
            ->where('id','<>',$param['id'])
            ->where('shop_code',session('shop_code'))
            ->where('kpi_id',$param['kpi_id'])
            ->where('position_id',$param['position_id'])
            ->where('department_id',$param['department_id'])
            ->where('group_id',$param['group_id'])
            ->where('staff_id',$param['staff_id'])
            ->where('province_id',$param['province_id'])
            ->where('city_id',$param['city_id'])
            ->where('channel_id',$param['channel_id'])
            ->where('month',$month)
            ->where('flag',$param['flag'])
            ->find();

        if(!empty($res)){
            $arr = array(
                'code'=>150,
                'msg'=>'本时间段已存在此目标，不能设置',
                'data'=>array()
            );
            db()->rollback();

            return $arr;
        }
        $day_number = diffBetweenTwoDays($start,$end);
        $day_number = $day_number+1;
        $data = array(
            'position_id'  =>  $param['position_id'],
            'position_code'  =>  $param['position_code'],
            'position_name'  =>  $param['position_name'],
            'region_id'  =>  $param['region_id'],
            'region_name'  =>  $param['region_name'],
            'channel_id'  =>  $param['channel_id'],
            'channel_name'  =>  $param['channel_name'],
            'province_id'  =>  $param['province_id'],
            'province_name'  =>  $param['province_name'],
            'city_id'  =>  $param['city_id'],
            'city_name'  =>  $param['city_name'],
            'department_id'  =>  $param['department_id'],
            'department_name'  =>  $param['department_name'],
            'group_id'  =>  $param['group_id'],
            'group_name'  =>  $param['group_name'],
            'staff_id'  =>  $param['staff_id'],
            'staff_name'  =>  $param['staff_name'],
            'month' =>  $month,
            'flag' => $param['flag'],
            'start' =>  $start,
            'end' =>  $end,
            'day_number' =>  $day_number,
            'avg_value' =>  sprintf('%.2f',$param['kpi_value']/$day_number),
            'kpi_id' =>  $param['kpi_id'],
            'kpi_name' =>  $param['kpi_name'],
            'kpi_value' =>  $param['kpi_value'],
            'kpi_unit' =>  $param['kpi_unit'],
            'order_sort' =>  $param['order_sort'],
            'brandclass_id' =>  session('brandclass_id'),
            'brandclass' =>  session('brandclass'),
        );
        db()->startTrans();
        $db = db('crm_s_kpi_staffgoal');
        $res = $db->where('id',$param['id'])->update($data);


        if($res === false){
            $arr = array(
                'code'=>100,
                'msg'=>'修改失败',
                'data'=>array()
            );
            db()->rollback();
            return $arr;
        }else{
            action_log($param,$res,0,session('staff_id'),session('staff_name'));
            $arr = array(
                'code'=>200,
                'msg'=>'修改成功',
                'data'=>$data
            );
            db()->commit();
            return $arr;
        }
    }
    function delGoal($id){
        db()->startTrans();
        $res = db('crm_s_kpi_staffgoal')->where('id',$id)->delete();
        if($res){
            action_log($id,'',0,session('staff_id'),session('staff_name'));
            db()->commit();
            return true;
        }else{
            db()->rollback();
            return false;
        }
    }
    function editGoal($id){
        $res = db('crm_s_kpi_staffgoal')->where('id',$id)->find();
        return $res;
    }
    //岗位列表
    function get_position_list($data){
        $mc = new \app\common\lib\mcInterface();
        $position_list = $mc->getPosition($data);
        if ($position_list === false) {
            $position_list = [];
        }
        return $position_list;
    }
    //品牌列表
    function brandclass_list(){
        $mc = new \app\common\lib\mcInterface();
        $brandclass_list = $mc->getBrand();
        if ($brandclass_list === false) {
            $brandclass_list = [];
        }
        return $brandclass_list;
    }
    //部门列表
    function department_list($data){
        // $url = '5a0aef152b750';
        // $res = sx_call($url,$data);
        // if($res['code'] == 200){
        //     return $res['data'];
        // }else{
        //     return [];
        // }
        $mc = new \app\common\lib\mcInterface();
        $department_list = $mc->getDepartment($data);
        if ($department_list === false) {
            $department_list = [];
        }
        return $department_list;
    }
    //岗位下的人员
    function positionStaffs($data){
        // $url = '5a19201a33c20';
        // $data['get_leave']  = 2;
        // $res = sx_call($url,$data);
        // if($res['code'] == 200){
        //     return $res['data'];
        // }else{
        //     return false;
        // }
        $mc = new \app\common\lib\mcInterface();
        $staff_list = $mc->getStaffInfo($data);
        if ($staff_list === false) {
            $staff_list = [];
        }
        return $staff_list;
    }

    //部门列表
    function get_department_list($param){
        $shop_code = $param['shop_code'] ? $param['shop_code'] : session('shop_code');
        // $url = '5a0aef152b750';
        // $res = sx_call($url,array('shop_code'=>$shop_code));
        // if($res['code'] == 200){
        //     return $res['data'];
        // }else{
        //     return false;
        // }
        $mc = new \app\common\lib\mcInterface();
        $department_list = $mc->getDepartment(array('shop_code'=>$shop_code));
        if ($department_list === false) {
            $department_list = [];
        }
        return $department_list;
    }
    
    // 获取 部门 岗位 组 员工
    function getdepartment($param){
        $shop_code = $param['shop_code'] ? $param['shop_code'] : session('shop_code');
        // $url = '5a0aef152b750';
        // return sx_call($url,array('shop_code'=>$shop_code));
        $mc = new \app\common\lib\mcInterface();
        $department_list = $mc->getDepartment(array('shop_code'=>$shop_code));
        if ($department_list === false) {
            $department_list = [];
        }
        return $department_list;
    }
    function getposition($param){
        $shop_code = $param['shop_code'] ? $param['shop_code'] : session('shop_code');
        // $url = '5a0b96b65c111';
        // return sx_call($url,array('shop_code'=>$shop_code));
        $mc = new \app\common\lib\mcInterface();
        $position_list = $mc->getPosition(array('shop_code'=>$shop_code));
        if ($position_list === false) {
            $position_list = [];
        }
        return $position_list;
    }
    // 查询小组列表 20200813
    public function getGroupList($param){
        $shop_code = $param['shop_code'] ? $param['shop_code'] : session('shop_code');
        $mc = new \app\common\lib\mcInterface();
        $group_list = $mc->getGroupInfo(array('shop_code'=>$shop_code));
        if ($group_list===false) {
            $group_list = [];
        }
        return $group_list;
    }
    function getStaffList($param){
        return [];
        // 这个接口根本找不到啊
        // $url = '59ff2d5de2cb6';
        // return sx_call($url,'');
    }

    function delFPSet($id){
        $db = db('crm_s_allocation_rule');
        db()->startTrans();
        $res = $db->where('id',$id)->delete();
        if($res){
            action_log($id,'',0,session('staff_id'),session('staff_name'));
            //清除cache
            cache('fpRuleStaffs_'.session('shop_code'),null);
            db()->commit();
            return true;
        }else{
            db()->rollback();
            return false;
        }
    }
    function getDefaultRule(){
        $res = db('crm_s_allocation_rule')->where('shop_code',session('shop_code'))->where('order_sort',9999)->find();
        $tar = new \app\crm\lib\Target();
        $res['name'] = $tar->get_target_name_by_id($res['allocationtype_value']);
        return $res;
    }
    //废弃
    function addDefaultFPSet($param){
        if($param['allocationtype'] == 0){
            $param['active_time'] = null;
            $param['allocationtype_value'] = null;
        }
        $data = array();
        if($param['dpg'] == 'position_name'){
            $data = array(
                'allocationtype' => $param['allocationtype'],
                'allocationtype_value' => $param['allocationtype_value'],
                'position_id' => $param['d_dpg'],
                'position_name' => $param['name'],
                'active_time' => $param['active_time'],
                'shop_name' => session('shop_name'),
                'shop_code' => session('shop_code'),
                'setkey' => session('setkey'),
                'order_sort' => $param['order_sort'],
            );
        }elseif($param['dpg'] == 'department_name'){
            $data = array(
                'allocationtype' => $param['allocationtype'],
                'allocationtype_value' => $param['allocationtype_value'],
                'department_id' => $param['d_dpg'],
                'department_name' => $param['name'],
                'active_time' => $param['active_time'],
                'shop_name' => session('shop_name'),
                'shop_code' => session('shop_code'),
                'setkey' => session('setkey'),
                'order_sort' => $param['order_sort'],
            );
        }elseif($param['dpg'] == 'group_name'){
            $data = array(
                'allocationtype' => $param['allocationtype'],
                'allocationtype_value' => $param['allocationtype_value'],
                'group_id' => $param['d_dpg'],
                'group_name' => $param['name'],
                'active_time' => $param['active_time'],
                'shop_name' => session('shop_name'),
                'shop_code' => session('shop_code'),
                'setkey' => session('setkey'),
                'order_sort' => $param['order_sort'],
            );
        }
        db()->startTrans();
        try{
            if($param['id']){
                $data1 = array(
                    'department_name' => '',
                    'position_name' => '',
                    'position_id' => '',
                    'department_id' => '',
                    'group_id' => '',
                    'group_name' => '',
                    'active_time' =>'',
                    'allocationtype_value' =>'',
                    'customer_condition' =>'',
                    'customer_value' =>''
                );
                db('crm_s_allocation_rule')->where('id',$param['id'])->update($data1);
                db('crm_s_allocation_rule')->where('id',$param['id'])->update($data);

            }else{
                db('crm_s_allocation_rule')->insert($data);
                $res = db_config('fp_timeout_'.session('shop_code'),60);
                if($res){
                    cache('fp_timeout_'.session('shop_code'),60);
                }
            }
            cache('fpRuleStaffs_'.session('shop_code'),null);
            action_log($param,'',0,session('staff_id'),session('staff_name'));
            db()->commit();
            return true;
        }catch (Exception $e){
            db()->rollback();
            return false;
        }

    }
    //上移
    function upOrderSort($param){
        $order_sort = db('crm_s_allocation_rule')->where('order_sort','EGT',$param['order_sort'])->where('order_sort','<',9999)->where('shop_code',session('shop_code'))->where('id','<>',$param['id'])->limit(1)->select();
        if(empty($order_sort)){
            return array('code'=>100,'msg'=>'已经最高，不能上移了');
        }
        db()->startTrans();
        try{
            if( $order_sort[0]['order_sort'] == 9998){
                $res = db('crm_s_allocation_rule')->where('id',$param['id'])->update(array('order_sort'=>9998));
            }else{
                $res = db('crm_s_allocation_rule')->where('id',$param['id'])->update(array('order_sort'=>$order_sort[0]['order_sort']+1));
            }
            db()->commit();
            return array('code'=>200,'msg'=>'上移成功');
        }catch (Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'上移失败');
        }

    }
    //下移
    function downOrderSort($param){
        $order_sort = db('crm_s_allocation_rule')->where('order_sort','<',$param['order_sort'])->order('order_sort desc')->where('order_sort','EGT',0)->where('shop_code',session('shop_code'))->where('id','<>',$param['id'])->limit(1)->select();
        if(empty($order_sort)){
            return array('code'=>100,'msg'=>'已经最低，不能下移了');
        }
        db()->startTrans();
        try{
            if($order_sort[0]['order_sort'] == 0){
                $res = db('crm_s_allocation_rule')->where('id',$param['id'])->update(array('order_sort'=>0));
            }else{
                $res = db('crm_s_allocation_rule')->where('id',$param['id'])->update(array('order_sort'=>$order_sort[0]['order_sort']-1));
            }
            db()->commit();
            return array('code'=>200,'msg'=>'下移成功');
        }catch (Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'下移失败');
        }

    }
    function addFPSet($param){
        if($param['allocationtype'] == 0){
            $param['allocationtype_value'] = '';
            $param['active_time'] = '';
        }
        
        if ($param['customer_condition'] == 'customer_channel') {
            $channel_ids = explode(',',$param['customer_value']);
            $channel_ids = array_unique($channel_ids);
            $param['customer_value'] = implode(',',$channel_ids);
        }

        if($param['dpg'] == 'staff_name'){
            $staff = $param['staff_name'];
            $arr = explode('-',$staff);
            $staffId = explode(',',$arr[0]);
            $staffName = explode(',',$arr[1]);
            $staff_value = [];
            for($i=0;$i<count($staffId);$i++){
                $staff_value[$i]['staff_id'] = $staffId[$i];
                $staff_value[$i]['staff_name'] = $staffName[$i];
            }
        }elseif($param['dpg'] == 'department_name'){
            $staff_value[0]['department_id'] = intval($param['department_id']);
            $staff_value[0]['department_name'] = trim($param['department_name']);
        }elseif($param['dpg'] == 'group_name'){
            $staff_value[0]['group_id'] = intval($param['group_id']);
            $staff_value[0]['group_name'] = trim($param['group_name']);
        }elseif($param['dpg'] == 'position_name'){
            $staff_value[0]['position_id'] = intval($param['position_id']);
            $staff_value[0]['position_name'] = trim($param['position_name']);
        }
        $staff_value = json_encode($staff_value);
        $staff_type= trim($param['dpg']);
        $data = array(
            'isopen' => $param['isopen'],
            'allocationtype' => $param['allocationtype'],
            'allocationtype_value'=> $param['allocationtype_value'],
            'customer_condition'  => $param['customer_condition'],
            'customer_value' => $param['customer_value'],
            'order_sort' => $param['order_sort'],
            'group_id'   => null,
            'group_name' => null,
            'position_id'=> null,
            'position_name' => null,
            'department_id' => null,
            'department_name' => null,
            'active_time'=> $param['active_time'],
            'shop_name'  => session('shop_name'),
            'shop_code'  => session('shop_code'),
            'setkey'     => session('setkey'),
            'staff_type' =>$staff_type,
            'staff_value'=>$staff_value,
            'belong_shop_name'=>$param['shop_name'] ? $param['shop_name'] :session('shop_name'),
            'belong_shop_code'=>$param['shop_code'] ? $param['shop_code'] :session('shop_code'),
            'brandclass_id'=>session('brandclass_id'),
        );
        if($data['customer_condition'] != 'default' && $data['order_sort'] >= 9999){
            return array('code'=>400,'msg'=>'非默认排序规则不能大于9998');
        }
         if($data['customer_condition'] == 'default'){
            $data['customer_value'] = '';
            $data['isopen'] = 1;//默认规则只能开启
            $param['customer_value'] = '';
         }

        db()->startTrans();
        if($param['id']){//修改
            if($data['customer_condition'] != 'default'){
                $info = db('crm_s_allocation_rule')
                    ->where('customer_condition',$param['customer_condition'])
                    ->where('customer_value',$param['customer_value'])
                    ->where('shop_code',session('shop_code'))
                    ->where('order_sort',9999)
                    ->where('id','<>',$param['id'])
                    ->find();
            }else{
                $info = db('crm_s_allocation_rule')
                    ->where('customer_condition',$param['customer_condition'])
                    ->where('customer_value',$param['customer_value'])
                    ->where('shop_code',session('shop_code'))
                    ->where('id','<>',$param['id'])
                    ->find();
            }

            if($info){
                db()->rollback();
                return array('code'=>100,'msg'=>'已存在此类型的分配规则，请重新选择');
            }
            $res = db('crm_s_allocation_rule')->where('id','=',$param['id'])->update($data);
        }else{//添加
            if($data['customer_condition'] != 'default'){
                $info = db('crm_s_allocation_rule')
                    ->where('customer_condition',$param['customer_condition'])
                    ->where('customer_value',$param['customer_value'])
                    ->where('shop_code',session('shop_code'))
                    ->where('order_sort',9999)
                    ->find();
            }else{
                $info = db('crm_s_allocation_rule')
                    ->where('customer_condition',$param['customer_condition'])
                    ->where('customer_value',$param['customer_value'])
                    ->where('shop_code',session('shop_code'))
                    ->find();
            }

            if($info){
                db()->rollback();
                return array('code'=>100,'msg'=>'已存在此类型的分配规则，请重新选择');
            }
            db('crm_s_allocation_rule')->insert($data);
            $res = db('crm_s_allocation_rule')->getLastInsID();
        }
        if($res !== false){
            db()->commit();
            //清除cache
            cache('fpRuleStaffs_'.session('shop_code'),null);
            action_log($param,'',0,session('staff_id'),session('staff_name'));
            return array('code'=>200,'msg'=>'分配规则设定成功','data'=>$data);
        }else{
            db()->rollback();
            return array('code'=>300,'msg'=>'分配规则设定失败');
        }
    }
    //渠道类型
    function getChannelclass(){
        // $url = '5a2757c0a9810';
        // $res = sx_call($url,array());
        // return $res['data'];
        $mc = new \app\common\lib\mcInterface();
        $channelclass = $mc->getChannelClass();
        if ($channelclass === false) {
            $channelclass = [];
        }
        return $channelclass;
    }
    //渠道名
    function getChannelInfo($channelclass){
        // $url = '59fd5e729e5a8';
        // $res = sx_call($url,array('channelclass'=>$channelclass));
        // return $res['data'];
        $mc = new \app\common\lib\mcInterface();
        $channelinfo = $mc->getChannelInfo(array('channelclass'=>$channelclass));
        if ($channelinfo === false) {
            $channelinfo = [];
        }
        return $channelinfo;
    }
    //渠道名 0903 
    function getQudao($shopCode = ''){
        // $url = '59fd5e729e5a8';
        // $res = sx_call($url,array('shop_code'=>session('shop_code')));
        // return $res['data'];
        $shopCode = $shopCode?$shopCode:session('shop_code');
        $sql = ' FIND_IN_SET("'.$shopCode.'",share_shops) OR shop_code="'.$shopCode.'" ';
        return db('crm_s_channel')->where($sql)->order('order_sort asc')->select();
    }
    //人员渠道表查询
    function staffTrench($shopCode = ''){
        $shopCode = $shopCode?$shopCode:session('shop_code');
        return db('crm_c_staff_trench_mate')->where('shop_code',$shopCode)->select();            
    }
    //人员渠道表 更新
    function staffTrenchMate($data){
        $data['shop_code'] = $data['shop_code']?$data['shop_code']:session('shop_code');
        $res = db('crm_c_staff_trench_mate')->where('shop_code',$data['shop_code'])->where('staff_id',$data['staff_id'])->find(); 
        $datas['trench'] = $data['trench'];
        $datas['time'] = date('Y-m-d H:i:s',time());
        if ($res) {
            $ros = db('crm_c_staff_trench_mate')->where('shop_code',$data['shop_code'])->where('staff_id',$data['staff_id'])->update($datas);
        }else{
            $datas['shop_code'] = $data['shop_code'];
            $datas['staff_id'] = intval($data['staff_id']);
            $datas['staff_name'] = $data['staff_name'];
            $ros = db('crm_c_staff_trench_mate')->insert($datas);
        }
        return $ros;
    }
    //来源 ericdel 来源不用了
    /*
    function getcustomer_cource(){
        $url = '59fd5ec462c88';
        $res = sx_call($url,array('shop_code'=>session('shop_code')));
        return $res['data'];
    }
    */
    //根据id获取相应的渠道名
    function getChannelByName($channelclass){
        // $url = '59fd5e729e5a8';
        // $res = sx_call($url,array('channelclass'=>$channelclass['channelclass'],'shop_code'=>session('shop_code')));
        // return $res['data'];
        $mc = new \app\common\lib\mcInterface();
        $channelinfo = $mc->getChannelInfo($channelclass);
        if ($channelinfo === false) {
            $channelinfo = [];
        }
        return $channelinfo;
    }
    //分区 ericdel 不用了
    /*
    function getcustomer_area(){
        $url = '5a004e9c3e030';
        $res = sx_call($url,array('shop_code'=>session('shop_code')));
        return $res['data'];
    }
    */
    //地域  ericdel 不用了
    /*
    function getcustomer_region(){
        $url = '59fd5fa926b98';
        $res = sx_call($url,array('shop_code'=>session('shop_code')));
        return $res['data'];
    }
    */
    function getShopChannelListById($channelId){
        $res = db('crm_s_channel s')->field('s.*')->join('crm_s_channel ss ','s.shop_code = ss.shop_code')->where('ss.id',$channelId)->select();
        return $res;
    }
    //人员 ericdel 没地方用
    /*
    function getRenyuan(){
        $url = '5a02666c9935d';
        $res = sx_call($url,array('shop_code'=>session('shop_code')));
        return $res['data'];
    }
    */
    function FPListJSON($shop_code){
        $shopCode = $shop_code ? $shop_code : session('shop_code');
        $result['code'] = 0;
        $result['msg'] = '';
        $res = db('crm_s_allocation_rule')->where('shop_code|belong_shop_code',$shopCode)->field('id,department_name,position_name,allocationtype,allocationtype_value,active_time,customer_condition,customer_value,group_name,order_sort,isopen,staff_type,staff_value')->order('order_sort asc')->select();
        $count = db('crm_s_allocation_rule')->where('shop_code|belong_shop_code',$shopCode)->count();

        // $res = db('crm_s_allocation_rule')->where('brandclass_id',session('brandclass_id'))->field('id,department_name,position_name,allocationtype,allocationtype_value,active_time,customer_condition,customer_value,group_name,order_sort,isopen,staff_type,staff_value')->order('order_sort asc')->select();
        // $count = db('crm_s_allocation_rule')->where('brandclass_id',session('brandclass_id'))->count();
        if($res){
            $tt = new Target();
            foreach($res as $k=>$v){
                $res[$k]['allocationtype_value'] = $tt->get_target_name_by_id($v['allocationtype_value']);
                if($v['active_time'] == 'this_week'){
                    $res[$k]['active_time'] = '本周';
                }elseif($v['active_time'] == 'last_week'){
                    $res[$k]['active_time'] = '上周';
                }elseif($v['active_time'] == 'this_month'){
                    $res[$k]['active_time'] = '本月';
                }elseif($v['active_time'] == 'last_month'){
                    $res[$k]['active_time'] = '上月';
                }elseif($v['active_time'] == 'near_week'){
                    $res[$k]['active_time'] = '最近一周';
                }elseif($v['active_time'] == 'near_month'){
                    $res[$k]['active_time'] = '最近一月';
                }
                if($v['customer_condition'] == 'customer_channel'){
                    $res[$k]['customer_condition'] = '渠道名称';
                }elseif($v['customer_condition'] == 'customer_source'){
                    $res[$k]['customer_condition'] = '客户来源';
                }elseif($v['customer_condition'] == 'customer_area'){
                    $res[$k]['customer_condition'] = '客户分区';
                }elseif($v['customer_condition'] == 'customer_region'){
                    $res[$k]['customer_condition'] = '地域';
                }elseif($v['customer_condition'] == 'default'){
                    $res[$k]['customer_condition'] = '默认';
                }elseif($v['customer_condition'] == 'add_organize'){
                    $res[$k]['customer_condition'] = '提报人';
                }else{
                    $res[$k]['customer_condition'] = '其他';
                }
                $value = json_decode($v['staff_value'],true);
                if($v['staff_type'] == 'department_name'){
                    foreach($value as $ke=>$va){
                        $res[$k]['department_name'] = $va['department_name'];
                    }
                }
                if($v['staff_type'] == 'group_name'){
                    foreach($value as $ke=>$va){
                        $res[$k]['group_name'] = $va['group_name'];
                    }
                }
                if($v['staff_type'] == 'position_name'){
                    foreach($value as $ke=>$va){
                        $res[$k]['position_name'] = $va['position_name'];
                    }
                }
                if($v['staff_type'] == 'staff_name'){
                    foreach($value as $ke=>$va){
                        $res[$k]['staff_name'] .= $va['staff_name'].',';
                    }
                    $res[$k]['staff_name'] = trim($res[$k]['staff_name'],',');
                }
                $region = '';
                if($v['customer_condition'] == 'customer_region'){
                    $a = explode(',',$v['customer_value']);
                    foreach($a as $kk=>$vv){
                        $tem = explode('-',$vv);
                        $region .= ','.end($tem);
                    }
                    $res[$k]['customer_value'] = trim($region,',');
                }
                $staff = '';
                if($v['customer_condition'] == 'add_organize'){
                    $a = explode(',',$v['customer_value']);
                    foreach($a as $kk=>$vv){
                        $tem = explode('-',$vv);
                        $staff .= ','.end($tem);
                    }
                    $res[$k]['customer_value'] = trim($staff,',');
                }
                $ch = '';
                if($v['customer_condition'] == 'customer_channel'){
                    $channels = db('crm_s_channel')->where('id','in',$v['customer_value'])->select();
                    foreach($channels as $kk=>$vv){
                        $ch .= ','.$vv['channel_name'];
                    }
                    $res[$k]['customer_value'] = trim($ch,',');
                }
            }
            $result['data'] = $res;
            $result['count'] = $count;
        }else{
            $result['data'] = array();
        }
        return ($result);
    }
    //追踪失败原因
    function fileReason($reason)
    {
        $res = db('crm_s_file_reason')->where('reason','like','%'.$reason.'%')->select();
        if($res){
            return ($res);
        }else{
            return false;
        }
    }
    function setReason($param){
        $data['shop_name'] = session('shop_name');
        $data['shop_code'] = session('shop_code');
        $data['setkey'] = session('setkey');
        $data['reason'] = $param['reason'];
        db()->startTrans();
        db('crm_s_file_reason')->insert($data);
        if(db('crm_s_file_reason')->getLastInsID()){
            db()->commit();
            action_log($param,'',0,session('staff_id'),session('staff_name'));
            return db('crm_s_file_reason')->getLastInsID();
        }else{
            db()->rollback();
            return false;
        }

    }
    function setRejectReason($param){
        $data['shop_name'] = session('shop_name');
        $data['shop_code'] = session('shop_code');
        $data['brandclass_id'] = session('brandclass_id');
        $data['brandclass'] = session('brandclass');
        $data['reason'] = $param['reason'];
        db()->startTrans();
        db('crm_s_reject_reason')->insert($data);
        if(db('crm_s_reject_reason')->getLastInsID()){
            db()->commit();
            action_log($param,'',0,session('staff_id'),session('staff_name'));
            return db('crm_s_reject_reason')->getLastInsID();
        }else{
            db()->rollback();
            return false;
        }
    }
    
    //短信模板
    function getModalToJSON($mtemplate_name)
    {
        $result['code'] = 0;
        $result['msg'] = '';
        $res = db('crm_s_message_templateinfo')->where('shop_code',session('shop_code'))->where('mtemplate_name','like','%'.$mtemplate_name.'%')->field('id,mtemplate_name,mtemplate_content,status')->select();
        $count = db('crm_s_message_templateinfo')->where('shop_code',session('shop_code'))->where('mtemplate_name','like','%'.$mtemplate_name.'%')->count();
        if($res){
            $result['data'] = $res;
            $result['count'] = $count;
        }else{
            $result['data'] = array();
        }
        return ($result);
    }
    //短信模板增加
    function addModal($param){
        $param['shop_name'] = session('shop_name');
        $param['shop_code'] = session('shop_code');
        $param['setkey'] = session('setkey');
        db()->startTrans();
        db('crm_s_message_templateinfo')->insert($param);
        $id = db('crm_s_message_templateinfo')->getLastInsID();
        if($id){
            db()->commit();
            action_log($param,'',0,session('staff_id'),session('staff_name'));
            return true;
        }else{
            db()->rollback();
            return false;
        }
    }
    function findMModal($id){
        $res = db('crm_s_message_templateinfo')->where('id',$id)->find();
        if($res){
            return $res;
        }else{
            return false;
        }
    }
    function editMModal($param){
        db()->startTrans();
        $res = db('crm_s_message_templateinfo')->where('id',$param['id'])->update($param);
        if($res === false){
            db()->rollback();
            return false;
        }else{
            db()->commit();
            action_log($param,'',0,session('staff_id'),session('staff_name'));
            return $res;
        }
    }
    
    function delMModal($id){
        db()->startTrans();
        $res = db('crm_s_message_templateinfo')->where('id',$id)->delete();
        if($res){
            db()->commit();
            action_log($id,'',0,session('staff_id'),session('staff_name'));
            return true;
        }else{
            db()->rollback();
            return false;
        }
    }
    
    //追踪失败原因
    function getReasonToJSON($reason)
    {
        $result['code'] = 0;
        $result['msg'] = '';
        $res = db('crm_s_file_reason')->where('shop_code',session('shop_code'))->where('reason','like','%'.$reason.'%')->select();
        $count = db('crm_s_file_reason')->where('shop_code',session('shop_code'))->where('reason','like','%'.$reason.'%')->count();
        if($res){
            $result['data'] = $res;
            $result['count'] = $count;
        }else{
            $result['data'] = array();
        }
        return ($result);
    }
    //追踪失败原因
    function getRejectReasonToJSON($reason)
    {
        $result['code'] = 0;
        $result['msg'] = '';
        $res = db('crm_s_reject_reason')->where('shop_code',session('shop_code'))->where('reason','like','%'.$reason.'%')->select();
        $count = db('crm_s_reject_reason')->where('shop_code',session('shop_code'))->where('reason','like','%'.$reason.'%')->count();
        if($res){
            $result['data'] = $res;
            $result['count'] = $count;
        }else{
            $result['data'] = array();
        }
        return ($result);
    }
    function editWalkFlow($param){
        $info = db('crm_s_sales_routines')->where('id',$param['id'])->find();
        db()->startTrans();
        $res = db('crm_s_sales_routines')->where('id',$param['id'])->update($param);
        if($res === false){
            db()->rollback();
            return false;
        }else{
            action_log($param,$info,0,session('staff_id'),session('staff_name'));
            db()->commit();
            return $res;
        }
    }
    function delWalkFlow($id){
        db()->startTrans();
        $res = db('crm_s_sales_routines')->where('id',$id)->delete();
        if($res){
            action_log($id,'',0,session('staff_id'),session('staff_name'));
            db()->commit();
            return $res;
        }else{
            db()->rollback();
            return false;
        }
    }
    //业务流程
    function getworkflowToJSON($step_content)
    {
        $result['code'] = 0;
        $result['msg'] = '';
        $res = db('crm_s_sales_routines')->where('shop_code',session('shop_code'))->column('id,step_name,step_content,step_stage');
        $count = db('crm_s_sales_routines')->where('shop_code',session('shop_code'))->count();
        if($res){
            $result['data'] = $res;
            $result['count'] = $count;
        }else{
            $result['data'] = array();
        }
        return ($result);
    }
    function addWorkFlow($param){
        $param['step_name'] = $param['step_name'];
        $param['step_content'] = $param['step_content'];
        $param['step_stage'] = $param['step_stage'];
        $param['shop_name'] = session('shop_name');
        $param['shop_code'] = session('shop_code');
        $param['setkey'] = session('setkey');
        db()->startTrans();
        db('crm_s_sales_routines')->insert($param);
        if(db('crm_s_sales_routines')->getLastInsID()){
            db()->commit();
            action_log($param,'',0,session('staff_id'),session('staff_name'));
            return db('crm_s_sales_routines')->getLastInsID();
        }else{
            db()->rollback();
            return false;
        }

    }
    //渠道类型列表
    function getchannelclassToJSON($reason)
    {
        $limit = $reason['limit'] ? $reason['limit'] : 10;
        $page = $reason['page'] ? $reason['page'] : 1;
        $result['code'] = 0;
        $result['msg'] = '';
        $date = explode(' - ',$reason['search_cost_date']);
        $start = $date[0] ? $date[0]: date('Y-m-01');
        $end = $date[1] ? $date[1]: date('Y-m-d');
        $where = [];
        if($reason['channel_id']) $where['channel_id'] = $reason['channel_id'];
        if($reason['province_id']) $where['province_id'] = $reason['province_id'];
        if($reason['city_id']) $where['city_id'] = $reason['city_id'];
        if($reason['department_id']) $where['department_id'] = $reason['department_id'];
        $res = db('crm_s_channel_cost')->where('shop_code',session('shop_code'))->where($where)->where('cost_date','between',[$start,$end])->order('cost_date desc')->page($page,$limit)->select();
        $count = db('crm_s_channel_cost')->where('shop_code',session('shop_code'))->where($where)->where('cost_date','between',[$start,$end])->count();
        if($res){
            foreach ($res as $key => $value) {
                $res[$key]['cost'] = sprintf('%.2f',$value['cost']);
                if (!$value['city_name']) {
                    $res[$key]['city_name'] = '';
                }
            }
            $result['data'] = $res;
            $result['count'] = $count;
        }else{
            $result['data'] = array();
        }
        return ($result);
    }
    //渠道花费返点列表
    function getChannelReturnToJSON($reason)
    {
        $result['code'] = 0;
        $result['msg'] = '';
        $page = $reason['page'] ? $reason['page'] : 1;
        $limit = $reason['limit'] ? $reason['limit'] : 10;
        if($reason['channel_id']) $where['channel_id'] = $reason['channel_id'];
        if($reason['province_id']) $where['province_id'] = $reason['province_id'];
        if($reason['city_id']) $where['city_id'] = $reason['city_id'];
        $res = db('crm_s_channel_cost_return')->where('shop_code',session('shop_code'))->where($where)->where('return_month','like','%'.$reason['search_return'].'%')->page($page)->limit($limit)->select();
        $count = db('crm_s_channel_cost_return')->where('shop_code',session('shop_code'))->where($where)->where('return_month','like','%'.$reason['search_return'].'%')->count();
        if($res){
            foreach ($res as $key => $value) {
                $res[$key]['cost'] = sprintf('%.2f',$value['cost']);
                if (!$value['city_name']) {
                    $res[$key]['city_name'] = '';
                }
            }
            $result['data'] = $res;
            $result['count'] = $count;
        }else{
            $result['data'] = array();
        }
        return ($result);
    }
    // 这个方法没有地方用啊  ericdel
    /*
    function getQD(){
        $url = '59fd5e729e5a8';
        $res = sx_call($url,array('shop_code'=>session('shop_code')));
        if($res['code'] == 200){
            return $res;
        }else{
            return false;
        }
    }*/
    function addQDType($channelclass){
        if($channelclass['province_id']){
            if(!empty($channelclass['province_id'])){
                $region = controller("Customer","lib")->getRegionByProvinceId(['id'=>$channelclass['province_id']]);
                $data['region_id'] = $region['id'];
                $data['region_name'] = $region['region_name'];
            }
        }

        $data['cost_date'] = $channelclass['cost_date'];
        // $data['cost'] = $channelclass['cost'];
        $data['province_id'] = $channelclass['province_id'] ? $channelclass['province_id'] : 0;
        $data['province_name'] = $channelclass['province_name'] ? $channelclass['province_name'] : null;
        $data['department_id'] = $channelclass['department_id'] ? $channelclass['department_id'] : 0;
        $data['department_name'] = $channelclass['department_name'] ? $channelclass['department_name'] : null;
        $data['channel_id'] = $channelclass['channel_id'];
        $data['channel_name'] = $channelclass['channel_name'];
        $data['channel_class_id'] = $channelclass['channel_class_id'];
        $data['channel_class_name'] = $channelclass['channel_class_name'];
        $data['channel_info_id'] = $channelclass['channel_info_id'];
        $data['channel_info_name'] = $channelclass['channel_info_name'];
        $data['staff_id'] = session('staff_id');
        $data['brandclass_id'] = session('brandclass_id');
        $data['shop_name'] = session('shop_name');
        $data['shop_code'] = session('shop_code');
        $data['setkey'] = session('setkey');
        $data['create_time'] = date('Y-m-d H:i:s',time());
        $citys = $channelclass['city'];
        $costArr = $channelclass['cost'];
        $costs = [];
        foreach($costArr as $ke=>$va){
            if(empty($va)){
                unset($costArr[$ke]);
            }else{
                array_push($costs,$costArr[$ke]);
            }
        }
        if(empty($citys)){
            return array('code'=>600,'msg'=>'城市选择有误，请重新选择');
        }
        if(empty($costs)){
            return array('code'=>700,'msg'=>'花费输入有误，请重新输入');
        }
        if(count($costs) != count($citys)){
            return array('code'=>800,'msg'=>'花费和城市有误，请重新操作');
        }

        foreach($citys as $k=>$v){
            $data['city_id'] = $v;
            $data['city_name'] = db('crm_s_shop_address')->where('id',$v)->where('shop_code',session('shop_code'))->value('name');
            $res = db('crm_s_channel_cost')->where('department_id',$data['department_id'])->where('channel_id', $data['channel_id'])->where('city_id',$data['city_id'])->where('province_id',$data['province_id'])->where('brandclass_id', session('brandclass_id'))->where('cost_date', $data['cost_date'])->find();
            if(!empty($data['city_id']) && $res['city_id'] == $data['city_id']){
                return array('code'=>100,'msg'=>'已存在'.$data['cost_date'].$data['department_id'].$data['channel_name'].$data['city_name'].'的花费，请重新添加');
            }
        }
        $ip = \think\Request::instance()->ip();
        db()->startTrans();
        try{
            $log = [];
            foreach($citys as $k=>$v){
                $data['city_id'] = $v;
                $data['city_name'] = db('crm_s_shop_address')->where('id',$v)->where('shop_code',session('shop_code'))->value('name');
                $data['cost'] = $costs[$k];
                db('crm_s_channel_cost')->insert($data);
                $id = db('crm_s_channel_cost')->getLastInsID();
                if($id) {
                    $new = '';
                    $new .= '操作店面：'.$data['shop_name'].'<br/>';
                    if($data['belong_shop_name'])$new .= '归属店：'.$data['belong_shop_name'].'<br/>';
                    if($data['department_name'])$new .= '部门：'.$data['department_name'].'<br/>';
                    if($data['region_name'])$new .= '地域：'.$data['region_name'].'<br/>';
                    if($data['province_name'])$new .= '省：'.$data['province_name'].'<br/>';
                    if($data['city_name'])$new .= '市：'.$data['city_name'].'<br/>';
                    $new .= '渠道：'.$data['channel_name'].'<br/>';
                    $new .= '花费：'.$data['cost'].'<br/>';
                    $new .= '日期：'.$data['cost_date'].'<br/>';
                    $log[$k]['module']     = 'crm';
                    $log[$k]['controller'] = 'Setting';
                    $log[$k]['action']     = 'addqdtype';
                    $log[$k]['old_data']   = json_encode([]);
                    $log[$k]['data'] = $new;
                    $log[$k]['customer_id']= 0;
                    $log[$k]['staff_name'] = session('staff_name');
                    $log[$k]['staff_id']   = session('staff_id');
                    $log[$k]['ip']         = $ip;
                    $log[$k]['create_time']= $data['create_time'];
                    //操作customer_cost表
                    $arr = explode(' - ', $data['cost_date']);//目前按天设定，之后可能会按区间计算
                    if (empty($arr[1])) {
                        $day = 1;
                    } else {
                        $day = diffBetweenTwoDays($arr[0], $arr[1]) + 1;
                    }
                    $avg = sprintf('%.4f',$data['cost']/$day);
                    for($i=0;$i<$day;$i++){
                        $info = db('crm_c_customer_cost')
                            ->where('shop_code',session('shop_code'))
                            ->where('channel_id',$data['channel_id'])
                            ->where('region_id',$data['region_id'])
                            ->where('province_id',$data['province_id'])
                            ->where('city_id',$data['city_id'])
                            ->where('channel_class_id',$data['channel_class_id'])
                            ->where('channel_info_id',$data['channel_info_id'])
                            ->where('brandclass_id',session('brandclass_id'))
                            ->where('return_avg',null)
                            ->where('cost_time',date('Y-m-d',strtotime($arr[0])+$i*24*60*60))
                            ->find();
                        // echo db()->getLastSql();die;
                        if(empty($info)){
                            $ins = array(
                                'shop_code'=>session('shop_code'),
                                'channel_class_id'=>$data['channel_class_id'],
                                'channel_class_name'=>$data['channel_class_name'],
                                'channel_info_id'=>$data['channel_info_id'],
                                'channel_info_name'=>$data['channel_info_name'],
                                'channel_id'=>$data['channel_id'],
                                'channel_name'=>$data['channel_name'],
                                'region_id'=>$data['region_id'],
                                'region_name'=>$data['region_name'],
                                'province_id' => $data['province_id'],
                                'province_name' => $data['province_name'],
                                'city_id' => $data['city_id'],
                                'city_name' => $data['city_name'],
                                'brandclass_id'=>session('brandclass_id'),
                                'cost_time'=>date('Y-m-d',strtotime($arr[0])+$i*24*60*60),
                                // 'cost_avg'=>$cost - $i*$avg,
                                'cost_avg'=>bcsub($data['cost'],bcmul($i,$avg,4),4)
                            );
                            // print_r($ins);die;
                            db('crm_c_customer_cost')->insert($ins);
                        }else{
                            $ins = array(
                                'shop_code'=>session('shop_code'),
                                'channel_class_id'=>$data['channel_class_id'],
                                'channel_class_name'=>$data['channel_class_name'],
                                'channel_info_id'=>$data['channel_info_id'],
                                'channel_info_name'=>$data['channel_info_name'],
                                'channel_id'=>$data['channel_id'],
                                'channel_name'=>$data['channel_name'],
                                'region_id'=>$data['region_id'],
                                'region_name'=>$data['region_name'],
                                'province_id' => $data['province_id'],
                                'province_name' => $data['province_name'],
                                'city_id' => $data['city_id'],
                                'city_name' => $data['city_name'],
                                'brandclass_id'=>session('brandclass_id'),
                                'cost_time'=>date('Y-m-d',strtotime($arr[0])+$i*24*60*60),
                                'cost_avg'=>bcsub($data['cost'],bcmul($i,$avg,4),4)
                            );
                            db('crm_c_customer_cost')->where('id',$info['id'])->update($ins);
                        }
                    }
                }
            }
            db('crm_action_log','db_logs')->insertAll($log);
            action_log($channelclass,'',0,session('staff_id'),session('staff_name'));
            cache('crm_channel_'.session('shop_code'),null);
            cache('all_channel_'.session('shop_code'),null);
            db()->commit();
            return  array('code'=>200,'msg'=>'','data'=>$data);
        }catch (Exception $e){
            db()->rollback();
            return  array('code'=>100,'msg'=>'渠道花费添加失败','data'=>$e->getMessage().db()->getLastSql());
        }
    }
    //花费返点添加
    function addQDReturn($channelclass){
        // if(!empty($channelclass['province_id'])){
        //     $region = controller("Customer","lib")->getRegionByProvinceId(['id'=>$channelclass['province_id']]);
        //     $channelclass['region_id'] = $region['id'];
        //     $channelclass['region_name'] = $region['region_name'];
        // }

        $channelclass['province_id'] = $channelclass['province_id'] ? $channelclass['province_id'] : 0;
        $channelclass['province_name'] = $channelclass['province_name'] ? $channelclass['province_name'] : null;
        $channelclass['city_id'] = $channelclass['city_id'] ? $channelclass['city_id'] : 0;
        $channelclass['city_name'] = $channelclass['city_name'] ? $channelclass['city_name'] : null;
        $res = db('crm_s_channel_cost_return')
            ->where('return_month',$channelclass['return_month'])
            ->where(array('channel_id'=>$channelclass['channel_id'],'channel_class_id'=>$channelclass['channel_class_id'],'channel_info_id'=>$channelclass['channel_info_id'],'province_id'=>$channelclass['province_id'],'city_id'=>$channelclass['city_id']))->where('brandclass_id', session('brandclass_id'))
            ->find();
        if($res['id']){
            return array('code'=>105,'msg'=>'本月已有此花费返点，不能继续添加');
        }
        //检查此渠道和地区上月是否设置花费
        $ret = $this->checkCostReturn(array('channel_id'=>$channelclass['channel_id'],'channel_class_id'=>$channelclass['channel_class_id'],'channel_info_id'=>$channelclass['channel_info_id'],'city_id'=>$channelclass['city_id']));

        if($ret['code'] == 100){
            return array('code'=>100,'msg'=>'该渠道和城市上月未设置花费，不能设置返点');
        }

        // if($channelclass['region_id'] == 0){
            $channelclass['region_id'] = 0;
            $channelclass['region_name'] = null;
        // }
        $channelclass['staff_id'] = session('staff_id');
        $channelclass['brandclass_id'] = session('brandclass_id');
        $channelclass['brandclass'] = session('brandclass');
        $channelclass['shop_name'] = session('shop_name');
        $channelclass['shop_code'] = session('shop_code');
        $channelclass['setkey'] = session('setkey');
        $channelclass['create_time'] = date('Y-m-d H:i:s',time());
        db()->startTrans();
        try{
            $id =db('crm_s_channel_cost_return')->insertGetId($channelclass);
            if($id){
                //操作分摊表
                $days = date('t',strtotime($channelclass['return_month']));
                $return_avg = sprintf('%.4f',$channelclass['return_cost']/$days);
                for($i=0;$i<$days;$i++){
                    $info = db('crm_c_customer_cost')
                        ->where('shop_code',session('shop_code'))
                        ->where('channel_id',$channelclass['channel_id'])
                        ->where('channel_class_id',$channelclass['channel_class_id'])
                        ->where('channel_info_id',$channelclass['channel_info_id'])
                        ->where('region_id',$channelclass['region_id'])
                        ->where('province_id',$channelclass['province_id'])
                        ->where('city_id',$channelclass['city_id'])
                        ->where('brandclass_id',session('brandclass_id'))
                        ->where('return_avg','<>',0)
                        ->where('cost_time',date('Y-m-d',strtotime($channelclass['return_month'])+$i*24*60*60))
                        ->find();

                    if(empty($info)){
                        $data = array(
                            'shop_code'=>session('shop_code'),
                            'channel_id'=>$channelclass['channel_id'],
                            'channel_name'=>$channelclass['channel_name'],
                            'channel_class_id'=>$channelclass['channel_class_id'],
                            'channel_class_name'=>$channelclass['channel_class_name'],
                            'channel_info_id'=>$channelclass['channel_info_id'],
                            'channel_info_name'=>$channelclass['channel_info_name'],
                            'region_id'=>$channelclass['region_id'],
                            'region_name'=>$channelclass['region_name'],
                            'province_id'=>$channelclass['province_id'],
                            'province_name'=>$channelclass['province_name'],
                            'city_id'=>$channelclass['city_id'],
                            'city_name'=>$channelclass['city_name'],
                            'brandclass_id'=>session('brandclass_id'),
                            'cost_time'=>date('Y-m-d',strtotime($channelclass['return_month'])+$i*24*60*60),
                            'return_avg'=>($i == $days-1) ? bcsub($channelclass['return_cost'],($days-1)*$return_avg,4) :$return_avg,
                        );
                        db('crm_c_customer_cost')->insert($data);
                    }else{
                        $data = array(
                            'shop_code'=>session('shop_code'),
                            'channel_id'=>$channelclass['channel_id'],
                            'channel_name'=>$channelclass['channel_name'],
                            'channel_class_id'=>$channelclass['channel_class_id'],
                            'channel_class_name'=>$channelclass['channel_class_name'],
                            'channel_info_id'=>$channelclass['channel_info_id'],
                            'channel_info_name'=>$channelclass['channel_info_name'],
                            'region_id'=>$channelclass['region_id'],
                            'region_name'=>$channelclass['region_name'],
                            'province_id'=>$channelclass['province_id'],
                            'province_name'=>$channelclass['province_name'],
                            'city_id'=>$channelclass['city_id'],
                            'city_name'=>$channelclass['city_name'],
                            'brandclass_id'=>session('brandclass_id'),
                            'cost_time'=>date('Y-m-d',strtotime($channelclass['return_month'])+$i*24*60*60),
                            'return_avg'=>($i == $days-1) ? bcsub($channelclass['return_cost'],($days-1)*$return_avg,4) :$return_avg,
                        );
                        db('crm_c_customer_cost')->where('id',$info['id'])->update($data);
                    }
                }
                db()->commit();
                action_log($channelclass,$res,0,session('staff_id'),session('staff_name'));
                return array('code'=>200,'msg'=>'花费返点设置成功');
            }else{
                db()->rollback();
                return array('code'=>300,'msg'=>'花费返点设置失败');
            }
        }catch (Exception $e){
            db()->rollback();
            return array('code'=>400,'msg'=>'花费返点设置失败','data'=>$e->getMessage());
        }

    }
    //花费返点删除
    function delQDReturn($id){
        db()->startTrans();
        //获取返点的地域，渠道id
        $info = db('crm_s_channel_cost_return')->where('id',$id)->find();
        try{
            $res = db('crm_s_channel_cost_return')->where('id',$id)->delete();
            db('crm_c_customer_cost')
                ->where('shop_code',session('shop_code'))
                ->where('channel_id',$info['channel_id'])
                ->where('channel_class_id',$info['channel_class_id'])
                ->where('channel_info_id',$info['channel_info_id'])
                ->where('region_id',$info['region_id'])
                ->where('province_id',$info['province_id'])
                ->where('city_id',$info['city_id'])
                ->where('brandclass_id',session('brandclass_id'))
                ->where('return_avg','<>',0)
                ->delete();
            db()->commit();
            action_log($id,'',0,session('staff_id'),session('staff_name'));
            return true;
        }catch (Exception $e){
            db()->rollback();
            return false;
        }
    }
    function delQDType($id){
        db()->startTrans();
        try{
            $cinfo = db('crm_s_channel_cost')->where('id',$id)->find();
            db('crm_s_channel_cost')->where('id',$id)->delete();
            //操作customer_cost表
            $arr = explode(' - ', $cinfo['cost_date']);//目前按天设定，之后可能会按区间计算
            if (empty($arr[1])) {
                $day = 1;
            } else {
                $day = diffBetweenTwoDays($arr[0], $arr[1]) + 1;
            }
            for($i=0;$i<$day;$i++) {
                $info = db('crm_c_customer_cost')
                    ->where('shop_code', session('shop_code'))
                    ->where('channel_id', $cinfo['channel_id'])
                    ->where('region_id', $cinfo['region_id'])
                    ->where('province_id',$cinfo['province_id'])
                    ->where('city_id',$cinfo['city_id'])
                    ->where('brandclass_id', session('brandclass_id'))
                    ->where('return_avg',null)
                    ->where('cost_time', date('Y-m-d', strtotime($arr[0]) + $i * 24 * 60 * 60))
                    ->find();
                db('crm_c_customer_cost')->where('id',$info['id'])->delete();
            }
            action_log($id,'',0,session('staff_id'),session('staff_name'));
            cache('crm_channel_'.session('shop_code'),null);
            cache('all_channel_'.session('shop_code'),null);
            db()->commit();

            return true;
        }catch (Exception $e){
            db()->rollback();
            return false;
        }

    }
    function editQDType($param){
        if(!empty($param['province_id'])){
            $region = controller("Customer","lib")->getRegionByProvinceId(['id'=>$param['province_id']]);
            $param['region_id'] = $region['id'];
            $param['region_name'] = $region['region_name'];
        }
        $param['department_id'] = $param['department_id'] ? $param['department_id'] : 0;
        $param['department_name'] = $param['department_name'] ? $param['department_name'] : null;
        $param['province_id'] = $param['province_id'] ? $param['province_id'] : 0;
        $param['province_name'] = $param['province_name'] ? $param['province_name'] : null;
        $param['city_id'] = $param['city_id'] ? $param['city_id'] : 0;
        $param['city_name'] = $param['city_name'] ? $param['city_name'] : null;
        $param['update_time'] = date('Y-m-d H:i:s',time());

        $res = db('crm_s_channel_cost')
            ->where('channel_id', $param['channel_id'])
            ->where('region_id', $param['region_id'])
            ->where('province_id', $param['province_id'])
            ->where('city_id', $param['city_id'])
            ->where('department_id',$param['department_id'])
            ->where('channel_class_id', $param['channel_class_id'])
            ->where('channel_info_id', $param['channel_info_id'])
            ->where('brandclass_id', session('brandclass_id'))
            ->where('id','<>',$param['id'])
            ->where('cost_date', $param['cost_date'])
            ->find();
        if(!empty($res) && $res['city_id'] == $param['city_id']){
            return array('code'=>100,'msg'=>'已存在此时间此渠道城市的花费，请重新编辑');
        }
        // $days = cal_days_in_month(CAL_GREGORIAN, $param['month'], $param['year']);//当月天数
        // $param['cost_avg'] = round($param['cost']/$days,2);//平均每天花费
        db()->startTrans();
        try{
            $cinfo = db('crm_s_channel_cost')->where('id',$param['id'])->find();//原数据
            $oldArr = explode(' - ', $cinfo['cost_date']);//目前按天设定，之后可能会按区间计算
            if (empty($oldArr[1])) {
                $day = 1;
            } else {
                $day = diffBetweenTwoDays($oldArr[0], $oldArr[1]) + 1;
            }
            for($i=0;$i<$day;$i++) {//删除原数据
                $date = date('Y-m-d', strtotime($oldArr[0]) + $i * 24 * 60 * 60);
                $csinfo = db('crm_c_customer_cost')
                    ->where('shop_code', session('shop_code'))
                    ->where('channel_id', $cinfo['channel_id'])
                    ->where('channel_class_id', $cinfo['channel_class_id'])
                    ->where('channel_info_id', $cinfo['channel_info_id'])
                    ->where('region_id', $cinfo['region_id'])
                    ->where('province_id', $cinfo['province_id'])
                    ->where('city_id', $cinfo['city_id'])
                    ->where('brandclass_id', session('brandclass_id'))
                    ->where('return_avg',null)
                    ->where('cost_time', $date)
                    ->find();
                if($csinfo['id']){
                    db('crm_c_customer_cost')->where('id',$csinfo['id'])->delete();
                }
            }
            $res = db('crm_s_channel_cost')->where('id',$param['id'])->update($param);
            //操作customer_cost表
            $arr = explode(' - ', $param['cost_date']);//目前按天设定，之后可能会按区间计算
            if (empty($arr[1])) {
                $day = 1;
            } else {
                $day = diffBetweenTwoDays($arr[0], $arr[1]) + 1;
            }
            $cost = $param['cost'];
            $avg = sprintf('%.4f',$param['cost']/$day);
            for($i=0;$i<$day;$i++){
                $date = date('Y-m-d',strtotime($arr[0])+$i*24*60*60);
                $info = db('crm_c_customer_cost')
                    ->where('shop_code',session('shop_code'))
                    ->where('channel_id',$param['channel_id'])
                    ->where('province_id',$param['province_id'])
                    ->where('city_id',$param['city_id'])
                    ->where('channel_class_id', $param['channel_class_id'])
                    ->where('channel_info_id', $param['channel_info_id'])
                    ->where('region_id',$param['region_id'])
                    ->where('brandclass_id',session('brandclass_id'))
                    ->where('return_avg',null)
                    ->where('cost_time',$date)
                    ->find();
                if(empty($info['id'])){
                    $data = array(
                        'shop_code'=>session('shop_code'),
                        'channel_class_id'=>$param['channel_class_id'],
                        'channel_class_name'=>$param['channel_class_name'],
                        'channel_info_id'=>$param['channel_info_id'],
                        'channel_info_name'=>$param['channel_info_name'],
                        'channel_id'=>$param['channel_id'],
                        'channel_name'=>$param['channel_name'],
                        'region_id'=>$param['region_id'],
                        'region_name'=>$param['region_name'],
                        'province_id'=>$param['province_id'],
                        'province_name'=>$param['province_name'],
                        'city_id'=>$param['city_id'],
                        'city_name'=>$param['city_name'],
                        'brandclass_id'=>session('brandclass_id'),
                        'cost_time'=>$date,
                        'cost_avg'=>bcsub($cost,bcmul($i,$avg,4),4)
                    );
                    db('crm_c_customer_cost')->insert($data);
                }else{
                    $data = array(
                        'shop_code'=>session('shop_code'),
                        'channel_class_id'=>$param['channel_class_id'],
                        'channel_class_name'=>$param['channel_class_name'],
                        'channel_info_id'=>$param['channel_info_id'],
                        'channel_info_name'=>$param['channel_info_name'],
                        'channel_id'=>$param['channel_id'],
                        'channel_name'=>$param['channel_name'],
                        'region_id'=>$param['region_id'],
                        'region_name'=>$param['region_name'],
                        'province_id'=>$param['province_id'],
                        'province_name'=>$param['province_name'],
                        'city_id'=>$param['city_id'],
                        'city_name'=>$param['city_name'],
                        'brandclass_id'=>session('brandclass_id'),
                        'cost_time'=>$date,
                        'cost_avg'=>bcsub($cost,bcmul($i,$avg,4),4)
                    );
                    db('crm_c_customer_cost')->where('id',$info['id'])->update($data);
                }
                $sql = db()->getLastSql();
            }
            $old = '';
            $old .= '操作店面：'.$cinfo['shop_name'].'<br/>';
            if($cinfo['department_name'])$old .= '部门：'.$cinfo['department_name'].'<br/>';
            if($cinfo['region_name'])$old .= '地域：'.$cinfo['region_name'].'<br/>';
            if($cinfo['province_name'])$old .= '省：'.$cinfo['province_name'].'<br/>';
            $old .= '市：'.$cinfo['city_name'].'<br/>';
            $old .= '渠道：'.$cinfo['channel_name'].'<br/>';
            $old .= '花费：'.$cinfo['cost'].'<br/>';
            $old .= '日期：'.$cinfo['cost_date'].'<br/>';
            $new = '';
            $new .= '操作店面：'.$cinfo['shop_name'].'<br/>';
            if($param['department_name'])$new .= '部门：'.$param['department_name'].'<br/>';
            if($param['region_name'])$new .= '地域：'.$param['region_name'].'<br/>';
            if($param['province_name'])$new .= '省：'.$param['province_name'].'<br/>';
            if($param['city_name'])$new .= '市：'.$param['city_name'].'<br/>';
            $new .= '渠道：'.$param['channel_name'].'<br/>';
            $new .= '花费：'.$param['cost'].'<br/>';
            $new .= '日期：'.$param['cost_date'].'<br/>';
            action_log($new, $old, session('staff_id'), 0, session('staff_name'));
            cache('crm_channel_'.session('shop_code'),null);
            cache('all_channel_'.session('shop_code'),null);
            db()->commit();

            return  array('code'=>200,'msg'=>'','data'=>$sql);
        }catch (Exception $e){
            db()->rollback();
            return  array('code'=>100,'msg'=>'渠道花费修改失败','data'=>$e->getMessage());
        }
    }
    //检查上月是否有渠道花费设置
    public function checkCostReturn($where){
        $time = date('Y-m',strtotime('-1 month'));
        if ($where['month']) {
            $time = $where['month'];
            unset($where['month']);
        }
        $res = db('crm_s_channel_cost')->where('cost_date','like','%'.$time.'%')->where($where)->where('shop_code',session('shop_code'))->select();
        if(empty($res)){
            $ret = array('code'=>100,'msg'=>'上月没有设置花费，不能设置返点');
        }else{
            $ret = array('code'=>200,'msg'=>'上月没有设置花费，不能设置返点');
        }
        return $ret;
    }
    //花费返点编辑
    function editQDReturn($param){
        // if($param['province_id']){
        //     $region = controller("Customer","lib")->getRegionByProvinceId(['id'=>$param['province_id']]);
        //     $param['region_id'] = $region['id'];
        //     $param['region_name'] = $region['region_name'];
        // }
        $res = db('crm_s_channel_cost_return')->where('return_month',$param['return_month'])->where(array('channel_id'=>$param['channel_id'],'channel_class_id'=>$param['channel_class_id'],'channel_info_id'=>$param['channel_info_id'],'province_id'=>$param['province_id'],'city_id'=>$param['city_id']))->where('shop_code',session('shop_code'))->where('id','<>',$param['id'])->find();
        if($res['id']){
            return array('code'=>105,'msg'=>'已有此花费返点，不能继续添加');
        }
        //检查此渠道和地区上月是否设置花费
        $ret = $this->checkCostReturn(array('channel_id'=>$param['channel_id'],'channel_class_id'=>$param['channel_class_id'],'channel_info_id'=>$param['channel_info_id'],'city_id'=>$param['city_id'],'month'=>$params['return_month']));

        if($ret['code'] == 100){
            return array('code'=>100,'msg'=>'该渠道和地域上月未设置花费，不能设置返点');
        }
        // if($param['region_id'] == 0){
            $param['region_id'] = 0;
            $param['region_name'] = null;
        // }
        $param['update_time'] = date('Y-m-d H:i:s',time());
        db()->startTrans();
        $info = db('crm_s_channel_cost_return')->where('id',$param['id'])->find();
        try{
            db('crm_s_channel_cost_return')->where('id',$param['id'])->update($param);
                //($info['region_id'] == $param['region_id']) && 
                if(($info['channel_id'] == $param['channel_id'])&&($info['channel_class_id'] == $param['channel_class_id'])&&($info['channel_info_id'] == $param['channel_info_id'])&&($info['province_id'] == $param['province_id'])&&($info['city_id'] == $param['city_id'])){
                    //操作分摊表
                    $days = date('t',strtotime($param['return_month']));
                    $return_avg = sprintf('%.4f',$param['return_cost']/$days);
                    for($i=0;$i<$days;$i++){
                        $info = db('crm_c_customer_cost')
                            ->where('shop_code',session('shop_code'))
                            ->where('channel_id',$param['channel_id'])
                            ->where('channel_class_id',$param['channel_class_id'])
                            ->where('channel_info_id',$param['channel_info_id'])
                            // ->where('region_id',$param['region_id'])
                            ->where('province_id',$param['province_id'])
                            ->where('city_id',$param['city_id'])
                            ->where('brandclass_id',session('brandclass_id'))
                            ->where('return_avg','<>',0)
                            ->where('cost_time',date('Y-m-d',strtotime($param['return_month'])+$i*24*60*60))
                            ->find();

                        if(empty($info)){
                            $data = array(
                                'shop_code'=>session('shop_code'),
                                'channel_id'=>$param['channel_id'],
                                'channel_name'=>$param['channel_name'],
                                'channel_class_id'=>$param['channel_class_id'],
                                'channel_class_name'=>$param['channel_class_name'],
                                'channel_info_id'=>$param['channel_info_id'],
                                'channel_info_name'=>$param['channel_info_name'],
                                'region_id'=>$param['region_id'],
                                'region_name'=>$param['region_name'],
                                'province_id'=>$param['province_id'],
                                'province_name'=>$param['province_name'],
                                'city_id'=>$param['city_id'],
                                'city_name'=>$param['city_name'],
                                'brandclass_id'=>session('brandclass_id'),
                                'cost_time'=>date('Y-m-d',strtotime($param['return_month'])+$i*24*60*60),
                                'return_avg'=>($i == $days-1) ? bcsub($param['return_cost'],($days-1)*$return_avg,4) :$return_avg,
                            );
                            db('crm_c_customer_cost')->insert($data);
                        }else{
                            $data = array(
                                'shop_code'=>session('shop_code'),
                                'channel_id'=>$param['channel_id'],
                                'channel_name'=>$param['channel_name'],
                                'channel_class_id'=>$param['channel_class_id'],
                                'channel_class_name'=>$param['channel_class_name'],
                                'channel_info_id'=>$param['channel_info_id'],
                                'channel_info_name'=>$param['channel_info_name'],
                                // 'region_id'=>$param['region_id'],
                                // 'region_name'=>$param['region_name'],
                                'province_id'=>$param['province_id'],
                                'province_name'=>$param['province_name'],
                                'city_id'=>$param['city_id'],
                                'city_name'=>$param['city_name'],
                                'brandclass_id'=>session('brandclass_id'),
                                'cost_time'=>date('Y-m-d',strtotime($param['return_month'])+$i*24*60*60),
                                'return_avg'=>($i == $days-1) ? bcsub($param['return_cost'],($days-1)*$return_avg,4) :$return_avg,
                            );
                            db('crm_c_customer_cost')->where('id',$info['id'])->update($data);
                        }
                    }
                }else{
                    db()->rollback();
                    return array('code'=>100,'msg'=>'该返点和渠道花费设置不统一，修改失败');
                }
                db()->commit();
                action_log($param,'',0,session('staff_id'),session('staff_name'));
                return array('code'=>200,'msg'=>'花费返点修改成功');
        }catch (Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'花费返点修改失败','data'=>$e->getMessage());
        }

    }
    function delFileReason($id){
        db()->startTrans();
        $res = db('crm_s_file_reason')->where('id',$id)->delete();
        if($res){
            db()->commit();
            action_log($id,'',0,session('staff_id'),session('staff_name'));
            return true;
        }else{
            db()->rollback();
            return false;
        }
    }
    function delRejectReason($id){
        db()->startTrans();
        $res = db('crm_s_reject_reason')->where('id',$id)->delete();
        if($res){
            db()->commit();
            action_log($id,'',0,session('staff_id'),session('staff_name'));
            return true;
        }else{
            db()->rollback();
            return false;
        }
    }
    function editReason($param){
        db()->startTrans();
        $res = db('crm_s_file_reason')->where('id',$param['id'])->update($param);
        if($res === false){
            db()->rollback();
            return false;
        }else{
            db()->commit();
            action_log($param,'',0,session('staff_id'),session('staff_name'));
            return $res;
        }
    }
    function editRejectReason($param){
        db()->startTrans();
        $res = db('crm_s_reject_reason')->where('id',$param['id'])->update($param);
        if($res === false){
            db()->rollback();
            return false;
        }else{
            db()->commit();
            action_log($param,'',0,session('staff_id'),session('staff_name'));
            return $res;
        }
    }
    function getTuCount(){
        $res = db('crm_s_staff_ability')->where('shop_code',session('shop_code'))->field('id')->select();
        return $res;
    }
    function get_staff_photo($staff_id){
        $file = "/public/upload/pic/".$staff_id.'.jpg';
        if(is_file($file)){
            return $file;
        }else{
            return '/public/img/user_tt_b.jpg';
        }
    }
    //分配开关
    function auto_fp($fpTime){//开关状态：1：开；2：关;默认1：自动分配(空值)
        $val = db_config('fp_switch_'.session('shop_code'));
        if ($val == 1) {
            $value = 2;
        } else {
            //查询有无默认规则
            $id = db('crm_s_allocation_rule')->where('customer_condition','default')->where('shop_code',session('shop_code'))->field('id')->find();
            if($id){
                $value = 1;
                $time = db_config('fp_time_'.session('shop_code'));
                $fpTimeOut = db_config('fp_timeout_'.session('shop_code'));
                if(empty($time) || empty($fpTimeOut)){
                    $arr = array('error'=>1,'msg'=>'开始结束时间或过期时间为空，不能开启自动');
                    return json($arr);
                }
            }else{
                $arr = array('error'=>1,'msg'=>'没有默认规则，不能开启自动');
                return json($arr);
            }
        }
        db()->startTrans();
        $res = db_config('fp_switch_'.session('shop_code'),$value);
        if($res){
            // db_config('fp_time_'.session('shop_code'),$fpTime['fp_time']);
            db()->commit();
            action_log($fpTime,$val,0,session('staff_id'),session('staff_name'));
            $arr = array('error'=>1,'msg'=>'操作成功');
        }else{
            db()->rollback();
            $arr = array('error'=>0,'msg'=>'操作失败');
        }
        return json($arr);
    }
    //自动接收开关
    function auto_jr(){//开关状态：1：开；0：关;默认1：自动分配(空值)
        $val = db_config('fp_switch_'.session('shop_code'));
        $old = db_config('auto_jr_'.session('shop_code'));
        if ($val == 1) {
            db()->startTrans();
            try{
                if($old == 1){
                    $new = 0;
                }else{
                    $new = 1;
                }
                $res=db_config('auto_jr_'.session('shop_code'),$new);
                db()->commit();
                action_log($new,$old,0,session('staff_id'),session('staff_name'));
                $arr = array('error'=>1,'msg'=>'操作成功','data'=>$res);
            }catch (\Exception $e){
                db()->rollback();
                $arr = array('error'=>0,'msg'=>'操作失败');
            }
        }else{
            $arr = array('error'=>1,'msg'=>'没有打开分配开关，不能开启自动接收');
            return json($arr);
        }

        return json($arr);
    }
    //分配开启时间区间
    function setFPTime($time){
        
        $arr = explode('-',$time['fp_time']);
        $arr[0] = trim($arr[0]);
        $arr[1] = trim($arr[1]);
        if(!empty($arr[0]) && !empty($arr[1]) && strtotime($arr[0]) >= strtotime($arr[1])){
            return array('code'=>100,'msg'=>'开始时间不能大于等于结束时间');
        }
        
         $res1 = db_config('fp_timeout_'.session('shop_code'),$time['timeout']);
         $res2 = db_config('fp_time_'.session('shop_code'),$time['fp_time']);
         $res3 = db_config('not_online_is_fp_'.session('shop_code'),$time['not_online_is_fp']);
         $res = db('crm_c_sysconfig')->where('ckey','fp_time_'.session('shop_code'))->update(array('cvalue'=>$time['fp_time']));
        if($res1 === false || $res2 === false || $res3 === false)
        {
            return array('code'=>100,'msg'=>'设置失败,请重试');
        }else{
            action_log($time,'',0,session('staff_id'),session('staff_name'));
            return array('code'=>200,'msg'=>'设置成功'.session('shop_code'));
        }
    }
    //无小组人员 0609  ericdel
    /*
    function getNoGroupStaff($dep){
        $res = db('CStaffGroupRelation')->field('staff_id')->select();//有小组人员.
        $ar = array();
        foreach($res as $ke=>$va){
            array_push($ar,$va['staff_id']);
        }
        $url = '5a7424f13aa54';
        $info = sx_call($url,$dep);//所有人员
        if($info['code'] == 200){
            $a = array();
            foreach($info['data'] as $k=>$v){
                array_push($a,$v['id']);
            }
            $arr = array_diff($a,$ar);//差集
            $ids = implode(',',$arr);
            $noGroup = sx_call('5a18e3fa516a1',array('staff_id'=>$ids));//所有无组人员
            if($noGroup['code'] == 200){
                return $noGroup;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }
    */
    //查看是否是小组管理员 0609
    function isGroupAdmin(){
        return db('CStaffGroupRelation')->where('staff_id',session('staff_id'))->field('is_admin')->find();
    }
    //查看有无小组 0609
    function isGroupStaff(){
        return db('CStaffGroupRelation')->where('staff_id',session('staff_id'))->field('group_id')->find();
    }
    // 0609
    function getGroupInfo(){
        $res = db('CStaffGroup')->where('create_staff_id',session('staff_id'))->find();
        if(empty($res)){
            $info = db('c_staff_group_relation')->where('staff_id',session('staff_id'))->field('group_id')->find();
            $res = db('CStaffGroup')->where('id',$info['group_id'])->find();
        }
        return $res;
    }
    //小组内所有人员0609 
    function getInGroupStaffInfo($id){
        $info = db('CStaffGroupRelation')->where('group_id',$id)->field('staff_id')->select();
        $ar = array();
        foreach($info as $ke=>$va){
            array_push($ar,$va['staff_id']);
        }
        $ids = implode(',',$ar);
        //请求接口，通过id获取名字
        $url = "5a18e3fa516a1";
        $res = sx_call($url,array('staff_id'=>$ids));
        return $res;
    }
    //添加或编辑小组 ericdel  小组相关全部在mc里了  crm里不用了
    // function addGroup($param){
    //     if($param['id']){//编辑
    //         db()->startTrans();
    //         try{
    //             $stat = 0;
    //             $member = $param['member'];
    //             $member .= ','.$param['create_staff_id'];
    //             unset($param['member']);
    //             if($member){

    //                 $api = '5a18e3fa516a1';
    //                 $res = sx_call($api,['staff_id'=>$member]);
    //                 if($res['code'] != 200){
    //                     $js = array('code'=>300,'msg'=>'无法获取员工信息，调用MC失败：('.$res['code']."):".$res['msg']);
    //                     db()->rollback();
    //                     return json($js);
    //                 }
    //                 if( count($res['data']) == 0){
    //                     $js = array('code'=>301,'msg'=>'没有找到有效的员工信息.');
    //                     db()->rollback();
    //                     return json($js);
    //                 }
    //                 //$arr = explode(',',$member);
    //                 //管理员id 0609
    //                 $id = db('CStaffGroup')->where('id',$param['id'])->value('create_staff_id');
    //                 /*if(!in_array($id,explode(',',$member))){
    //                     $js = array('code'=>302,'msg'=>'组长不能直接删除,请更换组长或清空小组!');
    //                     db()->rollback();
    //                     return json($js);
    //                 }*/
    //                 $stat++;
    //                 //删除小组所有人员 0609
    //                 //db('CStaffGroupRelation')->where('group_id',$param['id'])->where('staff_id','<>',$id)->delete();
    //                 db('CStaffGroupRelation')->where('group_id',$param['id'])->delete();
    //                 $stat++;
    //                 //如果管理员误删了，这里可以重新插入
    //                 /*
    //                 $g = db('CStaffGroupRelation')->where('staff_id',$id)->value('staff_id');
    //                 if(empty($g)){
    //                     db('CStaffGroupRelation')->insert(['staff_id'=>$id,'group_id'=>$param['id'],'is_admin'=>1]);
    //                 }*/
    //                 $data = [];
    //                 foreach($res['data'] as $v){
    //                     $tmpData = [
    //                         'group_id'=>$param['id'],
    //                         'staff_id'=>$v['id'],
    //                         'staff_name'=>$v['staffname'],
    //                         ];
    //                     if($v['id'] == $id){
    //                         $tmpData['is_admin'] = 1;
    //                     }else{
    //                         $tmpData['is_admin'] = 0;
    //                     }
    //                     $data[] = $tmpData;
    //                     unset($tmpData);
    //                 }
    //                 db('CStaffGroupRelation')->insertAll($data);
    //                 $stat++;
    //             }else{
    //                 //管理员id
    //                 $id = db('CStaffGroup')->where('id',$param['id'])->value('create_staff_id');
    //                 //删除小组所有人员
    //                 db('CStaffGroupRelation')->where('group_id',$param['id'])->where('staff_id','<>',$id)->delete();
    //             }
    //             $res = db('CStaffGroup')->where('id',$param['id'])->update($param);
    //             $stat++;
    //             action_log($param,[],0,session('staff_id'),session('staff_name'));
    //             db()->commit();
    //             $js = array('code'=>200,'msg'=>'编辑小组成功','data'=>'');
    //             return json($js);
    //         }catch (Exception $e){
    //             db()->rollback();
    //             $js = array('code'=>300,'msg'=>'编辑小组失败，已回滚'.$stat.$e->getMessage());
    //             return json($js);
    //         }
    //     }else{//添加
    //         if(empty($param['department_name']) || $param['department_name'] == ''){
    //             $js = array('code'=>600,'msg'=>'部门不能为空');
    //             return json($js);
    //         }
    //         $member = $param['member'];
    //         unset($param['member']);
    //         $param['create_staff_id'] = intval($param['create_staff_id']);
    //         $param['create_staff_name'] = trim($param['create_staff_name']);
    //         $param['shop_name'] = session('shop_name');
    //         $param['shop_code'] = session('shop_code');
    //         $param['setkey'] = session('setkey');
    //         $param['admin'] = trim($param['admin']);
    //         $param['create_time'] = date('Y-m-d H:i:s',time());
    //         db()->startTrans();
    //         try{
    //             db('CStaffGroup')->insert($param);
    //             $id = db()->getLastInsID();

    //             // db('CStaffGroupRelation')->insert(array('group_id'=>$id,'staff_id'=>$param['create_staff_id'],'is_admin'=>1,'staff_name'=>$param['create_staff_name']));

    //             if(!$member){
    //                 db('CStaffGroupRelation')->insert(array('group_id'=>$id,'staff_id'=>$param['create_staff_id'],'is_admin'=>1,'staff_name'=>$param['create_staff_name']));
    //                 $js = array('code'=>200,'msg'=>'创建小组成功');
    //                 db()->commit();
    //                 return json($js);
    //             }else{
    //                 $member .= ','.$param['create_staff_id'];
    //             }

    //             $api = '5a18e3fa516a1';
    //             $res = sx_call($api,['staff_id'=>$member]);
    //             if($res['code'] != 200 ){
    //                 $js = array('code'=>300,'msg'=>'无法获取员工信息，调用MC失败：('.$res['code']."):".$res['msg']);
    //                 db()->rollback();
    //                 return json($js);
    //             }
    //             if( count($res['data']) == 0){
    //                 $js = array('code'=>301,'msg'=>'没有找到有效的员工信息.');
    //                 db()->rollback();
    //                 return json($js);
    //             }
    //             $data = [];
    //             foreach($res['data'] as $v){
    //                 $tmpData = [
    //                     'group_id'=>$id,
    //                     'staff_id'=>$v['id'],
    //                     'staff_name'=>$v['staffname'],
    //                     ];
    //                 if($v['id'] == $param['create_staff_id']){
    //                     $tmpData['is_admin'] = 1;
    //                 }else{
    //                     $tmpData['is_admin'] = 0;
    //                 }
    //                 $data[] = $tmpData;
    //                 unset($tmpData);
    //             }
    //             db('CStaffGroupRelation')->insertAll($data);
    //             db()->commit();
    //             action_log($param,[],0,session('staff_id'),session('staff_name'));
    //             $js = array('code'=>200,'msg'=>'创建小组成功','data'=>'');
    //             return json($js);

    //         }catch (Exception $e){
    //             db()->rollback();
    //             $js = array('code'=>700,'msg'=>'创建小组失败,已回滚','data'=>$e->getMessage());
    //             return json($js);
    //         }
    //     }
    // }
    //删除并清空小组
    function delGroup($param){
        $info = db('CStaffGroup')->where('id',$param['id'])->find();
        if($info['create_staff_id'] != session('staff_id') && session('main_work_type') != SYSTEM_AUTH_ADMIN && check_right('menu1535542292') == false){
            return array('code'=>100,'msg'=>'没有删除权限，不能删除');
        }
        if($param['id']){
            db()->startTrans();
            try{
                db('CStaffGroupRelation')->where('group_id',$param['id'])->delete();
                db('CStaffGroup')->where('id',$param['id'])->delete();
                action_log($param,$info,0,session('staff_id'),session('staff_name'));
                db()->commit();
                return array('code'=>200,'msg'=>'小组删除成功');
            }catch (Exception $e){
                db()->rollback();
                return array('code'=>300,'msg'=>'小组删除失败','data'=>$e->getMessage());
            }
        }else{
            return array('code'=>400,'msg'=>'参数有误，删除失败');
        }
    }
    function delFromGroup($staff_id){
        $res = db('CStaffGroup')->where('create_staff_id',session('staff_id'))->field('id,create_staff_id')->find();
        if($res['create_staff_id'] == $staff_id){
            return json(array('msg'=>'您是组长，不能删除'));
        }
        if($res['id']){
            db()->startTrans();
            $del = db('CStaffGroupRelation')->where('staff_id',$staff_id)->delete();
            action_log($staff_id,$res,0,session('staff_id'),session('staff_name'));
            if($del){
                db()->commit();
                return json(array('msg'=>'删除成功'));
            }else{
                db()->rollback();
                return json(array('msg'=>'删除失败'));
            }
        }else{
            return json(array('msg'=>'小组不存在'));
        }
    }
    function addToGroup($staff_id){
        $res = db('CStaffGroup')->where('create_staff_id',session('staff_id'))->field('id,create_staff_id')->find();
        if(empty($res['id'])){
            return json(array('msg'=>'您还没创建小组，不能添加人员'));
        }
        if($res['create_staff_id'] == session('staff_id')){
            $data = array(
                'staff_id'=>$staff_id,
                'group_id'=>$res['id']
            );
            db()->startTrans();
            $id = db('CStaffGroupRelation')->insert($data);
            action_log($staff_id,$res,0,session('staff_id'),session('staff_name'));
            if($id){
                db()->commit();
                return json(array('msg'=>'添加人员成功'));
            }else{
                db()->rollback();
                return json(array('msg'=>'添加人员失败'));
            }
        }else{
            return json(array('msg'=>'您无权限添加人员'));
        }

    }
    function getTu(){
        $res = db('crm_s_staff_ability')->where('shop_code',session('shop_code'))->field('id,position_name,abilityItem,max,times')->select();
        if($res){
            $t = new Target();
            foreach ($res as $k => $v) {
                $arr = explode(',', $v['abilityItem']);
                $max = explode(',', $v['max']);
                $res[$k]['abilityItem'] = $arr;
                $arr1 = array();
                $arr2 = array();
                foreach ($arr as $ke => $va) {
                    $a = $t->get_target_name_by_id($va);
                    $arr1[] = "{name: '" . $a . "', max: ".$max[$ke]."}";
                    $va = 6000;
                    if($va > $max[$ke]){
                        $va = $max[$ke];
                    }
                    $arr2[] = $va;
                }
                if($v['times'] == 'week'){
                    $a = '本周';
                }elseif($v['times'] == 'last_week'){
                    $a = '上周';
                }elseif($v['times'] == 'month'){
                    $a = '本月';
                }elseif($v['times'] == 'last_month'){
                    $a = '上月';
                }elseif($v['times'] == 'near_month'){
                    $a = '最近一月';
                }elseif($v['times'] == 'near_week'){
                    $a = '最近一周';
                }
                $res[$k] = array('a'=> "[".implode(',',$arr1)."]",'b'=>"[".implode(',',$arr2)."]",'c'=>$v['position_name'].'['.$a.']');
            }
            return $res;
        }else{
            return  array('a'=> "[{ name: '成交量', max: 50},{ name: '进客量', max: 60},{ name: '有效量', max: 60},{ name: '电访量', max: 80},{ name: '客资量', max: 50},]",'b'=>"[30,30,30,30,30]",'c'=>'默认五维图');
        }
    }
    function abilitySet($param){
        if(count($param['ability'])<3){
            return array('code'=>100,'msg'=>'最少要选择3个能力');
        }
        $data['shop_name'] = session('shop_name');
        $data['shop_code'] = session('shop_code');
        $data['setkey'] = session('setkey');
        $data['position_name'] = $param['position_name'];
        $data['times'] = $param['times'];
        $data['abilityItem'] = implode(',',$param['ability']);
        $max = array();
        for($i=1;$i<=100;$i++){
            if($param['max'.$i] != ''){
                array_push($max,$param['max'.$i]);
            }
        }

        if(count($max) != count($param['ability'])){
            return array('code'=>100,'msg'=>'选择的能力和最大值不对应');
        }
        $data['max'] = implode(',',$max);

        db()->startTrans();
        try{
            if($param['id']){
                //查询此岗位本时间段是否有设定
                $info = db('crm_s_staff_ability')->where('position_name','=',$param['position_name'])->where('times',$param['times'])->where('id','<>',$param['id'])->where('shop_code',session('shop_code'))->find();
                if($info){
                    return array('code'=>100,'msg'=>'已有此五维图，请重新修改');
                }
                $res = db('crm_s_staff_ability')->where('id',$param['id'])->update($data);
            }else{
                //查询此岗位本时间段是否有设定
                $info = db('crm_s_staff_ability')->where('position_name','=',$param['position_name'])->where('times',$param['times'])->where('shop_code',session('shop_code'))->find();
                if($info){
                    return array('code'=>100,'msg'=>'已有此五维图，请重新添加');
                }
                db('crm_s_staff_ability')->insert($data);
            }
            db()->commit();
            action_log($param,'',0,session('staff_id'),session('staff_name'));
            return array('code'=>200,'msg'=>'五维图设置成功');
        }catch (\Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'五维图设置失败','data'=>$e->getMessage());
        }
    }
    function getAbilityList(){
        $res = db('crm_s_staff_ability')->select();
        $res['abilityItem'] = explode(',',$res);
        return $res;
    }
    function getAbility($param){
        $res = db('crm_s_staff_ability')->where('id',$param['id'])->find();
        if($res){
            return array('code'=>200,'data'=>$res);
        }else{
            return array('code'=>100,'msg'=>'获取信息失败');
        }
    }
    public function getTuToJSON($param){
        $result['code'] = 0;
        $result['msg'] = '';
        $page = $param['page'] ? $param['page'] : 1;
        $limit = $param['limit'] ? $param['limit'] : 10;
        $res = db('crm_s_staff_ability')->where('shop_code',session('shop_code'))->page($page,$limit)->select();
        $count = db('crm_s_staff_ability')->where('shop_code',session('shop_code'))->count();
        if($res){
            $t = new Target();
            foreach ($res as $k => $v) {
                $arr = explode(',', $v['abilityItem']);
                $a = array();
                foreach($arr as $ke=>$ve){
                    $a[$ke] = $t->get_target_name_by_id($ve);
                }
                $res[$k]['abilityItem'] = implode(',',$a);
                if($v['times'] == 'week'){
                    $res[$k]['times'] = '本周';
                }elseif($v['times'] == 'last_week'){
                    $res[$k]['times'] = '上周';
                }elseif($v['times'] == 'month'){
                    $res[$k]['times'] = '本月';
                }elseif($v['times'] == 'last_month'){
                    $res[$k]['times'] = '上月';
                }elseif($v['times'] == 'near_month'){
                    $res[$k]['times'] = '最近一月';
                }elseif($v['times'] == 'near_week'){
                    $res[$k]['times'] = '最近一周';
                }
            }

            $result['data'] = $res;
            $result['count'] = $count;
        }else{
            $result['data'] = array();
        }
        return ($result);
    }

    //删除五维图
    function delTu($id){
        db()->startTrans();
        $res = db('crm_s_staff_ability')->where('id',$id)->delete();
        action_log($id,'',0,session('staff_id'),session('staff_name'));
        if($res){
            db()->commit();
            return true;
        }else{
            db()->rollback();
            return false;
        }
    }
    //电访设定
    function addtelphoneRemark($param){
        $param['shop_name'] = session('shop_name');
        $param['shop_code'] = session('shop_code');
        $param['setkey'] = session('setkey');
        db()->startTrans();
        db('crm_s_telremark')->insert($param);
        $id = db('crm_s_telremark')->getLastInsID();
        if($id){
            db()->commit();
            action_log($param,'',0,session('staff_id'),session('staff_name'));
            return true;
        }else{
            db()->rollback();
            return false;
        }
    }
    function  getRemarkList(){
        $res = db('crm_s_telremark')->select();
        if($res){
            return $res;
        }else{
            return false;
        }
    }
    function  gettrackingKmarkerList($data){
        $data['shop_code'] = $data['shop_code'] ? $data['shop_code'] : session('shop_code');
        $res = db('crm_s_tracksign')->where('shop_code',$data['shop_code'])->where('is_delete',1)->select();
        if($res){
            return $res;
        }else{
            return [];
        }
    }


    //客资标记设定
    function addtrackingKmarker($param){
        $param['shop_name'] = session('shop_name');
        $param['shop_code'] = session('shop_code');
        $param['setkey'] = session('setkey');
        $param['tracksign'] = strtoupper($param['tracksign']);
        if(empty($param['tracksign'])){
            return array('code'=>400,'msg'=>'标记不可为空，请更改');
        }
        if(strtoupper($param['sign_color']) == 'FFFFFF'){
            $param['sign_color'] = NULL;
        }
        //判断是否重复
        $info = db('crm_s_tracksign')->where('shop_code',session('shop_code'))->where('is_delete',1)->where('tracksign',$param['tracksign'])->find();
        if($info['tracksign'] == $param['tracksign']){
            return array('code'=>100,'msg'=>'标记重复，请更改');
        }
        db()->startTrans();
        db('crm_s_tracksign')->insert($param);
        action_log($param,'',0,session('staff_id'),session('staff_name'));
        $id = db('crm_s_tracksign')->getLastInsID();
        if($id){
            db()->commit();
            return array('code'=>200,'msg'=>'标记设置成功');
        }else{
            db()->rollback();
            return array('code'=>300,'msg'=>'标记设置失败');
        }
    }
    
    //客户标记
    function getTrackingKmarkerToJSON($tracksign)
    {
        $result['code'] = 0;
        $result['msg'] = '';
        $res = db('crm_s_tracksign')->where('shop_code',session('shop_code'))->where('is_delete',1)->where('tracksign','like','%'.$tracksign.'%')->select();
        // $count = db('crm_s_tracksign')->where('shop_code',session('shop_code'))->where('is_delete',1)->where('tracksign','like','%'.$tracksign.'%')->count();
        if($res){
            $result['data'] = $res;
            $result['count'] = count($res);
            // $result['count'] = count($res)$count;
        }else{
            $result['data'] = array();
        }
        return $result;
    }
    
    function deledittrackingKmarker($id){
        $arr = config('signA');
        $ids = array_values($arr);
        if(in_array($id,$ids)){
            return array('code'=>500,'msg'=>'此标记是A客标记,不能删除!');
        }
        db()->startTrans();
        $res = db('crm_s_tracksign')->where('id',$id)->update(['is_delete'=>2]);
        if($res === false){
            db()->rollback();
            return array('code'=>100,'msg'=>'客资标记删除失败!','data'=>$id);
        }else{
            db()->commit();
            action_log($id,'',0,session('staff_id'),session('staff_name'));
            return array('code'=>200,'msg'=>'客资标记删除成功!');
        }
    }
    function edittrackingKmarker($param){
        $param['tracksign'] = strtoupper($param['tracksign']);
        if(empty($param['tracksign'])){
            return array('code'=>400,'msg'=>'标记不可为空，请更改');
        }
        if(strtoupper($param['sign_color']) == 'FFFFFF'){
            $param['sign_color'] = NULL;
        }
        // $sign = db('crm_s_markset')->where('shop_code',session('shop_code'))->where('mark_color','not null')->find();
        // if(!empty($sign)){
        //     return array('code'=>102,'msg'=>'追踪标记已设置颜色，请先去清除！');
        // }
        //判断是否重复
        $info = db('crm_s_tracksign')->where('id','<>',$param['id'])->where('shop_code',session('shop_code'))->where('tracksign',$param['tracksign'])->where('is_delete',1)->find();
        if($info['tracksign'] == $param['tracksign']){
            return array('code'=>100,'msg'=>'标记重复，请更改');
        }
        db()->startTrans();
        $res = db('crm_s_tracksign')->where(array('id'=>$param['id']))->update($param);
        if($res === false){
            db()->rollback();
            return array('code'=>300,'msg'=>'标记修改失败');
        }else{
            db()->commit();
            action_log($param,'',0,session('staff_id'),session('staff_name'));
            return array('code'=>200,'msg'=>'标记修改成功');
        }
    }

    // 根据shopCode获取规则集合
    function getRule($shopCode){
        $result['code'] = 0;
        $result['msg'] = '';
        $where = array(
            'belong_shop_code' => $shopCode,
            //'shop_code' => $shopCode,
            'isopen'    => 1
        );
        $res = db('crm_s_allocation_rule')->where($where)->select();

        // 按照 order_sort 排序
        $res = my_sort($res,'order_sort');
        return $res;
        // //取到客资信息
        // //确定要更新的数据沉淀
        // //取到客资的。luruid  shaikeid   jieshouid

        // $dataup[$lurid] = 'lurushijian';
        // $dataup[$shaikeid] = 'shaikeshijian';

        // $dataup[$jieshouid] = 'jieshoushijian';
        // foreach ($dataup as $key => $value) {
        //     # code...
        //     //判断value是当天还是非当天。。。日表、时表
        //     //更新数据。条件是，员工ID=$key，时间=$value

        // }

    }

    //菜单数据列表
    function getMenuList(){
        $data = db('crm_s_menu')->order('sort asc')->select();
        $res=formatTree(listToTree($data));
        if($res){
            return $res;
        }else{
            return false;
        }
    }

    //查询菜单数据
    function getMenuJSON($param){
        $page = $param['page'] ? $param['page'] : 1;
        $limit = $param['limit'] ? $param['limit'] : 10;
        $result['code'] = 0;
        $result['msg'] = '';
        $res = db('crm_s_menu')->where('menu_name','like','%'.$param['menu_name'].'%')
            ->order('sort asc')
            // ->page($page,$limit)
            ->select();
        $count = db('crm_s_menu')->where('menu_name','like','%'.$param['menu_name'].'%')->count();
        if($res){
            $result['data'] = formatTree(listToTree($res));
            $result['count'] = $count;
        }else{
            $result['data'] = array();
        }
        return ($result);
    }

    //功能菜单增加
    function addMenu($param){
        if($param['id']){
            $res = db('crm_s_menu')->where('id',$param['id'])->update($param);
            if($res===false){
                $this->error('失败', '/');
            }else{
                action_log($param,'',0,session('staff_id'),session('staff_name'));
                cache('CRM_menu_*',null);
                cache('CRM_menuAll',null);
                cache('CRM_menuAllS',null);
                $this->success('成功', '/');
            }
        }else{
            $param['menu_code']='menu'.time();
            $res=db('crm_s_menu')->insert($param);
            $id = db('crm_s_menu')->getLastInsID();
            if(!$id){
                $this->error('失败', '/');
            }else{
                action_log($param,'',0,session('staff_id'),session('staff_name'));
                cache('CRM_menu_*',null);
                cache('CRM_menuAll',null);
                cache('CRM_menuAllS',null);
                $this->success('成功', '/');
            }
        }

    }

    //功能菜单编辑
    // function editMenu($param){
    //    $res = db('crm_s_menu')->where('id',$param['id'])->update($param);
    //    if($res===false){
    //        $this->error('功能编辑失败', '/');
    //    }else{
    //        action_log($param,'',0,session('staff_id'),session('staff_name'));
    //        cache('menu_*',null);
    //        cache('CRM_menuAll',null);
    //        cache('CRM_menuAllS',null);
    //        $this->success('功能编辑成功', '/');
    //    }
    // }

    //功能菜单删除
    function delMenu($id){
        $data=db('crm_s_menu')->where('fid',$id)->where('status','<>','99')->find();
        if($data){
            $this->error('此菜单存在子菜单，请清空子菜单再操作', '/');
        }else{
            $res = db('crm_s_menu')->where('id',$id)->update(array('status'=>99));
            // $res = db('crm_s_menu')->where('id',$id)->delete();
            if($res===false){
                $this->error('功能删除失败', '/');
            }else{
                action_log($id,'',0,session('staff_id'),session('staff_name'));
                cache('CRM_menu_*',null);
                cache('CRM_menuAll',null);
                cache('CRM_menuAllS',null);
                $this->success('功能删除成功', '/');
            }
        }

    }


    //报表设定页面
    function getShopJSON($param){
        // $url = '5a005e0038270';
        $data['brandclass_id']= $param['brandclass_id'];
        // $res = sx_call($url, $data);
        $mc = new \app\common\lib\mcInterface();
        $res = $mc->getShopInfo($data);
        if ($res !== false) {
            $shopList = $res;
            foreach($shopList as $k=>$v){
                if($v['is_marketing']==2){
                    unset($shopList[$k]);
                }else{
                    $shopList[$k]['setting'] = db('crm_s_sta_setting')->where('shop_code',$v['shop_code'])->find();
                    $shopList[$k]['setting']['all_customer_consumptiontype'] = $shopList[$k]['setting']['all_customer_consumptiontype'] ? explode(',',$shopList[$k]['setting']['all_customer_consumptiontype']) : '';
                    $shopList[$k]['setting']['valid_customer_consumptiontype'] = $shopList[$k]['setting']['valid_customer_consumptiontype'] ? explode(',',$shopList[$k]['setting']['valid_customer_consumptiontype']) : '';
                    $shopList[$k]['setting']['into_customer_consumptiontype'] = $shopList[$k]['setting']['into_customer_consumptiontype'] ? explode(',',$shopList[$k]['setting']['into_customer_consumptiontype']) : '';
                    $shopList[$k]['setting']['order_customer_consumptiontype'] = $shopList[$k]['setting']['order_customer_consumptiontype'] ? explode(',',$shopList[$k]['setting']['order_customer_consumptiontype']) : '';
                    $shopList[$k]['consumptionType'] = cache('consumptionType_'.session('brandclass_id'));
                }
            }
            if(!empty($shopList)){
                $shopList = array_values($shopList);
            }
        }else{
            $shopList = '';
        }
        if(!empty($shopList)){
            $ret = array('code'=>200,'data'=>$shopList);
        }else{
            $ret = array('code'=>100,'data'=>'','msg'=>'暂无数据');
        }
        return json($ret);
    }

    //权限设定页面
    // function getPermissionJSON(){
    //     $config = db_config('use_client_module');
    //     if ($config==1) {
    //         $where['id'] = ['<>',1000];
    //     }
    //     $where['status'] = ['<>',99];
    //     $permission=db('crm_s_menu')->where($where)->order('sort')->select();
    //     foreach($permission as $k => $v){
    //         $permission[$k]['text']=$v['menu_name'];
    //     }
    //     $fid=0;
    //     $res=treeData($permission,$fid);
    //     echo json_encode($res);
    // }

    /**
     * 根据目录树，获取所有Tree结构的数据，并打上勾，以便在前端配置权限使用。
     * 
     * @param  [type] $arr   [权限树原始数据，合并了定制目录后的数据，合并数据使用函数：getAllMenu]
     * @param  [type] $allow [已有权限，如果传此参数，则有权限的会打勾，如果没传，则所有都不打勾]
     * @return [type]        [description]
     */
    function getAllMenuTree($arr,$allow){
        $ret = [];
        foreach ($arr as $k=>$value) {
            if($key){
                if(array_key_exists($key, $value)){
                    $ret[] = $value[$key];
                }
                if(count($value['children']) >0){
                    $cret = $this->getAllMenuTree($value['children'],$key);
                    $ret = array_merge($ret,$cret);
                }
            }else{
                $value['id'] = $value['menu_code'];
                $value['text'] = $value['menu_name'];
                $value['attributes'] = ['code'=>$value['menu_code']];
                if(count($value['children']) >0){
                    $value['children'] = $this->getAllMenuTree($value['children'],$allow);
                }else{
                    $value['checked'] = in_array($value['menu_code'], $allow);
                }
                $ret[$k] = $value;
            }
        }
        return $ret;
    }

    // 省市区设定页面
    function getProvinceJSON(){
        set_time_limit(0);
        $address = cache('crm_tree_address');
        if(empty($address)){
            //先查crm表,如果没有,在查mc
            $data['type']=1;
            $address=controller("Customer","lib")->crm_address($data);
            if(!empty($address)){
                foreach($address as $k=>$v){
                    $address[$k]['text']=$v['name'];
                    $address[$k]['children'] = controller("Customer","lib")->crm_address(['pid'=>$v['id'],'type'=>2]);
                    foreach($address[$k]['children'] as $key=>$val){
                        $address[$k]['children'][$key]['text']=$val['name'];
                        $address[$k]['children'][$key]['children'] = controller("Customer","lib")->crm_address(['pid'=>$val['id'],'type'=>3]);
                        foreach($address[$k]['children'][$key]['children'] as $kk=>$vv){
                            $address[$k]['children'][$key]['children'][$kk]['text'] = $vv['name'];
                        }
                    }
                }
            }else{
                $data['type']=1;
                $address=controller("Customer","lib")->mcAddress($data);
                foreach($address as $k=>$v){
                    $address[$k]['text']=$v['name'];
                    $address[$k]['children'] = controller("Customer","lib")->mcAddress(['pid'=>$v['id'],'type'=>2]);
                    foreach($address[$k]['children'] as $key=>$val){
                        $address[$k]['children'][$key]['text']=$val['name'];
                        $address[$k]['children'][$key]['children'] = controller("Customer","lib")->mcAddress(['pid'=>$val['id'],'type'=>3]);
                        foreach($address[$k]['children'][$key]['children'] as $kk=>$vv){
                            $address[$k]['children'][$key]['children'][$kk]['text'] = $vv['name'];
                        }
                    }
                }
            }
            cache('crm_tree_address',$address,3600*24*30);
        }
        echo json_encode($address);
    }

    //获取 岗位 权限
    public function getJurisdiction($params)
    {
        $positionDatas=controller('Setting','lib')->get_position_list(array('position_code'=>$params['position_code']));
        if($positionDatas[0]['work_type']==SYSTEM_AUTH_ADMIN ){

            $menu = include(APP_PATH.'menu.php');
            $menuCustomize = include(APP_PATH.'menu_customize.php');
            $allMenu = getAllMenu($menu,$menuCustomize);
            $ros = $this->arrayDuoZhuanEr($allMenu);
            $allow = [];
            foreach ($ros as $key => $value) {
                
                $allow[] = $value['menu_code'];
            }
        }else{

            $data=db('crm_s_position_menu')->where('position_code',$params['position_code'])->find();

            $allow = explode(',',$data['menu_code']);
        }
        return $allow;
    }

    //授权
    public function authorise($params){

        //检验所授予权限是否在自己所拥有权限内
        if(!check_right('menu1512029925')){
            $this->error('您没有权限，不可给岗位授权','/');
        }
        // print_r($params);exit;
        $positionData=controller('Setting','lib')->get_position_list(array('position_code'=>$params['position_code']));
        if($positionData[0]['work_type']==SYSTEM_AUTH_ADMIN){
            $this->error('此岗位为系统管理员，请不要修改此权限','/');
        }

        //判断自身是否是管理员
        $work_type=explode(',',trim($params['session_main_work_type'].','.$params['session_work_type'],','));
        $positionDatas=controller('Setting','lib')->get_position_list(array('position_code'=>$params['session_main_position_code']));
        if($positionDatas[0]['work_type']==SYSTEM_AUTH_ADMIN || in_array(SYSTEM_AUTH_ADMIN,$work_type)){

        }else{
            $menu = include(APP_PATH.'menu.php');
            $menuCustomize = include(APP_PATH.'menu_customize.php');
            $allMenu = getAllMenu($menu,$menuCustomize);
            $ros = $this->arrayDuoZhuanEr($allMenu);
            // $ros = getAuthMenu($menu,'auth',$menuCustomize);
            $menu_name = [];
            foreach ($ros as $key => $value) {
                //权限 名称
                $menu_name[$value['menu_code']] = $value['menu_name'];
            }


            //自身权限
            $data_menu=db('crm_s_position_menu')->where('position_code',$params['session_main_position_code'])->find();
            $allow = explode(',',$data_menu['menu_code']);

            if ($params['id']) {
                $menu_code = explode(',',$params['id']);

                foreach($menu_code as $v){
                    if(!in_array($v,$allow)) {
                        $this->error('您没有“'.$menu_name[$v].'”的权限，不能授予岗位此权限','/');
                    }
                }
            }
        }

        $codes = explode(',',$params['id']);
        if($params['position_code']){
            $detail['position_code']=$params['position_code'];
            $detail['menu_code']=implode(',',$codes);
            try{
                db()->startTrans();
                if(db('crm_s_position_menu')->where('position_code',$params['position_code'])->find()){
                    $res=db('crm_s_position_menu')->where('position_code',$params['position_code'])->update($detail);
                }else{
                    $res=db('crm_s_position_menu')->insert($detail);
                }
                // writeLog(session('staff_id'),session('staff_name'),'','','','','授权：'.$params['position_name'],json_encode(input('post.')),json_encode($detail));
                action_log($params,'',0,session('staff_id'),session('staff_name'));
                cache('CRM_menu_'.$params['position_code'],null);
                db()->commit();
                return array('code'=>200,'msg'=>'授权成功','data'=>'');
            }catch (\Exception $e){
                db()->rollback();
                return array('code'=>201,'msg'=>'授权失败，请稍后重试'.$e->getMessage(),'data'=>$e->getTrace());
            }
        }else{
            $this->error('不可修改自己的权限','/');
        }
    }

    // 多维数组转二维数组 数组:$arr key值:$name
    public function arrayDuoZhuanEr($arr){
        $ret = [];
        if(count($arr)>0){
            foreach ($arr as $k=>$value) {
                $arr = array();
                $arr['menu_code'] = $value['menu_code'];
                $arr['menu_name'] = $value['menu_name'];
                $ret[] = $arr;
                if(count($value['children']) >0){
                    $sbb = $this->arrayDuoZhuanEr($value['children']);
                    $ret = array_merge($ret,$sbb);
                }
            }
        }
        return $ret;
    }

    //根据岗位查询其功能权限
    public function getPositionMenu($position_code){
        $positionData=controller('Setting','lib')->get_position_list(array('position_code'=>$position_code));
        if($positionData[0]['work_type']==SYSTEM_AUTH_ADMIN){
            $menu=db('crm_s_menu')->select();
            $result['auth_admin']=1;
        }else{
            $data=db('crm_s_position_menu')->where('position_code',$position_code)->find();
            $menu=db('crm_s_menu')->where('menu_code','in',$data['menu_code'])->select();
        }
        $result['menu_id']=array_column($menu,'id');
        $this->success('查询成功','/',$result);
    }

    //提醒快捷开关
    public function remindSwitch($param){
        $count = db('crm_s_reminditemset')->where('id',$param['id'])->where('brandclass_id',session('brandclass_id'))->count();
        db()->startTrans();
        if(!$count){
            $param['brandclass_id'] = session('brandclass_id');
            $param['brandclass'] = session('brandclass');
            $res = db('crm_s_reminditemset')->insert($param);
        }else{
            $res = db('crm_s_reminditemset')->where('id',$param['id'])->where('brandclass_id',session('brandclass_id'))->update($param);
        }
        action_log($param,'',0,session('staff_id'),session('staff_name'));
        if($res === false){
            db()->rollback();
            return false;
        }else{
            db()->commit();
            return $res;
        }
    }

    //获取分配规则信息
    public function getFPIframeInfo($id){
        $res = db('crm_s_allocation_rule')->where('id',$id)->where('shop_code',session('shop_code'))->find();
        return $res;
    }
    //获取追踪标记
    public function getMark($id,$field='*'){
        $res = db('crm_s_markset')->field($field)->where('shop_code',session('shop_code'))->where('id',$id)->find();
        return $res;
    }
    //获取追踪标记
    public function getClub($id,$field='*'){
        $res = db('crm_s_club')->field($field)->where('brandclass_id',session('brandclass_id'))->where('id',$id)->find();
        return $res;
    }
    //获取客资标记
    public function getSign($id,$field='*'){
        $res = db('crm_s_tracksign')->field($field)->where('shop_code',session('shop_code'))->where('id',$id)->find();
        return $res;
    }
    //获取追踪标记 是否已录入颜色
    public function getMarkColor(){
        $res = db('crm_s_markset')->field('mark_color')->where('shop_code',session('shop_code'))->where('mark_color','not null')->find();
        return $res['mark_color'];
    }
    //获取客资标记 是否已录入颜色
    public function getSignColor(){
        $res = db('crm_s_tracksign')->field('sign_color')->where('shop_code',session('shop_code'))->where('sign_color','not null')->where('is_delete',1)->find();
        return $res['sign_color'];
    }
    //删除标记
    public function delMark($id){
        db()->startTrans();
        $res = db('crm_s_markset')->where('shop_code',session('shop_code'))->where('id',$id)->delete();
        if($res){
            db()->commit();
            cache('sales_sign_color_'.session('shop_code'),null);
            action_log($id,'',0,session('staff_id'),session('staff_name'));
            $arr = array('code'=>200,'msg'=>'删除成功');
        }else{
            db()->rollback();
            $arr = array('code'=>300,'msg'=>'删除成功');
        }
        return $arr;
    }
    //删除会所
    public function delClub($id){
        db()->startTrans();
        $res = db('crm_s_club')->where('brandclass_id',session('brandclass_id'))->where('id',$id)->delete();
        if($res){
            db()->commit();
            action_log($id,'',0,session('staff_id'),session('staff_name'));
            $arr = array('code'=>200,'msg'=>'删除成功');
        }else{
            db()->rollback();
            $arr = array('code'=>300,'msg'=>'删除失败，未找到此会所。');
        }
        return $arr;
    }
    public function getMarkToJSON($param){
        $result['code'] = 0;
        $result['msg'] = '';
        if($param['mark_name']){
            $result['count'] = db('crm_s_markset')->where('shop_code',session('shop_code'))->where('mark_name','like','%'.$param['mark_name'].'%')->field('id,mark_name,mark_color,shop_code')->order('id desc')->count();
            $result['data'] = db('crm_s_markset')->where('shop_code',session('shop_code'))->where('mark_name','like','%'.$param['mark_name'].'%')->order('id desc')->select();
        }else{
            $result['count'] = db('crm_s_markset')->where('shop_code',session('shop_code'))->order('id desc')->count();
            $result['data'] = db('crm_s_markset')->where('shop_code',session('shop_code'))->field('id,mark_name,mark_color,shop_code')->order('id desc')->select();
        }
        return(($result)) ;
    }
    public function getClubToJSON($param){
        $result['code'] = 0;
        $result['msg'] = '';
        if ($param['club_name']) {
            $where['club_name'] = $param['club_name'];
        }
        $where['brandclass_id'] = $param['brandclass_id'];
        $result['count'] = db('crm_s_club')->where($where)->count();
        $result['data'] = db('crm_s_club')->where($where)->field('id,club_name,brandclass_id')->select();
        $result['sql'] = db()->getLastSql();
        return(($result)) ;
    }
    //获取标记 追踪标记设定
    public function editMark($param){
        if(empty($param['mark_name'])){
            return array('code'=>100,'msg'=>'标记名称不能为空！');
        }
        if(strtoupper($param['mark_color']) == 'FFFFFF'){
            $param['mark_color'] = NULL;
        }

        db()->startTrans();
        if($param['id']){
            //判断是否重复
            $info = db('crm_s_markset')->where('id','<>',$param['id'])->where('shop_code',session('shop_code'))->where('mark_name',$param['mark_name'])->find();
            if($info['mark_name'] == $param['mark_name']){
                return array('code'=>100,'msg'=>'标记重复，请更改');
            }
            $res = db('crm_s_markset')->where('shop_code',session('shop_code'))->where('id',$param['id'])->update($param);
        }else{
            //判断是否重复
            $info = db('crm_s_markset')->where('shop_code',session('shop_code'))->where('mark_name',$param['mark_name'])->find();
            if($info['mark_name'] == $param['mark_name']){
                return array('code'=>300,'msg'=>'标记重复，请更改');
            }
            $param['shop_name'] = session('shop_name');
            $param['shop_code'] = session('shop_code');
            $param['setkey'] = session('setkey');
            $res = db('crm_s_markset')->insertGetId($param);
        }
        if($res === false){
            db()->rollback();
            $arr = array('code'=>100,'msg'=>'编辑失败');
        }else{
            cache('sales_sign_color_'.session('shop_code'),null);
            db()->commit();
            action_log($param,'',0,session('staff_id'),session('staff_name'));
            $arr = array('code'=>200,'msg'=>'编辑成功');
        }
        return $arr;
    }
    //修改会所名称
    public function editClub($param){
        if(empty($param['club_name'])){
            return array('code'=>100,'msg'=>'会所名称不能为空！');
        }

        db()->startTrans();
        if($param['id']){
            //判断是否重复
            $info = db('crm_s_club')->where('id','<>',$param['id'])->where('brandclass_id',session('brandclass_id'))->where('club_name',$param['club_name'])->find();
            if($info['club_name'] == $param['club_name']){
                return array('code'=>100,'msg'=>'会所名称重复，请更改');
            }
            $res = db('crm_s_club')->where('brandclass_id',session('brandclass_id'))->where('id',$param['id'])->update($param);
        }else{
            //判断是否重复
            $info = db('crm_s_club')->where('brandclass_id',session('brandclass_id'))->where('club_name',$param['club_name'])->find();
            if($info['club_name'] == $param['club_name']){
                return array('code'=>300,'msg'=>'标记重复，请更改');
            }
            $param['brandclass'] = session('brandclass');
            $param['brandclass_id'] = session('brandclass_id');
            // $param['setkey'] = session('setkey');
            $res = db('crm_s_club')->insertGetId($param);
        }
        if($res === false){
            db()->rollback();
            $arr = array('code'=>100,'msg'=>'编辑失败');
        }else{
            db()->commit();
            action_log($param,'',0,session('staff_id'),session('staff_name'));
            $arr = array('code'=>200,'msg'=>'编辑成功');
        }
        return $arr;
    }
    //获取成本设定添加
    public function addObtainCost($param){
        $arr = explode(' - ',$param['cost_time']);
        $param['days'] = diffBetweenTwoDays($arr[0],$arr[1])+1;
        if($param['days'] > 31){
            return array('code'=>400,'msg'=>'时间跨度已超过31天，不能设置');
        }
        //查询有无类型相同的设定
        $info = db('crm_s_obtain_cost')->where('id',$param['id'])->find();
        // if($info['id']){
        //     return array('code'=>100,'msg'=>'已有此类型的获取花费');
        // }
        $param['add_shop_name'] = session('belong_shop_name');
        $param['add_shop_code'] = session('belong_shop_code');
        $param['shop_name'] = session('shop_name');
        $param['shop_code'] = session('shop_code');
        $param['cost_avg'] = sprintf('%.4f',$param['cost_value']/$param['days']);//保留4位小数
        $param['create_time'] = date('Y-m-d H:i:s',time());
        db()->startTrans();
        try{
            $res = db('crm_s_obtain_cost')->insertGetId($param);
            //当月天数
            $days1 = date('t',strtotime($arr[0]));
            $days2 = date('t',strtotime($arr[1]));
            //判断是否是同一月
            if(date('m',strtotime($arr[0])) == date('m',strtotime($arr[1]))){//同一月
                //查看分摊表有无数据 有则修改，无则插入
                $info = db('crm_c_customer_cost')->where('cost_time','like','%'.date('Y-m',strtotime($arr[0])).'%')->where('channel_id',0)->where('region_id',0)->where('shop_code',session('shop_code'))->find();

                if(empty($info)){
                    $p = date('Y-m-',strtotime($arr[1]));
                    $array = array();
                    for($i=1;$i<=$days2;$i++){
                        array_push($array,['cost_time'=>$p.$i,'shop_code'=>session('shop_code'),'brandclass_id'=>session('brandclass_id')]);
                    }

                    $count = db('crm_c_customer_cost')->insertAll($array);
                    if($count != $days2){
                        db()->rollback();
                        return array('code'=>600,'msg'=>'同月跨度下花费分摊插入失败');
                    }
                }
            }else{//不同月
                $info1 = db('crm_c_customer_cost')->where('cost_time','like','%'.date('Y-m',strtotime($arr[0])).'%')->where('channel_id',0)->where('region_id',0)->where('shop_code',session('shop_code'))->find();
                $info2 = db('crm_c_customer_cost')->where('cost_time','like','%'.date('Y-m',strtotime($arr[1])).'%')->where('channel_id',0)->where('region_id',0)->where('shop_code',session('shop_code'))->find();
                if(empty($info1)){
                    $p = date('Y-m-',strtotime($arr[0]));
                    $array1 = array();
                    for($i=1;$i<=$days1;$i++){
                        array_push($array1,['cost_time'=>$p.$i,'shop_code'=>session('shop_code'),'brandclass_id'=>session('brandclass_id')]);
                    }
                    $count = db('crm_c_customer_cost')->insertAll($array1);
                    if($count != $days1){
                        db()->rollback();
                        return array('code'=>700,'msg'=>'不同月跨度下前月花费分摊插入失败');
                    }
                }
                if(empty($info2)){
                    $p = date('Y-m-',strtotime($arr[1]));
                    $array2 = array();
                    for($i=1;$i<=$days2;$i++){
                        array_push($array2,['cost_time'=>$p.$i,'shop_code'=>session('shop_code'),'brandclass_id'=>session('brandclass_id')]);
                    }
                    $count = db('crm_c_customer_cost')->insertAll($array2);
                    if($count != $days2){
                        db()->rollback();
                        return array('code'=>800,'msg'=>'不同月跨度下后月花费分摊插入失败');
                    }
                }
            }
            //查询原数据
            $oldData = db('crm_c_customer_cost')->where('shop_code',session('shop_code'))->where('cost_time','between',"$arr[0],"."$arr[1]")->where('channel_id',0)->where('region_id',0)->field('id,cost_time,cost_avg')->select();
            //去除平均值后的小数
            $last = $param['cost_value']-($param['days']-1)*$param['cost_avg'];
            //新数据
            $newData = array();
            for($i=0;$i<$param['days']-1;$i++){
                array_push($newData,['cost_time'=>$oldData[$i]['cost_time'],'cost_avg'=>$param['cost_avg']]);
            }
            array_push($newData,['cost_time'=>$arr[1],'cost_avg'=>$last]);
            // print_r($newData);die;
            for($i=0;$i<count($newData);$i++){
                db('crm_c_customer_cost')->where('shop_code',session('shop_code'))->where('cost_time',$newData[$i]['cost_time'])->where('channel_id',0)->where('region_id',0)->setInc('cost_avg',$newData[$i]['cost_avg']);
            }
            db()->commit();
            action_log($param,'',0,session('staff_id'),session('staff_name'));
            return array('code'=>200,'msg'=>'获取成本设定成功');
        }catch (Exception $e){
            db()->rollback();
            return array('code'=>300,'msg'=>'添加获取花费失败');
        }
    }
    //获取2个数组中平均值相减
    public function getDataDiff($oldData,$newData){
        $startDay = $oldData[0]['cost_time'] < $newData[0]['cost_time'] ? $oldData[0]['cost_time'] : $newData[0]['cost_time'];
        $c1 = count($oldData);
        $c2 = count($newData);
        $endDay = $oldData[$c1-1]['cost_time'] > $newData[$c2-1]['cost_time'] ? $oldData[$c1-1]['cost_time'] : $newData[$c2-1]['cost_time'];
        $thisDay = $startDay;
        $i = 0;
        $h = 0;
        $result = array();
        while($thisDay <= $endDay){
            if($oldData[$i]['cost_time'] == $thisDay){
                $old = $oldData[$i]['cost_avg'];
                $i++;
            }else{
                $old = 0;
            }
            if($newData[$h]['cost_time'] == $thisDay){
                $new = $newData[$h]['cost_avg'];
                $h++;
            }else{
                $new = 0;
            }
            $result[] = array('cost_time'=>$thisDay,'diff'=>$new - $old);
            $thisDay = date('Y-m-d',strtotime($thisDay)+24*60*60);
        }
        // print_r($result);die;
        return $result;
    }
    //获取成本设定编辑
    public function editObtainCost($param){
        $arr = explode(' - ',$param['cost_time']);
        $param['days'] = diffBetweenTwoDays($arr[0],$arr[1])+1;
        if($param['days'] > 31){
            return array('code'=>400,'msg'=>'时间跨度已超过1个月，不能设置');
        }

        $param['add_shop_name'] = session('belong_shop_name');
        $param['add_shop_code'] = session('belong_shop_code');
        $param['shop_name'] = session('shop_name');
        $param['shop_code'] = session('shop_code');
        $param['cost_avg'] = sprintf('%.4f',$param['cost_value']/$param['days']);//保留4位小数
        $param['update_time'] = date('Y-m-d H:i:s',time());
        //当月天数
        $days1 = date('t',strtotime($arr[0]));
        $days2 = date('t',strtotime($arr[1]));
        db()->startTrans();
        try{
            //判断是否是同一月
            if(date('m',strtotime($arr[0])) != date('m',strtotime($arr[1]))){//不同月
                $info2 = db('crm_c_customer_cost')->where('cost_time','like','%'.date('Y-m',strtotime($arr[1])).'%')->where('channel_id',0)->where('region_id',0)->where('shop_code',session('shop_code'))->find();
                if(empty($info2)){
                    $p = date('Y-m-',strtotime($arr[1]));
                    $array2 = array();
                    for($i=1;$i<=$days2;$i++){
                        array_push($array2,['cost_time'=>$p.$i,'shop_code'=>session('shop_code'),'brandclass_id'=>session('brandclass_id')]);
                    }
                    $count = db('crm_c_customer_cost')->insertAll($array2);
                    if($count != $days2){
                        db()->rollback();
                        return array('code'=>800,'msg'=>'不同月跨度下后月花费分摊插入失败');
                    }
                }
            }
            //查询原数据
            $info = db('crm_s_obtain_cost')->where('id',$param['id'])->find();
            //原数据时间和平均值
            $oldArr = explode(' - ',$info['cost_time']);
            $oldDays = diffBetweenTwoDays($oldArr[0],$oldArr[1])+1;
            $oldAvg = sprintf('%.4f',$info['cost_value']/$oldDays);//保留4位小数
            $oldData = array();

            for($i=0;$i<$oldDays-1;$i++){
                array_push($oldData,['cost_time'=>date('Y-m-d',strtotime($oldArr[0])+$i*24*60*60),'cost_avg'=>$oldAvg]);
            }
            //去除平均值后的小数
            $oldLast = bcsub($info['cost_value'],bcmul($oldDays-1,$info['cost_avg'],4),4);
            array_push($oldData,['cost_time'=>$oldArr[1],'cost_avg'=>$oldLast]);

            db('crm_s_obtain_cost')->update($param);

            //去除平均值后的小数
            $last = bcsub($param['cost_value'],bcmul($param['days']-1,$param['cost_avg'],4),4);
            //新数据
            $newData = array();
            for($i=0;$i<$param['days']-1;$i++){
                array_push($newData,['cost_time'=>date('Y-m-d',strtotime($arr[0])+$i*24*60*60),'cost_avg'=>$param['cost_avg']]);
            }
            array_push($newData,['cost_time'=>$arr[1],'cost_avg'=>$last]);

            $data = $this->getDataDiff($oldData,$newData);
            // print_r($data);die;
            foreach($data as $k=>$v){
                db('crm_c_customer_cost')->where('shop_code',session('shop_code'))->where('cost_time',$v['cost_time'])->where('channel_id',0)->where('region_id',0)->setInc('cost_avg',$v['diff']);
            }
            db()->commit();
            action_log($param,'',0,session('staff_id'),session('staff_name'));
            return array('code'=>200,'msg'=>'获取成本设定成功');

        }catch (Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'获取成本设定失败','data'=>$e->getMessage());
        }
    }
    //获取成本设定删除
    public function delObtainCost($param){
        db()->startTrans();
        //查询原数据
        $info = db('crm_s_obtain_cost')->where('id',$param['id'])->find();
        //原数据时间和平均值
        $oldArr = explode(' - ',$info['cost_time']);
        $oldDays = diffBetweenTwoDays($oldArr[0],$oldArr[1])+1;
        $oldAvg = sprintf('%.4f',$info['cost_value']/$oldDays);//保留4位小数
        $oldData = array();

        for($i=0;$i<$oldDays-1;$i++){
            array_push($oldData,['cost_time'=>date('Y-m-d',strtotime($oldArr[0])+$i*24*60*60),'cost_avg'=>$oldAvg]);
        }
        //去除平均值后的小数
        $oldLast = bcsub($info['cost_value'],bcmul($oldDays-1,$info['cost_avg'],4),4);
        array_push($oldData,['cost_time'=>$oldArr[1],'cost_avg'=>$oldLast]);
        try{
            for($i=0;$i<count($oldData);$i++) {
                db('crm_c_customer_cost')->where('shop_code', session('shop_code'))->where('cost_time', date('Y-m-d', strtotime($oldArr[0]) + $i * 24 * 60 * 60))->where('channel_id', 0)->where('region_id', 0)->setDec('cost_avg', $oldData[$i]['cost_avg']);
            }
            db('crm_s_obtain_cost')->delete($param['id']);
            db()->commit();
            action_log($param,'',0,session('staff_id'),session('staff_name'));
            return array('code'=>200,'msg'=>'删除获取花费成功');
        }catch (Exception $e){
            db()->rollback();
            return array('code'=>300,'msg'=>'删除获取花费失败');
        }
    }
    //渠道花费返点列表
    function getObtainCostToJSON($param)
    {
        $result['code'] = 0;
        $result['msg'] = '';
        $page = $param['page'] ? $param['page'] : 1;
        $limit = $param['limit'] ? $param['limit'] : 10;
        $res = db('crm_s_obtain_cost')->where('shop_code',session('shop_code'))->where('cost_type','like','%'.$param.'%')->page($page,$limit)->select();
        $count = db('crm_s_obtain_cost')->where('shop_code',session('shop_code'))->where('cost_type','like','%'.$param.'%')->page($page,$limit)->count();
        if($res){
            $result['data'] = $res;
            $result['count'] = $count;
        }else{
            $result['data'] = array();
        }
        return ($result);
    }
    //添加呼叫前缀
    public function addCallPrefix($param)
    {
        $param['shop_code'] = session('shop_code');
        $param['shop_name'] = session('shop_name');
        db()->startTrans();
        $res = db('crm_s_call_prefix')->insertGetId($param);
        if($res){
            db()->commit();
            action_log($param,'',0,session('staff_id'),session('staff_name'));
            return true;
        }else{
            db()->rollback();
            return false;
        }
    }
    //编辑呼叫前缀
    public function editCallPrefix($param)
    {
        db()->startTrans();
        $res = db('crm_s_call_prefix')->where('id',$param['id'])->update(['name'=>$param['name']]);
        if($res === false){
            db()->rollback();
            return false;
        }else{
            db()->commit();
            action_log($param,'',0,session('staff_id'),session('staff_name'));
            return true;
        }
    }
    //删除呼叫前缀
    public function delCallPrefix($param)
    {
        db()->startTrans();
        $res = db('crm_s_call_prefix')->where('id',$param['id'])->delete();
        if($res){
            db()->commit();
            action_log($param,'',0,session('staff_id'),session('staff_name'));
            return true;
        }else{
            db()->rollback();
            return false;
        }
    }
    //呼叫前缀列表
    function getCallPrefixToJSON($param)
    {
        $result['code'] = 0;
        $result['msg'] = '';
        $res = db('crm_s_call_prefix')->where('shop_code',session('shop_code'))->where('name','like','%'.$param.'%')->select();
        $count = db('crm_s_call_prefix')->where('shop_code',session('shop_code'))->where('name','like','%'.$param.'%')->count();
        if($res){
            $result['data'] = $res;
            $result['count'] = $count;
        }else{
            $result['data'] = array();
        }
        return ($result);
    }
    //添加呼叫中心
    public function addCallCenter($param)
    {
        db()->startTrans();
        $res = db('crm_s_call_center')->insertGetId($param);
        if($res){
            db()->commit();
            action_log($param,'',0,session('staff_id'),session('staff_name'));
            return true;
        }else{
            db()->rollback();
            return false;
        }
    }
    //编辑呼叫中心
    public function editCallCenter($param)
    {
        db()->startTrans();
        $res = db('crm_s_call_center')->where('id',$param['id'])->update($param);
        if($res === false){
            db()->rollback();
            return false;
        }else{
            db()->commit();
            action_log($param,'',0,session('staff_id'),session('staff_name'));
            return true;
        }
    }
    //删除呼叫中心
    public function delCallCenter($param)
    {
        db()->startTrans();
        $res = db('crm_s_call_center')->where('id',$param['id'])->delete();
        if($res){
            db()->commit();
            action_log($param,'',0,session('staff_id'),session('staff_name'));
            return true;
        }else{
            db()->rollback();
            return false;
        }
    }
    //呼叫中心列表
    function getCallCenterToJSON($param)
    {
        $result['code'] = 0;
        $result['msg'] = '';
        $res = db('crm_s_call_center')->select();
        $count = db('crm_s_call_center')->count();
        if($res){
            $result['data'] = $res;
            $result['count'] = $count;
        }else{
            $result['data'] = array();
        }
        return ($result);
    }
    //新增首页显示
    public function homeShowAdd($param){
        $arr = array_values($param['content']);
        if(count($arr) > 10){
            return array('code'=>400,'msg'=>'设置失败,最多可以勾选10个','data'=>'');
        }
        $arr1 = array_values($param['time']);
        if(count($arr1) > 10){
            return array('code'=>400,'msg'=>'设置失败,时间段最多可以勾选3个','data'=>'');
        }
        $str = implode(',',$arr);
        $time = implode(',',$arr1);
        //查询是否已有此岗位的设定
        $info = db('crm_s_home_show')->where('position_code',$param['position_code'])->where('shop_code',session('shop_code'))
            ->find();
        if($info['id']){
            return array('code'=>300,'msg'=>'已有此岗位的显示设定，不能设置','data'=>'');
        }
        $data['department_id'] = $param['department_id'];
        $data['department_name'] = $param['department_name'];
        $data['position_id'] = $param['position_id'];
        $data['position_name'] = $param['position_name'];
        $data['position_code'] = $param['position_code'];
        $data['content'] = $str;
        $data['time'] = $time;
        $data['shop_code'] = session('shop_code');
        $data['shop_name'] = session('shop_name');
        db()->startTrans();
        $res = db('crm_s_home_show')->insertGetId($data);
        if($res){
            db()->commit();
            action_log($param,'',0,session('staff_id'),session('staff_name'));
            $ret = array('code'=>200,'msg'=>'首页显示添加成功','data'=>$res);
        }else{
            db()->rollback();
            $ret = array('code'=>100,'msg'=>'首页显示添加失败','data'=>'');
        }
        return $ret;
    }
    //修改首页显示
    public function homeShowEdit($param){
        $arr = array_values($param['content']);
        if(count($arr) > 10){
            return array('code'=>400,'msg'=>'设置失败,统计方式最多可以勾选10个','data'=>'');
        }
        $arr1 = array_values($param['time']);
        if(count($arr1) > 10){
            return array('code'=>400,'msg'=>'设置失败,时间段最多可以勾选3个','data'=>'');
        }
        $str = implode(',',$arr);
        $time = implode(',',$arr1);
        //查询是否已有此岗位的设定
        $info = db('crm_s_home_show')->where('position_code',$param['position_code'])->where('shop_code',session('shop_code'))->where('id','<>',$param['id'])->find();
        if($info['id']){
            return array('code'=>300,'msg'=>'已有此岗位的显示设定，不能设置','data'=>'');
        }
        $data['department_id'] = $param['department_id'];
        $data['department_name'] = $param['department_name'];
        $data['position_id'] = $param['position_id'];
        $data['position_name'] = $param['position_name'];
        $data['position_code'] = $param['position_code'];
        $data['content'] = $str;
        $data['time'] = $time;
        db()->startTrans();
        $res = db('crm_s_home_show')->where('id',$param['id'])->update($data);
        if($res === false){
            db()->rollback();
            $ret = array('code'=>100,'msg'=>'首页显示修改失败','data'=>'');
        }else{
            db()->commit();
            action_log($param,'',0,session('staff_id'),session('staff_name'));
            $ret = array('code'=>200,'msg'=>'首页显示修改成功','data'=>$res);
        }
        return $ret;
    }
    //删除首页显示
    public function homeShowDel($param){
        db()->startTrans();
        $res = db('crm_s_home_show')->where('id',$param['id'])->delete();
        if($res === false){
            db()->rollback();
            $ret = array('code'=>100,'msg'=>'首页显示删除失败','data'=>'');
        }else{
            db()->commit();
            action_log($param,'',0,session('staff_id'),session('staff_name'));
            $ret = array('code'=>200,'msg'=>'首页显示删除成功','data'=>$res);
        }
        return $ret;
    }
    function homeShowJSON($param)
    {
        $page = $param['page'] ? $param['page'] : 1;
        $limit = $param['limit'] ? $param['limit'] : 10;
        $result['code'] = 0;
        $result['msg'] = '';
        $res = db('crm_s_home_show')->where('shop_code',session('shop_code'))->where('position_name','like','%'.$param['position_name'].'%')->page($page,$limit)->select();
        $count = db('crm_s_home_show')->where('shop_code',session('shop_code'))->where('position_name','like','%'.$param['position_name'].'%')->count();
        if($res){
            $result['data'] = $res;
            $result['count'] = $count;
        }else{
            $result['data'] = array();
        }
        return ($result);
    }
    //添加渠道补充
    public function addChannel($param){
        $data['channel_class_id'] = intval($param['channel_class_id']);
        $data['channel_class_name'] = $param['channel_class_name'];
        $data['channel_info_id'] = intval($param['channel_info_id']);
        $data['channel_info_name'] = $param['channel_info_name'];
        $signId = intval($param['sign_id']);
        $data['channel_name'] = trim($param['channel_name']);
        $data['brandclass_id'] = session('brandclass_id');
        $data['brandclass_name'] = session('brandclass');
        $data['shop_code'] = session('shop_code');
        $data['shop_name'] = session('shop_name');
        $data['setkey'] = session('setkey');
        $data['order_sort'] = intval($param['order_sort']);
        $data['share_shops']= trim($param['share_shops'],',').','.session('shop_code');
        $data['staff_id'] = session('staff_id');
        $data['staff_name'] = session('staff_name');
        $data['create_time'] = date("Y-m-d H:i:s");
        $data['channel_code'] = $param['channel_code'];
        if(session('shop_code') && $signId){
            $sign = $this->getSign($signId);
            if($sign){
                $data['bind_sign_ids'] = json_encode([
                    session('shop_code')=>[
                        'sign_id'=>$sign['id'],
                        'sign_name'=>$sign['tracksign'],
                    ]
                ]);
            }
        }
        
        db()->startTrans();
        $res = db('crm_s_channel')->insertGetId($data);
        if($res === false){
            db()->rollback();
            return array('code'=>100,'msg'=>'添加渠道名称失败','data'=>$data);
        }else{
            action_log($data,'',0,session('staff_id'),session('staff_name'));

            cache('crm_channel_*',null);
            cache('all_channel_*',null);
            db()->commit();
            session('channel',null);
            return array('code'=>200,'msg'=>'添加渠道名称成功','data'=>$res);
        }
    }
    //修改渠道补充
    public function editChannel($param){
        $id = intval($param['id']);
        $data['channel_class_id'] = intval($param['channel_class_id']);
        $data['channel_class_name'] = $param['channel_class_name'];
        $data['channel_info_id'] = intval($param['channel_info_id']);
        $data['channel_info_name'] = $param['channel_info_name'];
        $data['channel_name'] = trim($param['channel_name']);
        $data['brandclass_id'] = session('brandclass_id');
        $data['brandclass_name'] = session('brandclass');
        $signId = intval($param['sign_id']);

        $data['sign_name'] = $param['sign_name'];
        $data['setkey'] = session('setkey');
        $data['order_sort'] = intval($param['order_sort']);
        $data['share_shops']= trim($param['share_shops']);
        $data['channel_code'] = $param['channel_code'];
        if(session('shop_code')){
            $channelInfo = db('crm_s_channel')->where('id',$id)->find();
            $existSign = json_decode($channelInfo['bind_sign_ids'],true);
            if($channelInfo['bind_sign_ids']){
                if(array_key_exists(session('shop_code'), $existSign)){
                    unset($existSign[session('shop_code')]);
                }
            }
            if($signId){
                $sign = $this->getSign($signId);
                if($sign){
                    $existSign[session('shop_code')]=[
                            'sign_id'=>$sign['id'],
                            'sign_name'=>$sign['tracksign'],
                        ];
                }
            }
            $data['bind_sign_ids'] = json_encode($existSign);
        }
        db()->startTrans();
        $res = db('crm_s_channel')->where('id',$id)->update($data);
        if($res === false){
            db()->rollback();
            return array('code'=>100,'msg'=>'修改渠道名称失败','data'=>$data);
        }else{
            action_log($data,'',0,session('staff_id'),session('staff_name'));

            cache('crm_channel_*',null);
            cache('all_channel_*',null);
            db()->commit();
            session('channel',null);
            return array('code'=>200,'msg'=>'修改渠道名称成功','data'=>$res);
        }
    }
    //删除渠道补充
    public function  delChannel($id){
        if(empty($id)){
            return array('code'=>300,'msg'=>'参数有误','data'=>$id);
        }
        db()->startTrans();
        $res = db('crm_s_channel')->where('id',$id)->delete();
        if($res === false){
            db()->rollback();
            return array('code'=>100,'msg'=>'删除渠道名称失败','data'=>$res);
        }else{
            cache('crm_channel_*',null);
            cache('all_channel_*',null);
            session('channel',null);
            action_log($id,'',0,session('staff_id'),session('staff_name'));

            db()->commit();
            return array('code'=>200,'msg'=>'删除渠道名称成功','data'=>$res);
        }
    }
    // 渠道列表
    function getChannelToJSON($param)
    {
        $result['code'] = 0;
        $result['msg'] = '';
        $page = $param['page'] ? $param['page'] : 1;
        $limit = $param['limit'] ? $param['limit'] : 20;
        if(session('shop_code')){
            $sql = ' FIND_IN_SET("'.session('shop_code').'",share_shops) OR shop_code="'.session('shop_code').'" ';
        }else{
            if($param['shop_code']){
                $sql = ' FIND_IN_SET(share_shops,\''.$param['shop_code'].'\')';
            }
        }
        if (trim($param['channel_name'])) {
            $where['channel_name'] = ['like', '%'.$param['channel_name'].'%'];
        }else{
            if ((int)$param['channel_class_id']) {
                $where['channel_class_id'] = (int)$param['channel_class_id'];
            }
            if ((int)$param['channel_info_id']) {
                $where['channel_info_id'] = (int)$param['channel_info_id'];
            }
        }

        // $res = db('crm_s_channel')->where($sql)->where('channel_name','like','%'.$param['chan_name'].'%')->page($page,$limit)->order('order_sort asc')->select();
        $res = db('crm_s_channel')->where($sql)->where($where)->page($page,$limit)->order('order_sort asc')->select();
        // echo db()->getLastSql();die;
        $count = db('crm_s_channel')->where($sql)->where($where)->count();
        // $count = db('crm_s_channel')->where($sql)->where('channel_name','like','%'.$param['chan_name'].'%')->count();
        if($res){
            if(session('shop_code')){
                foreach ($res as $k => $v) {
                    $signids = json_decode($v['bind_sign_ids'],true);
                    if($signids[session('shop_code')]){
                        $res[$k]['sign_id'] = $signids[session('shop_code')]['sign_id'];
                        $res[$k]['sign_name'] = $signids[session('shop_code')]['sign_name'];
                    }
                }
            }
            $result['data'] = $res;
            $result['count'] = $count;
        }else{
            $result['data'] = array();
        }
        return ($result);
    }
    public function getChannelByCid($cid=''){
        //find_in_set("'.session('shop_code').'",share_shops)
        $where['id'] = ['<>',0];
        if (!empty($cid)) {
            $where['channel_info_id'] = $cid;
        }
        $res = db('crm_s_channel')->where($where)->where('find_in_set("'.session('shop_code').'",share_shops) or shop_code="'.session('shop_code').'"')->select();
        return $res;
    }
    public function crmProvinceSet($id){
        // cache('crm_address_app_'.session('shop_code'),null);
        if(!$id){
            db()->startTrans();
            $res = db('crm_s_shop_address')->where('shop_code',session('shop_code'))->delete();
            if($res === false){
                db()->rollback();
                return array('code'=>100,'msg'=>'清空省市区失败');
            }else{
                db()->commit();
                return array('code'=>200,'msg'=>'清空省市区成功');
            }
        }
        // $res = sx_call('59fd885ed3628',array('id'=>$id));
        $mc = new \app\common\lib\mcInterface();
        $res = $mc->getMcAddress(array('id'=>$id));
        
        if($res !== false){
            $info = $res;
            db()->startTrans();
            try{
                foreach($info as $k=>$v){
                    if($v['type'] == 2){
                        $fid[] = $v['id'];
                    }
                }
                if(!empty($fid)){
                    $pidArray = db('crm_s_address')->where('pid','in',$fid)->select();
                    $info = array_merge($info,$pidArray);
                }
                db('crm_s_shop_address')->where('shop_code',session('shop_code'))->delete();
                foreach($info as $k=>$v){
                    $arr[$k] = array(
                        'id'  => $v['id'],
                        'pid' => $v['pid'],
                        'name'=> $v['name'],
                        'type'=> $v['type'],
                        'shop_code'=>session('shop_code')
                    );
                }
                db('crm_s_shop_address')->insertAll($arr);
                action_log($id,'',0,session('staff_id'),session('staff_name'));
                cache('crm_tree_address',null);
                db()->commit();
                return array('code'=>200,'msg'=>'设置省市区成功');
            }catch (Exception $e){
                db()->rollback();
                return array('code'=>300,'msg'=>'设置省市区有误','data'=>$e->getMessage());
            }
        }else{
            return array('code'=>100,'msg'=>'信息查询错误');
        }
    }

    // 查询客资爆破设定列表
    public function getSwapList($data){
        $where = $data['where'];
        $order = $data['order'];
        $field = $data['field'];
        unset($data);
        $swapList = db('crm_s_swapset')->where($where)->order($order)->field($field)->select();
        return $swapList;
    }

    // 设定客资爆破活动
    public function setCustomerSwap($data){
        $staffs = $data['staffs'];
        $ids = '';
        $names = '';
        foreach ($staffs as $key => $value) {
            $ids .= $value.',';
            $staffInfo = getStaffInfoById($value);
            $names .= $staffInfo['staffname'].',';
        }
        $ids = trim($ids, ',');
        $names = trim($names, ',');
        // var_dump($names);
        $inData = [
            'swap_number'      => get_rand_string(4).time(),
            'swap_name'        => $data['swapName'],
            'swap_staff_ids'   => $ids,
            'swap_staff_names' => $names,
            'customer_start'   => date('Y-m-d', strtotime($data['customer_start'])),
            'customer_end'     => date('Y-m-d', strtotime($data['customer_end'])),
            'start_date'       => date('Y-m-d', strtotime($data['startDate'])),
            'end_date'         => date('Y-m-d', strtotime($data['endDate'])),
            'create_time'      => date('Y-m-d H:i:s'),
            'shop_code'        => session('shop_code'),
            'shop_name'        => session('shop_name'),
            'brandclass_id'    => session('brandclass_id'),
            'brandclass'       => session('brandclass'),
        ];
        unset($ids);unset($names);unset($data);
        $res = db('crm_s_swapset')->insert($inData);
        
        if ($res === false) {
            return array('code'=>100,'msg'=>'添加客资爆破活动失败','data'=>db()->getLastSql());
        }else{
            // 成功 记录日志
            history_log($inData,'','',session('staff_id'),session('staff_name'));
            unset($inData);
            return array('code'=>200,'msg'=>'添加客资爆破活动成功','data'=>$res);
        }
    }

    // 编辑客资爆破活动设定
    public function editCustomerSwap($param){
        $where = $param['where'];
        $data  = $param['data'];
        $type  = $param['type'];

        $today = date('Y-m-d');
        $swap = db('crm_s_swapset')->where($where)->find();
        if ($swap) {
            if ($today > $swap['start_date']) {
                $return = ['code'=>3, 'data'=>'活动的开始时间小于当天'];
            }else if ($today > $swap['end_date']) {
                $return = ['code'=>2, 'data'=>'活动的结束时间小于当天'];
            }else{
                // 活动之前可以编辑或删除客资
                switch ($type) {
                    case 'edit':
                        $staffs = $data['staffs'];
                        $ids = '';
                        $names = '';
                        foreach ($staffs as $key => $value) {
                            $ids .= $value.',';
                            $staffInfo = getStaffInfoById($value);
                            $names .= $staffInfo['staffname'].',';
                        }
                        $ids = trim($ids, ',');
                        $names = trim($names, ',');
                        $inData = [
                            'swap_name'        => $data['swapName'],
                            'swap_staff_ids'   => $ids,
                            'swap_staff_names' => $names,
                            'customer_start'   => date('Y-m-d', strtotime($data['customer_start'])),
                            'customer_end'     => date('Y-m-d', strtotime($data['customer_end'])),
                            'start_date'       => date('Y-m-d', strtotime($data['startDate'])),
                            'end_date'         => date('Y-m-d', strtotime($data['endDate'])),
                            'update_time'      => date('Y-m-d H:i:s'),
                        ];
                        break;
                    case 'del':
                        $inData['is_del']=2;
                        break;
                }
                $res = db('crm_s_swapset')->where($where)->update($inData);
                if ($res === false) {
                    $return = ['code'=>4, 'data'=>db()->getLastSql()];
                }else{
                    // 成功，记录日志
                    history_log($inData,$swap,'',session('staff_id'),session('staff_name'));
                    $return = ['code'=>200];
                }
            }
        }else{
            $return = ['code'=>1, 'data'=>'活动不存在'];
        }
        return $return;
    }

    //报表列表
    public function statistics_list_data($param){
        // $shops = cache('allShops');
        // if(empty($shops)){
        //     $shop = controller('crm/Customer','lib')->get_shop();
        //     $shops = [];
        //     foreach($shop as $k=>$v){
        //         $shops[$v['shop_code']] = $v['shop_name'];
        //     }
        //     cache('allShops',$shops);
        // }
        // $brands = cache('allBrands');
        // if(empty($brands)){
        //     $brand = controller('crm/Customer','lib')->getBrandClass();
        //     $brands = [];
        //     foreach($brand as $k=>$v){
        //         $brands[$v['id']] = $v['brandclass'];
        //     }
        //     cache('allBrands',$brands);
        // }

        // $result['code'] = 0;
        // $result['msg'] = '';

        // $page = $param['page'] ? $param['page'] : 1;
        // $limit = $param['limit'] ? $param['limit'] : 200;
        // $repType = $param['report_type_name'];
        // $position = session('main_position_code').','.session('position_code');
        // $position = explode(',',$position);
        // $str = ' 1=1 and (';
        // foreach($position as $k=>$v){
        //     $str .= ' FIND_IN_SET("'.$v.'",d.report_auth) or';
        // }
        // $str = trim($str,' or');
        // $str .= ')';
        // $info = db('crm_s_report_detail')->alias('d')->join('crm_s_report_form f','f.id=d.form_id')
        //     ->where($str)->where('report_type_name',$repType)
        //     ->field('d.id,f.report_name,f.report_url,f.report_class_name,d.shop_code,d.brandclass_id,f.code,f.sort')
        //     ->order('d.brandclass_id, d.shop_code asc')
        //     ->limit($limit)
        //     ->page($page)
        //     ->select();
        // foreach($info as $k=>$v){
        //     if(strpos($v['report_url'],'.html')){
        //         $info[$k]['report_url'] = str_replace('.html','/did/'.$v['id'],strtolower($v['report_url']));
        //     }else{
        //         $info[$k]['report_url'] = strtolower($v['report_url']).'/did/'.$v['id'];
        //     }
        //     $info[$k]['brandclass'] = $brands[$v['brandclass_id']];
        //     $info[$k]['shop_name']  = $shops[$v['shop_code']];
        //     // $info[$k]['report_name']= $brands[$v['brandclass_id']].'-'.$shops[$v['shop_code']].'-'.$v['report_name'];
        //     $info[$k]['report_name']= $v['report_name'];
        // }

        // //成都天使印象  判断报表展示权限report_class_name
        // if(session('productid') == '9128787616'){
        //     $menu = include(APP_PATH.'menu.php');
        //     $menuCustomize = include(APP_PATH.'menu_customize.php');
        //     $auth = getAuthMenu($menu,'auth',$menuCustomize);

        //     // $auth=getAuth($type='auth');
        //     $auth_arr = array_column($auth,'menu_url');
        //     foreach ($auth_arr as $key => $value) {
        //         $auth_arr[$key] = strtolower($value);
        //     }
        //     //判断权限的报表code
        //     $code = [
        //             'code1592808723',
        //             'code1592896053',
        //             'code1592899519',
        //             'code1592908984',
        //             'code1592981289',
        //             'code1592992364',
        //             'code1593050977',
        //             'code1593055246',
        //             'code1593057633',
        //             'code1593058089',
        //             'code1593322620',
        //             'code1593339260',
        //         ];
        //     foreach($info as $key=>$value){
        //         if(in_array($value['code'],$code)){
        //             if(!in_array(strtolower('/crm/report/'.$value['report_class_name']), $auth_arr)){
        //                 unset($info[$key]);
        //             }
        //         }
        //     }
        // }
        // $count = count($info);
        // if($info){
        //     array_multisort(array_column($info,'sort'),SORT_ASC,$info);
        //     $result['data'] = $info;
        //     $result['count'] = $count;
        // }else{
        //     $result['data'] = array();
        // }
        // return json($result);
        
        $menu = include(APP_PATH.'menu.php');
        $menuCustomize = include(APP_PATH.'menu_customize.php');
        $auth = getAuthMenu($menu,'auth',$menuCustomize);
        $report = [];
        foreach ($auth['list'] as $key => $value) {
            if ($value['menu_code'] == 'menu1512736477') {//提取统计分析
                $report = $value['children'];
            }
        }
        
        // unset($report[0]);
        foreach ($report as $k => $v) {
            if(strpos($v['menu_url'],'.html')){
                $report[$k]['menu_url'] = str_replace('.html','/menu_code/'.$v['menu_code'].'/did/'.$v['id'],strtolower($v['menu_url']));
            }else{
                $report[$k]['menu_url'] = strtolower($v['menu_url']).'/menu_code/'.$v['menu_code'].'/did/'.$v['id'];
            }
            if ($v['report_type_name'] != $param['report_type_name']) {
                unset($report[$k]);
            }
        }
        $result['code'] = 0;
        $result['msg'] = '';
        $result['data'] = array_merge($report);
        $result['count'] =count($report);

        return json($result);
    }
    public function addShopReturnSetting($param){
        $data['return_rule'] = intval($param['return_rule']);
        $data['return_value'] = intval($param['return_value']);
        if($data['return_rule'] == 1 && $data['return_value']>100){
            $data['return_value'] = 100;
        }

        $data['channel_id'] = $param['channel_id'];
        $data['channel_name'] = $param['channel_name'];
        $data['shop_code'] = session('shop_code');
        $data['shop_name'] = session('shop_name');
        $data['brandclass_id'] = session('brandclass_id');
        $data['brandclass'] = session('brandclass');
        $info = db('crm_s_shop_return_rule')->where('shop_code',session('shop_code'))->where('channel_id',$data['channel_id'])->find();
        if($info){
            return array('code'=>300,'msg'=>'返点规则已存在，不能再次添加','data'=>'');
        }
        db()->startTrans();
        try{
            db('crm_s_shop_return_rule')->insertGetId($data);
            action_log($param,'',0,session('staff_id'),session('staff_name'));
            db()->commit();
            return array('code'=>200,'msg'=>'添加返点规则成功','data'=>'');
        }catch (Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'添加返点规则失败','data'=>$e->getMessage());
        }
    }
    public function editShopReturnSetting($param){
        $id = intval($param['id']);
        $data['return_rule'] = intval($param['return_rule']);
        $data['return_value'] = intval($param['return_value']);
        if($data['return_rule'] == 1 && $data['return_value']>100){
            $data['return_value'] = 100;
        }
        $data['channel_id'] = $param['channel_id'];
        $data['channel_name'] = $param['channel_name'];
        $data['shop_code'] = session('shop_code');
        $info = db('crm_s_shop_return_rule')->where('shop_code',session('shop_code'))->where('channel_id',$data['channel_id'])->where('id','<>',$id)->find();
        if($info){
            return array('code'=>300,'msg'=>'此返点规则已存在，不能编辑','data'=>'');
        }
        db()->startTrans();
        try{
            db('crm_s_shop_return_rule')->where('id',$id)->update($data);
            action_log($param,'',0,session('staff_id'),session('staff_name'));
            db()->commit();
            return array('code'=>200,'msg'=>'修改返点规则成功','data'=>'');
        }catch (Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'修改返点规则失败','data'=>$e->getMessage());
        }
    }
    public function delShopReturnSetting($param){
        $id = intval($param['id']);
        db()->startTrans();
        try{
            db('crm_s_shop_return_rule')->where('id',$id)->delete();
            action_log($param,'',0,session('staff_id'),session('staff_name'));
            db()->commit();
            return array('code'=>200,'msg'=>'删除返点规则成功','data'=>'');
        }catch (Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'删除返点规则失败','data'=>$e->getMessage());
        }
    }
    //订单来源----start
    public function addSource($param){
        $data['source'] = trim($param['source']);
        $data['shop_code'] = session('shop_code');
        $data['shop_name'] = session('shop_name');
        $data['brandclass_id'] = session('brandclass_id');
        $data['brandclass'] = session('brandclass');
        $info = db('crm_s_order_source')->where('shop_code',session('shop_code'))->where('source',$data['source'])->where('is_delete',1)->find();
        if($info){
            return array('code'=>300,'msg'=>'订单来源已存在，不能再次添加','data'=>'');
        }
        db()->startTrans();
        try{
            db('crm_s_order_source')->insert($data);
            action_log($param,'',0,session('staff_id'),session('staff_name'));
            db()->commit();
            return array('code'=>200,'msg'=>'添加订单来源成功','data'=>'');
        }catch (Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'添加订单来源失败','data'=>$e->getMessage());
        }
    }
    public function editSource($param){
        $id = intval($param['id']);
        $data['source'] = trim($param['source']);
        $data['shop_code'] = session('shop_code');
        $info = db('crm_s_order_source')->where('shop_code',session('shop_code'))->where('source',$data['source'])->where('is_delete',1)->where('id','<>',$id)->find();
        if($info){
            return array('code'=>300,'msg'=>'此订单来源已存在，不能编辑','data'=>'');
        }
        db()->startTrans();
        try{
            db('crm_s_order_source')->where('id',$id)->update($data);
            action_log($param,'',0,session('staff_id'),session('staff_name'));
            db()->commit();
            return array('code'=>200,'msg'=>'修改订单来源成功','data'=>'');
        }catch (Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'修改订单来源失败','data'=>$e->getMessage());
        }
    }
    public function delSource($param){
        $id = intval($param['id']);
        db()->startTrans();
        try{
            db('crm_s_order_source')->where('id',$id)->update(['is_delete'=>2]);
            action_log($param,'',0,session('staff_id'),session('staff_name'));
            db()->commit();
            return array('code'=>200,'msg'=>'删除订单来源成功','data'=>'');
        }catch (Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'删除订单来源失败','data'=>$e->getMessage());
        }
    }
    //订单来源----end
    public function addCustomerInterface($param){
        $data['token'] = strtoupper(md5(md5(get_rand_string().time())));
        $data['url'] =url('Index/addCustomerThird',['token'=>$data['token']],true,true);
        $data['create_time'] = date('Y-m-d H:i:s');
        $data['create_staff_id'] = session('staff_id');
        $data['create_staff_name'] = session('staff_name');
        $data['status'] = intval($param['status']);
        $data['is_delete'] = 2;
        $data['shop_code'] = session('shop_code');
        $data['shop_name'] = session('shop_name');
        $json['staff_name'] = $param['staff_name'];
        $json['customer_name'] = trim($param['customer_name']);
        $json['customer_sex'] = trim($param['customer_sex']);
        $json['customer_tel'] = trim($param['customer_tel']);
        $json['customer_qq'] = trim($param['customer_qq']);
        $json['ip'] = trim($param['ip']);
        $json['customer_wechat'] = trim($param['customer_wechat']);
        $json['customer_channel'] = trim($param['customer_channel']);
        $json['access_model'] = trim($param['access_model']);
        $json['consultation_type'] = trim($param['consultation_type']);
        $json['customer_cource'] = trim($param['customer_cource']);
        $json['customer_memo'] = trim($param['customer_memo']);
        $json['channel_plan_number'] = trim($param['channel_plan_number']);
        $json['ad_page'] = trim($param['ad_page']);

        $data['field_config'] = json_encode($json);
        db()->startTrans();
        try{
            db('crm_s_customer_interface')->insert($data);
            action_log($param,[],0,session('staff_id'),session('staff_name'));
            db()->commit();
            return array('code'=>200,'msg'=>'录入接口添加成功');
        }catch (Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'录入接口添加失败','data'=>$e->getMessage());
        }
    }
    public function editCustomerInterface($param){
        $data['update_time'] = date('Y-m-d H:i:s');
        $data['status'] = intval($param['status']);
        $json['staff_name'] = $param['staff_name'];
        $json['customer_name'] = trim($param['customer_name']);
        $json['customer_sex'] = trim($param['customer_sex']);
        $json['customer_tel'] = trim($param['customer_tel']);
        $json['customer_qq'] = trim($param['customer_qq']);
        $json['customer_wechat'] = trim($param['customer_wechat']);
        $json['ip'] = trim($param['ip']);
        $json['customer_channel'] = trim($param['customer_channel']);
        $json['access_model'] = trim($param['access_model']);
        $json['consultation_type'] = trim($param['consultation_type']);
        $json['customer_cource'] = trim($param['customer_cource']);
        $json['customer_memo'] = trim($param['customer_memo']);
        $json['channel_plan_number'] = trim($param['channel_plan_number']);
        $json['ad_page'] = trim($param['ad_page']);

        $data['field_config'] = json_encode($json);
        $info = db('crm_s_customer_interface')->where('id',$param['id'])->find();
        db()->startTrans();
        try{
            db('crm_s_customer_interface')->where('id',$param['id'])->update($data);
            action_log($param,$info,0,session('staff_id'),session('staff_name'));
            db()->commit();
            return array('code'=>200,'msg'=>'录入接口修改成功');
        }catch (Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'录入接口修改失败','data'=>$e->getMessage());
        }
    }
    /** 
     * 数组分页函数  核心函数  array_slice 
     * 用此函数之前要先将数据库里面的所有数据按一定的顺序查询出来存入数组中 
     * $count   每页多少条数据 
     * $page   当前第几页 
     * $array   查询出来的所有数组 
     * order 0 - 不变     1- 反序 
     */   
      
    function page_array($count,$page,$array,$order){  
        global $countpage; #定全局变量  
        $page=(empty($page))?'1':$page; #判断当前页面是否为空 如果为空就表示为第一页面   
           $start=($page-1)*$count; #计算每次分页的开始位置  
        if($order==1){  
          $array=array_reverse($array);  
        }     
        $totals=count($array);    
        $countpage=ceil($totals/$count); #计算总页面数  
        $pagedata=array();  
        $pagedata=array_slice($array,$start,$count);  
        return $pagedata;  #返回查询数据  
    }  
    /** 
     * 分页及显示函数 
     * $countpage 全局变量，照写 
     * $url 当前url 
     */  
    function show_array($countpage,$url){  
         $page=empty($_GET['page'])?1:$_GET['page'];  
         if($page > 1){  
            $uppage=$page-1;  
      
         }else{  
            $uppage=1;  
         }  
      
         if($page < $countpage){  
            $nextpage=$page+1;  
      
         }else{  
                $nextpage=$countpage;  
         }  
             
        $str='<div style="border:1px; width:300px; height:30px; color:#9999CC">';  
        $str.="<span>共  {$countpage}  页 / 第 {$page} 页</span>";  
        $str.="<span><a href='$url?page=1'>   首页  </a></span>";  
        $str.="<span><a href='$url?page={$uppage}'> 上一页  </a></span>";  
        $str.="<span><a href='$url?page={$nextpage}'>下一页  </a></span>";  
        $str.="<span><a href='$url?page={$countpage}'>尾页  </a></span>";  
        $str.='</div>';  
        return $str;  
    } 
    //获取手机地址配置
    public function telAddress(){
        $res = db('crm_c_sysconfig')->where('ckey','tel_address_grant')->find();
        return $res;
    }
    //保存手机地址配置
    public function telAddressMate($val){
        if (!$val) {
            return array('code'=>100,'msg'=>'请选择至少一个地址');exit;
        }
        $res = db('crm_c_sysconfig')->where('ckey','tel_address_grant')->find();
        if ($res['cvalue']&&$res['cvalue']==$val) {
            return array('code'=>101,'msg'=>'现有配置与原先一样');exit;
        }
        if($res['ckey']){
            $data['cvalue'] = $val;
            $staff = db('crm_c_sysconfig')->where('ckey','tel_address_grant')->update($data);
        }else{
            $data['cvalue'] = $val;
            $data['ckey'] = 'tel_address_grant';
            $staff = db('crm_c_sysconfig')->insert($data);
        }
        if ($staff) {
            return array('code'=>200,'msg'=>'成功');
        }else{
            return array('code'=>300,'msg'=>'失败');
        }
    }

    /*
     * 获取两个日期之间的所有日期
     * start 2020-04-02
     * end   2020-04-16
     */
    public function prDates($start,$end){
        $dt_start = strtotime($start);
        $dt_end = strtotime($end);
        $value = [];
        while ($dt_start<=$dt_end){
            $value[] = date('Y-m-d',$dt_start);
            $dt_start = strtotime('+1 day',$dt_start);
        }
        return $value;
    }

    // -------------------------- 南宁定制 start ------------------------- //
    //花费品牌设定
    function getBrandSet($name){
        $result['code'] = 0;
        $result['msg'] = '';
        $res = db('crm_s_brandset')->where('name','like','%'.$name.'%')->select();
        $count = db('crm_s_brandset')->where('name','like','%'.$name.'%')->count();
        if($res){
            $result['data'] = $res;
            $result['count'] = $count;
        }else{
            $result['data'] = array();
        }
        return ($result);
    }

    //粉丝互动量列表
    function getFansToJSON($params){
        $limit = $params['limit'] ? $params['limit'] : 10;
        $page = $params['page'] ? $params['page'] : 1;
        $result['code'] = 0;
        $result['msg'] = '';
        $date = explode(' - ',$params['search_date']);
        $start = $date[0] ? $date[0]: date('Y-m-01');
        $end = $date[1] ? $date[1]: date('Y-m-d');
        $where = [];
        if($params['channel_id']) $where['channel_name'] = ['in',$params['channel_id']];
        if($params['city_id']) $where['city_id'] = $params['city_id'];

        $res = db('crm_s_fans')->where('shop_code',session('shop_code'))->where($where)->where('date','between',[$start,$end])->order('date desc')->page($page,$limit)->select();
        $count = db('crm_s_fans')->where('shop_code',session('shop_code'))->where($where)->where('date','between',[$start,$end])->count();
        if($res){
            $result['data'] = $res;
            $result['count'] = $count;
        }else{
            $result['data'] = array();
        }
        return ($result);
    }

    function addFans($params){
        $data['date'] = $params['date'];
        $data['channel_id']   = $params['channel_id'];
        $data['channel_name'] = $params['channel_name'];
        $data['channel_class_id']   = $params['channel_class_id'];
        $data['channel_class_name'] = $params['channel_class_name'];
        $data['channel_info_id']    = $params['channel_info_id'];
        $data['channel_info_name']  = $params['channel_info_name'];

        $data['city_id']   = $params['city_id'];
        $data['city_name'] = $params['city_name'];
        $data['kf_staff_id']   = $params['kf_staff_id'];
        $data['kf_staff_name'] = $params['kf_staff_name'];
        $data['tg_staff_id']   = $params['tg_staff_id'];
        $data['tg_staff_name'] = $params['tg_staff_name'];
        $data['subscribe_num'] = $params['subscribe_num'];
        $data['unsubscribe_num'] = $params['unsubscribe_num'];
        $data['private_num'] = $params['private_num'];
        $data['effective_form'] = $params['effective_form'];
        $data['chat_num']   = $params['chat_num'];
        $data['kezi_num'] = $params['kezi_num'];

        $data['brandclass_id'] = session('brandclass_id');
        $data['shop_name'] = session('shop_name');
        $data['shop_code'] = session('shop_code');

        $res = db('crm_s_fans')
            ->where('channel_id', $data['channel_id'])
            ->where('city_id',$data['city_id'])
            ->where('date', $data['date'])
            ->where('kf_staff_id', $data['kf_staff_id'])
            ->where('tg_staff_id', $data['tg_staff_id'])
            ->find();

        if($res && $params['id']){
            if($res['id'] == $data['id']){
                return array('code'=>100,'msg'=>'已存在'.$data['date'].$data['channel_name'].$data['city_name'].'-客服【'.$data['kf_staff_name'].'】，推广【'.$data['tg_staff_name'].'】的粉丝互动量，请重新添加');
            }
        }elseif($res){
            return array('code'=>100,'msg'=>'已存在'.$data['date'].$data['channel_name'].$data['city_name'].'-客服【'.$data['kf_staff_name'].'】，推广【'.$data['tg_staff_name'].'】的粉丝互动量，请重新添加');
        }


        $ip = \think\Request::instance()->ip();
        db()->startTrans();
        try{

            if($params['id']){
                $old = db('crm_s_fans')->where('id',$params['id'])->find();
                $data['update_time'] = date('Y-m-d H:i:s',time());
                $data['update_staff_id'] = session('staff_id');
                $data['update_staff_name'] = session('staff_name');

                db('crm_s_fans')->where('id',$params['id'])->update($data);
            }else{
                $old = [];
                $data['add_time'] = date('Y-m-d H:i:s',time());
                $data['add_staff_id'] = session('staff_id');
                $data['add_staff_name'] = session('staff_name');

                db('crm_s_fans')->insertGetId($data);
            }


            $new = '';
            $new .= '操作店面：'.$data['shop_name'].'<br/>';
            if($data['city_name'])$new .= '市：'.$data['city_name'].'<br/>';
            $new .= '渠道：'.$data['channel_name'].'<br/>';
            $new .= '关注量：'.$data['subscribe_num'].'<br/>';
            $new .= '取消量：'.$data['unsubscribe_num'].'<br/>';
            $new .= '有效对话：'.$data['chat_num'].'<br/>';
            $new .= '客资量：'.$data['kezi_num'].'<br/>';

            $log = [];
            $log['module']     = 'crm';
            $log['controller'] = 'Setting';
            $log['action']     = 'addFans';
            $log['old_data']   = json_encode($old);
            $log['data'] = $new;
            $log['customer_id']= 0;
            $log['staff_name'] = session('staff_name');
            $log['staff_id']   = session('staff_id');
            $log['ip']         = $ip;
            $log['create_time']= date('Y-m-d H:i:s',time());

            db('action_log','db_logs')->insert($log);
            action_log($params,'',0,session('staff_id'),session('staff_name'));

            db()->commit();
            return  array('code'=>200,'msg'=>'','data'=>$data);
        }catch (Exception $e){
            db()->rollback();
            return  array('code'=>100,'msg'=>'粉丝互动量添加失败','data'=>$e->getMessage().db()->getLastSql());
        }
    }

    function delFans($id){
        db()->startTrans();
        try{
            db('crm_s_fans')->where('id',$id)->delete();
            action_log($id,'',0,session('staff_id'),session('staff_name'));
            db()->commit();

            return array('code'=>200,'msg'=>'操作成功');
        }catch (Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'删除失败','data'=>$e->getMessage().db()->getLastSql());
        }
    }

    //人员渠道表 指定人员 查询
    function staffTrenchs($staff_id){
        if ($staff_id) {
            $data = db('crm_c_staff_trench_mate')->where('staff_id',$staff_id)->find();  
        }else{
            $data = '';
        }
        return $data;        
    }
    //渠道类型列表
    function getchannelclassToQqbbJSON($reason)
    {
        $limit = $reason['limit'] ? $reason['limit'] : 10;
        $page = $reason['page'] ? $reason['page'] : 1;
        $result['code'] = 0;
        $result['msg'] = '';
        $date = explode(' - ',$reason['search_cost_date']);
        $start = $date[0] ? $date[0]: date('Y-m-01');
        $end = $date[1] ? $date[1]: date('Y-m-d');
        $where = [];
        if($reason['channel_id']) $where['channel_name'] = ['in',$reason['channel_id']];
        if($reason['staffname']) $where['cost_staff'] = ['in',$reason['staffname']];//['in',implode(',',$reason['staffname'])];
        // if($reason['province_id']) $where['province_id'] = $reason['province_id'];
        if($reason['city_id']) $where['city_id'] = $reason['city_id'];
        if($reason['department_id']) $where['department_id'] = $reason['department_id'];

        $staffTrench = controller('crm/Setting','lib')->staffTrenchs(session('staff_id'));
        
        if($staffTrench['trench']){

            $arr_staffTrench = explode(",",trim($staffTrench['trench'],","));
            $where['channel_name'] = ["in",$arr_staffTrench];

            if($reason['channel_id']){
                $channel_id = explode(',',trim($reason['channel_id'],","));
                foreach($channel_id as $key=>$value){
                    if(!in_array($value,$arr_staffTrench)){
                        unset($channel_id[$key]);
                    }
                }    
                $where['channel_name'] = ["in",$channel_id];
            }
        }

        $res = db('crm_s_channel_cost')
            ->where('shop_code',session('shop_code'))->where($where)->where('cost_date','between',[$start,$end])
            ->order('cost_date desc')
            // ->page($page,$limit)
            ->select();

        $count = db('crm_s_channel_cost')->where('shop_code',session('shop_code'))->where($where)->where('cost_date','between',[$start,$end])->count();
        if($res){
            $starts = $start." 00:00:00";
            $ends = $end." 23:59:59";
            //毛客资
            $kezi = db('crm_c_customerinfo')
                ->where('c_from',1)
                ->where('is_status',1)
                ->where('dj_day','between',[$starts,$ends])
                ->where('add_shop_code','in',session('shop_code'))
                ->field("b_id,city_id,customer_channel,dj_staff,is_valid,dj_day,is_fp,yx_day")
                ->select();
            //有效客资
            // $kezi_y = db('crm_c_customerinfo')
            //     ->where('c_from',1)
            //     ->where('is_status',1)
            //     // ->where('yx_day','between',[$starts,$ends])
            //     ->where('dj_day','between',[$starts,$ends])
            //     ->where('add_shop_code','in',session('shop_code'))
            //     ->field("b_id,city_id,customer_channel,dj_staff,is_valid,yx_day")
            //     ->select();

            $result['kezi'] = db()->getLastSql();
            foreach ($res as $key => $value) {
                $res[$key]['cost'] = sprintf('%.2f',$value['cost']);
                if (!$value['city_name']) {
                    $res[$key]['city_name'] = '';
                }
                $res[$key]['kz'] = 0;
                $res[$key]['kz_youxiao'] = 0;
                $res[$key]['fp'] = 0;

                foreach ($kezi as $k => $v) {
                    if ($value['b_id'] == $v['b_id'] && $value['city_id'] == $v['city_id'] && $value['channel_name'] == $v['customer_channel'] && $value['cost_staff'] == $v['dj_staff'] && $value['cost_date'] == date("Y-m-d",strtotime($v['dj_day'])) && in_array($v['is_valid'], [1,2,3,4,5])) {
                        //客资量
                        $res[$key]['kz'] += 1; 
                    }

                    if ($value['b_id'] == $v['b_id'] && $value['city_id'] == $v['city_id'] && $value['channel_name'] == $v['customer_channel'] && $value['cost_staff'] == $v['dj_staff'] && $value['cost_date'] == date("Y-m-d",strtotime($v['dj_day'])) && in_array($v['is_valid'], [1,2,3,4,5]) && $v['is_fp'] == 1) {
                        //客资分配量
                        $res[$key]['fp'] += 1; 
                    }

                    if ($value['b_id'] == $v['b_id'] && $value['city_id'] == $v['city_id'] && $value['channel_name'] == $v['customer_channel'] && $value['cost_staff'] == $v['dj_staff'] && $value['cost_date'] == date("Y-m-d",strtotime($v['yx_day'])) && $v['is_valid'] == 1) {
                        //有效客资量
                        $res[$key]['kz_youxiao'] += 1;

                    }
                }
                // foreach ($kezi_y as $k => $v) {
                //     if ($value['b_id'] == $v['b_id'] && $value['city_id'] == $v['city_id'] && $value['channel_name'] == $v['customer_channel'] && $value['cost_staff'] == $v['dj_staff'] && $value['cost_date'] == date("Y-m-d",strtotime($v['yx_day'])) && $v['is_valid'] == 1) {
                //         //有效客资量
                //         $res[$key]['kz_youxiao'] += 1;

                //     }
                // }
            }
            foreach ($res as $key => $value) {
                //客资成本
                $res[$key]['kz_cb'] = sprintf('%.2f',$value['cost']/$value['kz']);
                //有效客资成本
                $res[$key]['kz_youxiao_cb'] = sprintf('%.2f',$value['cost']/$value['kz_youxiao']);
                //有效率
                // $res[$key]['yxl'] = (sprintf('%.2f',$value['kz_youxiao']/$value['kz'])*100)."%";
                //南宁 cc 定的规则 2021-05-19  有效率 = 客资分配量 / 客资量
                $res[$key]['yxl'] = (sprintf('%.2f',$value['fp']/$value['kz'])*100)."%";

                //合计
                $res['合计']['id'] = '';
                $res['合计']['department_name'] = '合计';
                $res['合计']['city_name'] = '';
                $res['合计']['cost'] += sprintf('%.2f',$value['cost']);
                $res['合计']['show_num'] += $value['show_num'];
                $res['合计']['click_num'] += $value['click_num'];
                $res['合计']['kz'] += $res[$key]['kz'];
                $res['合计']['fp'] += $res[$key]['fp'];
                $res['合计']['kz_youxiao'] += $res[$key]['kz_youxiao'];

            }

            //客资成本
            $res['合计']['kz_cb'] = sprintf('%.2f',$res['合计']['cost']/$res['合计']['kz']);
            //有效客资成本
            $res['合计']['kz_youxiao_cb'] = sprintf('%.2f',$res['合计']['cost']/$res['合计']['kz_youxiao']);
                //有效率
            $res['合计']['yxl'] = (sprintf('%.2f',$res['合计']['kz_youxiao']/$res['合计']['kz'])*100)."%";
            $result['data'] = $res;
            $result['count'] = $count;
        }else{
            $result['data'] = array();
        }
        return ($result);
    }

    function addQDTypeQqbb($channelclass){

        $data['staff_id']  = $channelclass['cost_staff_id'] ? $channelclass['cost_staff_id'] : session('staff_id');
        $data['cost_staff']= $channelclass['cost_staff'] ? $channelclass['cost_staff'] : session('staff_name');

        $data['cost_date'] = $channelclass['cost_date'];
        $data['cost'] = $channelclass['cost'];
        $data['province_id'] = $channelclass['province_id'];
        $data['province_name'] = $channelclass['province_name'];
        $data['city_id']   = $channelclass['city_id'];
        $data['city_name'] = $channelclass['city_name'];

        $data['department_id']   = $channelclass['department_id'] ? $channelclass['department_id'] : 0;
        $data['department_name'] = $channelclass['department_name'] ? $channelclass['department_name'] : null;
        $data['channel_id']   = $channelclass['channel_id'];
        $data['channel_name'] = $channelclass['channel_name'];
        $data['channel_class_id']   = $channelclass['channel_class_id'];
        $data['channel_class_name'] = $channelclass['channel_class_name'];
        $data['channel_info_id']    = $channelclass['channel_info_id'];
        $data['channel_info_name']  = $channelclass['channel_info_name'];
        
        $data['brandclass_id'] = session('brandclass_id');
        $data['shop_name'] = session('shop_name');
        $data['shop_code'] = session('shop_code');
        $data['setkey']    = session('setkey');
        $data['create_time'] = date('Y-m-d H:i:s',time());
        
        $data['b_id']   = $channelclass['b_id'];
        $data['b_name'] = $channelclass['b_name'];
        $data['show_num']  = $channelclass['show_num'];
        $data['click_num'] = $channelclass['click_num'];
        
        $data['subscribe_num'] = $channelclass['subscribe_num'];
        $data['private_num'] = $channelclass['private_num'];
        $data['effective_form'] = $channelclass['effective_form'];

        $res = db('crm_s_channel_cost')
            ->where('department_id',$data['department_id'])
            ->where('channel_id', $data['channel_id'])
            ->where('city_id',$data['city_id'])
            ->where('brandclass_id', session('brandclass_id'))
            ->where('cost_date', $data['cost_date'])
            ->where('b_id', $data['b_id'])
            ->find();
        if(!empty($data['city_id']) && $res['city_id'] == $data['city_id']){
            return array('code'=>100,'msg'=>'已存在'.$data['cost_date'].$data['department_id'].$data['channel_name'].$data['city_name'].$data['b_name'].'的花费，请重新添加');
        }

        $ip = \think\Request::instance()->ip();
        db()->startTrans();
        try{

            db('crm_s_channel_cost')->insertGetId($data);

            $new = '';
            $new .= '操作店面：'.$data['shop_name'].'<br/>';
            if($data['belong_shop_name'])$new .= '归属店：'.$data['belong_shop_name'].'<br/>';
            if($data['department_name'])$new .= '部门：'.$data['department_name'].'<br/>';
            if($data['city_name'])$new .= '市：'.$data['city_name'].'<br/>';
            if($data['b_name'])$new .= '品牌：'.$data['b_name'].'<br/>';
            $new .= '渠道：'.$data['channel_name'].'<br/>';
            $new .= '花费：'.$data['cost'].'<br/>';
            $new .= '展现量：'.$data['show_num'].'<br/>';
            $new .= '点击量：'.$data['click_num'].'<br/>';
            $new .= '日期：'.$data['cost_date'].'<br/>';

            $log = [];
            $log['module']     = 'crm';
            $log['controller'] = 'Setting';
            $log['action']     = 'addqdtype';
            $log['old_data']   = json_encode([]);
            $log['data'] = $new;
            $log['customer_id']= 0;
            $log['staff_name'] = session('staff_name');
            $log['staff_id']   = session('staff_id');
            $log['ip']         = $ip;
            $log['create_time']= $data['create_time'];

            db('action_log','db_logs')->insert($log);
            action_log($channelclass,'',0,session('staff_id'),session('staff_name'));
            cache('crm_channel_'.session('shop_code'),null);
            db()->commit();
            return  array('code'=>200,'msg'=>'','data'=>$data);
        }catch (Exception $e){
            db()->rollback();
            return  array('code'=>100,'msg'=>'渠道花费添加失败','data'=>$e->getMessage().db()->getLastSql());
        }
    }

    function editQDTypeQqbb($param){

        $param['department_id'] = $param['department_id'] ? $param['department_id'] : 0;
        if (param['department_name']) {
            $param['department_name'] = $param['department_name'] ? $param['department_name'] : null;
        }
        $param['city_id'] = $param['city_id'] ? $param['city_id'] : 0;
        $param['city_name'] = $param['city_name'] ? $param['city_name'] : null;
        $param['update_time'] = date('Y-m-d H:i:s',time());

        $res = db('crm_s_channel_cost')
            ->where('channel_id', $param['channel_id'])
            ->where('city_id', $param['city_id'])
            ->where('department_id',$param['department_id'])
            ->where('channel_class_id', $param['channel_class_id'])
            ->where('channel_info_id', $param['channel_info_id'])
            ->where('brandclass_id', session('brandclass_id'))
            ->where('b_id', $param['b_id'])
            ->where('id','<>',$param['id'])
            ->where('cost_date', $param['cost_date'])
            ->find();
        if(!empty($res) && $res['city_id'] == $param['city_id']){
            return array('code'=>100,'msg'=>'已存在此时间此渠道城市品牌的花费，请重新编辑');
        }
        // $days = cal_days_in_month(CAL_GREGORIAN, $param['month'], $param['year']);//当月天数
        // $param['cost_avg'] = round($param['cost']/$days,2);//平均每天花费
        db()->startTrans();
        try{
            $cinfo = db('crm_s_channel_cost')->where('id',$param['id'])->find();//原数据

            db('crm_s_channel_cost')->where('id',$param['id'])->update($param);

            $old = '';
            $old .= '操作店面：'.$cinfo['shop_name'].'<br/>';
            if($cinfo['department_name'])$old .= '部门：'.$cinfo['department_name'].'<br/>';
            if($cinfo['city_name'])$old .= '市：'.$cinfo['city_name'].'<br/>';
            $old .= '渠道：'.$cinfo['channel_name'].'<br/>';
            $old .= '花费：'.$cinfo['cost'].'<br/>';
            $old .= '日期：'.$cinfo['cost_date'].'<br/>';

            $new = '';
            $new .= '操作店面：'.$cinfo['shop_name'].'<br/>';
            if($param['department_name'])$new .= '部门：'.$param['department_name'].'<br/>';
            if($param['city_name'])$new .= '市：'.$param['city_name'].'<br/>';
            $new .= '渠道：'.$param['channel_name'].'<br/>';
            $new .= '花费：'.$param['cost'].'<br/>';
            $new .= '日期：'.$param['cost_date'].'<br/>';
            action_log($new, $old, session('staff_id'), 0, session('staff_name'));
            cache('crm_channel_'.session('shop_code'),null);
            cache('all_channel_'.session('shop_code'),null);
            db()->commit();

            return  array('code'=>200,'msg'=>'');
        }catch (Exception $e){
            db()->rollback();
            return  array('code'=>100,'msg'=>'渠道花费修改失败','data'=>$e->getMessage());
        }
    }

    //渠道充值列表
    function getchannelrechargeQqbbJSON($reason)
    {
        $limit = $reason['limit'] ? $reason['limit'] : 10;
        $page = $reason['page'] ? $reason['page'] : 1;
        $result['code'] = 0;
        $result['msg'] = '';
        $date = explode(' - ',$reason['search_time']);
        $start = $date[0] ? $date[0]: date('Y-m-01');
        $end = $date[1] ? $date[1]: date('Y-m-d');
        $where = [];

        if($reason['channel_id']) $where['channel_name'] = ['in',$reason['channel_id']];
        if($reason['staffname']) $where['add_staff_name'] = ['in',$reason['staffname']];//['in',implode(',',$reason['staffname'])];

        if($reason['city_id']) $where['city_id'] = $reason['city_id'];

        // $staffTrench = controller('crm/Setting','lib')->staffTrenchs(session('staff_id'));
        
        // if($staffTrench['trench']){

        //     $arr_staffTrench = explode(",",trim($staffTrench['trench'],","));
        //     $where['channel_name'] = ["in",$arr_staffTrench];

        //     if($reason['channel_id']){
        //         $channel_id = explode(',',trim($reason['channel_id'],","));
        //         foreach($channel_id as $key=>$value){
        //             if(!in_array($value,$arr_staffTrench)){
        //                 unset($channel_id[$key]);
        //             }
        //         }    
        //         $where['channel_name'] = ["in",$channel_id];
        //     }
        // }

        $res = db('crm_s_channel_recharge')
            ->where('shop_code',session('shop_code'))->where($where)->where('time','between',[$start,$end])
            ->order('channel_name asc,time desc')
            // ->page($page,$limit)
            ->select();
        $result['sql'] = db()->getlastsql();

        if(count($res) > 0){
            foreach ($res as $key => $value) {
                $res[$key]['add_staff_time'] = substr($value['add_staff_time'], 0,11);
                $res[$key]['update_staff_time'] = $value['update_staff_time']?substr($value['update_staff_time'], 0,11):'';
            }
        }

        $count = db('crm_s_channel_recharge')->where('shop_code',session('shop_code'))->where($where)->where('time','between',[$start,$end])->count();

        $result['data'] = $res;
        $result['count'] = $count;
        
        return ($result);
    }

    function addChannelRecharge($channelclass){
        $data['province_id'] = $channelclass['province_id'];
        $data['province_name'] = $channelclass['province_name'];
        $data['city_id']   = $channelclass['city_id'];
        $data['city_name'] = $channelclass['city_name'];

        $data['channel_id']   = $channelclass['channel_id'];
        $data['channel_name'] = $channelclass['channel_name'];
        // $data['channel_class_id']   = $channelclass['channel_class_id'];
        // $data['channel_class_name'] = $channelclass['channel_class_name'];
        $data['channel_info_id']    = $channelclass['channel_info_id'];
        $data['channel_info_name']  = $channelclass['channel_info_name'];
        
        $data['money'] = $channelclass['money'];
        $data['money_fd'] = $channelclass['money_fd'];
        $data['time'] = $channelclass['time'];

        $data['brandclass_id'] = session('brandclass_id');
        $data['shop_name'] = session('shop_name');
        $data['shop_code'] = session('shop_code');

        if ($channelclass['id']) {
            $data['update_staff_id']    = session('staff_id');
            $data['update_staff_name']    = session('staff_name');
            $data['update_staff_time'] = date('Y-m-d H:i:s',time());
        }else{
            $data['add_staff_id']    = session('staff_id');
            $data['add_staff_name']    = session('staff_name');
            $data['add_staff_time'] = date('Y-m-d H:i:s',time());
        }

        // $res = db('crm_s_channel_recharge')
        //     ->where('channel_id', $data['channel_id'])
        //     ->where('city_id',$data['city_id'])
        //     ->where('brandclass_id', session('brandclass_id'))
        //     ->find();
        // if(!empty($data['city_id']) && $res['city_id'] == $data['city_id']){
        //     return array('code'=>100,'msg'=>'已存在'.$data['channel_name'].'-'.$data['city_name'].'的渠道充值，请重新添加');
        // }

        $ip = \think\Request::instance()->ip();
        db()->startTrans();
        try{
            $old = '';
            if ($channelclass['id']) {
                $cinfo = db('crm_s_channel_recharge')->where("id",$channelclass['id'])->find();

                db('crm_s_channel_recharge')->where('id',$channelclass['id'])->update($data);

                $old .= '操作店面：'.$cinfo['shop_name'].'<br/>';
                $old .= '市：'.$cinfo['city_name'].'<br/>';
                $old .= '渠道：'.$cinfo['channel_name'].'<br/>';
                $old .= '充值金额：'.$cinfo['money'].'<br/>';
                $old .= '充值日期：'.$cinfo['time'].'<br/>';
            }else{
                db('crm_s_channel_recharge')->insertGetId($data);
            }

            $new = '';
            $new .= '操作店面：'.$data['shop_name'].'<br/>';
            $new .= '市：'.$data['city_name'].'<br/>';
            $new .= '渠道：'.$data['channel_name'].'<br/>';
            $new .= '充值金额：'.$data['money'].'<br/>';
            $new .= '充值日期：'.$data['time'].'<br/>';

            action_log($new,$old,0,session('staff_id'),session('staff_name'));

            db()->commit();
            return  array('code'=>200,'msg'=>'渠道充值操作成功','data'=>$data);
        }catch (Exception $e){
            db()->rollback();
            return  array('code'=>100,'msg'=>'渠道充值操作失败','data'=>$e->getMessage().db()->getLastSql());
        }
    }

    //删除渠道充值
    function delChannelRecharge($id){
        db()->startTrans();
        try{
            $cinfo = db('crm_s_channel_recharge')->where('id',$id)->find();
            db('crm_s_channel_recharge')->where('id',$id)->delete();

            action_log($id,'',0,session('staff_id'),session('staff_name'));

            db()->commit();
            return true;
        }catch (Exception $e){
            db()->rollback();
            return false;
        }

    }
    // -------------------------- 南宁定制 end ------------------------- //
}