<?php
namespace app\worker\controller;

use app\worker\BaseController;
use app\common\model\Param as ParamModel;
use app\common\model\Worker as WorkerModel;
use app\common\model\Demand as DemandModel;
use app\common\model\DemandCate as DemandCateModel;
use app\common\model\DemandLog as DemandLogModel;
use app\common\model\User as UserModel;
use app\common\model\UserIntegral as UserIntegralModel;

use app\common\validate\Demand as DemandValidate;
use think\exception\ValidateException;

use think\facade\Session;
use think\facade\Db;
use think\facade\Request;

class Demand extends BaseController
{
	
	
	// 我的报名记录
	public function logList()
	{
        $workerid = $this->access_worker['id'];

        $workerid = 89;

        $data = Db::name("demand_log")
                     ->alias('a')
                     ->field('c.ftitle,b.title,a.id,a.gworkerid,a.demandid')
                     ->where('a.workerid',$workerid)
                     ->join('demand b','a.demandid = b.id','LEFT')
                     ->join('worker c','a.gworkerid = c.id','LEFT')
                     ->select()
                     ->toArray();

        $gworker_data = assoc_unique($data,'gworkerid');
        $demand_data = assoc_unique($data,'demandid');

		return view('demand/loglist',[
			'gworker_data'		=> $gworker_data,
			'demand_data'		=> $demand_data
		]);
	} 
	
	public function delLog()
	{
		$idarr = input('idarr/a');

        $workerid = $this->access_worker['id'];
        $workerid = 89;
		$res = Db::name('demand_log')
                ->where('workerid',$workerid)
                ->whereIn('id',$idarr)
                ->update(['del_status'=>(int)2]);

		if ($res){
			exit(json_encode(array(
				'code' 	=> 0,
				'msg'	=> ""
			)));
		}
		exit(json_encode(array(
			'code' 	=> 1,
			'msg'	=> "删除失败，请稍后重试"
		)));
	}
	
	public function fieldLog()
	{
		$id = input('id/d',0); 
		$log = DemandLogModel::findOrEmpty($id);
		if ($log->isEmpty()){
			exit(json_encode(array(
				'code' 	=> 1,
				'msg'	=> "信息不存在"
			)));
		}else{
			$log->save([
				input('field/s')  => input('value')
			]);
		}
		exit(json_encode(array(
			'code' 	=> 0
		)));
	}
	
	public function listLog()
	{
		$limit = input('limit/d',20);
		$page = input('page/d',1);
		$map = array();
        $gworkerid = input('gworkerid/d');
        $demandid = input('demandid/d');

        $workerid = $this->access_worker['id'];
        $workerid = 89;
        $map[] = ['workerid', '=', $workerid];
        $map[] = ['del_status', '=', 1];
		if (!empty($gworkerid)){
			$map[] = ['gworkerid', '=', $gworkerid];
		}
		if (!empty($demandid)){
			$map[] = ['demandid', '=', $demandid];
		}
		$list = DemandLogModel::with(['gworker','worker','demand'])->where($map)->order('id','DESC')->limit($limit)->page($page)->select();
		$count = DemandLogModel::where($map)->count();
		if ($count==0){
			exit(json_encode(array(
				'code' 	=> 1,
				'msg'	=> "未查询到数据"
			)));
		}
		exit(json_encode(array(
			'code' 	=> 0,
			'msg'	=> "",
			'count' => $count,
			'data'  => $list
		)));
	}
	
