<?php

namespace app\mainapp\controller;

use app\mainapp\BaseController;

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\Param as ParamModel;
use app\common\model\WorkerLog as WorkerLogModel;
use app\common\model\DemandSnatch as DemandSnatchModel;

class Demand extends BaseController
{

    // 我接的订单
    public function pageDemandLog()
    {
        page_result(0, "", []);
    }

    public function listDemandLog()
    {
        $ppage     = input('ppage/d', 1);
        $psize     = input('psize/d', 20);
        $gworkerid = input('gworkerid/d', 0);
        $map[]     = ['gworkerid', '=', $gworkerid];
        $status    = input('status/d', 0);
        if (empty($status)) {
            $plist = DemandLogModel::with(['demand', 'worker'])->where($map)->order(['createtime' => 'desc', 'id' => 'desc'])->page($ppage)->limit($psize)->append(['status_text'])->select();
        } else {
            $plist = DemandLogModel::hasWhere('demand', ['status' => $status])->with(['demand', 'worker'])->where($map)->order(['createtime' => 'desc', 'id' => 'desc'])->page($ppage)->limit($psize)->append(['status_text'])->select();
        }


        $plist->append(['demand.ftype_text'])->toArray();
        page_result(0, "", [
            'plist'   => $plist,
            'pstatus' => $psize > count($plist) ? 'noMore' : 'more',
        ]);
    }

    public function delDemandLog()
    {
        $gworkerid = input('gworkerid/d', 0);
        $logid     = input('logid/d', 0);
        $demandlog = DemandLogModel::where(['gworkerid' => $gworkerid])->findOrEmpty($logid);
        if ($demandlog->isEmpty()) {
            page_result(1, "接单记录信息不存在。");
        }
        $demandlog->delete();
        page_result(0, "", []);
    }


    // 招聘总列表
    public function pageDemand()
    {
        $catelist = DemandCateModel::field('id as value, title, priority')->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' => '其他']];
        $ftypelist   = [['value' => 0, 'title' => '全部'], ['value' => 1, 'title' => '一次性'], ['value' => 2, 'title' => '小时工'], ['value' => 3, 'title' => '管理费'], ['value' => 4, 'title' => '其他']];
        $rectypelist = [['value' => 0, 'title' => '全部'], ['value' => 1, 'title' => '普通订单'], ['value' => 2, 'title' => '悬赏单']];
        page_result(0, "", [
            'catelist'     => $catelist,
            'wtypelist'    => $wtypelist,
            'rectypelist'  => $rectypelist,
            'ftypelist'    => $ftypelist,
            'provincelist' => $this->provincelist,
        ]);
    }

