<?php

namespace app\mainapp\controller;

use app\common\model\WorkerThird;
use app\common\service\IntegralService;
use app\mainapp\BaseController;

use app\common\model\User as UserModel;
use app\common\model\Comjobs as ComjobsModel;
use app\common\model\ComjobsCate as ComjobsCateModel;
use app\common\model\ComjobsLog as ComjobsLogModel;
use app\common\model\ComjobsStar as ComjobsStarModel;
use app\common\model\ComjobsShare as ComjobsShareModel;
use app\common\model\WorkerLog as WorkerLogModel;
use app\common\model\Worker as WorkerModel;
use app\common\model\Broker as BrokerModel;
use app\common\model\ComjobsReport as ComjobsReportModel;
use app\common\model\UserParam as UserParamModel;
use app\common\model\UserIntegral as UserIntegralModel;
use app\common\model\UserFollow as UserFollowModel;

use chuanglan\Chuanglan;
use echowx\WxProgram;

class Comjobs extends BaseController
{

    // 报备信息
    public function setReport()
    {
        $comjobsid = input('comjobsid/d', 0);
        $comjobs   = ComjobsModel::with('worker')->where('status', 'in', '3,4')->where('id', '=', $comjobsid)->findOrEmpty();
        if ($comjobs->isEmpty()) {
            page_result(1, "招聘信息不存在。");
        }
        $userid    = input('userid/d', 0);
        $brokerall = BrokerModel::where('userid', '=', $userid)->where('status', '=', 1)->where('powerreport', '=', 1)->select();
        page_result(0, "", [
            'comjobs'    => $comjobs,
            'brokerall'  => $brokerall,
            'arrivetime' => date("Y-m-d", strtotime("+1 day")),
        ]);
    }

    public function getUserList()
    {
        $ppage       = input('ppage/d', 1);
        $psize       = input('psize/d', 20);
        $map         = [];
        $userid      = input('userid/d', 0);
        $brokeridarr = BrokerModel::where('userid', '=', $userid)->column('id');
        if (empty($brokeridarr)) {
            page_result(1, "经纪人信息不存在。");
        }
        $map[]     = ['brokerid', 'IN', $brokeridarr];
        $searchval = input('searchval/s', "");
        if (!empty($searchval)) {
            $map[] = ['nickname|realname|mobile', 'like', '%' . $searchval . '%'];
        }
        $plist = UserModel::where($map)->order(['id' => 'desc'])->page($ppage)->limit($psize)->select();
        page_result(0, "", [
            'plist'   => $plist,
            'pstatus' => $psize > count($plist) ? 'noMore' : 'more',
        ]);
    }

    public function disIdcard()
    {
        $picpath = input('picpath/s', "");
        $picpath = root_path() . "public" . $picpath;
        $idcard  = aliyun_ocr_idcard($picpath);
        if ($idcard == false) {
            page_result(1, "身份证信息识别失败。");
        }
        page_result(0, "", [
            'idcard' => $idcard,
        ]);
    }

    public function addReport()
    {
        $comjobsid = input('comjobsid/d', 0);
        $comjobs   = ComjobsModel::where('id', '=', $comjobsid)->findOrEmpty();
        if ($comjobs->isEmpty()) {
            page_result(1, "招聘信息不存在。");
        }
        $brokerid = input('brokerid/d', 0);
        $broker   = BrokerModel::where('id', '=', $brokerid)->findOrEmpty();
        if ($broker->isEmpty()) {
            page_result(1, "经纪人信息不存在。");
        }
        $data = [
            'comjobsid'  => $comjobsid,
            'workerid'   => $comjobs->workerid,
            'agentid'    => $broker->agentid,
            'brokerid'   => $brokerid,
            'realname'   => input('realname/s', ""),
            'mobile'     => input('mobile/s', ""),
            'idcard'     => input('idcard/s', ""),
            'arrivetime' => input('arrivetime/s', ""),
            'status'     => 1,
            'remark'     => input('remark/s', ""),
            'retremark'  => "",
            'createtime' => date("Y-m-d H:i:s"),
        ];
        ComjobsReportModel::create($data);
        page_result(0, "", []);
    }