	public function exportLog()
	{
		$map = array();
		$workerdemandarr = explode(",", input('workerdemand/s'));
		$workerid = isset($workerdemandarr[0]) ? $workerdemandarr[0] : 0;
		$demandid = isset($workerdemandarr[1]) ? $workerdemandarr[1] : 0;
		if (!empty($workerid)){
			$map[] = ['workerid', '=', $workerid];
		}
		if (!empty($demandid)){
			$map[] = ['demandid', '=', $demandid];
		}
		$xlsData = DemandLogModel::with(['gworker','worker','demand'])->where($map)->order('id','DESC')->select()->toArray();
		$xlsCell = array(
			array('id','表ID'),
			array('gworker.title','接单公司名称'),
			array('gworker.realname','接单公司联系人姓名'),
			array('gworker.mobile','接单公司联系人手机号'),
			array('worker.title','发单公司'),
			array('demand.title','订单标题'),
			array('createtime','接单时间'),
		);
		export_excel("接单报名记录",$xlsCell,$xlsData);
	}
	
	
	// 企业招聘
	public function demandList()
	{
        if (Request::isAjax()){
            $limit = input('limit/d',20);
            $page = input('page/d',1);
            $map = array();
            $workerid = $this->access_worker['id'];
            $map[] = ['workerid', '=', $workerid];

            $keywords = input('keywords/s', "");
            if (!empty($keywords)){
                $map[] =['title', 'like', '%'.$keywords.'%'];
            }

            $cateid = input('cateid/d', 0);
            if (!empty($cateid)){
                $map[] = ['cateid', '=', $cateid];
            }
            $wtype = input('wtype/d');
            if (!empty($wtype)){
                $map[] = ['wtype', '=', $wtype];
            }
            $ftype = input('ftype/d');
            if (!empty($ftype)){
                $map[] = ['ftype', '=', $ftype];
            }
            $status = input('status/d');
            if (!empty($status)){
                $map[] = ['status', '=', $status];
            }else{
                $map[] = ['status', '<', 6];
            }
            $isfree = input('isfree/d',0);
            if (!empty($isfree)){
                $map[] = ['isfree', '=', $isfree];
            }
            $list = DemandModel::with(['worker','demandCate'])
                ->withCount(['demandLog'])
                ->where($map)
                ->order(['priority'=>'desc','id'=>'desc',])
                ->limit($limit)
                ->page($page)
                ->append(['wtype_text','ftype_text','status_text','isfree_text'])
                ->select();
            $count = DemandModel::where($map)->count();
            if ($count==0){
                exit(json_encode(array(
                    'code' 	=> 1,
                    'msg'	=> "未查询到数据"
                )));
            }
            exit(json_encode(array(
                'code' 	=> 0,
                'msg'	=> "",
                'count' => $count,
                'data'  => $list
            )));

        }else{
            $catelist = DemandCateModel::order(['priority'=>'desc','id'=>'desc'])->select();
            $param = ParamModel::where(1)->findOrEmpty();
            $access_worker = Session::get('access_worker');

            $is_released = 1;
            if($access_worker['status'] == 1)
            {
                $is_released = is_released($access_worker['id']);
            }
            return view('demand/demandlist',[
                'param' => $param,
                'catelist' => $catelist,
                'wtype' => $access_worker['wtype'],
                'is_released' => $is_released['code']
            ]);
        }

	}
	
	public function demandForm()
	{
        $worker_data = Session::get('access_worker');

		$catelist = DemandCateModel::order(['priority'=>'desc','id'=>'desc'])->select();
		return view('demand/demandform',[
			'catelist'		=> $catelist,
			'title'		=> $worker_data['title']
		]);
	}


    public function demandFormWyd()
    {
        $worker_data = Session::get('access_worker');
        $catelist = DemandCateModel::order(['priority'=>'desc','id'=>'desc'])->select();
        return view('demand/demandformwyd',[
            'catelist'		=> $catelist,
            'title'		=> $worker_data['title']
        ]);
    }


	//修改订单状态
	public function editDemandStatus()
    {
        $id = input('id/d', 0);
        $workerid = $this->access_worker['id'];
        if (Request::isAjax()){

            $status = input('status/d', 0);
            $res = Db::name("demand")
                ->where('workerid',$workerid)
                ->where('id',$id)
                ->update(['status'=>$status]);

            if($res){
                exit(json_encode(array(
                    'code' 	=> 0
                )));
            }

        }else{
            $data = Db::name('demand')
                ->field('id,workerid,title,status')
                ->where('workerid',$workerid)
                ->where('id',$id)
                ->find();

            if($data['status'] == 1){
                $data['status_text'] = '待修改';
            }elseif($data['status'] == 2){
                $data['status_text'] = '待审核';
            }elseif($data['status'] == 3){
                $data['status_text'] = '已上架';
            }elseif($data['status'] == 4){
                $data['status_text'] = '已停招';
            }elseif($data['status'] == 5){
                $data['status_text'] = '已下架';
            }elseif($data['status'] == 6){
                $data['status_text'] = '已删除';
            }

            return view('demand/editdemandstatus',[
                'data' => $data
            ]);
        }

    }
	
