<?php
namespace app\worker\controller;

use app\worker\BaseController;
use app\common\model\ComjobsReport as ComjobsReportModel;
use app\common\model\ReportLog as ReportLogModel;

use app\common\model\Comjobs as ComjobsModel;
use app\common\model\Agent as AgentModel;

use app\common\validate\Report as ReportValidate;
use think\exception\ValidateException;
use think\facade\Db;

class Comjobsreport extends BaseController
{


	// 报备记录
	public function reportList()
	{

        $workerid = $this->access_worker['id'];
        $comjobslist = ComjobsModel::where('workerid',$workerid)->select();
        $agentlist = Db::name('agent')
                    ->alias('a')
                    ->field('a.id,a.title')
                    ->join('worker b','b.id = a.workerid','LEFT')
                    ->where('a.workerid',$workerid)
                    ->select()
                    ->toArray();
		$statusarr = array(1=>'待审核', 2=>'待面试', 3=>'已入职', 4=>'无效报备');
		return view('comjobsreport/reportlist',[
			'comjobslist'	=> $comjobslist,
			'agentlist'		=> $agentlist,
			'statusarr'		=> $statusarr
		]);
	}

    // 报备记录(待审核)
    public function reportExamine()
    {
        $workerid = $this->access_worker['id'];
        $comjobslist = ComjobsModel::where('workerid',$workerid)->select();
        $agentlist = Db::name('agent')
                    ->alias('a')
                    ->field('a.id,a.title')
                    ->join('worker b','b.id = a.workerid','LEFT')
                    ->where('a.workerid',$workerid)
                    ->select()
                    ->toArray();
        $statusarr = array(1=>'待审核', 2=>'待面试', 3=>'已入职', 4=>'无效报备');
        return view('comjobsreport/reportexamine',[
            'comjobslist'	=> $comjobslist,
            'agentlist'		=> $agentlist,
            'statusarr'		=> $statusarr
        ]);
    }
	
	public function listReport()
	{
		$limit = input('limit/d',20);
		$page = input('page/d',1);

        $workerid = $this->access_worker['id'];

		$map = array();
        $map[] = ['a.workerid', '=', $workerid];
        $date6 = input('date6');

        if(!empty($date6))
        {
            $date6 =explode('~',$date6);
            $startTime = strtotime($date6[0]);
            $endTime = strtotime($date6[1]);
            $map[] = ['a.createtime', 'between', [$startTime,$endTime]];
        }

		$comjobsid = input('comjobsid/d', 0);
		if (!empty($comjobsid)){
			$map[] = ['a.comjobsid', '=', $comjobsid];
		}
		$agentid = input('agentid/s', "");
		if ($agentid!=""){
			$map[] = ['a.agentid', '=', intval($agentid)];
		}
		$status = input('status/d', 0);
		if (!empty($status)){
			$map[] = ['a.status', '=', $status];
		}


		$list = Db::name('comjobs_report')
                ->alias('a')
                ->field('a.id,a.status,a.realname,a.mobile,a.idcard,a.arrivetime,from_unixtime(a.createtime) createtime,b.title comjobs_title,c.title agent_title,d.title broker_title')
                ->join('comjobs b','b.id = a.comjobsid','LEFT')
                ->join('agent c','c.id = a.agentid','LEFT')
                ->join('broker d','d.agentid = c.id','LEFT')
                ->where($map)
                ->order('id','DESC')
                ->limit($limit)
                ->page($page)
                ->select()
                ->toArray();

		$count = Db::name('comjobs_report')
                ->alias('a')
                ->join('comjobs b','b.id = a.comjobsid','LEFT')
                ->join('agent c','c.id = a.agentid','LEFT')
                ->join('broker d','d.agentid = c.id','LEFT')
                ->where($map)
                ->count();

		foreach($list as $k=>$v)
        {
            if($v['status'] == 1){
                $list[$k]['status_text'] = '待审核';
            }elseif($v['status'] == 2){
                $list[$k]['status_text'] = '待面试';
            }elseif($v['status'] == 3){
                $list[$k]['status_text'] = '已入职';
            }elseif($v['status'] == 4){
                $list[$k]['status_text'] = '无效报备';
            }
        }

		if ($count==0){
			exit(json_encode(array(
				'code' 	=> 1,
				'msg'	=> "未查询到数据"
			)));
		}
		exit(json_encode(array(
			'code' 	=> 0,
			'msg'	=> "",
			'count' => $count,
			'data'  => $list 
		)));
	}

	
	public function exportReport()
	{
		$map = array();
		$comjobsid = input('comjobsid/d', 0);
		if (!empty($comjobsid)){
			$map[] = ['comjobsid', '=', $comjobsid];
		}
		$agentid = input('agentid/d', 0);
		if (!empty($agentid)){
			$map[] = ['agentid', '=', $agentid];
		}
		$status = input('status/d', 0);
		if (!empty($status)){
			$map[] = ['status', '=', $status];
		}
		$xlsData = ComjobsReportModel::with(['comjobs','agent','broker'])->where($map)->order('id','DESC')->append(['status_text'])->select()->toArray();
		$xlsCell = array(
			array('id','表ID'),
			array('comjobs.title','招聘标题'),
			array('agent.title','代理门店'),
			array('broker.title','职业顾问'),
			array('realname','姓名'),
			array('mobile','手机号'),
			array('idcard','身份证号'),
			array('arrivetime','预计到达时间'),
			array('remark','报名备注'),
			array('status_text','状态'),
			array('createtime','接单时间')
		);
		export_excel("报备记录",$xlsCell,$xlsData);
	}
	
