<?php
namespace Erpadmin\Controller;
use Think\Controller;
class CompanyController extends ErpadminbaseController {
	/**
	 * [index 公司列表]
	 * @Author   L    <L@gmail.com>
	 * @DateTime 2018-09-25
	 */
    public function index()
    {
        if (I('is_ajax')) {
            $field = I('field');//排序字段名
            $order = I('order');//排序方式 asc desc
            $limit = I('limit',30,'int');//每页条数
            $limit = $limit > 150 ? 150 : $limit;

            $where = " where a.id > 0 ";

            $keyword = I('keyword');
            if ($keyword) {
                $where .= " and a.companyName like '%{$keyword}%'";
            }
            

            $Model = new \Think\Model;
            $count_sql = "SELECT COUNT(*) FROM __COMPANY__ a JOIN (SELECT COUNT(*) AS companyUserCount,gongsiid FROM __YONGHU__ WHERE status=1 and lock1=0 GROUP BY gongsiid) b ON a.id = b.gongsiid JOIN  __YONGHU__  c ON a.admin_id = c.id {$where}";
            $company_count_arr = $Model->query($count_sql);
            $company_count = $company_count_arr[0]['COUNT(*)'];

            $Page = new \Think\Page($company_count,$limit);

            $select_sql = "SELECT a.*,b.companyUserCount,c.ygmingcheng,c.dianhua FROM __COMPANY__ a JOIN (SELECT COUNT(*) AS companyUserCount,gongsiid FROM __YONGHU__ WHERE status=1 and lock1=0 GROUP BY gongsiid) b ON a.id = b.gongsiid JOIN  __YONGHU__  c ON a.admin_id = c.id {$where} ORDER BY a.id DESC limit ".$Page->firstRow.",".$Page->listRows;
            $company_select = $Model->query($select_sql);
            foreach ($company_select as $key => $value) {
                $company_select[$key]['addTime_d'] = date('Y-m-d H:i',$value['addTime']);
                $company_select[$key]['upTime_d'] = date('Y-m-d H:i',$value['upTime']);
                switch ($value['status']) {
                    case '-1':
                        $status_d = '停用';
                        break;
                    case '0':
                        $status_d = '待审核';
                        break;
                    case '1':
                        $status_d = '正常';
                        break;
                    default:
                        $status_d = '未知';
                        break;
                }
                $company_select[$key]['status_d'] = $status_d;
            }
            $return = array(
                'code'=>0,
                'msg'=>'',
                'count'=>$company_count,
                'data'=>$company_select
            );
            $this->ajaxReturn($return);
        } else {
        	$this->display();
        }
    }

    public function getLoginCountLine()
    {
        $company_id = I('company_id');
        $Model = new \Think\Model();
        $ThisWeek = $this->getThisWeekOf(date());
        $start_time = strtotime($ThisWeek[0]);
        $end_time = strtotime($ThisWeek[6])+3600*24;
        $sql = "SELECT FROM_UNIXTIME(shijian,'%Y-%m-%d') as create_date,count(id) as value 
                from __DLRIZHI__ WHERE shijian >= {$start_time} and shijian < {$end_time}   GROUP BY create_date";
        $sql = "select a.create_date,
    SUM(CASE a.dlleibie WHEN 'pc' THEN a.value ELSE 0 END ) z1,
    SUM(CASE a.dlleibie WHEN 'mobile' THEN a.value ELSE 0 END ) z2
     from (select FROM_UNIXTIME(shijian, '%Y-%m-%d') as create_date,dlleibie,count(id) as value from __DLRIZHI__ 
     WHERE gongsiid = {$company_id} and shijian >= {$start_time} and shijian < {$end_time}  
     group by create_date,dlleibie) a
     GROUP BY a.create_date;";
        $all = $Model->query($sql);
        //p($all);die;
        $arr = array();
        $arr2 = array();
        foreach ($all as $key => $value) {
            $arr[$value['create_date']] = $value;
        }
        foreach ($ThisWeek as $k => $v) {
            $arr2[] = $v;
            $series1[] = $arr[$v]['z1']?$arr[$v]['z1']:'';
            $series2[] = $arr[$v]['z2']?$arr[$v]['z2']:'';
        }

        $return_data = array(
            'status'=>1,
            'info'=>'',
            'data'=>array(
                'xAxis'=>$arr2,
                'series1'=>$series1,
                'series2'=>$series2
            )
        );

        $this->ajaxReturn($return_data);
    }