	public function editDemand()
	{
		$id = input('id/d', 0);
        $workerid = $this->access_worker['id'];
        $user = UserModel::findOrEmpty($this->access_worker['userid']);
        $param = ParamModel::where(1)->findOrEmpty();
        if ($user->isEmpty()){
            exit(json_encode(array(
                'code' 	=> 1,
                'msg'	=> "用户信息不存在"
            )));
        }

		$wtype = input('wtype/d', 1);
		$zwagall = $wtype==1 ? input('zwagall/s', "") : '';
		$data = [
			'workerid'			=> $workerid,
			'title'				=> input('title/s', ""),
			'cateid'			=> input('cateid/d', 0),
			'province'			=> input('province/s', ""),
			'city'				=> input('city/s', ""),
			'district'			=> input('district/s', ""),
			'agegroup'			=> input('agegroup/s', ""),
			'tags'				=> input('tags/a', array()),
			'enddate'			=> input('enddate/s', ""),
			'requirement'		=> input('requirement/s', ""),
			'comdetails'		=> input('comdetails/s', ""),
			'wtype'				=> $wtype,
			'bwagall'			=> input('bwagall/s', ""),
			'zwagall'			=> $zwagall,
			'ftype'				=> input('ftype/d', 1),
			'fwagall'			=> input('fwagall/s', ""),
			'telephone'			=> input('telephone/s', ""),
			'remark'			=> input('remark/s', ""),
			'isfree'			=> 1
		];
		try {
		    validate(DemandValidate::class)->check($data);
		} catch (ValidateException $e) {
		    exit(json_encode(array(
		        'code' 	=> 1,
		        'msg'	=> $e->getError()
		    )));
		}
		if (empty($id)){

            if($this->access_worker['status'] == 1)
            {
                $is_released = is_released($workerid);

                if($is_released['code'] == 1001)
                {
                    return $is_released;

                }

            }else{

                if ($user->integral < $param->adddemand){
                    page_result1(1, "每次发布订单信息需要扣除".$param->adddemand."聘豆，你当前聘豆不足。");
                }
            }


            $data['video'] = input('new_video/s', "");
            $data['updatetime'] = time();
            $data['createtime'] = time();
            $data['status'] = (int)2;
            $data['volume'] = 0;
			$data['telearr'] = array(); 
			$demand = DemandModel::create($data);
            $intdata = array(
                'userid'		=> $user->id,
                'title'			=> "发布订单信息扣除",
                'intvalue'		=> 0 - $param->adddemand,
                'intmoney'		=> 0.00,
                'onlycontent'	=> "",
                'remark'		=> input('title/s', ""),
                'itype'			=> 4,
                'createtime'	=> date("Y-m-d H:i:s"),
                'yeartime'		=> date("Y"),
                'monthtime'		=> date("Ym")
            );
            UserIntegralModel::create($intdata);
            $integral = intval($user->integral) - intval($param->adddemand);
            $user->save([
                'integral'	=> $integral
            ]);
		}else{
            $old_video = input('old_video/s','');
            $new_video = input('new_video/s','');
            if(!empty($new_video)){
                    $data['video'] = $new_video;
            }else{
                if(!empty($old_video))
                {
                    $data['video'] = $old_video;
                }
            }

            $data['createtime'] = time();
            $data['status'] = input('status/d', 0);
			$demand = DemandModel::find($id);
			DemandLogModel::update([ 'workerid' => input('workerid/d', 0) ],['demandid'=>$demand->id]); 
			$demand->save($data);
		}
		exit(json_encode(array(
			'code' 	=> 0
		)));
	}

