<?php

namespace app\admin\controller;

use app\admin\BaseController;
use app\common\model\Worker as WorkerModel;
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\DemandSnatch as DemandSnatchModel;
use app\common\model\DemandReport as DemandReportModel;

use app\common\validate\Demand as DemandValidate;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Request;

class Demand extends BaseController
{


    // 报名记录
    /*public function logList()
    {
        $workerlist = WorkerModel::with('demand')->order(['id' => 'desc'])->select();
        return view('demand/loglist', [
            'workerlist' => $workerlist,
        ]);
    }*/

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

            $list  = DemandReportModel::with(['demand','snatch','snatch.worker','worker','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/loglist');
        }
    }

    public function delLog()
    {
        $idarr  = input('idarr/a');
        $log    = DemandLogModel::whereIn('id', $idarr)->select();
        $result = $log->delete();
        if ($result) {
            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             = [];
        $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];
        }
        $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()
    {
        $workerlist = WorkerModel::order(['id' => 'desc'])->select();
        $catelist   = DemandCateModel::order(['priority' => 'desc', 'id' => 'desc'])->select();
        return view('demand/demandlist', [
            'workerlist' => $workerlist,
            'catelist'   => $catelist,
        ]);
    }

    public function demandForm()
    {
        $id         = input('id/d, 0');
        $demand     = DemandModel::findOrEmpty($id);
        $workerlist = WorkerModel::order(['id' => 'desc'])->select();
        $catelist   = DemandCateModel::order(['priority' => 'desc', 'id' => 'desc'])->select();
        return view('demand/demandform', [
            'catelist'   => $catelist,
            'workerlist' => $workerlist,
            'demand'     => $demand,
        ]);
    }

    public function editDemand()
    {
        $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', ""),
            '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', ""),
            '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),
        ];
        try {
            validate(DemandValidate::class)->check($data);
        } catch (ValidateException $e) {
            exit(json_encode([
                'code' => 1,
                'msg'  => $e->getError(),
            ]));
        }
        if (empty($id)) {
            $data['telearr'] = [];
            $data['video']   = input('new_video/s', "");
            $demand          = DemandModel::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 = 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([
                input('field/s') => input('value'),
            ]);
        }
        exit(json_encode([
            'code' => 0,
        ]));
    }

    public function delDemand()
    {
        $idarr = input('idarr/a');
        DemandLogModel::whereIn('demandid', $idarr)->delete();
        $result = Db::name('demand')->whereIn('id', $idarr)->update(['deletetime' => time()]);
        if ($result) {
            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];
        }
        $daterange = input('daterange/s', "");
        if (!empty($daterange)) {
            $daterangearr = explode("~", $daterange);
            $map[]        = ['createtime', '>= time', trim($daterangearr[0])];
            $map[]        = ['createtime', '<= time', trim($daterangearr[1])];
        }
        $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 cateList()
    {
        return view('demand/catelist');
    }

    public function cateForm()
    {
        $id   = input('id/d', 0);
        $cate = DemandCateModel::findOrEmpty($id);
        return view('demand/cateform', [
            'cate' => $cate,
        ]);
    }

    public function listCate()
    {
        $limit = input('limit');
        $page  = input('page');
        $list  = DemandCateModel::order(['priority' => 'desc', 'id' => 'desc'])->limit($limit)->page($page)->select();
        $count = DemandCateModel::count();
        if ($count == 0) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "未查询到数据",
            ]));
        }
        exit(json_encode([
            'code'  => 0,
            'msg'   => "",
            'count' => $count,
            'data'  => $list,
        ]));
    }

    public function fieldCate()
    {
        $id   = input('id/d', 0);
        $info = DemandCateModel::find($id);
        $info->save([
            input('field/s') => input('value/s', ""),
        ]);
        exit(json_encode([
            'code' => 0,
        ]));
    }

    public function editCate()
    {
        $id = input('id/d');
        if (empty($id)) {
            $cate = DemandCateModel::create([
                'title'    => input('title/s', ""),
                'priority' => input('priority/d', 0),
            ]);
        } else {
            $cate = DemandCateModel::find($id);
            $cate->save([
                'title'    => input('title/s', ""),
                'priority' => input('priority/d', 0),
            ]);
        }
        exit(json_encode([
            'code' => 0,
        ]));
    }

    public function delCate()
    {
        $id     = input('id/d');
        $cate   = DemandCateModel::where('id', $id)->select();
        $result = $cate->delete();
        if ($result) {
            exit(json_encode([
                'code' => 0,
                'msg'  => "",
            ]));
        }
        exit(json_encode([
            'code' => 1,
            'msg'  => "删除失败，请稍后重试",
        ]));
    }

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

            $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];
            }
            $workerid = input('workerid/d', 0);
            if (!empty($workerid)) {
                $map[] = ['workerid', '=', $workerid];
            }
            $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();
            $workerlist = WorkerModel::order(['id' => 'desc'])->select();

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

    }

    public function otherForm()
    {
        $id         = input('id/d, 0');
        $demand     = DemandOtherModel::findOrEmpty($id);
        $workerlist = WorkerModel::order(['id' => 'desc'])->select();

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

    public function editOther()
    {
        $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['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 snatchList()
    {
        if (Request::isAjax()) {
            $limit = input('limit/d', 20);
            $page  = input('page/d', 1);
            $map   = [];

            $worker_id = input('worker_id/d', 0);
            if (!empty($worker_id)) {
                $map[] = ['worker_id', '=', $worker_id];
            }
            $status = input('status/d', 0);
            if (!empty($status)) {
                $map[] = ['status', '=', $status];
            }
            $list = DemandSnatchModel::with(['demand', 'worker', '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 {
            $workerlist = WorkerModel::order(['id' => 'desc'])->select();
            return view('demand/snatchlist', [
                'workerlist' => $workerlist,
            ]);
        }
    }

    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 snatchstatus()
    {
        $id = input('id/d, 0');
        $status = input('status/d, 0');

        $snatch = DemandSnatchModel::findOrEmpty($id);
        if ($snatch->isEmpty()) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "信息不存在",
            ]));
        } else {
            $snatch->save([
                'status' => $status,
            ]);
        }

        exit(json_encode([
            'code' => 0,
        ]));
    }

    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,
            ]);
        }
    }
}
