<?php

namespace app\admin\controller;

use app\admin\BaseController;
use app\common\model\RensheCode;
use app\common\model\Worker as WorkerModel;
use app\common\model\Comjobs as ComjobsModel;
use app\common\model\ComjobsCate as ComjobsCateModel;
use app\common\model\ComjobsLog as ComjobsLogModel;
use app\common\model\ComjobsStar as ComjobsStarModel;

use app\common\model\ComjobsShare as ComjobsShareModel;

use app\common\model\WorkerThird;
use app\common\service\RensheService;
use app\common\validate\Comjobs as ComjobsValidate;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Log;

class Comjobs extends BaseController
{


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

    public function delLog()
    {
        $idarr  = input('idarr/a');
        $log    = ComjobsLogModel::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 = ComjobsLogModel::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              = [];
        $workercomjobsarr = explode(",", input('workercomjobs/s'));
        $workerid         = isset($workercomjobsarr[0]) ? $workercomjobsarr[0] : 0;
        $comjobsid        = isset($workercomjobsarr[1]) ? $workercomjobsarr[1] : 0;
        if (!empty($workerid)) {
            $map[] = ['workerid', '=', $workerid];
        }
        if (!empty($comjobsid)) {
            $map[] = ['comjobsid', '=', $comjobsid];
        }
        $status = input('status/d', 0);
        if (!empty($status)) {
            $map[] = ['status', '=', $status];
        }
        $list  = ComjobsLogModel::with(['user', 'worker', 'comjobs'])->where($map)->order('id', 'DESC')->limit($limit)->page($page)->append(['status_text'])->select();
        $count = ComjobsLogModel::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              = [];
        $workercomjobsarr = explode(",", input('workercomjobs/s'));
        $workerid         = isset($workercomjobsarr[0]) ? $workercomjobsarr[0] : 0;
        $comjobsid        = isset($workercomjobsarr[1]) ? $workercomjobsarr[1] : 0;
        if (!empty($workerid)) {
            $map[] = ['workerid', '=', $workerid];
        }
        if (!empty($comjobsid)) {
            $map[] = ['comjobsid', '=', $comjobsid];
        }
        $status = input('status/d', 0);
        if (!empty($status)) {
            $map[] = ['status', '=', $status];
        }
        $xlsData = ComjobsLogModel::with(['user', 'worker', 'comjobs'])->where($map)->order('id', 'DESC')->append(['status_text'])->select()->toArray();
        $xlsCell = [
            ['id', '表ID'],
            ['user.nickname', '昵称'],
            ['user.realname', '姓名'],
            ['user.mobile', '手机号'],
            ['worker.title', '劳务公司'],
            ['comjobs.title', '招聘标题'],
            ['status_text', '公司反馈'],
            ['remark', '反馈备注'],
            ['createtime', '报名时间'],
        ];
        export_excel("招聘报名记录", $xlsCell, $xlsData);
    }


    // 企业招聘
    public function comjobsList()
    {
        $workerlist = WorkerModel::order(['id' => 'desc'])->select();
        $catelist   = ComjobsCateModel::order(['priority' => 'desc', 'id' => 'desc'])->select();
        return view('comjobs/comjobslist', [
            'workerlist' => $workerlist,
            'catelist'   => $catelist,
        ]);
    }

    public function comjobsForm()
    {
        $id            = input('id/d, 0');
        $comjobs       = ComjobsModel::findOrEmpty($id);
        $workerlist    = WorkerModel::order(['id' => 'desc'])->select();
        $catelist      = ComjobsCateModel::order(['priority' => 'desc', 'id' => 'desc'])->select();
        $communitylist = RensheCode::getList('community');
        $agelist       = RensheCode::getList('age');
        $educationlist = RensheCode::getList('education');
        $emptimelist   = RensheCode::getList('emp_time');
        $welfarelist   = RensheCode::getList('welfare');
        return view('comjobs/comjobsform', [
            'catelist'      => $catelist,
            'workerlist'    => $workerlist,
            'communitylist' => $communitylist,
            'agelist'       => $agelist,
            'educationlist' => $educationlist,
            'emptimelist'   => $emptimelist,
            'welfarelist'   => $welfarelist,
            'comjobs'       => $comjobs,
        ]);
    }