    public function editdemandformWyd()
    {
        $id = input('id/d', 0);
        $workerid = $this->access_worker['id'];
        $user = UserModel::findOrEmpty($this->access_worker['userid']);
        $param = ParamModel::where(1)->findOrEmpty();
        if ($user->isEmpty()){
            exit(json_encode(array(
                'code' 	=> 1,
                'msg'	=> "用户信息不存在"
            )));
        }

        $wtype = input('wtype/d', 1);
        $zwagall = $wtype==1 ? input('zwagall/s', "") : '';
        $data = [
            'workerid'			=> $workerid,
            'title'				=> input('title/s', ""),
            'cateid'			=> input('cateid/d', 0),
            'province'			=> input('province/s', ""),
            'city'				=> input('city/s', ""),
            'district'			=> input('district/s', ""),
            'agegroup'			=> input('agegroup/s', ""),
            'tags'				=> input('tags/a', array()),
            'enddate'			=> input('enddate/s', ""),
            'requirement'		=> input('requirement/s', ""),
            'comdetails'		=> input('comdetails/s', ""),
            'wtype'				=> $wtype,
            'bwagall'			=> input('bwagall/s', ""),
            'zwagall'			=> $zwagall,
            'ftype'				=> input('ftype/d', 1),
            'fwagall'			=> input('fwagall/s', ""),
            'telephone'			=> input('telephone/s', ""),
            'remark'			=> input('remark/s', ""),
            'isfree'			=> 2
        ];
        try {
            validate(DemandValidate::class)->check($data);
        } catch (ValidateException $e) {
            exit(json_encode(array(
                'code' 	=> 1,
                'msg'	=> $e->getError()
            )));
        }
        if (empty($id)){

            if($this->access_worker['status'] == 1)
            {
                $is_released = is_released($workerid);

                if($is_released['code'] == 1001)
                {
                    return $is_released;

                }

            }else{

                if ($user->integral < $param->adddemandwyd){
                    page_result1(1, "每次发布无忧单需要扣除".$param->adddemandwyd."聘豆，你当前聘豆不足。");
                }
            }


            $data['video'] = input('new_video/s', "");
            $data['updatetime'] = time();
            $data['createtime'] = time();
            $data['status'] = (int)2;
            $data['volume'] = 0;

            $data['telearr'] = array();
            $demand = DemandModel::create($data);

            $intdata = array(
                'userid'		=> $user->id,
                'title'			=> "发布无忧单扣除",
                'intvalue'		=> 0 - $param->adddemandwyd,
                'intmoney'		=> 0.00,
                'onlycontent'	=> "",
                'remark'		=> input('title/s', ""),
                'itype'			=> 4,
                'createtime'	=> date("Y-m-d H:i:s"),
                'yeartime'		=> date("Y"),
                'monthtime'		=> date("Ym")
            );
            UserIntegralModel::create($intdata);
            $integral = intval($user->integral) - intval($param->adddemandwyd);
            $user->save([
                'integral'	=> $integral
            ]);
        }else{
            $data['updatetime'] = time();
            $data['status'] = input('status/d', 0);
            $old_video = input('old_video/s','');
            $new_video = input('new_video/s','');
            if(!empty($new_video)){
                $data['video'] = $new_video;
            }else{
                if(!empty($old_video))
                {
                    $data['video'] = $old_video;
                }
            }
            $demand = DemandModel::find($id);
            DemandLogModel::update([ 'workerid' => input('workerid/d', 0) ],['demandid'=>$demand->id]);
            $demand->save($data);
        }
        exit(json_encode(array(
            'code' 	=> 0
        )));
    }
	
	public function fieldDemand()
	{
		$id = input('id/d',0); 
		$demand = DemandModel::findOrEmpty($id);
		if ($demand->isEmpty()){
			exit(json_encode(array(
				'code' 	=> 1,
				'msg'	=> "信息不存在"
			)));
		}else{
			$demand->save([
                'telephone'  => input('value'),
                    ]);
		}
		exit(json_encode(array(
			'code' 	=> 0
		)));
	}
	
	public function delDemand()
	{
        $workerid = $this->access_worker['id'];
		$idarr = input('idarr/a');

        $res = Db::name('demand')
                ->where(['workerid'=>$workerid])
                ->whereIn('id',$idarr)
                ->update(['status'=>6]);
		if ($res){
			exit(json_encode(array(
				'code' 	=> 0,
				'msg'	=> ""
			)));
		}
		exit(json_encode(array(
			'code' 	=> 1,
			'msg'	=> "删除失败，请稍后重试"
		)));
	}
	
	public function listDemand()
	{
		$limit = input('limit/d',20);
		$page = input('page/d',1);
		$map = array();
		$keywords = input('keywords/s', "");
		if (!empty($keywords)){
			$map[] =['title', 'like', '%'.$keywords.'%'];
		}
		$workerid = input('workerid/d', 0);
		if (!empty($workerid)){
			$map[] = ['workerid', '=', $workerid];
		}
		$cateid = input('cateid/d', 0);
		if (!empty($cateid)){
			$map[] = ['cateid', '=', $cateid];
		}
		$wtype = input('wtype/d');
		if (!empty($wtype)){
			$map[] = ['wtype', '=', $wtype];
		}
		$ftype = input('ftype/d');
		if (!empty($ftype)){
			$map[] = ['ftype', '=', $ftype];
		}
		$status = input('status/d');
		if (!empty($status)){
			$map[] = ['status', '=', $status];
		}
		$isfree = input('isfree/d',0);
		if (!empty($isfree)){
			$map[] = ['isfree', '=', $isfree];
		}
		$list = DemandModel::with(['worker','demandCate'])
                ->withCount(['demandLog'])
                ->where($map)
                ->order(['priority'=>'desc','id'=>'desc',])
                ->limit($limit)
                ->page($page)
                ->append(['wtype_text','ftype_text','status_text','isfree_text'])
                ->select();
		$count = DemandModel::where($map)->count();
		if ($count==0){
			exit(json_encode(array(
				'code' 	=> 1,
				'msg'	=> "未查询到数据"
			)));
		}
		exit(json_encode(array(
			'code' 	=> 0,
			'msg'	=> "",
			'count' => $count,
			'data'  => $list
		)));
	}

}