    public function getLoginCountPie()
    {
        $company_id = I('company_id');
        $Model = new \Think\Model();
        $ThisWeek = $this->getThisWeekOf(date());
        $start_time = strtotime($ThisWeek[0]);
        $end_time = strtotime($ThisWeek[6])+3600*24;

        $sql1 = "SELECT (case dlleibie when 'pc' THEN '电脑端' when 'mobile' then '移动端' ELSE '' END) as name,count(id) as value 
                from __DLRIZHI__ WHERE gongsiid={$company_id} and shijian >= {$start_time} and shijian < {$end_time}   GROUP BY dlleibie";
        $data1 = $Model->query($sql1);
        

        $return_data = array(
            'status'=>1,
            'info'=>'',
            'data'=>array(
                'legend'=>$legend,
                'data1'=>$data1
            )
        );

        $this->ajaxReturn($return_data);
    }

    public function companyDetails()
    {
        if (I('is_ajax')) {
            $requestType = I('requestType');
            $id = I('id');
            $company_find = M('company')->where(array('id'=>$id))->find();
            switch ($requestType) {
                case '1':
                    $bumen_select = M('bumen')->where(array('gongsiid'=>$company_find['id']))->select();
                    $return = array(
                        'code'=>0,
                        'msg'=>'',
                        'count'=>'',
                        'data'=>$bumen_select
                    );
                    $this->ajaxReturn($return);
                case '2':
                    $limit = I('limit',30,'int');//每页条数
                    $limit = $limit > 150 ? 150 : $limit;

                    $keyword = I('keyword');
                    $status = I('status');

                    $where['gongsiid'] = $company_find['id'];
                    if ($status == 1) {
                        $where['status'] = 1;
                    } elseif ($status == -1) {
                        $where['status'] = 0;
                    }

                    if ($keyword) {
                        $map['dianhua'] = array('like','%'.$keyword.'%');
                        $map['ygmingcheng']  = array('like', '%'.$keyword.'%');
                        $map['_logic'] = 'or';
                        $where['_complex'] = $map;
                    }
                    
                    

                    $yonghu_count = M('yonghu')->where($where)->count();
                    $Page = new \Think\Page($yonghu_count,$limit);
                    $yonghu_select = M('yonghu')->where($where)->limit($Page->firstRow.",".$Page->listRows)->field('mima',true)->select();
                    $return = array(
                        'code'=>0,
                        'msg'=>'',
                        'count'=>$yonghu_count,
                        'data'=>$yonghu_select
                    );
                    $this->ajaxReturn($return);
                    break;
                case '3':
                    $node_select = M('node')->where()->limit()->select();
                    $company_node_select = M('nodes')->where(array('company_id'=>$company_find['id']))->select();
                    $company_node_arr = array();
                    foreach ($company_node_select as $key => $value) {
                        $company_node_arr[] = $value['node_id'];
                    }
                    $node_select_return = array();
                    foreach ($node_select as $key => $value) {
                        if (in_array($value['id'], $company_node_arr)) {
                            $node_select_return[] = $value;
                        }

                    }
                    $return = array(
                        'code'=>0,
                        'msg'=>'',
                        'count'=>'',
                        'data'=>$node_select_return
                    );
                    $this->ajaxReturn($return);
                    break;
                default:
                    # code...
                    break;
            }
        } else {
            $id = I('id');
            $company_find = M('company')->where(array('id'=>$id))->find();
            $company_admin_find = M('yonghu')->where(array('id'=>$company_find['admin_id']))->field('mima',true)->find();
            $company_yonghu_count = M('yonghu')->where(array('gongsiid'=>$company_find['id']))->count();
            $this->assign('company_yonghu_count',$company_yonghu_count);
            $this->assign('company_admin_find',$company_admin_find);
            $this->assign('company_find',$company_find);
            $this->display('companyDetails');
        }
    }

    public function editStatus()
    {
        if (IS_POST) {
            $id = I('post.id');
            $status = I('post.status');
            $save_data['status'] = $status;
            $save_data['upTime'] = time();

            $save_return = M('company')->where(array('id'=>$id))->save($save_data);
            if (!$save_return) {
                $this->error('保存失败!');
            } else {
                if ($status == 1) {
                    $nodes = M('node')->where()->select();
                    foreach ($nodes as $key => $value) {
                        $add_data[] = array(
                            'node_id'=>$value['id'],
                            'company_id'=>$id
                        );
                    } 
                    M('nodes')->addAll($add_data);
                }
                
                $this->success('保存成功!');
            }
        } else {
            $id = I('get.id');
            $company_find = M('company')->where(array('id'=>$id))->find();
            if (!$company_find) {
                $this->error('没查找到此公司!');
            }
            $this->status = $company_find['status'];
            $this->display('editStatus');
        }
        
    }