    // 招聘总列表
    public function pageComjobs()
    {
        $searchval = trim(input('searchval/s', ""));
        $map       = [];
        if (!empty($searchval)) {
            $map[] = ['title', 'like', '%' . $searchval . '%'];
        }

        $catelist = ComjobsCateModel::field('id as value, title, priority')->where($map)->order(['priority' => 'desc', 'id' => 'desc'])
            ->select()->toArray();
        array_unshift($catelist, ['value' => 0, 'title' => '全部']);
        $wtypelist   = [['value' => 0, 'title' => '全部'], ['value' => 1, 'title' => '按月'], ['value' => 2, 'title' => '按时'], ['value' => 3, 'title' => '按件'], ['value' => 4, 'title' => '按项目'], ['value' => 5, 'title' => '其他']];
        $rectypelist = [['value' => 0, 'title' => '全部'], ['value' => 1, 'title' => '普通招聘'], ['value' => 2, 'title' => '悬赏聘']];
        page_result(0, "", [
            'catelist'     => $catelist,
            'wtypelist'    => $wtypelist,
            'rectypelist'  => $rectypelist,
            'provincelist' => $this->provincelist,
        ]);
    }

    public function listComjobs()
    {
        $ppage     = input('ppage/d', 1);
        $psize     = input('psize/d', 20);
        $map       = [];
        $map[]     = ['createtime', '<=', time()];
        $map[]     = ['status', 'in', '3,4'];
        $searchval = input('searchval/s', "");
        $whereor   = [];
        if (!empty($searchval)) {
            $whereor[] = ['title', 'like', '%' . $searchval . '%'];
            $lmap      = [];
            $lmap[]    = ['title', 'like', '%' . $searchval . '%'];
            $worklike  = WorkerModel::where($lmap)->select();

            $wkids = [];
            foreach ($worklike as $lk => $v) {
                $wkids[] = $v["id"];
            }
            $whereor[] = ['workerid', 'in', $wkids];
        }
        $cateid = input('cateid/s', "");
        if (!empty($cateid)) {
            $map[] = ['cateid', 'IN', $cateid];
        }
        $wtype = input('wtype/d', 0);
        if ($wtype != 0) {
            $map[] = ['wtype', '=', $wtype];
        }
        $rectype = input('rectype/d', 0);
        if ($rectype != 0) {
            $map[] = ['recruitment_cate', '=', $rectype];
        }
        $district = input('district/s', "");
        if (!empty($district)) {
            $map[] = ['district', '=', $district];
        }
        $community = input('community/s', "");
        if (!empty($community)) {
            $map[] = ['community', '=', $community];
        }
        $orderby = ['status' => 'asc', 'updatetime' => 'desc', 'id' => 'desc'];
        $plist   = ComjobsModel::with(['worker'])->where($map)->where(function ($q) use ($whereor) {
            $q->whereOr($whereor);
        })->order($orderby)->page($ppage)->limit($psize)->select();

        //数据处理
        //第三方id
        $third_ids   = [];
        $third_lists = [];
        foreach ($plist as $l) {
            if (!empty($l['third_id'])) {
                $third_ids[] = $l['third_id'];
            }
        }
        if (!empty($third_ids)) {
            $third_lists = WorkerThird::where('id', 'in', $third_ids)->column('*', 'id');
        }
        $plist = $plist->toArray();
        foreach ($plist as $k => $v) {
            if (!empty($v['third_id'])) {
                $plist[$k]['worker']['title'] = $third_lists[$v['third_id']]['name'];
            }
        }

        page_result(0, "", [
            'plist'   => $plist,
            'pstatus' => $psize > count($plist) ? 'noMore' : 'more',
        ]);
    }

