<?php

namespace app\api\controller;

use app\api\model\Category;
use app\api\model\Factory;
use app\api\model\Job;
use app\api\model\JobCollect;
use app\api\model\JobKeyword;
use app\common\model\Inform;
use app\common\model\Label;
use app\common\model\User;
use fast\Tree;
use app\common\controller\Wechat;
use app\common\controller\Api;

/**
 * 首页接口
 * @ApiWeigh(2)
 */
class Index extends Api
{
    protected $noNeedLogin = ['categoryList','factoryList','jobList','jobInfo','agentContent'];
    protected $noNeedRight = ['*'];

    /**
     * @ApiWeigh    (99)
     * @ApiTitle    (首页分类)
     * @ApiSummary  (首页分类)
     * @ApiMethod   (POST)
     *
     * @ApiReturn({
        "code": 1,
        "msg": "请求成功",
        "time": "1605707229",
        "data": [{
            "id": 1, //分类ID
            "name": "附近工作", //分类名称
            "image": "https://app.mockplus.cn/api/v1/file/thumb?&img=https://img02.mockplus.cn/idoc/sketch/2020-11-02/4077abe2-8f9e-4cf0-b95f-7a402ba0394e.F42C51D8-3246-425F-B6D9-436A3BD0FF3B.png&p=25"
        }]
    })
     */
    public function categoryList()
    {
        $list = Category::order('weigh asc')->field('id,name,image')->select();
        $this->success('请求成功',$list);
    }

    /**
     * @ApiWeigh    (97)
     * @ApiTitle    (工厂列表)
     * @ApiSummary  (工厂列表)
     * @ApiMethod   (POST)
     *
     * @ApiReturn({
        "code": 1,
        "msg": "请求成功",
        "time": "1605944895",
        "data": [{
            "id": 2, //工厂ID
            "factory_name": "你好", //工厂名称
            "factory_price": "1.00" //工厂工价
        }]
    })
     */
    public function factoryList()
    {
        $list = Factory::order('weigh desc')->field('id,factory_name,factory_price')->select();
        $this->success('请求成功',$list);
    }

    /**
     * @ApiWeigh (95)
     * @ApiTitle    (搜索历史)
     * @ApiSummary  (搜索历史)
     * @ApiMethod   (POST)
     *
     * @ApiHeaders  (name=token, type=string, required=false, description="请求的Token")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1606218663",
        "data": [ //关键词
            "nihao"
        ]
    })
     */
    public function keywordList()
    {
        $list = JobKeyword::where('user_id',$this->auth->id)
            ->order('updatetime desc')
            ->limit(10)
            ->column('keyword');
        $this->success('成功',$list);
    }

    /**
     * @ApiWeigh (93)
     * @ApiTitle    (搜索历史-清空)
     * @ApiSummary  (搜索历史-清空)
     * @ApiMethod   (POST)
     *
     * @ApiHeaders  (name=token, type=string, required=false, description="请求的Token")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1601351666",
        "data": null
    })
     */
    public function keywordClear()
    {
        JobKeyword::where('user_id',$this->auth->id)->delete();
        $this->success('清空搜索历史成功');
    }