    public function editComjobs()
    {
        $id      = input('id/d', 0);
        $wtype   = input('wtype/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'             => array_values(input('tags/a', [])),
            'enddate'          => input('enddate/s', ""),
            'requirement'      => input('requirement/s', ""),
            'comdetails'       => input('comdetails/s', ""),
            'companydetails'   => input('companydetails/s', ""),
            'retmoney'         => input('retmoney/d', ""),
            'picall'           => input('picall/a', []),
            'recruit_num'      => input('recruit_num/d', 1),
            'wtype'            => $wtype,
            'bwagall'          => input('bwagall/s', ""),
            'zwagall'          => $zwagall,
            'fwagall'          => input('fwagall/s', ""),
            'telephone'        => input('telephone/s', ""),
            'remark'           => input('remark/s', ""),
            'status'           => input('status/d', 1),
            'priority'         => input('priority/d', 0),
            'updatetime'       => input('updatetime/s', ""),
            'createtime'       => input('createtime/s', ""),
            'volume'           => input('volume/d', 0),
            'recruitment_cate' => input('recruitment_cate/d', 1),
            'latitude'         => input('latitude/f', 0),
            'longitude'        => input('longitude/f', 0),
            'address'          => input('address/s', ''),
            'community'        => input('community/s', ''),
            'is_worry'         => input('is_worry/d', 0),
            'education'        => input('education/s', ''),
            'emp_time'         => array_values(input('emp_time/a', [])),
        ];
        try {
            validate(ComjobsValidate::class)->check($data);
        } catch (ValidateException $e) {
            exit(json_encode([
                'code' => 1,
                'msg'  => $e->getError(),
            ]));
        }
        if (empty($id)) {
            $data['video'] = input('new_video/s', "");
            ComjobsModel::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;
                }
            }