	public function setComtype()
	{
		$idarr = input('idarr/a');
		$comjobsid = input('comjobsid/d', 0);
		$comjobs = ComjobsModel::with(['company'])->findOrEmpty($comjobsid);
		if ($comjobs->isEmpty()){
			exit(json_encode(array(
				'code' 	=> 1,
				'msg'	=> "请选择招聘信息和代理门店"
			)));
		}
		$data = [
			'comjobsid'			=> $comjobs->id,
			'comtype'			=> input('comtype/s', ""),
			'comprice'			=> input('comprice/s', ""),
			'comremark'			=> input('comremark/s', ""),
			'updatetime'		=> input('updatetime/s', date("Y-m-d H:i"))
		];
		ComjobsReportModel::whereIn('id',$idarr)->update($data);
		$reportall = ComjobsReportModel::whereIn('id',$idarr)->select()->toArray();
		$logdata = array();
		$statusarr = array(1=>'待审核', 2=>'待面试', 3=>'已入职', 4=>'无效报备');
		$agentall = AgentModel::column('realname', 'id');
		foreach($reportall as $key=>$item){
			$logdata[] = array(
				'reportid'		=> $item['id'],
				'logstatus'		=> $statusarr[$item['status']],
				'editrealname'	=> "管理员",
				'comjobstil'	=> $comjobs->isEmpty() ? "" : $comjobs->title,
				'agenttil'		=> empty($agentall[$item['agentid']]) ? "未报备" : $agentall[$item['agentid']],
				'realname'		=> $item['realname'],
				'mobile'		=> $item['mobile'],
				'idcard'		=> $item['idcard'],
				'comtype'		=> input('comtype/s', ""),
				'comprice'		=> input('comprice/s', ""),
				'comremark'		=> input('comremark/s', ""),
				'arrivetime'	=> $item['arrivetime'],
				'remark'		=> $item['remark'],
				'createtime'	=> date("Y-m-d H:i")
			);
		}
		$reportlog = new ReportLogModel;
		$reportlog->saveAll($logdata);
		exit(json_encode(array(
			'code' 	=> 0,
			'msg'	=> ""
		)));
	}
	
	public function setStatus()
	{
		$idarr = input('idarr/a');
		$status = input('status/d', 1);
		ComjobsReportModel::whereIn('id',$idarr)->update(['status'=>$status]);
		exit(json_encode(array(
			'code' 	=> 0,
			'msg'	=> ""
		)));
	}
	
	public function delReport()
	{
		$idarr = input('idarr/a');

        $ComjobsReport = ComjobsReportModel::whereIn('id',$idarr)->select();
        $result = $ComjobsReport->delete();

		if ($result){
			exit(json_encode(array(
				'code' 	=> 0,
				'msg'	=> ""
			)));
		}
		exit(json_encode(array(
			'code' 	=> 1,
			'msg'	=> "删除失败，请稍后重试"
		)));
	}
	
	public function reportImport()
	{
		$id = input('id/d, 0');
		$comjobslist = ComjobsModel::with(['comjobsRefund.agentGroups'])->order(['id'=>'desc'])->select();
		$agentlist = AgentModel::order(['id'=>'asc'])->select();
		return view('comjobsreport/reportimport',[
			'comjobslist'	=> $comjobslist,
			'agentlist'		=> $agentlist
		]);
	}
	