    // 招聘详情
    public function getComjobs()
    {
        $comjobsid = input('comjobsid/d', 0);
        $comjobs   = ComjobsModel::with('worker')->where('status', 'in', '3,4')->where('id', '=', $comjobsid)->findOrEmpty();
        if (!empty($comjobs['company_name'])) {
            $comjobs['worker']['title']    = $comjobs['company_name'];
            $comjobs['worker']['city']     = $comjobs['city'];
            $comjobs['worker']['district'] = $comjobs['district'];
            $comjobs['worker']['address']  = $comjobs['address'];
        }
        if ($comjobs->isEmpty()) {
            page_result(1, "招聘信息不存在。");
        }
        $comjobs->inc('volume', 1)->update();
        $comjobslist  = ComjobsModel::with('worker')->where(['status' => 3, 'workerid' => $comjobs->workerid])->where('createtime', '<=', time())->order(['updatetime' => 'desc', 'createtime' => 'desc', 'id' => 'desc'])->limit(5)->select();
        $userid       = input('userid/d', 0);
        $comjobsstar  = ComjobsStarModel::where(['userid' => $userid, 'comjobsid' => $comjobsid])->count();
        $workerlog    = WorkerLogModel::where(['workerid' => $comjobs->workerid, 'userid' => $userid])->whereDay('createtime')->findOrEmpty();
        $comjobsshare = ComjobsShareModel::where(['status' => 1])->order(['priority' => 'desc', 'id' => 'desc'])->select();
        if ($workerlog->isEmpty()) {
            WorkerLogModel::create([
                'workerid'   => $comjobs->workerid,
                'userid'     => $userid,
                'ltotal'     => 1,
                'createtime' => date("Y-m-d"),
            ]);
        } else {
            $workerlog->inc('ltotal', 1)->update();
        }
        if ($userid == 0) {
            $brokertol = 0;
        } else {
            $brokertol = BrokerModel::where('userid', '=', $userid)->where('status', '=', 1)->where('powerreport', '=', 1)->count();
        }
        page_result(0, "", [
            'comjobs'      => $comjobs,
            'comjobslist'  => $comjobslist,
            'comjobsstar'  => $comjobsstar,
            'comjobsshare' => $comjobsshare,
            'brokertol'    => $brokertol,
        ]);
    }

    // 招聘海报
    public function getComjobsImage()
    {
        $comjobsid = input('comjobsid/d', 0);
        $shareid   = input('shareid/d', 0);
        $userid    = input('userid/d', 0);
        $share     = ComjobsShareModel::findOrEmpty($shareid);
        $user      = UserModel::findOrEmpty($userid);
        $comjobs   = ComjobsModel::findOrEmpty($comjobsid);
        if ($share->isEmpty() || $user->isEmpty() || $comjobs->isEmpty()) {
            page_result(1, "招聘、海报或用户信息不存在");
        }
        $filename       = $comjobsid . "_" . $userid . "_post.jpg";
        $dst_comjobspic = root_path("public/attachment/comjobspic") . $filename;
        $url_comjobspic = request()->domain() . "/attachment/comjobspic/" . $filename;
        $wxprogram      = new WxProgram();
        $comjobspic     = $wxprogram->wxacode_get_unlimited($comjobsid . "&" . $userid, "pages/comjobs/detail", 430, "attachment/comjobspic/" . $comjobsid . "_" . $userid . ".jpg");
        image_copy_image($share->tilpic, $comjobspic, 500, 1270, 200, 200, $dst_comjobspic);
        image_copy_image($url_comjobspic, $user->avatar, 50, 1040, 90, 90, $dst_comjobspic);

        $font = root_path("public/static/images") . "msyh.ttf";

        $fnickname = subtext($user->nickname, 16);
        image_copy_text($dst_comjobspic, $fnickname, $font, 24, 0, 170, 1070, 0x00, 0x00, 0x00);

        $ftitle = subtext($comjobs->title, 20);
        image_copy_text($dst_comjobspic, $ftitle, $font, 20, 0, 60, 1200, 0x66, 0x66, 0x66);

        $texttil = "";
        if ($comjobs->wtype == 1) {
            $texttil .= $comjobs->bwagall . "~" . $comjobs->zwagall . "元/月";
        } elseif ($comjobs->wtype == 2) {
            $texttil .= $comjobs->bwagall . "元/日";
        } elseif ($comjobs->wtype == 3) {
            $texttil .= $comjobs->bwagall . "元/时";
        } elseif ($comjobs->wtype == 4) {
            $texttil .= "其他";
        }
        $texttil .= " | " . $comjobs->city . " | " . $comjobs->agegroup;
        $texttil = subtext($texttil, 35);
        image_copy_text($dst_comjobspic, $texttil, $font, 20, 0, 60, 1255, 0x66, 0x66, 0x66);
        page_result(0, "", [
            'comjobspic' => $url_comjobspic,
        ]);
    }