    public function editCompanyNode()
    {
        if (IS_POST) {
            $nodes = I('post.nodes');
            $nodes = explode(",", $nodes);
            $company_id = I('post.company_id');
            M('nodes')->where(array('company_id'=>$company_id))->delete();
            $add_data = array();
            foreach ($nodes as $key => $value) {
                $pid = M('node')->where(array('id'=>$value))->getField('pid');
                if ($pid != 0) {
                    array_push($nodes,$pid);
                }
            }
            $index = 0;
            foreach ($nodes as $key => $value) {
                $pid = M('node')->where(array('id'=>$value))->getField('pid');
                if ($pid != 0) {
                    array_push($nodes,$pid);
                }
                $index++;
            }
            $nodes = array_unique($nodes);
            foreach ($nodes as $key => $value) {
                $add_data[] = array(
                    'node_id'=>$value,
                    'company_id'=>$company_id
                );
            }
            //p($add_data);die;
            $add_return = M('nodes')->addAll($add_data);
            if (!$add_return) {
                $this->error('保存失败!');
            } else {
                $this->success('保存成功!');
            }
            
        } else {
            if (I('is_ajax')) {
                $node_select = M('node')->where()->limit()->select();
                $company_id = I('get.company_id');
                $company_node_select = M('nodes')->where(array('company_id'=>$company_id))->select();
                $company_node_arr = array();
                foreach ($company_node_select as $key => $value) {
                    $company_node_arr[] = $value['node_id'];
                }
                //p($company_node_arr);die;
                foreach ($node_select as $key => $value) {
                    if (in_array($value['id'], $company_node_arr) && $value['level'] == 3) {
                        $node_select[$key]['lay_is_checked'] = true;
                    }
                }
                $return = array(
                    'code'=>0,
                    'msg'=>'',
                    'count'=>'',
                    'data'=>$node_select
                );
                $this->ajaxReturn($return);
            } else {
                $this->display('editCompanyNode');
            }
        }
        
    }

    /**
     * [addCompany 公司信息添加]
     * @Author   L    <L@gmail.com>
     * @DateTime 2018-09-25
     */
    public function addCompany()
    {
    	if (IS_POST) {
            //p(I('post.'));

            if (I('post.password') != I('post.spassword')) {
                $this->error('密码不一致!');
            } 
            $yonghu_find = M('yonghu')->where(array('dianhua'=>I('post.phone')))->find();
            if ($yonghu_find) {
                $this->error('电话已被注册!');
            }

            $add_company_data['companyName'] = I('post.companyName');
            $add_company_data['adderss'] = I('post.adderss');
            $add_company_data['onlyCode'] = StrOrderOne();
            $add_company_data['status'] = 1;
            $add_company_data['addTime'] = time();
            $add_company_data['upTime'] = time();
            $add_company_data['address'] = I('post.address');

            $add_user_data['ygmingcheng'] = I('post.nickname');
            $add_user_data['dianhua'] = I('post.phone');
            $add_user_data['mima'] = pass_salt(I('post.password'));
            $add_user_data['status'] = 1;
            $add_user_data['lock1'] = 0;

            $add_bumen_data['bmming'] = I('post.companyName');
            $add_bumen_data['level'] = 1;

            $company_add_return = M('company')->add($add_company_data);
            $add_user_data['gongsiid'] = $company_add_return;
            $add_bumen_data['gongsiid'] = $company_add_return;
            $bumen_add_return = M('bumen')->add($add_bumen_data);
            $add_user_data['bumen'] = $bumen_add_return;
            $add_user_data['groups'] = $bumen_add_return;
            $user_add_return = M('yonghu')->add($add_user_data);
            M('company')->where(array('id'=>$company_add_return))->setField('admin_id',$user_add_return);
            $this->success('添加成功!');
        } else {
            $this->display('addCompany');
        }
    }

    /**
     * [editCompany 公司信息编辑]
     * @Author   L    <L@gmail.com>
     * @DateTime 2018-09-25
     */
    public function editCompany()
    {
    	# code...
    }

    /**
     * [delCompany 公司信息删除]
     * @Author   L    <L@gmail.com>
     * @DateTime 2018-09-25
     */
    public function delCompany()
    {
    	# code...
    }


}