	public function importReport()
	{
		$execlfile = input('execlfile/s', "");
		if (empty($execlfile)){
			exit(json_encode(array(
				'code' 	=> 1,
				'msg'	=> "请上传导入文件"
			)));
		}
		$comjobsid = input('comjobsid/d', 0);
		$comjobs = ComjobsModel::findOrEmpty($comjobsid);
		$agentid = input('agentid/d', 0);
		$agent = AgentModel::findOrEmpty($agentid);
		$filedata = read_excel( $execlfile );
		$sucnumber = 0;
		$errnumber = 0;
		$errarr = "";
		$statusarr = array(1=>'待审核', 2=>'待面试', 3=>'已入职', 4=>'无效报备');
		foreach( $filedata as $k=>$v ){
			$tabcomjobsid = intval($v[1]);
			if (empty($tabcomjobsid)){
				$tabcomjobs = $comjobs;
			}else{
				$tabcomjobs = ComjobsModel::findOrEmpty($tabcomjobsid);
			}
			$tabagentid = intval($v[2]);
			if (empty($tabagentid)){
				$tabagent = $agent;
			}else{
				$tabagent = AgentModel::findOrEmpty($tabagentid);
			}
			if( $tabcomjobs->isEmpty() ){
				$errarr .= $v[0] . "，";
				$errnumber++;
				continue;
			}else{
				$data = array(
					'comjobsid'			=> $tabcomjobs->id,
					'agentid'			=> $tabagent->isEmpty() ? 0 : $tabagent->id,
					'brokerid'			=> 0,
					'realname'			=> trim($v[3]),
					'mobile'			=> trim($v[4]),
					'idcard'			=> trim($v[5]),
					'gender'			=> trim($v[6])=='男' ? 1 : 2,
					'comtype'			=> empty(trim($v[7])) ? trim($v[7]) : input('comtype/s', ""),
					'comprice'			=> empty(trim($v[8])) ? trim($v[8]) : input('comprice/s', ""),
					'comremark'			=> empty(trim($v[9])) ? trim($v[9]) : input('comremark/s', ""),
					'arrivetime'		=> trim($v[10]),
					'remark'			=> trim($v[11]),
					'status'			=> intval($v[12]),
					'updatetime'		=> date("Y-m-d H:i"),
					'createtime'		=> date("Y-m-d H:i")
				);
				try {
				    validate(ReportValidate::class)->check($data);
				} catch (ValidateException $e) {
					$errarr .= $v[0] . "，";
					$errnumber++;
					continue;
				}
				$report = new ComjobsReportModel;
				$report->save($data);
				$logdata = array(
					'reportid'		=> $report->id,
					'logstatus'		=> $statusarr[$report->status],
					'editrealname'	=> "管理员",
					'comjobstil'	=> $tabcomjobs->title,
					'agenttil'		=> $tabagent->isEmpty() ? "未报备" : $tabagent->title,
					'realname'		=> trim($v[3]),
					'mobile'		=> trim($v[4]),
					'idcard'		=> trim($v[5]),
					'comtype'		=> empty(trim($v[7])) ? trim($v[7]) : input('comtype/s', ""),
					'comprice'		=> empty(trim($v[8])) ? trim($v[8]) : input('comprice/s', ""),
					'comremark'		=> empty(trim($v[9])) ? trim($v[9]) : input('comremark/s', ""),
					'arrivetime'	=> trim($v[10]),
					'remark'		=> trim($v[11]),
					'createtime'	=> date("Y-m-d H:i")
				);
				ReportLogModel::create($logdata);
				$sucnumber++;
			}
		}
		exit(json_encode(array(
			'code' 			=> 0,
			'sucnumber'		=> $sucnumber,
			'errnumber'		=> $errnumber,
			'errarr'		=> $errarr
		)));
	}
	
	
	public function reportForm()
	{
		$id = input('id/d, 0');
		$report = Db::name('comjobs_report')
                 ->alias('a')
                 ->field('a.id,a.realname,a.mobile,a.idcard,a.status,a.remark,a.retremark,b.title')
                 ->join('comjobs b','b.id = a.comjobsid','LEFT')
                 ->where('a.id',$id)
                 ->find();

		$statusarr = array(1=>'待审核', 2=>'待面试', 3=>'已入职', 4=>'无效报备');
		return view('comjobsreport/reportform',[
			'report'		=> $report,
			'title'		=> $this->access_worker['title'],
			'statusarr'		=> $statusarr
		]);
	}
	 
	public function editReport()
	{
		$id = input('id/d', 0);
        $workerid = $this->access_worker['id'];
		$data = array(
			'retremark'			=> input('retremark/s', ""),
			'status'			=> input('status/d', 1),
			'updatetime'		=> time()
		);

		if (empty($id)){
			$report = new ComjobsReportModel;
			$report->save($data); 
		}else{
			$report = ComjobsReportModel::find($id);
			$report->save($data); 
		}
		exit(json_encode(array(
			'code' 	=> 0
		)));
	}
	
	// 记录
	public function logList()
	{
		$reportid = input('reportid/d',0);
		$report = ComjobsReportModel::findOrEmpty($reportid);
		return view('comjobsreport/loglist',[
			'reportid'		=> $reportid,
			'report'		=> $report
		]); 
	}
	
	public function listLog()
	{
		$limit = input('limit/d',50);
		$page = input('page/d',1);
		$map = array();
		$map[] = ['reportid', '=', input('reportid/d',0)];
        $map[] = ['delstatus', '<>', 2];
		$list = ReportLogModel::with(['report'])->where($map)->order(['id'=>'desc'])->limit($limit)->page($page)->select();
		$count = ReportLogModel::where($map)->count();
		if ($count==0){
			exit(json_encode(array(
				'code' 	=> 1,
				'msg'	=> "未查询到数据"
			)));
		}
		exit(json_encode(array(
			'code' 	=> 0,
			'msg'	=> "",
			'count' => $count,
			'data'  => $list
		)));
	}
	
	

}