    // public function getComjobsImage()
    // {
    // 	$comjobsid = input('comjobsid/d', 0);
    // 	$comjobs = ComjobsModel::where('status','in','3,4')->where('id','=',$comjobsid)->findOrEmpty()->toArray();
    // 	if (empty($comjobs)){
    // 		page_result(1, "招聘信息不存在。");
    // 	}
    // 	$userid = input('userid/d',0);
    // 	$user = UserModel::findOrEmpty($userid);

    // 	$filename = $comjobsid."_".$userid."_".md5(time()).".jpg";
    // 	$dst_comjobspic = root_path("public/attachment/comjobspic").$filename;
    // 	$url_comjobspic = request()->domain()."/attachment/comjobspic/".$filename;

    // 	$shareid = input('shareid/d',0);
    // 	$share = WorkerShareModel::findOrEmpty($shareid);

    // 	$bg_image = request()->domain() ."/static/images/comjobs_bg.jpg";
    // 	image_copy_image($bg_image, $user->avatar, 55,170,640,320,$dst_comjobspic);

    // 	$scene = $comjobsid."&".$userid;
    // 	$wxprogram = new WxProgram();
    // 	$comjobscode = $wxprogram->wxacode_get_unlimited($scene, "pages/comjobs/detail", 430, "attachment/comjobspic/".md5(time()).".jpg");
    // 	image_copy_image($url_comjobspic, $comjobscode, 285,940,180,180,$dst_comjobspic);

    // 	$font = root_path("public/static/images")."msyh.ttf";
    // 	$title = subtext($comjobs['title'], 12);
    // 	image_copy_text($dst_comjobspic, $title, $font, 32, 750, 580, 0x2c, 0xac, 0x3f);

    // 	$tags = @implode(" ", $comjobs['tags']);
    // 	$tags = subtext($tags, 12);
    // 	image_copy_text($dst_comjobspic, $tags, $font, 24, 740, 650, 0x03, 0x32, 0xa4);

    // 	if ($comjobs['wtype']==1){
    // 		$wagall = '薪资待遇：'.  $comjobs['bwagall'].'-'.$comjobs['zwagall'].'元/月';
    // 	}elseif ($comjobs['wtype']==2){
    // 		$wagall = '薪资待遇：'.  $comjobs['bwagall'].'元/日';
    // 	}elseif ($comjobs['wtype']==3){
    // 		$wagall = '薪资待遇：'.  $comjobs['bwagall'].'元/时';
    // 	}elseif ($comjobs['wtype']==4){
    // 		$wagall = '薪资待遇：其他';
    // 	}
    // 	image_copy_text($dst_comjobspic, $wagall, $font, 24, 750, 710, 0x03, 0x32, 0xa4);

    // 	image_copy_text($dst_comjobspic, config('wxconfig.appName'), $font, 36, 750, 90, 0xff, 0xff, 0xff);

    // 	page_result(0, "", array(
    // 		'comjobspic'	=> $url_comjobspic
    // 		));
    // }


