<?php

namespace app\worker\controller;

use app\worker\BaseController;
use app\common\model\Param as ParamModel;
use app\common\model\Demand as DemandModel;
use app\common\model\DemandOther as DemandOtherModel;
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\model\DemandSnatch as DemandSnatchModel;
use app\common\model\DemandReport as DemandReportModel;

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([
                'code' => 0,
                'msg'  => "",
            ]));
        }
        exit(json_encode([
            'code' => 1,
            'msg'  => "删除失败，请稍后重试",
        ]));
    }

    public function fieldLog()
    {
        $id  = input('id/d', 0);
        $log = DemandLogModel::findOrEmpty($id);
        if ($log->isEmpty()) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "信息不存在",
            ]));
        } else {
            $log->save([
                input('field/s') => input('value'),
            ]);
        }
        exit(json_encode([
            'code' => 0,
        ]));
    }

    public function listLog()
    {
        $limit     = input('limit/d', 20);
        $page      = input('page/d', 1);
        $map       = [];
        $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([
                'code' => 1,
                'msg'  => "未查询到数据",
            ]));
        }
        exit(json_encode([
            'code'  => 0,
            'msg'   => "",
            'count' => $count,
            'data'  => $list,
        ]));
    }

    public function exportLog()
    {
        $map             = [];
        $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 = [
            ['id', '表ID'],
            ['gworker.title', '接单公司名称'],
            ['gworker.realname', '接单公司联系人姓名'],
            ['gworker.mobile', '接单公司联系人手机号'],
            ['worker.title', '发单公司'],
            ['demand.title', '订单标题'],
            ['createtime', '接单时间'],
        ];
        export_excel("接单报名记录", $xlsCell, $xlsData);
    }


    // 企业招聘
    public function demandList()
    {
        if (Request::isAjax()) {
            $limit    = input('limit/d', 20);
            $page     = input('page/d', 1);
            $map      = [];
            $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([
                    'code' => 1,
                    'msg'  => "未查询到数据",
                ]));
            }
            exit(json_encode([
                '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 = ['code' => 0];
            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([
                    '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([
                'code' => 1,
                'msg'  => "用户信息不存在",
            ]));
        }

        $wtype   = input('wtype/d', 1);
        $type    = input('type/d', 1);
        $zwagall = $wtype == 1 ? input('zwagall/s', "") : '';
        $data    = [
            'workerid'    => $workerid,
            'title'       => input('title/s', ""),
            'num'         => input('num/d', 1),
            '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', []),
            'enddate'     => input('enddate/s', ""),
            'requirement' => input('requirement/s', ""),
            'comdetails'  => input('comdetails/s', ""),
            'picall'      => input('picall/a', []),
            'wtype'       => $wtype,
            'type'        => $type,
            '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([
                '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']    = [];
            $demand             = DemandModel::create($data);
            $intdata            = [
                '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([
            '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([
                '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', []),
            '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([
                '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'] = [];
            $demand          = DemandModel::create($data);

            $intdata = [
                '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([
            'code' => 0,
        ]));
    }

    public function fieldDemand()
    {
        $id     = input('id/d', 0);
        $demand = DemandModel::findOrEmpty($id);
        if ($demand->isEmpty()) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "信息不存在",
            ]));
        } else {
            $demand->save([
                'telephone' => input('value'),
            ]);
        }
        exit(json_encode([
            '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([
                'code' => 0,
                'msg'  => "",
            ]));
        }
        exit(json_encode([
            'code' => 1,
            'msg'  => "删除失败，请稍后重试",
        ]));
    }

    public function listDemand()
    {
        $limit    = input('limit/d', 20);
        $page     = input('page/d', 1);
        $map      = [];
        $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([
                'code' => 1,
                'msg'  => "未查询到数据",
            ]));
        }
        exit(json_encode([
            'code'  => 0,
            'msg'   => "",
            'count' => $count,
            'data'  => $list,
        ]));
    }

    // 企业招聘
    public function otherList()
    {
        if (Request::isAjax()) {
            $limit    = input('limit/d', 20);
            $page     = input('page/d', 1);
            $map      = [];
            $workerid = $this->access_worker['id'];
            $map[]    = ['workerid', '=', $workerid];

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

            $keywords = input('keywords/s', "");
            if (!empty($keywords)) {
                $map[] = ['company_name|company_contact|company_mobile', '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  = DemandOtherModel::with(['worker', 'demandCate'])
                ->where($map)
                ->order(['priority' => 'desc', 'id' => 'desc',])
                ->limit($limit)
                ->page($page)
                ->append(['wtype_text', 'ftype_text', 'status_text', 'isfree_text'])
                ->select();
            $count = DemandOtherModel::where($map)->count();
            if ($count == 0) {
                exit(json_encode([
                    'code' => 1,
                    'msg'  => "未查询到数据",
                ]));
            }
            exit(json_encode([
                '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');

            return view('demand/otherlist', [
                'param'    => $param,
                'catelist' => $catelist,
                'wtype'    => $access_worker['wtype'],
            ]);
        }

    }

    public function otherForm()
    {
        $worker_data = Session::get('access_worker');
        $id          = input('id/d, 0');
        $demand      = DemandOtherModel::where('workerid', $worker_data['id'])->findOrEmpty($id);

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

    public function editOther()
    {
        $worker_data = Session::get('access_worker');
        $id          = input('id/d', 0);
        $wtype       = input('wtype/d', 1);
        $type        = input('type/d', 1);
        $zwagall     = $wtype == 1 ? input('zwagall/s', "") : '';
        $data        = [
            'workerid'        => input('workerid/d', 0),
            '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', []),
            'enddate'         => input('enddate/s', ""),
            'requirement'     => input('requirement/s', ""),
            'comdetails'      => input('comdetails/s', ""),
            'type'            => $type,
            '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', ""),
            'status'          => input('status/d', 1),
            'isfree'          => input('isfree/d', 1),
            'priority'        => input('priority/d', 0),
            'updatetime'      => input('updatetime/s', ""),
            'createtime'      => input('createtime/s', ""),
            'volume'          => input('volume/d', 0),
            'company_name'    => input('remark/s', ""),
            'company_contact' => input('remark/s', ""),
            'company_mobile'  => input('remark/s', ""),
        ];
        try {
            validate(DemandValidate::class)->check($data);
        } catch (ValidateException $e) {
            exit(json_encode([
                'code' => 1,
                'msg'  => $e->getError(),
            ]));
        }
        if (empty($id)) {
            $data['workerid'] = $worker_data['id'];
            $data['telearr']  = [];
            $data['video']    = input('new_video/s', "");
            DemandOtherModel::create($data);
        } 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;
                }
            }

            $demand = DemandOtherModel::find($id);
            $demand->save($data);
        }
        exit(json_encode([
            'code' => 0,
        ]));
    }

    // 企业招聘
    public function allhall()
    {
        if (Request::isAjax()) {
            $limit = input('limit/d', 20);
            $page  = input('page/d', 1);
            $map   = [];
            $map[] = ['status', '=', 3];

            $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];
            }
            $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([
                    'code' => 1,
                    'msg'  => "未查询到数据",
                ]));
            }
            exit(json_encode([
                'code'  => 0,
                'msg'   => "",
                'count' => $count,
                'data'  => $list,
            ]));

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

            return view('demand/allhall', [
                'param'    => $param,
                'catelist' => $catelist,
            ]);
        }

    }

    public function snatchDemand()
    {
        $id = input('id/d', 0);
        if (empty($id)) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "未查询到数据",
            ]));
        }

        if (Request::isAjax()) {
            //数据校验
            $num = input('num/d', 0);
            if ($num <= 0) {
                exit(json_encode([
                    'code' => 1,
                    'msg'  => "抢单人数必须大于等于0",
                ]));
            }
            $demand = DemandModel::find($id);
            if (empty($demand)) {
                exit(json_encode([
                    'code' => 1,
                    'msg'  => "订单不存在 ",
                ]));
            }
            if ($demand['status'] != 3) {
                exit(json_encode([
                    'code' => 1,
                    'msg'  => "订单已结束",
                ]));
            }
            $total  = DemandSnatchModel::where('status', '>', 1)->where('demand_id', $id)->sum('num');
            $remain = $demand['num'] - $total;
            if ($demand['num'] - $total < $num) {
                exit(json_encode([
                    'code' => 1,
                    'msg'  => "订单剩余{$remain}人，请输入该人数以下的值",
                ]));
            }

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

            exit(json_encode(['code' => 0]));
        } else {
            return view('demand/snatchDemand', [
                'id' => $id,
            ]);
        }
    }

    public function roblist()
    {
        if (Request::isAjax()) {
            $limit       = input('limit/d', 20);
            $page        = input('page/d', 1);
            $worker_data = Session::get('access_worker');
            $map         = [['worker_id', '=', $worker_data['id']]];

            $status = input('status/d', 0);
            if (!empty($status)) {
                $map[] = ['status', '=', $status];
            }
            $list = DemandSnatchModel::with(['demand', 'demand.worker'])
                ->where($map)
                ->order(['id' => 'desc'])
                ->limit($limit)
                ->page($page)
                ->append(['status_text'])
                ->select();

            $count = DemandSnatchModel::where($map)->count();
            if ($count == 0) {
                exit(json_encode([
                    'code' => 1,
                    'msg'  => "未查询到数据",
                ]));
            }
            exit(json_encode([
                'code'  => 0,
                'msg'   => "",
                'count' => $count,
                'data'  => $list,
            ]));

        } else {
            return view('demand/roblist');
        }
    }

    public function demandDetail()
    {
        $id = input('id/d, 0');
        if (empty($id)) {
            return '未查询到数据';
        }
        $demand = DemandModel::with(['worker', 'demand_cate'])->findOrEmpty($id);
        if ($demand->isEmpty()) {
            return '未查询到数据';
        }

        $typelist   = [1 => '代招', 2 => '劳务派遣'];
        $wtypelist  = [1 => '按月', 2 => '按时', 3 => '按件', 4 => '按项目', 5 => '其他'];
        $ftypelist  = [1 => '一次性', 2 => '小时工', 3 => '管理费', 4 => '其他'];
        $statuslist = [1 => '待修改', 2 => '待审核', 3 => '已上架', 4 => '已停招', 5 => '已下架'];
        return view('demand/demanddetail', [
            'demand'     => $demand,
            'typelist'   => $typelist,
            'wtypelist'  => $wtypelist,
            'ftypelist'  => $ftypelist,
            'statuslist' => $statuslist,
        ]);
    }

    public function report()
    {
        $id = input('id/d', 0);
        if (empty($id)) {
            return '未查询到数据';
        }

        if (Request::isAjax()) {
            //订单信息
            $snatch = DemandSnatchModel::with('demand')->find($id);
            if (empty($snatch)) {
                exit(json_encode([
                    'code' => 1,
                    'msg'  => "订单不存在",
                ]));
            }

            if ($snatch['status'] != 2) {
                exit(json_encode([
                    'code' => 1,
                    'msg'  => "该订单暂时无法报备",
                ]));
            }

            $snatch_num = DemandReportModel::where('snatchid', $id)->count();
            if ($snatch_num >= $snatch['num']) {
                exit(json_encode([
                    'code' => 1,
                    'msg'  => "人数已满",
                ]));
            }

            $mobile       = input('mobile/s', '');
            $idcard       = input('idcard/s', '');
            $mobile_check = DemandReportModel::where('snatchid', $id)->where('mobile', $mobile)->find();
            if (!empty($mobile_check)) {
                exit(json_encode([
                    'code' => 1,
                    'msg'  => "该手机号已报备，请勿重复",
                ]));
            }
            $idcard_check = DemandReportModel::where('snatchid', $id)->where('idcard', $idcard)->find();
            if (!empty($idcard_check)) {
                exit(json_encode([
                    'code' => 1,
                    'msg'  => "该身份证号已报备，请勿重复",
                ]));
            }

            DemandReportModel::create([
                'demandid'   => $snatch['demand_id'],
                'snatchid'   => $id,
                'workerid'   => $snatch['demand']['workerid'],
                'realname'   => input('realname/s', ''),
                'mobile'     => $mobile,
                'idcard'     => $idcard,
                'arrivetime' => input('arrivetime/s', ''),
                'remark'     => input('remark/s', ''),
                'createtime' => time(),
            ]);
            if ($snatch_num + 1 == $snatch['num']) {
                $snatch->status == 3;
                $snatch->save();
            }
            exit(json_encode(['code' => 0]));
        } else {
            return view('demand/report', [
                'id' => $id,
            ]);
        }
    }

    public function reportLog()
    {
        $id = input('id/d', 0);
        if (empty($id)) {
            return '未查询到数据';
        }

        if (Request::isAjax()) {
            $limit = input('limit/d', 20);
            $page  = input('page/d', 1);
            $map   = [['snatchid', '=', $id]];
            $map   = $this->dealLikeInput($map, ['realname', 'mobile', 'idcard']);

            $list  = DemandReportModel::with(['agent', 'broker'])
                ->where($map)
                ->order(['id' => 'desc'])
                ->limit($limit)
                ->page($page)
                ->select();
            $count = DemandReportModel::where($map)->count();
            if ($count == 0) {
                exit(json_encode([
                    'code' => 1,
                    'msg'  => "未查询到数据",
                ]));
            }
            exit(json_encode([
                'code'  => 0,
                'msg'   => "",
                'count' => $count,
                'data'  => $list,
            ]));

        } else {
            return view('demand/reportlog', [
                'id' => $id,
            ]);
        }
    }

    public function snatchDetailList()
    {
        $id = input('id/d', 0);
        if (empty($id)) {
            return '未查询到数据';
        }

        if (Request::isAjax()) {
            $limit = input('limit/d', 20);
            $page  = input('page/d', 1);
            $map   = [['demand_id', '=', $id], ['status', '>', 1]];

            $list = DemandSnatchModel::with(['worker'])
                ->where($map)
                ->order(['id' => 'desc'])
                ->limit($limit)
                ->page($page)
                ->select();
            if (!$list->isEmpty()) {
                foreach ($list as $v) {
                    $v['snatch_num'] = DemandReportModel::where('snatchid', $v['id'])->count();
                }
            }

            $count = DemandSnatchModel::where($map)->count();
            if ($count == 0) {
                exit(json_encode([
                    'code' => 1,
                    'msg'  => "未查询到数据",
                ]));
            }
            exit(json_encode([
                'code'  => 0,
                'msg'   => "",
                'count' => $count,
                'data'  => $list,
            ]));

        } else {
            return view('demand/snatchdetaillist', ['id' => $id]);
        }
    }
}