    /**
     * @ApiWeigh    (91)
     * @ApiTitle    (附近工作 | 长期工 | 短期工 | 兼职)
     * @ApiSummary  (职位列表)
     * @ApiMethod   (POST)
     *
     * @ApiHeaders (name=token, type=string, required=false, description="请求的Token")
     * @ApiParams   (name="page", type="inter", required=false, description="当前页(默认1)")
     * @ApiParams   (name="page_num", type="inter", required=false, description="每页显示数据个数(默认10)")
     * @ApiParams   (name="lng", type="string", required=false, description="经度,(附近工作必填)")
     * @ApiParams   (name="lat", type="string", required=false, description="纬度,(附近工作必填)")
     * @ApiParams   (name="type", type="string", required=false, description="分类:1=长期工,2=兼职,3=短期工")
     * @ApiParams   (name="keyword", type="string", required=false, description="搜索关键词")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1605954640",
        "data": {
            "total": 2, //数据总数
            "per_page": 15,
            "current_page": 1,
            "last_page": 1,
            "data": [{
                "id": 2, //职位ID
                "job_name": "测试职位2", //职位名称
                "cover": "http://www.recruit.top/uploads/20201121/3451459c2469a191a84de24d2e6852b5.png", //职位封面图
                "factory_price": "40.00", //工厂工价(元/时)
                "subsidy_price": "40.00", //平台补贴(元/时)
                "factory_price_total": "40.00", //工价
                "salary": "6000~7000", //月收入
                "people_num": 23, //报名人数
                "label_name": [     //标签
                    "包吃",
                    "包住"
                ]
            }]
        }
    })
     */
    public function jobList()
    {
        $page = $this->request->param('page', 1, 'intval');
        $page_num = $this->request->param('page_num', 10, 'intval');
        $lng = $this->request->param('lng');
        $lat = $this->request->param('lat');
        $type = $this->request->param('type'); //分类:1=长期工,2=兼职,3=短期工
        $keyword = $this->request->param('keyword');
        $where = '';
        // 关键字
        if(!empty($keyword)){
            // 记录搜索关键词
            if($this->auth->id){
                $has = JobKeyword::where('user_id',$this->auth->id)
                    ->where('keyword',$keyword)
                    ->find();
                if(!$has){
                    $keyword_list = JobKeyword::order('createtime asc')->select();
                    // 超过10条的删除
                    if(count($keyword_list) > 10){
                        JobKeyword::where('id',$keyword_list[0]['id'])->delete();
                    }
                    JobKeyword::create([
                        'user_id' => $this->auth->id,
                        'keyword' => $keyword
                    ]);
                }else{
                    $has->updatetime = time();
                    $has->save();
                }
            }
            $where .= "job_name like '%{$keyword}%'";
            $wherela = "title like '%{$keyword}%'";
            $ids = Label::where($wherela)->field('id')->column('id');   //标签所有id
            if(!empty($ids)){
                // 标签搜索
                $label_findinset = [];
                foreach ($ids as $label_id){
                    $label_findinset[] = "find_in_set({$label_id},label_ids)";
                }
                $label_where = implode(' or ',$label_findinset);
                $where = "($where or ($label_where))";
            }
        }
        $where .= $where ? ' and ' : '';
        $where .= "putdata = '0'";
        // 哪些人及其下级可查看
        if($this->auth->id){
            $parentsIds = Tree::instance()->init(collection(User::select())->toArray())->getParentsIds($this->auth->id, true);
            // 部分可看
            $findinset = [];
            foreach ($parentsIds as $pid){
                $findinset[] = "find_in_set({$pid},user_ids)";
            }
            // 部分不可看
            $findinsetn = [];
            foreach ($parentsIds as $pid){
                $findinsetn[] = "find_in_set({$pid},user_ids) = 0";
            }
            $where .= $where ? ' and ' : '';
            $where .= "((".implode(' or ',$findinset)." and lookdata = '1') or (lookdata = '0') or (".implode(' or ',$findinsetn)." and lookdata = '2'))";
        }
        // 附近
        $juli = 0;
        if($lng && $lat){
            $juli = "ROUND(
                6378.138 * 2 * ASIN(
                    SQRT(
                        POW(
                            SIN(
                                (
                                    {$lat} * PI() / 180 - lat * PI() / 180
                                ) / 2
                            ),
                            2
                        ) + COS({$lat} * PI() / 180) * COS(lat * PI() / 180) * POW(
                            SIN(
                                (
                                    {$lng} * PI() / 180 - lng * PI() / 180
                                ) / 2
                            ),
                            2
                        )
                    )
                ) * 1000
            )";
        }
        // 职位类型
        if($type){
            $where .= $where ? ' and ' : '';
            $where .= "find_in_set({$type},type)";
        }
        $data = Job::where($where)
            ->field("*,$juli juli,if($juli > 1000,CONCAT(ROUND($juli/1000,1),'km'),CONCAT($juli,'m')) distance")
            ->order(['juli'=>'asc','weigh'=>'desc'])
            ->paginate($page_num,false,['page'=>$page])
            ->each(function($v){
                $v->visible(['id','cover','job_name','salary','people_num','factory_price_total','factory_price','subsidy_price','label_ids'])->append(['distance']);
            })->toArray();
        $this->success('成功',$data);
    }

    /**
     * @ApiWeigh    (91)
     * @ApiTitle    (职位收藏)
     * @ApiSummary  (职位收藏)
     * @ApiMethod   (POST)
     *
     * @ApiHeaders (name=token, type=string, required=false, description="请求的Token")
     * @ApiParams   (name="page", type="inter", required=false, description="当前页(默认1)")
     * @ApiParams   (name="page_num", type="inter", required=false, description="每页显示数据个数(默认10)")
     * @ApiParams   (name="keyword", type="string", required=false, description="搜索关键词")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1605954640",
        "data": {
            "total": 2, //数据总数
            "per_page": 15,
            "current_page": 1,
            "last_page": 1,
            "data": [{
                "id": 2, //职位ID
                "job_name": "测试职位2", //职位名称
                "cover": "http://www.recruit.top/uploads/20201121/3451459c2469a191a84de24d2e6852b5.png", //职位封面图
                "factory_price": "40.00", //工厂工价(元/时)
                "subsidy_price": "40.00", //平台补贴(元/时)
                "factory_price_total": "40.00", //工价
                "salary": "6000~7000", //月收入
                "people_num": 23 //报名人数
            }]
        }
    })
     */
    public function collectList()
    {
        $page = $this->request->param('page', 1, 'intval');
        $page_num = $this->request->param('page_num', 10, 'intval');
        $keyword = $this->request->param('keyword');
        $where = '';
        // 关键字
        if(!empty($keyword)){
            // 记录搜索关键词
            if($this->auth->id){
                $has = JobKeyword::where('user_id',$this->auth->id)
                    ->where('keyword',$keyword)
                    ->find();
                if(!$has){
                    $keyword_list = JobKeyword::order('createtime asc')->select();
                    // 超过10条的删除
                    if(count($keyword_list) > 10){
                        JobKeyword::where('id',$keyword_list[0]['id'])->delete();
                    }
                    JobKeyword::create([
                        'user_id' => $this->auth->id,
                        'keyword' => $keyword
                    ]);
                }else{
                    $has->updatetime = time();
                    $has->save();
                }
            }
            $where .= "j.job_name like '%{$keyword}%'";
        }
        // 哪些人及其下级可查看
        if($this->auth->id){
            $parentsIds = Tree::instance()->init(collection(User::select())->toArray())->getParentsIds($this->auth->id, true);
            foreach ($parentsIds as $pid){
                $findinset[] = "find_in_set({$pid},user_ids)";
            }
            $where .= $where ? ' and ' : '';
            $where .= "(".implode(' or ',$findinset)." or user_ids = '')";
        }

        $data = Job::alias('j')
            ->join('job_collect jc','jc.job_id = j.id and user_id = '.$this->auth->id)
            ->where($where)
            ->field('j.*')
            ->order(['jc.createtime'=>'desc','j.weigh'=>'desc'])
            ->paginate($page_num,false,['page'=>$page])
            ->each(function($v){
                $v->visible(['id','cover','job_name','salary','people_num','factory_price_total','factory_price','subsidy_price']);
            })->toArray();
        $this->success('成功',$data);
    }

    /**
     * @ApiWeigh    (89)
     * @ApiTitle    (职位详情)
     * @ApiSummary  (职位详情)
     * @ApiMethod   (POST)
     *
     * @ApiParams   (name="job_id", type="inter", required=true, description="职位ID")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1606033046",
        "data": {
            "id": 1, //职位ID
            "job_name": "测试职位", //职位名称
            "images": [{ //图片
                "type": "image", //文件类型:image=图片,video=视频
                "url": "http://www.recruit.top/uploads/20201121/3451459c2469a191a84de24d2e6852b5.png" //文件地址
            }],
            "content": "<p>456</p>", //职位详情
            "factory_price": "60.00", //正常工价
            "subsidy_price": "10.00", //平台补贴价格
            "factory_price_total": "70.00", //补贴后工价
            "salary": "5000~6000", // 月收入
            "label_name": [         //标签
                "包吃",
                "包住"
            ],
            "is_collect": 0 ,//是否收藏:0=否,1=是
            "inform": {//通知
                "id": 5,   //通知id
                "content": "hi哈佛地方",   //通知内容
                "status": "1",
                "job_id": 7
            }
        }
    })
     */
    public function jobInfo()
    {
        $user_id = $this->auth->id;  //用户id
        $job_id = $this->request->param('job_id');
        empty($job_id) && $this->error('缺少必需参数');
        $info = Job::get($job_id);
        empty($info) && $this->error('职位信息不存在');
        $collect = JobCollect::where('user_id',$this->auth->id)->where('job_id',$job_id)->find();
        $info->is_collect = !empty($collect) ? 1 : 0;
        $deposit = new Inform;
        $info['inform'] = $deposit->where(['status'=>'1','job_id'=>$job_id,'deletetime'=>null])->order('id desc')->field('id,content,status,job_id')->find();
        $info->visible(['id','images','job_name','factory_price_total','factory_price','subsidy_price','salary','content','lng','lat','label_ids'])->append(['is_collect','inform']);
        $info['content'] = str_replace("<img src=\"/uploads", "<img style=\"width: 100%;!important\" src=\"" . request()->domain() . "/uploads", $info['content']);
        $this->success('成功',$info);
    }

    /**
     * @ApiWeigh    (87)
     * @ApiTitle    (收藏职位)
     * @ApiSummary  (收藏职位)
     * @ApiMethod   (POST)
     *
     * @ApiParams   (name="job_id", type="inter", required=true, description="职位ID")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "收藏成功/取消收藏成功",
        "time": "1606033046",
        "data": null
    })
     */
    public function jobCollect()
    {
        $job_id = $this->request->param('job_id');
        empty($job_id) && $this->error('缺少必需参数');
        $info = Job::get($job_id);
        empty($info) && $this->error('职位信息不存在');
        $where = [
            'user_id' => $this->auth->id,
            'job_id' => $job_id
        ];
        $collect = JobCollect::where($where)->find();
        if(!empty($collect)){
            $collect->delete();
            $this->success('取消收藏成功');
        }
        JobCollect::create($where);
        $this->success('收藏成功');
    }

    /**
     * @ApiWeigh    (85)
     * @ApiTitle    (职位海报)
     * @ApiSummary  (职位海报)
     * @ApiMethod   (POST)
     * @ApiParams   (name="job_id", type="inter", required=true, description="职位ID")
     * @ApiReturn   ({
        'code':'1',
        'msg':'返回成功',
        "data": {
            "url": "http://www.recruit.top/uploads/job/1.png", //职位海报地址
        }
    })
     */
    public function jobPoster()
    {
        $job_id = $this->request->param('job_id');
        empty($job_id) && $this->error('缺少必需参数');
        $job = Job::get($job_id);
        empty($job) && $this->error('职位信息不存在');

        // 本地路径
        $dir = 'uploads/job';
        if (!file_exists($dir)){
            mkdir($dir,0777,true);
        }

        // 职位小程序码
        $user_id = $this->auth->id > 0 ? $this->auth->id : 0;
        $qrcode_id = "{$job_id}_{$user_id}";
        $qrcode = $dir.'/qrcode_'.$qrcode_id.'.png';
//        $qrcode_width = 192;
        $qrcode_width = 1100;
        if(!file_exists($qrcode) || imagesx(imagecreatefromjpeg(ROOT_PATH.'public/'.$qrcode)) != $qrcode_width){
            $response = Wechat::miniProgram()->app_code->getUnlimit($qrcode_id, [
                'page'  => 'pages/zhiwei_xq/zhiwei_xq',
                'width' => $qrcode_width, //最小宽度280
            ]);
            if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
                $response->saveAs($dir, str_replace($dir.'/','',$qrcode));
            }
            // 280不满足,再缩小
            \think\Image::open($qrcode)->thumb($qrcode_width,$qrcode_width,\think\Image::THUMB_CENTER)->save($qrcode);
        }