            $comjobs = ComjobsModel::find($id);
            ComjobsLogModel::update(['workerid' => input('workerid/d', 0)], ['comjobsid' => $comjobs->id]);
            $comjobs->save($data);
        }
        exit(json_encode([
            'code' => 0,
        ]));
    }

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

    public function delComjobs()
    {
        $idarr = input('idarr/a');
        ComjobsLogModel::whereIn('comjobsid', $idarr)->delete();
        ComjobsStarModel::whereIn('comjobsid', $idarr)->delete();
        $result = Db::name('comjobs')->whereIn('id', $idarr)->update(['deletetime' => time()]);

        if ($result) {
            exit(json_encode([
                'code' => 0,
                'msg'  => "",
            ]));
        }
        exit(json_encode([
            'code' => 1,
            'msg'  => "删除失败，请稍后重试",
        ]));
    }

    public function listComjobs()
    {
        $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];
        }
        $status = input('status/d');
        if (!empty($status)) {
            $map[] = ['status', '=', $status];
        }
        $daterange = input('daterange/s', "");
        if (!empty($daterange)) {
            $daterangearr = explode("~", $daterange);
            $map[]        = ['createtime', '>= time', trim($daterangearr[0])];
            $map[]        = ['createtime', '<= time', trim($daterangearr[1])];
        }
        $list  = ComjobsModel::with(['worker', 'comjobsCate'])->withCount(['comjobsLog'])->where($map)->order(['priority' => 'desc', 'id' => 'desc',])->limit($limit)->page($page)->append(['wtype_text', 'status_text'])->select();
        $count = ComjobsModel::where($map)->count();

        $list = $list->toArray();
        foreach ($list as $k => $v) {
            if (!empty($v['company_name'])) {
                $list[$k]['worker']['title'] = $v['company_name'];
            }
        }

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

    // 岗位类型
    public function cateList()
    {
        return view('comjobs/catelist');
    }

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

    public function listCate()
    {
        $limit = input('limit');
        $page  = input('page');
        $list  = ComjobsCateModel::order(['priority' => 'desc', 'id' => 'desc'])->limit($limit)->page($page)->select();
        $count = ComjobsCateModel::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 = ComjobsCateModel::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 = ComjobsCateModel::create([
                'title'    => input('title/s', ""),
                'priority' => input('priority/d', 0),
            ]);
        } else {
            $cate = ComjobsCateModel::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   = ComjobsCateModel::where('id', $id)->select();
        $result = $cate->delete();
        if ($result) {
            exit(json_encode([
                'code' => 0,
                'msg'  => "",
            ]));
        }
        exit(json_encode([
            'code' => 1,
            'msg'  => "删除失败，请稍后重试",
        ]));
    }


    // 推广海报
    public function shareList()
    {
        return view('comjobs/sharelist', []);
    }

    public function shareForm()
    {
        $id    = input('id/d', 0);
        $share = ComjobsShareModel::findOrEmpty($id);
        return view('comjobs/shareform', [
            'share' => $share,
        ]);
    }

    public function editShare()
    {
        $id   = input('id/d', 0);
        $data = [
            'title'    => input('title/s', ""),
            'tilpic'   => input('tilpic/s', ""),
            'status'   => input('status/d', 1),
            'priority' => input('priority/d', 0),
        ];
        if (empty($id)) {
            $share = ComjobsShareModel::create($data);
        } else {
            $share = ComjobsShareModel::find($id);
            $share->save($data);
        }
        exit(json_encode([
            'code' => 0,
        ]));
    }

    public function listShare()
    {
        $limit  = input('limit');
        $page   = input('page');
        $map    = [];
        $status = input('status/d', 0);
        if (!empty($status)) {
            $map[] = ['status', '=', $status];
        }
        $list  = ComjobsShareModel::where($map)->order(['priority' => 'desc', 'id' => 'desc'])->limit($limit)->page($page)->append(['status_text'])->select();
        $count = ComjobsShareModel::where($map)->count();
        if ($count == 0) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "未查询到数据",
            ]));
        }
        exit(json_encode([
            'code'  => 0,
            'msg'   => "",
            'count' => $count,
            'data'  => $list,
        ]));
    }

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

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

    public function synRenshe()
    {
        //发送数据
        $id   = input('id/d', 0);
        $service = new RensheService();
        $res     = $service->jobInfoByComId($id);

        if ($res['code'] == 200) {
            return json(['code' => 0]);
        } else {
            return json([
                'code' => 1,
                'msg'  => '网络异常，请重试',
            ]);
        }
    }

    public function import()
    {
        $data       = ['cate', 'title', 'type', 'zwagall', 'community', 'province', 'city', 'district', 'education', 'agegroup', 'tags', 'comdetails', 'requirement',
                       'worker', 'telephone', 'name', 'address', 'time', 'emp_time', 'is_worry'];
        $list       = importExecl('21.xlsx', $data, 2);
        $data       = [];
        $wtype      = ['按月' => 1, '按时' => 2, '按件' => 3, '按项目' => 4, '面议' => 5];
        $rensheCode = RensheCode::select();
        $renshe     = [];
        foreach ($rensheCode as $v) {
            $renshe[$v['type']][$v['name']] = $v['code'];
        }
        $cateList = ComjobsCateModel::column('id', 'title');

        foreach ($list as $v) {
            if (empty($v['cate'])) {
                continue;
            }
            $item = [];
            if (empty($cateList[$v['cate']])) {
                halt($cateList, $v);
            }
            $item['cateid']  = $cateList[$v['cate']];
            $item['title']   = $v['title'];
            $item['wtype']   = $wtype[$v['type']];
            $item['zwagall'] = $v['zwagall'];
            if (!empty($renshe['community'][$v['community']])) {
                $item['community'] = $renshe['community'][$v['community']];
            }
            $item['province'] = $v['province'];
            $item['city']     = $v['city'];
            $item['district'] = $v['district'];
            if (!empty($renshe['education'][$v['education']])) {
                $item['education'] = $v['education'];
            }
            if (!empty($renshe['age'][$v['agegroup']])) {
                $item['agegroup'] = $v['agegroup'];
            }
            $tags = explode(',', $v['tags']);
            if (empty($tags[0])) {
                $tags = [];
            }
            $item['tags']        = $tags;
            $item['comdetails']  = $v['comdetails'];
            $item['requirement'] = $v['requirement'];
            $item['workerid']    = 8;
            $item['telephone']   = (string)$v['telephone'];
            $item['address']     = (string)$v['address'];
            $emp_time            = explode(',', $v['emp_time']);
            if (empty($emp_time[0])) {
                $emp_time = [];
            }
            $item['emp_time']   = $emp_time;
            $item['is_worry']   = $v['is_worry'] ? $v['is_worry'] : 0;
            $item['priority']   = 0;
            $item['status']     = 3;
            $item['createtime'] = $item['updatetime'] = time();
            $data[]             = $item;
        }
        foreach ($data as $v) {
            ComjobsModel::create($v);
        }

    }
}
