<?php
namespace Work\Lib;

use Dever;
Class Manage 
{
	public function getCoor_api()
	{
		$id = Dever::input('id');
		$info = false;
		if ($id) {
			$info = Dever::db('work/branch')->one($id);
		}

		$group = Dever::input('group');
		$temp = explode(',', $group);
		$group_id = $temp[0];
		$admin_id = false;
		if (isset($temp[1])) {
			$admin_id = $temp[1];
		} else {
			return 'no';
		}

		$admin = Dever::load('manage/company')->getAdmin($group_id, $admin_id);
		$config = array();
		$config['struct']['coor'] = array
        (
            'type'      => 'varchar-2000',
            'name'      => '协调人',
            'default'   => '',
            'desc'      => '请先选择协调人',
            'match'     => 'option',
            'update'    => 'checkbox',
            'value'		=> $info ? $info['coor'] : false,
            'option' 	=> $admin,
        );

		$data = array();

		$result = Dever::load('manage/database')->update_struct($config, false, array(), -1, '', true);

		return implode('', $result);
	}

	public function setInfoStatus_api ()
	{
		Dever::config('base')->hook = true;
		$id = Dever::input('id');
		$status = Dever::input('status');
		$type = Dever::input('type');

		if ($id) {
			$info = Dever::db('work/info')->find($id);
			$update['where_id'] = $info['id'];
			if ($type == 1) {
				$update['status'] = 4;
			} else {
				$update['status'] = 3;
			}
			$update = $this->finish($update, $info);
			Dever::db('work/info')->update($update);
			return 'ok';
		}
	}

	private function finish($update, $info)
	{
		$update['fdate'] = time();
		$update['chdate'] = time();
		$app = Dever::db('work/appoint')->getAdmin(array('info_id'=>$info['id'],'admin'=>$info['audit_admin']));
		if ($app && $app['admin']) {
			$update['fpeople'] = $app['admin'];
		} else {
			if ($info['branch_id']) {
				$branch = explode(',',$info['branch_id']);
				if (isset($branch[1]) && $branch[1]) {
					$update['fpeople'] = $branch[1];
				}
			} else {
				$update['fpeople'] = $info['audit_admin'];
			}
		}
		
		$log = Dever::db('work/info_log')->find(array('info_id'=>$info['id']));
		if ($log) {
			$w = array();
			$w['where_id'] = $log['id'];
			$w['fdate'] = time();
			if($update['status'] == 4){
				$w['cloce_date'] = time();
			}
			Dever::db('work/info_log')->update($w);
		}

		return $update;
	}
	public function insertInfo($id,$name,$data) {
		$mobile = Dever::param('mobile',$data);
		if(!preg_match('/^1[3|5|6|7|8|9]\d{9}$/', $mobile)){
            Dever::alert('手机号不正确');
        }
		$cate_id = Dever::param('cate_id',$data);
		if ($cate_id[0]<0) {
			Dever::alert('问题类型不能为空');
		}
	}
	public function updateInfo($id,$name,$data) 
	{
		Dever::config('base')->hook = true;
		$mobile = Dever::param('mobile',$data);
		$cate_id = Dever::param('cate_id',$data);
		$name = Dever::param('name',$data);
		$email = Dever::param('email',$data);
		$user = Dever::db('work/user')->find(array('mobile'=>$mobile));
		if ($user) {
			if ($name && $user['name'] != $name) {
				Dever::db('work/user')->update(array('where_id'=>$user['id'],'name'=>$name));
			}
		} else {
			$member = Dever::db('agent/member')->find(array('mobile'=>$mobile));
			if ($member) {
				$insert['agent_uid'] = $member['id'];
			}
			$option = Dever::db('option/member')->find(array('mobile'=>$mobile));
			if ($option) {
				$insert['option_uid'] = $option['id'];
			}
			$passport = Dever::db('passport/user')->find(array('mobile'=>$mobile));
			if ($passport) {
				$insert['passport_uid'] = $passport['id'];
			}
			if ($name) {
				$insert['name'] = $name;
			}
			$insert['mobile'] = $mobile;
			if ($insert) {
				Dever::db('work/user')->insert($insert);
			}
		}
		
		$info = Dever::db('work/info')->find($id);

		if ($info) {
			$w = array();

			if (!$info['work_num']) {
				$w['work_num'] = $this->getWorkId();
			}

			if ($info['cate_id']) {
				$cate_id = explode(',', $info['cate_id']);
				if (isset($cate_id[1]) && $cate_id[1]) {
					$info['question'] = $w['question'] = $cate_id[1];
				}
				if (!$info['cate'] || $info['cate']<=0) {
					$w['cate'] = $cate_id[0];
				}
			}

			if ($info['question']) {
				$product = Dever::db('work/question')->find($info['question']);
				$w['product'] = $product['product_id'];
			}

			if ($info['branch_id'] && strstr($info['branch_id'], ',') && $info['branch_id'] != -1) {
				$branch_id = explode(',', $info['branch_id']);
				$w['group'] = $branch_id[0];
				$w['appoint_id'] = $branch_id[1];
			}

			if ($info['status'] == 3 || $info['status'] == 4) {
				$w = $this->finish($w, $info);
			}

			if ($w) {
				$w['where_id'] = $id;
				Dever::db('work/info')->update($w);
			}
			if ($email && $email == 2) {
				if ($w) 
				$admin = Dever::db('manage/admin')->find($branch_id[1]);
                $res = Dever::load('work/lib/manage')->getTotal($admin['id'],'1,2');
                // $url = Dever::url('project/database/list?project=work&table=info&search_option_dever_auth=2&search_option_state=1&[refer]', 'manage');
                $work_list =Dever::url('project/database/list?project=work&table=info&search_option_dever_auth=2&search_option_state=1&[refer]', 'manage');
                $url = Dever::url('home?link=' . urlencode($work_list) . '&group=10&parent_menu=work&menu=work.my' , 'manage');
                $content = '你有'.$res.'个待处理工单,<a href="'.$url.'">点此跳转至工单系统查看</a>';
                Dever::load('work/lib/cron')->send($admin['email'],$admin['username'],'你有新的工单待处理',$content);
			}
		}
	}
	public function getWorkId()
	{
	    $where['work_num'] = Dever::order('W');
	    $state = Dever::db('work/info')->one($where);
	    if (!$state) {
	        return $where['work_num'];
	    } else {
	        return $this->getWorkId();
	    }
	}
	public function getUser($id)
	{
		$info = Dever::db('work/info')->find($id);
		if ($info && isset($info['mobile']) && $info['mobile']) {
			$data= Dever::db('work/user')->find(array('mobile'=>$info['mobile']));
			if ($data) {
			$html['user'] = $data['name'].'<br/>'.$data['mobile'];
			if (isset($info['fdate']) && $info['fdate']) {
				$fdate = date('Y-m-d H:i:s',$info['fdate']);
			} else {
				$fdate = '';
			}
			$html['time'] = date('Y-m-d H:i:s',$info['cdate']).'<br/>'.$fdate;
			$cate_id = explode(',',$info['cate_id']);
			$cate_name = '';
			$question_name = '';
			if (isset($cate_id[0]) && $cate_id[0]) {
				$cate = Dever::db('work/q_cate')->find($cate_id[0]);
				$cate_name = $cate['name'];
			}
			if (isset($cate_id[1]) && $cate_id[1]) {
				$question = Dever::db('work/question')->find($cate_id[1]);
				$question_name = $question['name'];
			}
			if ($info['audit_admin']) {
				$audit = Dever::db('manage/admin')->find($info['audit_admin']);
				if ($audit) {
					$admin['group'] = explode(',',$audit['group']);
			        foreach ($admin['group'] as $k => $v) {
			            $group = Dever::db('manage/group')->find(array('company_id'=>$info['company_id'],'id'=>$v));
			        }
					$html['chuangjian'] = $group['name'].' / ' .$audit['username'];
				}
			}
			$html['cate_name'] = $cate_name.'<br/>'.$question_name;
				return $html;
			} else {
				return '';
			}
		} else {
			return '';
		}
		
		
	}
	public function xietiao_api($id)
	{
		$data = Dever::db('work/branch')->find($id);
		$data['group'] = explode(',',$data['group']);
		$group = Dever::db('manage/group')->find($data['group'][0]);

		$admin = Dever::load('manage/company')->getAdmin($group['id'], $data['group'][1]);
		$gad = Dever::db('manage/admin')->find($data['group'][1]);
		$res = array();
		foreach ($admin as $k => $v) {
			$res[$k] = $v['username'].'<br/>'.$v['email'];
		}
		// $total = Dever::db('work/info')->getquestTotal(array('group'=>$data['group'][0]));
		$html = array();
		$html['group'] = $group['name'].'<br/>'.$gad['username'];
		$html['name'] = implode('<br/>',$res);
		$total = Dever::db('work/question')->getTotal(array('branch_id'=>$data['group_id']));
		$html['num'] = $total;
		return $html;
	}
	#获取客户信息
	public function search_api()
	{
		$value = Dever::input('value');
		if(!preg_match('/^1[3|5|6|7|8|9]\d{9}$/', $value)){
            return '代理商手机号不正确';
        }
        if ($value) {
        	$name = '';
        	$role_name = '';
        	$user = Dever::db('work/user')->find(array('mobile'=>$value));
        	if(!$user) {
        		$member = Dever::db('agent/member')->find(array('mobile'=>$value));
        		if ($member) {
        			$name = $member['name'];
        			$type = "代理商";
        			$role = Dever::db('setting/role')->find($member['role']);
        			if ($role ) {
        				$role_name = $role['name'];
        			}
        			$option = Dever::db('option/member')->find(array('mobile'=>$value));
        			if ($option) {
        				$type = $type.'<br/>期权账户';
        				$passport = Dever::db('passport/user')->find(array('mobile'=>$value));
        				if ($passport) {
        					$type = $type.'<br/>小程序';
        				}
        			} else {
        				$passport = Dever::db('passport/user')->find(array('mobile'=>$value));
        				if ($passport) {
        					$type = $type.'<br/>小程序';
        				}
        			}
        		} else {
        			$option = Dever::db('option/member')->find(array('mobile'=>$value));
        			if ($option) {
        				$name = $option['name'];
        				$type = '期权账户';
        				$passport = Dever::db('passport/user')->find(array('mobile'=>$value));
        				if ($passport) {
        					$type = $type.'<br/>小程序';
        				}
        			} else {
        				$passport = Dever::db('passport/user')->find(array('mobile'=>$value));
        				if ($passport) {
        					$name = $passport['username'];
        					$type = '小程序';
        				} else {
        					$type = '无系统关联关系';
        				}
        			}
        		}
        	} else {
        		$name = $user['name'];
        		$type = '客服系统用户';
        		if ($user['agent_uid'] && $user['agent_uid'] > 0) {
        			$member = Dever::db('agent/member')->find($user['agent_uid']);
        			$role = Dever::db('setting/role')->find($member['role']);
        			if ($role) {
        				$role_name = $role['name'];
        			}
        			$type = $type.'<br/>代理商';
        		}
        		if ($user['option_uid'] && $user['option_uid'] > 0) {
        			$type = $type.'<br/>期权账户';
        		}
        		if ($user['passport_uid'] && $user['passport_uid'] > 0) {
        			$type = $type.'<br/>小程序';
        		}
        	}
        	$table = array();
        	if ($name && $role_name) {
        		$table['head'] = array('名称', '电话号码', '平台' ,'角色');
        		$table['body'] = array($name, $value, $type, $role_name);
        	} elseif ($name && !$role_name) {
        		$table['head'] = array('名称', '电话号码', '平台');
        		$table['body'] = array($name, $value, $type);
        	} elseif (!$name && $role_name) {
        		$table['head'] = array('电话号码', '平台' ,'角色');
        		$table['body'] = array($value, $type, $role_name);
        	} else if (!$name && !$role_name) {
        		$table['head'] = array('电话号码', '平台');
        		$table['body'] = array($value, $type );
        	}
        	
        	$result[] = array
            (
                'type' => 'table',
                'content' => $table,
            );

            $html = Dever::show('', $result, false, false);
            return array('html' => $html, 'data' => array('name' => $name));
        }
	}
	public function admin($id)
	{
		$data = Dever::db('work/product')->find(array($id));
		$admin_id = explode(',',$data['admin_id']);
		$admin = Dever::db('manage/admin')->find($admin_id[1]);
		if ($admin) {
			return $admin['username'].'<br/>'.$admin['email'];
		}
	}
	public function branch($id)
	{
		if (isset($id) && $id) {
			$group = Dever::db('manage/group')->find($id);
			if (isset($group) && isset($group['name']) &&  $group['name']) {
				return $group['name'];
			}
		}
		
	}
	#工单列表导出
	public function out_info($data)
	{
		$header = array('客户名称','手机号','问题类型','问题类型描述','优先级','问题描述','处理结果','创建时间','完成时间');
		$body = array();
		$config = Dever::db('work/info')->config['config_status'];
		foreach ($data as $k => $v ) {
			$cate_name = '';
			$cate_id = explode(',',$v['cate_id']);
			if (isset($cate_id[0]) && $cate_id[0]) {
				$cate = Dever::db('work/q_cate')->find(array('id'=>$cate_id[0]));
				if ($cate) {
					$cate_name = $cate['name'];
				}
			}
			$question_name = '';
			if (isset($cate_id[1]) && $cate_id[1]) {
				$question = Dever::db('work/question')->find(array('id'=>$cate_id[1]));
				if ($question) {
					$question_name = $question['name'];
				}
			}
			$priority_name = '';
			$priority = Dever::db('work/priority')->find(array('id'=>$v['priority_id']));
			if ($priority) {
				$priority_name = $priority['name'];
			}
			$status_name = Dever::status($config,$v['status']);
			$cdate = date('Y-m-d H:i',$v['cdate']);
			$fdate = '';
			if ($v['fdate']){
				$fdate = date('Y-m-d H:i',$v['fdate']);
			}
			$d = array
			(
				$v['name'],
				$v['mobile'],
				$cate_name,
				$question_name,
				$priority_name,
				$v['desc'],
				$status_name,
				$cdate,
				$fdate,
			);
			$body[] = $d;
		}
		$file = Dever::input('excel_name');
    	return Dever::excelExport($body, $header, $file);
	}

	public function getTotal($admin_id,$status=false)
	{
		$company = Dever::load('manage/company.get');
		$where = array();
		
		if ($status){
			$where['status'] = $status;
			if ($where['status'] == '1,2') {
				$where['appoint_id'] = $admin_id;
			} else {
				$where['fpeople'] = $admin_id;
			}
			
		} else {
			$where['audit_admin'] = $admin_id;
		}
		if ($company) {
			$where['company_id'] = $company;
		}
		
		$data = Dever::db('work/info')->getTotal($where);
		return $data;
	}
	public function getmyTotal($admin_id,$type) {
		// $info = Dever::db('work/info')->getmyAll(array('audit_admin'=>$admin_id,'state'=>1));
	    $data = Dever::db('work/info_log')->getmyAll(array('app_admin_id'=>$admin_id,'state'=>1));
	    $res = Dever::db('work/info_log')->getmyAll(array('admin_id'=>$admin_id));
	    $work_info = array_merge($data,$res);
	    $rest = array();
	    foreach($work_info as $k=>$v){
	        $rest[$v['info_id']]=$v;
	    }
	    // print_R($data);die;
	    $search_ids = '';
	    if ($rest) {
	        $search_ids = implode(',',array_keys($rest));
	    }
	    if ($type == 1) {
	    	return count($rest);
	    } else {
	    	return $search_ids;
	    }
	}
}