    // 招聘海报
    public function getComjobsCode()
    {
        $comjobsid = input('comjobsid/d', 0);
        $comjobs   = ComjobsModel::where('status', 'in', '3,4')->where('id', '=', $comjobsid)->findOrEmpty()->toArray();
        if (empty($comjobs)) {
            page_result(1, "招聘信息不存在。");
        }
        $userid = input('userid/d', 0);
        $user   = UserModel::findOrEmpty($userid);

        $filename       = $comjobsid . "_" . $userid . "_" . md5(time()) . ".jpg";
        $dst_comjobspic = root_path("public/attachment/comjobspic") . $filename;
        $url_comjobspic = request()->domain() . "/attachment/comjobspic/" . $filename;

        $bg_image = request()->domain() . "/static/images/comjobs_bg.jpg";
        image_copy_image($bg_image, $user->avatar, 55, 170, 640, 320, $dst_comjobspic);

        $scene       = $comjobsid . "&" . $userid;
        $wxprogram   = new WxProgram();
        $comjobscode = $wxprogram->wxacode_get_unlimited($scene, "pages/comjobs/detail", 430, "attachment/comjobspic/" . md5(time()) . ".jpg");
        image_copy_image($url_comjobspic, $comjobscode, 285, 940, 180, 180, $dst_comjobspic);

        $font  = root_path("public/static/images") . "msyh.ttf";
        $title = subtext($comjobs['title'], 12);
        image_copy_text($dst_comjobspic, $title, $font, 32, 750, 580, 0x2c, 0xac, 0x3f, 0x00);

        $tags = @implode(" ", $comjobs['tags']);
        $tags = subtext($tags, 12);
        image_copy_text($dst_comjobspic, $tags, $font, 24, 740, 650, 0x03, 0x32, 0xa4, 0x00);

        if ($comjobs['wtype'] == 1) {
            $wagall = '薪资待遇：' . $comjobs['bwagall'] . '-' . $comjobs['zwagall'] . '元/月';
        } elseif ($comjobs['wtype'] == 2) {
            $wagall = '薪资待遇：' . $comjobs['bwagall'] . '元/日';
        } elseif ($comjobs['wtype'] == 3) {
            $wagall = '薪资待遇：' . $comjobs['bwagall'] . '元/时';
        } elseif ($comjobs['wtype'] == 4) {
            $wagall = '薪资待遇：其他';
        }
        image_copy_text($dst_comjobspic, $wagall, $font, 24, 750, 710, 0x03, 0x32, 0xa4, 0x00);

        image_copy_text($dst_comjobspic, config('wxconfig.appName'), $font, 36, 750, 90, 0xff, 0xff, 0xff, 0x00);

        page_result(0, "", [
            'comjobspic' => $url_comjobspic,
        ]);
    }


    // 关注招聘信息
    public function delStar()
    {
        $starid = input('starid/d', 0);
        $userid = input('userid/d', 0);
        $star   = ComjobsStarModel::where(['id' => $starid, 'userid' => $userid])->findOrEmpty();
        if ($star->isEmpty()) {
            page_result(1, "关注信息不存在或已被删除。");
        }
        $star->delete();
        page_result(0, "", []);
    }

    public function setComjobsStar()
    {
        $comjobsid = input('comjobsid/d', 0);
        $comjobs   = ComjobsModel::findOrEmpty($comjobsid);
        if ($comjobs->isEmpty()) {
            page_result(1, "招聘信息不存在");
        }
        $userid = input('userid/d', 0);
        $user   = UserModel::findOrEmpty($userid);
        if ($user->isEmpty()) {
            page_result(1, "用户信息不存在");
        }
        $star = ComjobsStarModel::where(['userid' => $userid, 'comjobsid' => $comjobsid])->findOrEmpty();
        if ($star->isEmpty()) {
            $star->save([
                'comjobsid'  => $comjobsid,
                'userid'     => $userid,
                'createtime' => time(),
            ]);
            page_result(0, "", ['comjobsstar' => 1]);
        } else {
            $star->delete();
            page_result(0, "", ['comjobsstar' => 0]);
        }
    }

    public function listStar()
    {
        $ppage  = input('ppage/d', 1);
        $psize  = input('psize/d', 20);
        $userid = input('userid/d', 0);
        $map[]  = ['userid', '=', $userid];
        $plist  = ComjobsStarModel::with(['comjobs.worker'])->where($map)->order(['createtime' => 'desc', 'id' => 'desc'])->page($ppage)->limit($psize)->select();
        page_result(0, "", [
            'plist'   => $plist,
            'pstatus' => $psize > count($plist) ? 'noMore' : 'more',
        ]);
    }

