<?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 getBrandList(){
        return db('CBrandclass')->order('id desc')->select();
    }
    //获取店面列表
    function getShopList($id = 0,$shop_name = ''){
        if($id){
            $result = db('CShopset')->where('id','<>',$id)->order('id desc')->select();
        }else{
            if($shop_name){
                $result = db('CShopset')->where('shop_name',''%'.','%'.$shop_name.'%')->order('id desc')->select();
            }else{
                $result = db('CShopset')->order('id desc')->select();
            }
        }
        return $result;
    }
    function  getShopListByFP(){
        $result = db('CShopset')->order('id desc')->select();
        return $result;
    }
    //获取店面列表
    function getShopListCount($id = 0,$shop_name = ''){
        if($id){
            $result = db('CShopset')->where('id','<>',$id)->order('id desc')->count();
        }else{
            if($shop_name){
                $result = db('CShopset')->where('shop_name','like','%'.$shop_name.'%')->order('id desc')->count();
            }else{
                $result = db('CShopset')->order('id desc')->count();
            }
        }
        return $result;
    }
    //获取店面列表接口
    function getStoreJson($shop_name = ''){
        $result['code'] = 0;
        $result['msg'] = '';
        if($shop_name){
            $result['count'] = db('CShopset')->where('shop_code',session('shop_code'))->where('shop_name','like','%'.$shop_name.'%')->field('id,brandclass,shop_name,shop_code,sn,numberorder,shopaddress,receiv_shop_code')->order('id desc')->count();
            $result['data'] = db('CShopset')->where('shop_code',session('shop_code'))->where('shop_name','like','%'.$shop_name.'%')->order('id desc')->select();
        }else{
            $result['count'] = db('CShopset')->order('id desc')->count();
            $result['data'] = db('CShopset')->field('id,brandclass,shop_name,shop_code,sn,numberorder,shopaddress,receiv_shop_code')->order('id desc')->select();
        }
        return(($result)) ;
    }
    function setStore($params){
        $db = db('CShopset');
        $db->insert($params);
        $id = $db->getLastInsID();
        $db->startTrans();
        if($id){
            action_log($params,'',0,session('staff_id'),session('staff_name'));
            $db->commit();
            return $id;
        }else{
            $db->rollback();
            $res = array('error'=>1,'code'=>400,'msg'=>'店面设置有误！');
            return $res;
        }
    }
    function remindList1(){
        $res = db('SReminditemset')->where('brandclass_id',session('brandclass_id'))->where('id','remind1')->find();
        if($res){
            return $res;
        }else{
            return false;
        }
    }
    function remindList2(){
        $res = db('SReminditemset')->where('brandclass_id',session('brandclass_id'))->where('id','remind2')->find();
        if($res){
            return $res;
        }else{
            return false;
        }
    }
    function remindList3(){
        $res = db('SReminditemset')->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('SReminditemset')->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('SReminditemset')->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('SReminditemset')->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('SReminditemset')->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('SReminditemset');
        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 getShopSN($code){
        $res = db('CShopset')->where('receiv_shop_code','in',$code)->field('sn')->select();
        return implode(',',array_column($res, 'sn'));
    }
    function updateStore($param){
        $db = db('CShopset');
        $db->startTrans();
        $res = $db->where('id',$param['id'])->update($param);
        if($res){
            action_log($param,'',0,session('staff_id'),session('staff_name'));
            $db->commit();
            return $res;
        }else{
            $db->rollback();
            return false;
        }

    }
    function delStore($id){
        $db = db('CShopset');
        $db->startTrans();
        $res = $db->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 editStore($id){
        $db = db('CShopset');
        $db->startTrans();
        $res = $db->where('id',$id)->find();
        if($res === false){
            $db->rollback();
            return false;
        }else{
            action_log($id,'',0,session('staff_id'),session('staff_name'));
            $db->commit();
            return ($res);
        }
    }
    function getKPIList(){
        $tar = new \app\crm\lib\Target();
        return $tar->getAllTarget();
    }
    function setGoal($param){
        $param['flag'] = $param['flag'] ? $param['flag'] : 'brandclass';
        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('SKpiStaffgoal')
                ->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('SKpiStaffgoal')
                ->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' =>  session('shop_name'),
            'shop_code' =>  session('shop_code'),
            'setkey' =>  session('setkey'),
            'brandclass_id' =>  session('brandclass_id'),
            'brandclass' =>  session('brandclass'),
        );
        db()->startTrans();
        db('SKpiStaffgoal')->insert($data);
        $res = db('SKpiStaffgoal')->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(check_right('menu1512637269')){
                $result['data'] = db('SKpiStaffgoal')->where('shop_code',session('shop_code'))->where($where)->page($page,$limit)->order('order_sort')->select();
                $result['count'] = db('SKpiStaffgoal')->where('shop_code',session('shop_code'))->where($where)->count();
        }elseif(check_right('menu1531471639')){//部门权限
                $result['data'] = db('SKpiStaffgoal')->where('shop_code',session('shop_code'))->where($where)->page($page,$limit)->order('order_sort')->select();
                $result['count'] = db('SKpiStaffgoal')->where('shop_code',session('shop_code'))->where($where)->count();
        }elseif(check_right('menu1529653231')){
                $result['data'] = db('SKpiStaffgoal')->where('shop_code',session('shop_code'))->where($where)->where('group_id','>',0)->page($page,$limit)->order('order_sort')->select();
                $result['count'] = db('SKpiStaffgoal')->where('shop_code',session('shop_code'))->where($where)->where('group_id','>',0)->count();
        }else{
                $result['data'] = db('SKpiStaffgoal')->where('shop_code',session('shop_code'))->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('SKpiStaffgoal')->where('shop_code',session('shop_code'))->where($where)->where('staff_id > 0 position_code<>""')->count();
        }
        return ($result);
    }
    function updateGoal($param){
        $param['flag'] = $param['flag'] ? $param['flag'] : 'brandclass';
        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('SKpiStaffgoal')
            ->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('SKpiStaffgoal');
        $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('SKpiStaffgoal')->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('SKpiStaffgoal')->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()
    {
//        $brandclass_list = session('brandclass_list');
//        if(empty($detail)){
            $url = "5a44c4782c1b6";
            $res = sx_call($url, '');
            if ($res['code'] == 200) {
                $info = $res['data'];
//                session('brandclass_list',$info);
                return $info;
            }
//        }else {
//                return $brandclass_list;
//        }
    }

    //部门列表
    function department_list($data){
        $url = '5a0aef152b750';
        $res = sx_call($url,$data);
        if($res['code'] == 200){
            return $res['data'];
        }else{
            return [];
        }
    }
    //岗位下的人员
    function positionStaffs($data){
        $url = '5a19201a33c20';
        $data['get_leave']  = 2;
        $res = sx_call($url,$data);
        if($res['code'] == 200){
            return $res['data'];
        }else{
            return false;
        }
    }

    //部门列表
    function get_department_list($param){
        // $res = db('SDepartmentinfo')->where('gradeType',4)->where('shop_code',session('shop_code'))->field('id,department_name')->select();
        $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;
        }
    }
    
    // 获取 部门 岗位 组 员工
    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));
    }
    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));
    }
    function getGroupList($param){
        $shop_code = $param['shop_code'] ? $param['shop_code'] : session('shop_code');
        $res = db('CStaffGroup')->where('shop_code',$shop_code)->select();
        return $res;
    }
    function getStaffList($param){
        $url = '59ff2d5de2cb6';
        return sx_call($url,'');
    }

    function delFPSet($id){
        $db = db('SAllocationRule');
        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('SAllocationRule')->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('SAllocationRule')->where('id',$param['id'])->update($data1);
                db('SAllocationRule')->where('id',$param['id'])->update($data);

            }else{
                db('SAllocationRule')->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('SAllocationRule')->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('SAllocationRule')->where('id',$param['id'])->update(array('order_sort'=>9998));
            }else{
                $res = db('SAllocationRule')->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('SAllocationRule')->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('SAllocationRule')->where('id',$param['id'])->update(array('order_sort'=>0));
            }else{
                $res = db('SAllocationRule')->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){
        // var_dump($param);die;
        // 如果是默认顺序或者登录时间顺序 业绩算法和时间区间为空
        if($param['allocationtype'] == 0 || $param['allocationtype'] == 2){
            $param['allocationtype_value'] = '';
            $param['active_time'] = '';
        }
        // 客资录入第一步条件
        // if ($param['customer_condition'] == 'customer_channel') {
        if ($param['customer_condition'] != 'default') {
            // $channel_ids = explode(',',$param['customer_value']);
            // $channel_ids = array_unique($channel_ids);
            $param['customer_value'] = implode($param['customer_value'],',');
        }
        // var_dump($param['customer_value']);die;
        // 第三步 如果是根据 员工分配
        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];
            }*/
            foreach ($param['staffs'] as $key => $value) {
                $staff_value[$key]['staff_id'] = $value['staff_id'];
                $staff_value[$key]['staff_name'] = $value['staff_name'];
            }
        }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']);
            foreach ($param['gids'] as $key => $value) {
                $staff_value[$key]['group_id'] = $value;
                $staff_value[$key]['group_name'] = db('c_staff_group')->where('id',$value)->value('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']);
        }
        // 接收客资的员工，自然排序及客资接收上限
        $fp_staffs = json_encode($param['staffs']);

        $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,
            'fp_staffs'   => $fp_staffs,
            '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('SAllocationRule')
                    ->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('SAllocationRule')
                    ->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'=>'已存在此类型的分配规则，请重新选择','sql'=>db()->getLastSql());
            }
            $res = db('SAllocationRule')->where('id','=',$param['id'])->update($data);
        }else{//添加
            if($data['customer_condition'] != 'default'){
                $info = db('SAllocationRule')
                    ->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('SAllocationRule')
                    ->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('SAllocationRule')->insert($data);
            $res = db('SAllocationRule')->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('id'=>''));
        return $res['data'];
    }
    //渠道名
    function getChannelInfo($channelclass){
        $url = '59fd5e729e5a8';
        $res = sx_call($url,array('channelclass'=>$channelclass));
        return $res['data'];
    }
    //渠道名
    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)';
        return db('s_channel')->where('shop_code',$shopCode)->order('order_sort asc')->select();
    }
    //人员渠道表查询
    function staffTrench($shopCode = ''){
        $shopCode = $shopCode?$shopCode:session('shop_code');
        return db('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('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('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('c_staff_trench_mate')->insert($datas);
        }
        return $ros;
    }
    //来源
    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'];
    }
    //分区
    function getcustomer_area(){
        $url = '5a004e9c3e030';
        $res = sx_call($url,array('shop_code'=>session('shop_code')));
        return $res['data'];
    }
    //地域
    function getcustomer_region(){
        $url = '59fd5fa926b98';
        $res = sx_call($url,array('shop_code'=>session('shop_code')));
        return $res['data'];
    }
    //渠道名称
    function getQudaoInfo($channelclass){
        $res = db('SChannelinfo')->where('shop_code','=',session('shop_code'))->where('channelclass',$channelclass)->field('id,channelclass,channel_name')->select();
        return $res;
    }
    function getShopChannelListById($channelId){

        $res = db('s_channel s')->field('s.*')->join('s_channel ss ','s.id = ss.id')->where('ss.id',$channelId)->select();
        return $res;
    }

    //人员
    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('SAllocationRule')->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('SAllocationRule')->where('shop_code|belong_shop_code',$shopCode)->count();

        // $res = db('SAllocationRule')->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('SAllocationRule')->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('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('SFileReason')->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('SFileReason')->insert($data);
        if(db('SFileReason')->getLastInsID()){
            db()->commit();
            action_log($param,'',0,session('staff_id'),session('staff_name'));
            return db('SFileReason')->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('s_reject_reason')->insert($data);
        if(db('s_reject_reason')->getLastInsID()){
            db()->commit();
            action_log($param,'',0,session('staff_id'),session('staff_name'));
            return db('s_reject_reason')->getLastInsID();
        }else{
            db()->rollback();
            return false;
        }
    }
    //微信模板
    function getWXModalToJSON($wx_template_name)
    {
        $result['code'] = 0;
        $result['msg'] = '';
        $res = db('SWxTemplateModel')->where('shop_code',session('shop_code'))->where('wx_template_name','like','%'.$wx_template_name.'%')->field('id,wx_template_name,wx_template_title,wx_template_content,status')->select();
        $count = db('SWxTemplateModel')->where('shop_code',session('shop_code'))->where('wx_template_name','like','%'.$wx_template_name.'%')->count();
        if($res){
            $result['data'] = $res;
            $result['count'] = $count;
        }else{
            $result['data'] = array();
        }
        return ($result);
    }
    //短信模板
    function getModalToJSON($mtemplate_name)
    {
        $result['code'] = 0;
        $result['msg'] = '';
        $res = db('SMessageTemplateinfo')->where('shop_code',session('shop_code'))->where('mtemplate_name','like','%'.$mtemplate_name.'%')->field('id,mtemplate_name,mtemplate_content,status')->select();
        $count = db('SMessageTemplateinfo')->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('SMessageTemplateinfo')->insert($param);
        $id = db('SMessageTemplateinfo')->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('SMessageTemplateinfo')->where('id',$id)->find();
        if($res){
            return $res;
        }else{
            return false;
        }
    }
    //微信模板增加
    function addWXModal($param){
        $param['shop_name'] = session('shop_name');
        $param['shop_code'] = session('shop_code');
        $param['setkey'] = session('setkey');
        db()->startTrans();
        db('SWxTemplateModel')->insert($param);
        $id = db('SWxTemplateModel')->getLastInsID();
        if($id){
            db()->commit();
            action_log($param,'',0,session('staff_id'),session('staff_name'));
            return true;
        }else{
            db()->rollback();
            return false;
        }
    }
    function editMModal($param){
        db()->startTrans();
        $res = db('SMessageTemplateinfo')->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 editWXModal($param){
        db()->startTrans();
        $res = db('SWxTemplateModel')->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('SMessageTemplateinfo')->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 delWXModal($id){
        db()->startTrans();
        $res = db('SWxTemplateModel')->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'] = '';
        $where['shop_code'] = session('shop_code');
        if($reason) $where['reason'] = ['like','%'.$reason.'%'];
        $res = db('SFileReason')->where($where)->select();
        $count = db('SFileReason')->where($where)->count();
        if($res){
            $result['data'] = $res;
            $result['count'] = $count;
        }else{
            $result['data'] = array();
        }
        return ($result);
    }
    //追踪失败原因
    function getRejectReasonToJSON($reason)
    {
        $result['code'] = 0;
        $result['msg'] = '';
        $where['shop_code'] = session('shop_code');
        if($reason) $where['reason'] = ['like','%'.$reason.'%'];
        $res = db('s_reject_reason')->where($where)->select();
        $count = db('s_reject_reason')->where($where)->count();
        if($res){
            $result['data'] = $res;
            $result['count'] = $count;
        }else{
            $result['data'] = array();
        }
        return ($result);
    }
    function editWalkFlow($param){
        $info = db('SSalesRoutines')->where('id',$param['id'])->find();
        db()->startTrans();
        $res = db('SSalesRoutines')->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('SSalesRoutines')->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('SSalesRoutines')->where('shop_code',session('shop_code'))->column('id,step_name,step_content,step_stage');
        $count = db('SSalesRoutines')->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('SSalesRoutines')->insert($param);
        if(db('SSalesRoutines')->getLastInsID()){
            db()->commit();
            action_log($param,'',0,session('staff_id'),session('staff_name'));
            return db('SSalesRoutines')->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('SChannelCost')->where('shop_code',session('shop_code'))->where($where)->where('cost_date','between',[$start,$end])->order('cost_date desc')->page($page,$limit)->select();
        $count = db('SChannelCost')->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('SChannelCostReturn')->where('shop_code',session('shop_code'))->where($where)->where('return_month','like','%'.$reason['search_return'].'%')->page($page)->limit($limit)->select();
        $count = db('SChannelCostReturn')->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);
    }
    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('s_shop_address')->where('id',$v)->where('shop_code',session('shop_code'))->value('name');
            $res = db('SChannelCost')->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('s_shop_address')->where('id',$v)->where('shop_code',session('shop_code'))->value('name');
                $data['cost'] = $costs[$k];
                db('SChannelCost')->insert($data);
                $id = db('SChannelCost')->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('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('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('c_customer_cost')->where('id',$info['id'])->update($ins);
                        }
                    }
                }
            }
            db('action_log','db_logs')->insertAll($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 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('SChannelCostReturn')
            ->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'],'province_id'=>$channelclass['province_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('SChannelCostReturn')->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('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('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('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('SChannelCostReturn')->where('id',$id)->find();
        try{
            $res = db('SChannelCostReturn')->where('id',$id)->delete();
            db('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('SChannelCost')->where('id',$id)->find();
            db('SChannelCost')->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('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('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);
            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('SChannelCost')
            ->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('SChannelCost')->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('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('c_customer_cost')->where('id',$csinfo['id'])->delete();
                }
            }
            $res = db('SChannelCost')->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('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('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('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/>';
            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['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);
            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'));
        $res = db('SChannelCost')->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('SChannelCostReturn')->where('return_month',$param['return_month'])->where(array('channel_id'=>$param['channel_id'],'region_id'=>$param['region_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'],'region_id'=>$param['region_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']));

        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('SChannelCostReturn')->where('id',$param['id'])->find();
        try{
            db('SChannelCostReturn')->where('id',$param['id'])->update($param);
                if(($info['region_id'] == $param['region_id']) && ($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('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('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('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('SFileReason')->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('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('SFileReason')->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('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 getPostitionList(){
        $res = db('SPositionset')->where('gradeType',4)->select();
        if($res){
            return $res;
        }else{
            return false;
        }
    }
    function getTuCount(){
        $res = db('SStaffAbility')->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('SAllocationRule')->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('code'=>100,'msg'=>'开始结束时间或过期时间为空，不能开启自动');
                    return $arr;
                }
            }else{
                $arr = array('code'=>101,'msg'=>'没有默认规则，不能开启自动');
                return $arr;
            }
        }
        db()->startTrans();
        try {
            $res = db_config('fp_switch_'.session('shop_code'),$value);
            action_log($fpTime,$val,0,session('staff_id'),session('staff_name'));
            db()->commit();
            $arr = array('code'=>200,'msg'=>'操作成功');
        } catch (\Exception $e) {
            db()->rollback();
            $arr = array('code'=>102,'msg'=>'操作失败','error'=>$e->getMessage());
        }
        
        return $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('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'));
        }
    }
    // 无小组人员
    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;
        }
    }
    //查看是否是小组管理员
    function isGroupAdmin(){
        return db('CStaffGroupRelation')->where('staff_id',session('staff_id'))->field('is_admin')->find();
    }
    //查看有无小组
    function isGroupStaff(){
        return db('CStaffGroupRelation')->where('staff_id',session('staff_id'))->field('group_id')->find();
    }
    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;
    }
    //小组内所有人员
    function getInGroupStaffInfo($id){
        $info = db('CStaffGroupRelation')->where('group_id',$id)->column('*','staff_id');
        $ar = array();
        foreach($info as $ke=>$va){
            array_push($ar,$va['staff_id']);
        }
        $ids = implode(',',$ar);
        //请求接口，通过id获取名字 20200312
        $mc = new \app\common\lib\mcInterface();
        $arrStaff = array('staff_id'=>$ids);
        $staffList = $mc->getStaffByIds($arrStaff);

        $return = [];
        foreach ($staffList as $k => $v) {
            $temp['id'] = $v['id'];
            $temp['staffname'] = $v['staffname'];
            $temp['staffnumber'] = $v['staffnumber'];
            $temp['is_admin'] = $info[$v['id']]['is_admin'];
            array_push($return, $temp);
        }
        return $return;
    }
    //添加或编辑小组
    function addGroup($param){
        if($param['id']){//编辑
            db()->startTrans();
            try{
                $gid = $param['id'];
                // 更新小组表信息
                $updateGroup['group_name'] = $param['group_name'];
                $updateGroup['department_id'] = $param['department_id'];
                $updateGroup['department_name'] = $param['department_name'];
                $updateGroup['create_staff_id'] = $param['create_staff_id'];
                $updateGroup['create_staff_name'] = $param['create_staff_name'];
                $updateGroup['admin'] = $param['admin'];
                db('c_staff_group')->where('id',$gid)->update($updateGroup);
                // 删除小组所有人员
                db('c_staff_group_relation')->where('group_id',$gid)->delete();

                if(!$param['member']){
                    db('c_staff_group_relation')->insert(array('group_id'=>$gid,'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['member'].','.$param['create_staff_id'];
                
                    // 请求接口，通过id获取名字 20200312
                    $mc = new \app\common\lib\mcInterface();
                    $arrStaff = array('staff_id'=>$member);
                    $staffList = $mc->getStaffByIds($arrStaff);

                    $data = [];
                    foreach($staffList as $k => $v){
                        $tmpData = [
                            'group_id'=>$gid,
                            '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'=>300,'msg'=>'编辑小组失败，已回滚'.$e->getMessage());
                return json($js);
            }
        }else{//添加
            // 写入小组信息表
            $inGroupData['group_name'] = $param['group_name'];
            $inGroupData['department_id'] = $param['department_id'];
            $inGroupData['department_name'] = $param['department_name'];
            $inGroupData['create_staff_id'] = $param['create_staff_id'];
            $inGroupData['create_staff_name'] = $param['create_staff_name'];
            $inGroupData['shop_name'] = session('shop_name');
            $inGroupData['shop_code'] = session('shop_code');
            $inGroupData['admin'] = $param['admin'];
            $inGroupData['create_time'] = date('Y-m-d H:i:s',time());
            db()->startTrans();
            try{
                $gid = db('c_staff_group')->insertGetId($inGroupData);
                // 如果没有选择小组人员，则组内只有组长一人
                if(!$param['member']){
                    db('c_staff_group_relation')->insert(array('group_id'=>$gid,'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['member'].','.$param['create_staff_id'];
                
                    // 请求接口，通过id获取名字 20200312
                    $mc = new \app\common\lib\mcInterface();
                    $arrStaff = array('staff_id'=>$member);
                    $staffList = $mc->getStaffByIds($arrStaff);

                    $data = [];
                    foreach($staffList as $k => $v){
                        $tmpData = [
                            'group_id'=>$gid,
                            '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('SStaffAbility')->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('SStaffAbility')->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('SStaffAbility')->where('id',$param['id'])->update($data);
            }else{
                //查询此岗位本时间段是否有设定
                $info = db('SStaffAbility')->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('SStaffAbility')->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('SStaffAbility')->select();
        $res['abilityItem'] = explode(',',$res);
        return $res;
    }
    function getAbility($param){
        $res = db('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('s_staff_ability')->where('shop_code',session('shop_code'))->page($page,$limit)->select();
        $count = db('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('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('STelremark')->insert($param);
        $id = db('STelremark')->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('STelremark')->select();
        if($res){
            return $res;
        }else{
            return false;
        }
    }
    function  gettrackingKmarkerList(){
        $res = cache('tracksign_'.session('shop_code'));
        if(empty($res)){
            $res = db('STracksign')->where('shop_code',session('shop_code'))->where('is_delete',1)->select();
            cache('tracksign_'.session('shop_code'),$res,60*60*2);
        }

        if($res){
            return $res;
        }else{
            return false;
        }
    }

    //客资标记设定
    function addtrackingKmarker($param){
        $param['shop_name'] = session('shop_name');
        $param['shop_code'] = session('shop_code');
        $param['setkey'] = session('setkey');
        $param['tracksign'] = strtoupper($param['tracksign']);
        $param['customer_valid'] = (int)$param['customer_valid'];
        if(empty($param['tracksign'])){
            return array('code'=>400,'msg'=>'标记不可为空，请更改');
        }
        if(strtoupper($param['sign_color']) == 'FFFFFF'){
            $param['sign_color'] = NULL;
        }
        //判断是否重复
        $info = db('STracksign')->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('STracksign')->insert($param);
        action_log($param,'',0,session('staff_id'),session('staff_name'));
        $id = db('STracksign')->getLastInsID();
        if($id){
            db()->commit();
            return array('code'=>200,'msg'=>'标记设置成功');
        }else{
            db()->rollback();
            return array('code'=>300,'msg'=>'标记设置失败');
        }
    }
    //电访备注
    function getTelphoneRemarkToJSON($telremark)
    {
        $result['code'] = 0;
        $result['msg'] = '';
        $res = db('STelremark')->where('shop_code',session('shop_code'))->where('telremark','like','%'.$telremark.'%')->select();
        $count = db('STelremark')->where('shop_code',session('shop_code'))->where('telremark','like','%'.$telremark.'%')->count();
        if($res){
            $result['data'] = $res;
            $result['count'] = $count;
        }else{
            $result['data'] = array();
        }
        return ($result);
    }
    //客户标记
    function getTrackingKmarkerToJSON($tracksign)
    {
        $result['code'] = 0;
        $result['msg'] = '';
        $res = db('STracksign')->where('shop_code',session('shop_code'))->where('is_delete',1)->where('tracksign','like','%'.$tracksign.'%')->select();
        foreach ($res as $key => $value) {
            $res[$key]['customer_valid'] = getIsValidAttr($value['customer_valid']);
        }
        $count = db('STracksign')->where('shop_code',session('shop_code'))->where('is_delete',1)->where('tracksign','like','%'.$tracksign.'%')->count();
        if($res){
            $result['data'] = $res;
            $result['count'] = $count;
        }else{
            $result['data'] = array();
        }
        return ($result);
    }
    function deltelphoneRemark($id){
        db()->startTrans();
        $res = db('STelremark')->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 edittelphoneRemark($param){
        db()->startTrans();
        $info = db('STelremark')->where(array('id'=>$param['id']))->find();
        $res = db('STelremark')->where(array('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 deledittrackingKmarker($id){
        $arr = config('signA');
        $ids = array_values($arr);
        if(in_array($id,$ids)){
            return array('code'=>500,'msg'=>'此标记是A客标记,不能删除!');
        }
        db()->startTrans();
        $res = db('STracksign')->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('s_markset')->where('shop_code',session('shop_code'))->where('mark_color','not null')->find();
        // if(!empty($sign)){
        //     return array('code'=>102,'msg'=>'追踪标记已设置颜色，请先去清除！');
        // }
        //判断是否重复
        $info = db('STracksign')->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('STracksign')->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('s_allocationRule')->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('SMenu')->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('SMenu')->where('menu_name','like','%'.$param['menu_name'].'%')
            ->order('sort asc')
            // ->page($page,$limit)
            ->select();
        $count = db('SMenu')->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('SMenu')->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('SMenu')->insert($param);
            $id = db('SMenu')->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('SMenu')->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('SMenu')->where('fid',$id)->find();
        if($data){
            $this->error('此菜单存在子菜单，请清空子菜单再操作', '/');
        }else{
            $res = db('SMenu')->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);
        if ($res['code'] == 200) {
            $shopList = $res['data'];
            foreach($shopList as $k=>$v){
                if($v['is_marketing']==2){
                    unset($shopList[$k]);
                }else{
                    $shopList[$k]['setting'] = db('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(){
    //     $permission=db('SMenu')->order('sort')->where('status', '<>', '99')->select();
    //     $report = db('s_report_form')->alias('f')
    //         ->join('s_report_detail d','f.id=d.form_id','left')
    //         ->where('f.status',2)
    //         ->group('d.form_id')
    //         ->field('ifnull(d.id,0)+'.REPORT_ID.' as id,f.report_name as menu_name,5 as fid,f.code as menu_code,f.report_url as menu_url,"" as menu_icon,0 as status,0 as sort')
    //         ->select();
    //     // echo db()->getLastSql();die;
    //     $permissions = array_merge($permission,$report);
    //     // var_dump($report);
    //     // var_dump($permissions);die;
    //     foreach($permissions as $k => $v){
    //         $permissions[$k]['text']=$v['menu_name'];
    //     }

    //     $fid=0;
    //     $res=treeData($permissions,$fid);
    //     echo json_encode($res);
    // }

    //获取 岗位 权限
    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('s_position_menu')->where('position_code',$params['position_code'])->find();

            $allow = explode(',',$data['menu_code']);
        }
        return $allow;
    }
    /**
     * 根据目录树，获取所有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 authorise($params){

        //检验所授予权限是否在自己所拥有权限内
        if(!check_right('menu1512029925')){
            $this->error('您没有权限，不可给岗位授权','/');
        }

        $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);
            $menu_name = [];
            foreach ($ros as $key => $value) {
                //权限 名称
                $menu_name[$value['menu_code']] = $value['menu_name'];
            }
            //自身权限
            $data_menu=db('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']);
        // foreach ($codes as $key => $value) {
        //     if($value == 'menu1640831173'){
        //         array_push($codes,"menu1640831174","menu1640831175","menu1640831176","menu1640831177","menu1640831178","menu1640831179","menu1640831180","menu1640831181","menu1640831182","menu1640831183","menu1640831184","menu1640831185","menu1640831186","menu1640831187");
        //     }
        //     if($value == 'menu1640831188'){
        //         array_push($codes,"menu1640831189","menu1640831190","menu1640831191","menu1640831192","menu1640831193");
        //     }
        // }
        if($params['position_code']){
            $detail['position_code']=$params['position_code'];
            $detail['menu_code']=implode(',',$codes);
            try{
                db()->startTrans();
                if(db('s_position_menu')->where('position_code',$params['position_code'])->find()){
                    $res=db('s_position_menu')->where('position_code',$params['position_code'])->update($detail);
                }else{
                    $res=db('s_position_menu')->insert($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('不可修改自己的权限','/');
        }
        /*// $auth=getAuth($type='auth');
        $auth = session('crm_auth');
        $menuList=cache('CRM_menuAll');
        foreach ($menuList as $k=>$menuInfo){
            if(!in_array($menuInfo['id'], explode(',',$params['id']))){
                unset($menuList[$k]);
            }
        }
        foreach($menuList as $k=>$v){
            //print_r($menuData[$v['id']]['menu_name']);print_r(array_column($auth,'id'));die;
            if(!in_array($v['id'],array_column($auth,'id'))) {
                $this->error('您没有“'.$v['menu_name'].'”的权限，不能授予岗位此权限','/');
            }
        }

        $data=db('SMenu')->where('id','in',$params['id'])->select();
        if($params['position_code']){
            // 查看当前岗位所有的报表权限
            $where = " FIND_IN_SET('".$params['position_code']."',report_auth)";
            // $isInReport = db('s_report_detail')->where($where)->column('report_auth','id');

            $isInReport = db('s_menu')->alias('m')
                ->join('s_report_form f','m.menu_code=f.code','left')
                ->join('s_report_detail d','d.form_id=f.id','left')
                ->where($where)->column('report_auth','m.id');
            
            // 将menu_id里的报表id取出来
            $report = explode(',',$params['id']);
            $reportId = [];
            foreach ($report as $key => $value) {
                if ($value>REPORT_ID && $value<REPORT_ID_END) {
                    array_push($reportId, $value);
                }
            }
            // 循环需要设定的报表id
            foreach ($reportId as $key => $value) {
                // 如果之前没有设定 （新增）
                if (!in_array($value, $isInReport)) {
                    $did = db('s_menu')->alias('m')
                        ->join('s_report_form f','m.menu_code=f.code','left')
                        ->join('s_report_detail d','d.form_id=f.id','left')
                        ->where('m.id',$value)->value('d.id');
                    $report_auth = db('s_report_detail')->where('id',$did)->value('report_auth');
                    if ($report_auth) {
                        $nowRepAuth = trim($report_auth,',').','.$params['position_code'];
                    }else{
                        $nowRepAuth = $params['position_code'];
                    }
                    db('s_report_detail')->where('id',$did)->update(array('report_auth'=>$nowRepAuth) );
                }
            }
            // var_dump($reportId);
            // 循环岗位下所有的报表
            foreach ($isInReport as $key => $value) {
                // 如果岗位下的报表权限不在设定的id里（删除）                
                if (!in_array($key,$reportId)) {
                    $report_auth = str_replace($params['position_code'],'',$value);
                    $did = db('s_menu')->alias('m')
                        ->join('s_report_form f','m.menu_code=f.code','left')
                        ->join('s_report_detail d','d.form_id=f.id','left')
                        ->where('m.id',$key)->value('d.id');
                    db('s_report_detail')->where('id',$did)->update(array('report_auth'=>$report_auth));
                }
            }
            // die;
            $detail['position_code']=$params['position_code'];
            $detail['menu_code']=implode(',',array_column($data,'menu_code'));
            if(db('s_position_menu')->where('position_code',$params['position_code'])->find()){
                $res=db('s_position_menu')->where('position_code',$params['position_code'])->update($detail);
            }else{
                $res=db('s_position_menu')->insert($detail);
            }

            if($res===false){
                $this->error('授权失败', '/');
            }else{
                action_log($params,'',0,session('staff_id'),session('staff_name'));
                cache('CRM_menu_'.$params['position_code'],null);
                $this->success('授权成功','/');
            }
        }else{
            $this->error('不可修改自己的权限','/');
        }*/
    }

    //根据岗位查询其功能权限
    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('s_menu')->select();
            $result['auth_admin']=1;
        }else{
            $data=db('s_position_menu')->where('position_code',$position_code)->find();
            $menu=db('s_menu')->where('menu_code','in',$data['menu_code'])->select();
            // 20200417
            $report = db('s_report_form')->alias('f')
                ->join('s_report_detail d','f.id=d.form_id','left')
                ->where('f.status',2)
                ->where('d.report_auth','like','%'.$position_code.'%')
                ->group('d.form_id')
                ->field('d.id+'.REPORT_ID.' as id,f.report_name as menu_name,5 as fid,f.code as menu_code,f.report_url as menu_url,"" as menu_icon,0 as status,0 as sort')
                ->select();
            $menus = array_merge($menu,$report);
        }
        $result['menu_id']=array_column($menus,'id');
        $this->success('查询成功','/',$result);
    }

    //提醒快捷开关
    public function remindSwitch($param){
        $count = db('SReminditemset')->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('SReminditemset')->insert($param);
        }else{
            $res = db('SReminditemset')->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('s_allocation_rule')->where('id',$id)->where('shop_code',session('shop_code'))->find();
        return $res;
    }
    //获取追踪标记
    public function getMark($id,$field='*'){
        $res = db('s_markset')->field($field)->where('shop_code',session('shop_code'))->where('id',$id)->find();
        return $res;
    }
    //获取客资标记
    public function getSign($id,$field='*'){
        $res = db('s_tracksign')->field($field)->where('shop_code',session('shop_code'))->where('id',$id)->find();
        return $res;
    }
    //获取追踪标记 是否已录入颜色
    public function getMarkColor(){
        $res = db('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('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('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 getMarkToJSON($param){
        $result['code'] = 0;
        $result['msg'] = '';
        if($param['mark_name']){
            $result['count'] = db('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('s_markset')->where('shop_code',session('shop_code'))->where('mark_name','like','%'.$param['mark_name'].'%')->order('id desc')->select();
        }else{
            $result['count'] = db('s_markset')->where('shop_code',session('shop_code'))->order('id desc')->count();
            $result['data'] = db('s_markset')->where('shop_code',session('shop_code'))->field('id,mark_name,mark_color,shop_code')->order('id desc')->select();
        }
        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('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('s_markset')->where('shop_code',session('shop_code'))->where('id',$param['id'])->update($param);
        }else{
            //判断是否重复
            $info = db('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('s_markset')->insertGetId($param);
        }
        if($res === false){
            db()->rollback();
            $arr = array('code'=>100,'msg'=>'编辑失败');
        }else{
            cache('sales_sign_color_'.session('shop_code'),null);
            cache('markset_'.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 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('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('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('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('c_customer_cost')->insertAll($array);
                    if($count != $days2){
                        db()->rollback();
                        return array('code'=>600,'msg'=>'同月跨度下花费分摊插入失败');
                    }
                }
            }else{//不同月
                $info1 = db('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('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('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('c_customer_cost')->insertAll($array2);
                    if($count != $days2){
                        db()->rollback();
                        return array('code'=>800,'msg'=>'不同月跨度下后月花费分摊插入失败');
                    }
                }
            }
            //查询原数据
            $oldData = db('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('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('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('c_customer_cost')->insertAll($array2);
                    if($count != $days2){
                        db()->rollback();
                        return array('code'=>800,'msg'=>'不同月跨度下后月花费分摊插入失败');
                    }
                }
            }
            //查询原数据
            $info = db('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('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('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('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('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('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('s_obtain_cost')->where('shop_code',session('shop_code'))->where('cost_type','like','%'.$param.'%')->page($page,$limit)->select();
        $count = db('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('SCallPrefix')->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('SCallPrefix')->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('SCallPrefix')->fetchSql(true)->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('SCallPrefix')->where('shop_code',session('shop_code'))->where('name','like','%'.$param.'%')->select();
        $count = db('SCallPrefix')->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('SCallCenter')->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('SCallCenter')->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('SCallCenter')->fetchSql(true)->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('SCallCenter')->select();
        $count = db('SCallCenter')->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('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('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('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('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('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('s_home_show')->where('shop_code',session('shop_code'))->where('position_name','like','%'.$param['position_name'].'%')->page($page,$limit)->select();
        $count = db('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'];
        $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['share_shops']= trim($param['share_shops'],',').','.session('shop_code');
        $data['setkey'] = session('setkey');
        $data['order_sort'] = intval($param['order_sort']);
        $data['staff_id'] = session('staff_id');
        $data['staff_name'] = session('staff_name');
        $data['create_time'] = date("Y-m-d H:i:s");
        db()->startTrans();
        $res = db('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');
        $data['shop_code'] = session('shop_code');
        $data['shop_name'] = session('shop_name');
        $data['share_shops']= trim($param['share_shops'],',').','.session('shop_code');
        $data['setkey'] = session('setkey');
        $data['order_sort'] = intval($param['order_sort']);
        db()->startTrans();
        $res = db('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('s_channel')->where('id',$id)->delete();
        if($res === false){
            db()->rollback();
            return array('code'=>100,'msg'=>'删除渠道名称失败','data'=>$res);
        }else{
            cache('crm_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;
        $res = db('s_channel')->where('FIND_IN_SET("'.session('shop_code').'",share_shops)')->where('channel_name','like','%'.$param['chan_name'].'%')->page($page,$limit)->order('order_sort asc')->select();
        $count = db('s_channel')->where('FIND_IN_SET("'.session('shop_code').'",share_shops)')->where('channel_name','like','%'.$param['chan_name'].'%')->count();
        if($res){
            $result['data'] = $res;
            $result['count'] = $count;
        }else{
            $result['data'] = array();
        }
        return ($result);
    }
    public function getChannelByCid($cid){
        $res = db('s_channel')->where('channel_info_id',$cid)->where('FIND_IN_SET("'.session('shop_code').'",share_shops)')->select();
        return $res;
    }
    public function crmProvinceSet($id){
        // cache('crm_address_app_'.session('shop_code'),null);
        if(!$id){
            db()->startTrans();
            $res = db('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('s_address')->where('pid','in',$fid)->select();
                    $info = array_merge($info,$pidArray);
                }
                db('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('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());
            }


            /*$info = $res['data'];
            db()->startTrans();
            try{
                db('s_shop_address')->where('shop_code',session('shop_code'))->delete();
                foreach($info as $k=>$v){
                    $arr = array(
                        'id' => $v['id'],
                        'pid' => $v['pid'],
                        'name'=>$v['name'],
                        'type'=>$v['type'],
                        'shop_code'=>session('shop_code')
                    );

                    db('s_shop_address')->insert($arr);
                }
                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'=>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('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('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('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('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;
        $str1 = ' 1=1 ';
        if(session('main_work_type') != SYSTEM_AUTH_ADMIN){ //管理员查全部
            $position = session('main_position_code').','.session('position_code');
            $position = explode(',',$position);

            if ($position) {
                $str2 = ' and ';
                $str3 = '';
                foreach($position as $k=>$v){
                    if ($v) {
                        $str3 .= '  FIND_IN_SET("'.$v.'",d.report_auth) or';
                    }
                }
                $str3 = trim($str3,' or');
            }
            if ($str3) {
                $str3 = $str2.$str3;
            }
        }
        $str = $str1.$str3;
        // var_dump($str);die;
        $info = db('s_report_detail')->alias('d')->join('s_report_form f','f.id=d.form_id','left')
            ->where($str)
            ->field('d.id,f.report_name,f.report_url,f.report_class_name,d.shop_code,d.brandclass_id,f.type')
            // ->order('d.brandclass_id, d.shop_code asc')
            ->order('f.type,f.`order` asc')
            ->limit($limit)
            // ->fetchSql(true)
            ->page($page)
            ->select();
        // var_dump($info);die;
        $sql = db()->getLastSql();
        
        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'];
            }
            if ($v['type']==1) {
                $info[$k]['type'] = '电商推广类';
            }else if ($v['type']==2) {
                $info[$k]['type'] = '网销客服类';
            }else if ($v['type']==3) {
                $info[$k]['type'] = '转介绍类';
            }
            $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'];
        }
        // var_dump($info);die;
        $result['sql'] = $sql;
        $count = count($info);
        if($info){
            $result['data'] = $info;
            $result['count'] = $count;
        }else{
            $result['data'] = array();
        }
        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('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('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('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('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('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('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('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('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('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('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'] = 'http://'.$_SERVER['HTTP_HOST'].'/crm/Index/addCustomerThird/';
        $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['customer_label'] = trim($param['customer_label']);
        $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('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['customer_label'] = trim($param['customer_label']);
        $json['channel_plan_number'] = trim($param['channel_plan_number']);
        $json['ad_page'] = trim($param['ad_page']);

        $data['field_config'] = json_encode($json);
        $info = db('s_customer_interface')->where('id',$param['id'])->find();
        db()->startTrans();
        try{
            db('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('c_sysconfig')->where('ckey','tel_address_grant')->find();
        return $res;
    }
    //保存手机地址配置
    public function telAddressMate($val){
        if ($val === false) {
            return array('code'=>100,'msg'=>'请选择至少一个地址');exit;
        }
        $res = db('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('c_sysconfig')->where('ckey','tel_address_grant')->update($data);
        }else{
            $data['cvalue'] = $val;
            $data['ckey'] = 'tel_address_grant';
            $staff = db('c_sysconfig')->insert($data);
        }
        if ($staff) {
            return array('code'=>200,'msg'=>'成功');
        }else{
            return array('code'=>300,'msg'=>'失败');
        }
    }

    // 根据小组ID获取组员
    public function getGroupStaff($gids){

        $staff = db('c_staff_group_relation')->where('group_id','in',$gids)->order('group_id')->select();
        if (!$staff) {
            $return['code'] = 200;
            $return['data'] = '';
        }else{
            
            $return['code'] = 200;
            $return['data'] = $staff;
        }
        return $return;
    }

    // 多维数组转二维数组 数组:$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;
    }

}