<?php

namespace app\mainapp\controller;

use app\common\model\Config;
use app\common\model\RensheCode;
use app\common\model\Village;
use app\common\model\WorkerThird;
use app\common\service\RensheService;
use app\mainapp\BaseController;
use think\facade\Db;

use app\common\model\Slide as SlideModel;
use app\common\model\Article as ArticleModel;
use app\common\model\Navigation as NavigationModel;

use app\common\model\User as UserModel;
use app\common\model\Worker as WorkerModel;
use app\common\model\Agent as AgentModel;

use app\common\model\Comjobs as ComjobsModel;
use app\common\model\Param as ParamModel;

use app\common\model\Sinpage as SinpageModel;
use app\common\model\ComjobsCate as ComjobsCateModel;

class Index extends BaseController
{

    public function getHomeData()
    {
        $userid    = input('userid/d', 0);
        $workerall = WorkerModel::where('userid', '=', $userid)->select();
        $sinpage   = SinpageModel::where(1)->find();
        page_result(0, "", [
            'apptreaty' => $sinpage->apptreaty,
            'workerall' => $workerall->isEmpty() ? null : $workerall,
        ]);
    }

    public function getIndexData()
    {
        $param      = ParamModel::where(1)->find();
        $slide      = SlideModel::where('pagetab', '=', 'index')->order(['priority' => 'desc', 'id' => 'desc'])->limit(10)->select();
        $navigation = NavigationModel::where('pagetab', '=', 'index')->order(['priority' => 'desc', 'id' => 'desc'])->select();
        $article    = ArticleModel::where([['status', '=', 1], ['priority', '>', 0], ['status', '=', 1], ['createtime', '<=', time()]])->order(['priority' => 'desc', 'id' => 'desc'])->limit(10)->select();
        page_result(0, "", [
            'param'      => $param,
            'slide'      => $slide,
            'navigation' => $navigation,
            'article'    => $article,
        ]);
    }

    public function listComjobs()
    {
        $ids = ComjobsModel::where('enddate', '<', time() - 86400)->where('status', '=', 3)->column('id');
        if (!empty($ids)) {
            ComjobsModel::where('id', 'in', $ids)->update(['status' => 4]);
            $service = new RensheService();
            foreach ($ids as $id) {
                $service->jobInfoByComId($id);
            }
        }
        $ppage = input('ppage/d', 1);
        $psize = input('psize/d', 20);
        $map[] = ['createtime', '<=', time()];
        $map[] = ['priority', '>', 0];
        $map[] = ['status', 'in', '3,4'];
        $plist = ComjobsModel::with(['worker'])->where($map)->order(['status' => 'asc', 'priority' => 'desc', 'updatetime' => 'desc', 'id' => 'desc'])->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 listComjobsofnear()
    {
        $lat = input('lat', 0); //纬度
        $lng = input('lng', 0); //经度
        if (input('ppage/d') == '' or input('ppage/d') == 0) {
            $page = 1;
        } else {
            $page = input('ppage/d');
        }
        if (input('psize/d') == '') {
            $limit = 20;
        } else {
            $limit = input('psize/d');
        }
        $pagelistcount = $limit; //每页显示条数
        $sql           = distance_sql($lng, $lat);
        $row           = Db::query("select * ," . $sql . "as distance from echo_comjobs where deletetime=0 and status in (3,4) order by distance limit " . $pagelistcount * ($page - 1) . "," . $pagelistcount);

        //第三方id和工作列表
        $third_ids    = [];
        $third_lists  = [];
        $worker_ids   = [];
        $worker_lists = [];
        foreach ($row as $l) {
            if (!empty($l['third_id'])) {
                $third_ids[] = $l['third_id'];
            }
            $worker_ids[] = $l["workerid"];
        }
        if (!empty($third_ids)) {
            $third_lists = WorkerThird::where('id', 'in', $third_ids)->column('*', 'id');
        }
        if (!empty($worker_ids)) {
            $worker_lists = WorkerModel::where('id', 'in', $worker_ids)->column('*', 'id');
        }

        foreach ($row as $k => $v) {
            $row[$k]["tags"] = json_decode($v["tags"]);
            if (!empty($v['third_id'])) {
                $row[$k]["worker"]["title"] = $third_lists[$v['third_id']]['name'];
            } else {
                $workerinfo                 = $worker_lists[($v["workerid"])];
                $row[$k]["worker"]["title"] = $workerinfo["title"];
            }
            $row[$k]["distance"] = round(calcDistance($lat, $lng, $v["latitude"], $v["longitude"]), 2) . "千米";
        }

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

    }

    public function listComjobsLike()
    {
        $ppage = input('ppage/d', 1);
        $psize = input('psize/d', 20);

        $map[] = ['createtime', '<=', time()];
        $map[] = ['priority', '>', 0];
        $map[] = ['status', 'in', '3,4'];

        $userid = input('userid/d', 0);
        if (!empty($userid)) {
            $user = UserModel::where('id', $userid)->find();
            if (!empty($user['com_cate'])) {
                $ids   = ComjobsCateModel::where('title', 'in', $user['com_cate'])->column('id');
                $map[] = ['cateid', 'in', $ids];
            }
        }
        $plist = ComjobsModel::with(['worker'])->where($map)->order(['status' => 'asc', 'priority' => 'desc', 'updatetime' => 'desc', 'id' => 'desc'])->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 getRensheCode()
    {
        $type = input('type', '');
        if (empty($type)) {
            page_result(0, "", []);
        }

        $list = RensheCode::getList($type);
        page_result(0, "", $list);
    }

    public function getComCate()
    {
        $catelist = ComjobsCateModel::order(['priority' => 'desc', 'id' => 'desc'])->select();
        page_result(0, "", $catelist);
    }

    public function getConfig()
    {
        $code = input('code', '');
        $post = Config::getConfigValue($code);
        page_result(0, "", $post);
    }

    public function getWorker()
    {
        $workerids = AgentModel::field('workerid')->where('status',1)->distinct(true)->select()->column('workerid');
        $list = WorkerModel::field('id,title')->where('status',5)->whereIn('id',$workerids)->select();
        $agent = AgentModel::field('id,title')->where('status',1)->where('workerid',$list[0]['id'])->select();

        page_result(0,'',[$list,$agent]);
    }

    public function getAgentByWorker()
    {
        $workerid = input('workerid',0);
        if (empty($workerid)) {
            page_result(0, "", []);
        }
        $agent = AgentModel::field('id,title')->where('status',1)->where('workerid',$workerid)->select();

        page_result(0,'',$agent);
    }

    public function getTown()
    {
        $town = file_get_contents(root_path('public/static/jscss').'town.json');
        page_result(0,'',json_decode($town,true));
    }
}