//        //将职位图片首图保存到本地
//        $images = db('job')->where('id',$job_id)->value('images');
//        $image = cdnurl(explode(',',$images)[0],true);
//        // $image = 'https://recruit.brofirst.cn'.explode(',',$images)[0];
//        $job_image = $dir.'/image_'.$job_id.'.png';
//        file_put_contents($job_image,file_get_contents($image));
//        \think\Image::open($job_image)->thumb(637,352,\think\Image::THUMB_CENTER)->save($job_image);
//
//        $path_ttf = ROOT_PATH.'public/assets/fonts/PingFang.ttf';
//        $filename = $dir.'/'.$job_id.'.png';
//
//        $image = \think\Image::open(ROOT_PATH.'public/assets/img/miniProgram/job_back_v2.png');
//        // 职位名称居中
//        $size = 30;
//        $box1 = imagettfbbox($size, 0, $path_ttf, $job['job_name']);
//        $box1_minx = min($box1[0], $box1[2], $box1[4], $box1[6]);
//        $box1_maxx = max($box1[0], $box1[2], $box1[4], $box1[6]);
//        /* 计算文字初始坐标和尺寸 */
//        $w = $box1_maxx - $box1_minx;
//        $box1_minx += ($image->width() - $w) / 2;
//
//        // 工价
//        $size_11 = 25;
//        $factory_price_total = '工价:'.$job['factory_price_total'].'元/小时';
//        $box2 = imagettfbbox($size_11, 0, $path_ttf, $factory_price_total);
//        $box2_minx = min($box2[0], $box2[2], $box2[4], $box2[6]);
//        $box2_maxx = max($box2[0], $box2[2], $box2[4], $box2[6]);
//        /* 计算文字初始坐标和尺寸 */
//        $w = $box2_maxx - $box2_minx;
//        $box2_minx += $image->width() - $w - 106;
//
//        // 工资
//        $salary = '工资:'.$job['salary'];
//        $box3 = imagettfbbox($size_11, 0, $path_ttf, $salary);
//        $box3_minx = min($box3[0], $box3[2], $box3[4], $box3[6]);
//        $box3_maxx = max($box3[0], $box3[2], $box3[4], $box3[6]);
//        /* 计算文字初始坐标和尺寸 */
//        $w = $box3_maxx - $box3_minx;
//        $box3_minx += $image->width() - $w - 106;
//
//        // 备注居中
//        $last_text = '码上报名';
//        $box4 = imagettfbbox($size, 0, $path_ttf, $last_text);
//        $box4_minx = min($box4[0], $box4[2], $box4[4], $box4[6]);
//        $box4_maxx = max($box4[0], $box4[2], $box4[4], $box4[6]);
//        /* 计算文字初始坐标和尺寸 */
//        $w = $box4_maxx - $box4_minx;
//        $box4_minx += ($image->width() - $w) / 2;
//
//        $image->water($job_image,[25,25])
//            ->text($job['job_name'],$path_ttf,$size,'#323233',[$box1_minx,411])
//            ->text($job['job_name'],$path_ttf,$size,'#323233',[$box1_minx+1,411]) //画两遍,加粗
//            ->text($factory_price_total,$path_ttf,$size_11,'#323233',[$box2_minx,477])
//            ->text($factory_price_total,$path_ttf,$size_11,'#323233',[$box2_minx+1,477])
//            ->text($salary,$path_ttf,$size_11,'#323233',[$box3_minx,532])
//            ->text($salary,$path_ttf,$size_11,'#323233',[$box3_minx+1,532])
//            ->text($last_text,$path_ttf,$size,'#FE9515',[$box4_minx,641])
//            ->text($last_text,$path_ttf,$size,'#FE9515',[$box4_minx+1,641])
//            ->water($qrcode,[249,698])
//            ->save($filename);
//        $url = request()->domain().'/'.$filename.'?v='.time();
        $url = request()->domain().'/'.$qrcode.'?v='.time();
        $this->success('成功',compact('url'));
    }

    /**
     * @ApiWeigh    (83)
     * @ApiTitle    (入驻代理)
     * @ApiSummary  (入驻代理)
     * @ApiMethod   (POST)
     * @ApiReturn   ({
        'code':'1',
        'msg':'返回成功',
        "data": "<p>入驻代理介绍</p>" //入驻代理介绍
    })
     */
    public function agentContent()
    {
        $this->success('成功',config('site.agent_content'));
    }
}