    // 报名招聘信息
    public function delLog()
    {
        $logid  = input('logid/d', 0);
        $userid = input('userid/d', 0);
        $log    = ComjobsLogModel::where(['id' => $logid, 'userid' => $userid])->findOrEmpty();
        if ($log->isEmpty()) {
            page_result(1, "报名记录信息不存在或已被删除。");
        }
        $log->delete();
        page_result(0, "", []);
    }

    public function listLog()
    {
        $ppage  = input('ppage/d', 1);
        $psize  = input('psize/d', 20);
        $userid = input('userid/d', 0);
        $map[]  = ['userid', '=', $userid];
        $plist  = ComjobsLogModel::with(['comjobs.worker'])->where($map)->order(['createtime' => 'desc', 'id' => 'desc'])->page($ppage)->limit($psize)->append(['status_text'])->select();
        page_result(0, "", [
            'plist'   => $plist,
            'pstatus' => $psize > count($plist) ? 'noMore' : 'more',
        ]);
    }

    public function setComjobsLog()
    {
        $comjobsid = input('comjobsid/d', 0);
        $comjobs   = ComjobsModel::findOrEmpty($comjobsid);
        if ($comjobs->isEmpty()) {
            page_result(1, "招聘信息不存在");
        }
        if (strtotime($comjobs->enddate) + 86400 < time()) {
            page_result(1, "该招聘信息报名已截止，不能再报名了。");
        }
        $userid = input('userid/d', 0);
        $user   = UserModel::findOrEmpty($userid);
        if ($user->isEmpty()) {
            page_result(1, "用户信息不存在");
        }
        $log    = ComjobsLogModel::where(['comjobsid' => $comjobsid, 'userid' => $userid])->findOrEmpty();
        $worker = WorkerModel::where('id', $comjobs->workerid)->field(['id', 'is_public', 'mobile'])->find();
        $return = ['is_public' => $worker['is_public']];
        if ($worker['is_public'] == 1) {
            $return['mobile'] = $comjobs['telephone'];
        }
        if ($log->isEmpty()) {
            $log->save([
                'workerid'   => $comjobs->workerid,
                'comjobsid'  => $comjobsid,
                'userid'     => $userid,
                'status'     => 1,
                'remark'     => "",
                'createtime' => time(),
            ]);
            UserFollowModel::create([
                'userid'     => $userid,
                'ftype'      => "招聘报名",
                'fstatus'    => 1,
                'remark'     => $comjobs->title,
                'createtime' => time(),
            ]);

            if ($worker['mobile']) {
                $msg    = '尊敬的雇主您好！已有候选人在“晋江人力”小程序上投递简历应聘您发布的岗位，请您及时查看处理！';
                $mobile = $worker['mobile'];
                $sms    = new Chuanglan();
                $sms->send($mobile, ['message' => $msg]);
            }

            $return['msg'] = '恭喜您，报名成功，我们会尽快给您安排面试上班!!!。';
            page_result(0, "", $return);
        } else {
            $return['msg'] = '你已报名过了，无需重复报名。';
            page_result(0, "", $return);
        }
    }

    public function shareComjobs()
    {
        $userid = input('userid/d', 0);

        $param = UserParamModel::where(1)->findOrEmpty();
        if (!empty($param['sharejobnum'])) {
            $check = UserIntegralModel::where('createtime','>=',strtotime(date('Y-m-d')))
                ->where('createtime','<=',strtotime(date('Y-m-d 23:59:59')))
                ->where('userid',$userid)
                ->where('itype',10)
                ->count();
            if ($check >= $param['sharejobnum']) {
                page_result(0, "已超过次数");
            }
        }

        /*$integralService = new IntegralService();
        $integralService->add($userid,IntegralService::SHAREJOB,10);*/
        page_result(0, "分享成功");
    }

}