    public function listDemand()
    {
        $ppage     = input('ppage/d', 1);
        $psize     = input('psize/d', 20);
        $map       = [];
        $map[]     = ['createtime', '<=', time()];
        $map[]     = ['status', '=', '3'];
        $searchval = input('searchval/s', "");
        if (!empty($searchval)) {
            $map[] = ['title', 'like', '%' . $searchval . '%'];
        }
        $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[] = ['isfree', '=', $rectype];
        }
        $ftype = input('ftype/d', 0);
        if ($ftype != 0) {
            $map[] = ['ftype', '=', $ftype];
        }
        $district = input('district/s', "");
        if (!empty($district)) {
            $map[] = ['district', '=', $district];
        }
        $orderby = ['status' => 'asc', 'updatetime' => 'desc', 'id' => 'desc'];
        $plist   = DemandModel::with(['worker', 'demandCate'])->where($map)->order($orderby)->page($ppage)->limit($psize)->append(['ftype_text', 'type_text'])->select();
        page_result(0, "", [
            'plist'   => $plist,
            'pstatus' => $psize > count($plist) ? 'noMore' : 'more',
        ]);
    }

    // 招聘订单详情
    public function getDemand()
    {
        $demandid = input('demandid/d', 0);
        $demand   = DemandModel::with(['worker'])->where('status', 'in', '3,4')->where('id', '=', $demandid)->append(['ftype_text', 'type_text'])->findOrEmpty();
        if ($demand->isEmpty()) {
            page_result(1, "订单信息不存在。");
        }
        $demand->inc('volume', 1)->update();
        $demandlist = DemandModel::with(['worker', 'demandCate'])->where(['status' => 3, 'workerid' => $demand->workerid])->where('createtime', '<=', time())->order(['updatetime' => 'desc', 'createtime' => 'desc', 'id' => 'desc'])->limit(5)->select();
        $userid     = input('userid/d', 0);
        $workerlog  = WorkerLogModel::where(['workerid' => $demand->workerid, 'userid' => $userid])->whereDay('createtime')->findOrEmpty();
        if ($workerlog->isEmpty()) {
            WorkerLogModel::create([
                'workerid'   => $demand->workerid,
                'userid'     => $userid,
                'ltotal'     => 1,
                'createtime' => date("Y-m-d"),
            ]);
        } else {
            $workerlog->inc('ltotal', 1)->update();
        }
        $iscantele = in_array($userid, $demand->telearr);
        $param     = ParamModel::where(1)->findOrEmpty();
        page_result(0, "", [
            'param'      => $param,
            'demand'     => $demand,
            'iscantele'  => $iscantele,
            'demandlist' => $demandlist,
        ]);
    }

    // 接单招聘信息
    public function delLog()
    {
        $logid  = input('logid/d', 0);
        $userid = input('userid/d', 0);
        $log    = DemandLogModel::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  = DemandLogModel::with(['demand.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 demandSnatch()
    {
        $id = input('id/d', 0);
        if (empty($id)) {
            page_result(1, "未查询到数据。");
        }

        //数据校验
        $num      = input('num/d', 0);
        $workerid = input('workerid/d', 0);
        if ($num <= 0) {
            page_result(1, "抢单人数必须大于0。");
        }
        if (empty($workerid)) {
            page_result(1, "登录信息异常，请重新登录。");
        }
        $demand = DemandModel::find($id);
        if (empty($demand)) {
            page_result(1, "订单不存在。");
        }
        $check = DemandSnatchModel::where('demand_id', $id)->where('worker_id', $workerid)->find();
        if (!empty($check)) {
            page_result(1, "请勿重复抢单。");
        }
        $total  = DemandSnatchModel::where('status', '>', 1)->where('demand_id', $id)->sum('num');
        $remain = $demand['num'] - $total;
        if ($demand['num'] - $total < $num) {
            page_result(1, "订单剩余{$remain}人，请输入该人数以下的值。");
        }

        //抢单
        DemandSnatchModel::create([
            'demand_id'  => $id,
            'worker_id'  => $workerid,
            'num'        => $num,
            'status'     => 1,
            'createtime' => date("Y-m-d H:i:s"),
        ]);
        if (($demand['num'] - $total) == $num) {
            $demand->status = 4;
            $demand->save();
        }

        page_result(0, "", []);
    }

    public function listSnatch()
    {
        $ppage    = input('ppage/d', 1);
        $psize    = input('psize/d', 20);
        $workerid = input('workerid/d', 0);
        $map[]    = ['worker_id', '=', $workerid];
        $status   = input('status/d', 0);
        if (!empty($status)) {
            $map[] = [
                ['status', '=', $status],
            ];
        }
        $plist = DemandSnatchModel::with(['demand', 'worker'])
            ->where($map)
            ->order(['createtime' => 'desc', 'id' => 'desc'])
            ->page($ppage)
            ->limit($psize)
            ->append(['status_text', 'demand'=>['ftype_text','wtype_text']])
            ->select();

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

//    public function setDemandLog()
//    {
//        $demandid = input('demandid/d', 0);
//        $demand   = DemandModel::findOrEmpty($demandid);
//        if ($demand->isEmpty()) {
//            page_result(1, "订单信息不存在");
//        }
//        if (strtotime($demand->enddate) + 86400 < time()) {
//            page_result(1, "该订单信息接单已截止，不能再接单了。");
//        }
//        $gworkerid = input('gworkerid/d', 0);
//        $worker    = WorkerModel::findOrEmpty($gworkerid);
//        if ($worker->isEmpty()) {
//            page_result(1, "劳务企业信息不存在");
//        }
//        $log = DemandLogModel::where(['demandid' => $demandid, 'gworkerid' => $gworkerid])->findOrEmpty();
//        if ($log->isEmpty()) {
//            $log = new DemandLogModel;
//            $log->save([
//                'workerid'   => $demand->workerid,
//                'demandid'   => $demandid,
//                'gworkerid'  => $gworkerid,
//                'createtime' => time(),
//            ]);
//            $userid = input('userid/d', 0);
//            $user   = UserModel::where(1)->findOrEmpty($userid);
//            $param  = ParamModel::where(1)->findOrEmpty();
//            if ($user->integral < $param->teldemand) {
//                page_result(1, "接单&咨询该订单会扣除" . $param->teldemand . "积分，你当前积分不足。");
//            }
//            $intdata = [
//                'userid'      => $userid,
//                'title'       => "接单&咨询订单信息扣除",
//                'intvalue'    => 0 - $param->teldemand,
//                'intmoney'    => 0.00,
//                'onlycontent' => "",
//                'remark'      => $demand->title,
//                'itype'       => 5,
//                'status'      => 2,
//                'createtime'  => date("Y-m-d H:i:s"),
//                'yeartime'    => date("Y"),
//                'monthtime'   => date("Ym"),
//            ];
//            UserIntegralModel::create($intdata);
//            $integral = intval($user->integral) - intval($param->teldemand);
//            $user->save([
//                'integral' => $integral,
//            ]);
//            $telearr   = $demand->telearr;
//            $telearr[] = $userid;
//            $demand->save([
//                'telearr' => $telearr,
//            ]);
//            page_result(0, "", []);
//        } else {
//            page_result(1, "你已接单过了，无需重复接单。");
//        }
//    }

    // public function teleDemand()
    // {
    // 	$demandid = input('demandid/d', 0);
    // 	$demand = DemandModel::findOrEmpty($demandid);
    // 	if ($demand->isEmpty()){
    // 		page_result(1, "订单信息不存在");
    // 	}
    // 	$userid = input('userid/d', 0);
    // 	if (in_array($userid, $demand->telearr)){
    // 		page_result(0, "", array(
    // 			'iscantele'		=> true
    // 		));
    // 	}
    // 	$user = UserModel::where(1)->findOrEmpty($userid);
    // 	$param = ParamModel::where(1)->findOrEmpty();
    // 	if ($user->integral < $param->teldemand){
    // 		page_result(1, "接单&咨询该订单会扣除".$param->teldemand."积分，你当前积分不足。");
    // 	}
    // 	$intdata = array(
    // 	    'userid'		=> $userid,
    // 	    'title'			=> "接单&咨询订单信息扣除",
    // 	    'intvalue'		=> 0 - $param->teldemand,
    // 	    'intmoney'		=> 0.00,
    // 		'onlycontent'	=> "",
    // 	    'remark'		=> $demand->title,
    // 	    'itype'			=> 5,
    // 		'status'		=> 2,
    // 	    'createtime'	=> date("Y-m-d H:i:s"),
    // 	    'yeartime'		=> date("Y"),
    // 	    'monthtime'		=> date("Ym")
    // 	);
    // 	UserIntegralModel::create($intdata);
    // 	$integral = intval($user->integral) - intval($param->teldemand);
    // 	$user->save([
    // 		'integral'	=> $integral
    // 	]);
    // 	$telearr = $demand->telearr;
    // 	$telearr[] = $userid;
    // 	$demand->save([
    // 		'telearr' => $telearr
    // 	]);
    // 	page_result(0, "", array(
    // 		'iscantele'		=> true
    // 	));
    // }


}