<?php

namespace app\worker\controller;

use app\common\model\RensheCode;
use app\common\service\ComjobsService;
use app\common\service\SmsService;
use app\worker\BaseController;
use app\common\model\Param as ParamModel;
use app\common\model\User as UserModel;
use app\common\model\Worker as WorkerModel;
use app\common\model\Comjobs as ComjobsModel;
use app\common\model\ComjobsPcate as ComjobsPcateModel;
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\UserIntegral as UserIntegralModel;

use think\facade\Session;
use think\facade\Db;

use app\common\model\ComjobsSearchCate as ComjobsSearchCateModel;
use app\common\model\ComjobsSearch as ComjobsSearchModel;

class Comjobs extends BaseController
{


    // 报名记录
    public function logList()
    {
        $workerid    = $this->access_worker['id'];
        $comjobslist = ComjobsModel::where(['workerid' => $workerid])
            ->order(['id' => 'desc'])
            ->where('del_status', 0)
            ->select();

        $comjobs_cate_data = Db::name('comjobs')
            ->alias('a')
            ->field('any_value(a.id) id,a.cateid,any_value(a.workerid) workerid,any_value(b.title) title')
            ->where('a.workerid', $workerid)
            ->join('comjobs_cate b', 'a.cateid = b.id', 'LEFT')
            ->group('a.cateid')
            ->select();

        return view('comjobs/loglist', [
            'comjobslist'       => $comjobslist,
            'comjobs_cate_data' => $comjobs_cate_data,
        ]);
    }

    public function delLog()
    {
        $workerid = $this->access_worker['id'];
        $idarr    = input('idarr/a');
//		$log = ComjobsLogModel::where(['workerid'=>$workerid])->whereIn('id',$idarr)->select();
//		$result = $log->delete();
        $comjobsLog_data = Db::name('comjobs_log')
            ->where(['workerid' => $workerid])
            ->whereIn('id', $idarr)
            ->update(['del_status' => 1]);
        if ($comjobsLog_data) {
            exit(json_encode([
                'code' => 0,
                'msg'  => "",
            ]));
        }
        exit(json_encode([
            'code' => 1,
            'msg'  => "删除失败，请稍后重试",
        ]));
    }

    public function fieldLog()
    {
        $workerid = $this->access_worker['id'];
        $id       = input('id/d', 0);
        $log      = ComjobsLogModel::where(['workerid' => $workerid])->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()
    {
        $workerid = $this->access_worker['id'];
        $limit    = input('limit/d', 20);
        $page     = input('page/d', 1);
        $where    = [];
        $where[]  = ['a.workerid', '=', $workerid];
        $where[]  = ['a.del_status', '=', 0];
        $cateid   = input('cateid/d', 0);

        if (!empty($cateid)) {
            $where[] = ['b.cateid', '=', $cateid];
        }
        $comjobsid = input('comjobsid/d', 0);
        if (!empty($comjobsid)) {
            $where[] = ['a.comjobsid', '=', $comjobsid];
        }
        $status = input('status/d', 0);
        if (!empty($status)) {
            $where[] = ['a.status', '=', $status];
        }

        $list = Db::name("comjobs_log")
            ->alias('a')
            ->field('a.id,a.status,a.remark,from_unixtime(a.createtime) createtime,a.del_status,d.avatar,d.realname,d.nickname,d.mobile,c.title cate,b.title,b.recruitment_cate')
            ->where($where)
            ->join('comjobs b', 'a.comjobsid = b.id', 'LEFT')
            ->join('comjobs_cate c', 'b.cateid = c.id', 'LEFT')
            ->join('user d', 'a.userid = d.id', 'LEFT')
            ->order('a.id desc')
            ->limit($limit)
            ->page($page)
            ->select()
            ->toArray();


        foreach ($list as $k => $v) {
            if ($v['recruitment_cate'] == 1) {
                $list[$k]['recruitment_text'] = '普通招聘';
            } elseif ($v['recruitment_cate'] == 2) {
                $list[$k]['recruitment_text'] = '悬赏聘';
            }

            if ($v['status'] == 1) {
                $list[$k]['status_text'] = '未跟进';
            } elseif ($v['status'] == 2) {
                $list[$k]['status_text'] = '未面试';
            } elseif ($v['status'] == 3) {
                $list[$k]['status_text'] = '面试通过';
            } elseif ($v['status'] == 4) {
                $list[$k]['status_text'] = '面试未通过';
            } elseif ($v['status'] == 5) {
                $list[$k]['status_text'] = '用户放弃';
            } elseif ($v['status'] == 6) {
                $list[$k]['status_text'] = '已入职';
            } elseif ($v['status'] == 7) {
                $list[$k]['status_text'] = '已离职';
            }
        }

        $count = Db::name("comjobs_log")
            ->alias('a')
            ->where($where)
            ->join('comjobs b', 'a.comjobsid = b.id', 'LEFT')
            ->join('comjobs_cate c', 'b.cateid = c.id', 'LEFT')
            ->join('user d', 'a.userid = d.id', 'LEFT')
            ->count();
        if ($count == 0) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "未查询到数据",
            ]));
        }
        exit(json_encode([
            'code'  => 0,
            'msg'   => "",
            'count' => $count,
            'data'  => $list,
        ]));
    }

    public function exportLog()
    {
        $workerid = $this->access_worker['id'];
        $where    = [];
        $where[]  = ['a.workerid', '=', $workerid];
        $where[]  = ['a.del_status', '=', 0];
        $cateid   = input('cateid/d', 0);

        if (!empty($cateid)) {
            $where[] = ['b.cateid', '=', $cateid];
        }
        $comjobsid = input('comjobsid/d', 0);
        if (!empty($comjobsid)) {
            $where[] = ['a.comjobsid', '=', $comjobsid];
        }
        $status = input('status/d', 0);
        if (!empty($status)) {
            $where[] = ['a.status', '=', $status];
        }

        $xlsData = Db::name("comjobs_log")
            ->alias('a')
            ->field('a.id,a.status,a.remark,from_unixtime(a.createtime) createtime,d.realname,d.nickname,d.mobile,c.title cate,b.title,b.recruitment_cate')
            ->where($where)
            ->join('comjobs b', 'a.comjobsid = b.id', 'LEFT')
            ->join('comjobs_cate c', 'b.cateid = c.id', 'LEFT')
            ->join('user d', 'a.userid = d.id', 'LEFT')
            ->order('a.id desc')
            ->select()
            ->toArray();


        foreach ($xlsData as $k => $v) {
            if ($v['recruitment_cate'] == 1) {
                $xlsData[$k]['recruitment_text'] = '普通招聘';
            } elseif ($v['recruitment_cate'] == 2) {
                $xlsData[$k]['recruitment_text'] = '悬赏聘';
            }

            if ($v['status'] == 1) {
                $xlsData[$k]['status_text'] = '未跟进';
            } elseif ($v['status'] == 2) {
                $xlsData[$k]['status_text'] = '未面试';
            } elseif ($v['status'] == 3) {
                $xlsData[$k]['status_text'] = '面试通过';
            } elseif ($v['status'] == 4) {
                $xlsData[$k]['status_text'] = '面试未通过';
            } elseif ($v['status'] == 5) {
                $xlsData[$k]['status_text'] = '用户放弃';
            } elseif ($v['status'] == 6) {
                $xlsData[$k]['status_text'] = '已入职';
            } elseif ($v['status'] == 7) {
                $xlsData[$k]['status_text'] = '已离职';
            }
        }

        $xlsCell = [
            ['id', '表ID'],
            ['realname', '姓名'],
            ['nickname', '昵称'],
            ['mobile', '手机号'],
            ['title', '招聘标题'],
            ['cate', '岗位类别'],
            ['recruitment_text', '招聘类别'],
            ['status_text', '公司反馈'],
            ['remark', '反馈备注'],
            ['createtime', '报名时间'],
        ];
        export_excel("招聘报名记录", $xlsCell, $xlsData);
    }


    // 企业招聘
    public function comjobsList()
    {
        $param         = ParamModel::where(1)->findOrEmpty();
        $access_worker = Session::get('access_worker');
        $catelist      = ComjobsCateModel::order(['priority' => 'desc', 'id' => 'desc'])->select();
        $is_released   = 0;
        if ($access_worker['status'] == 1) {
            $is_released = is_released($access_worker['id'])['code'];
        }

        return view('comjobs/comjobslist', [
            'param'       => $param,
            'wtype'       => $access_worker['wtype'],
            'catelist'    => $catelist,
            'is_released' => $is_released,
        ]);
    }


    // 上传视频
    public function upload_video()
    {
        $file     = request()->file("file");
        $savename = \think\facade\Filesystem::disk('public')->putFile('video', $file);
        if ($file) {
            $filename = str_replace(strrchr($_FILES['file']['name'], "."), "", $_FILES['file']['name']);
            exit(json_encode([
                'code' => 0,
                'msg'  => "",
                'data' => [
                    'src'   => request()->domain() . "/attachment/" . str_replace("\\", "/", $savename),
                    'title' => $filename,
                ],
            ]));
        } else {
            exit(json_encode([
                'code' => 1,
                'msg'  => "上传失败，请稍后重试",
            ]));
        }
    }

    public function comjobsForm()
    {
        $worker        = $this->access_worker;
        $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', [
            'worker'        => $worker,
            'catelist'      => $catelist,
            'workerlist'    => $workerlist,
            'communitylist' => $communitylist,
            'agelist'       => $agelist,
            'educationlist' => $educationlist,
            'emptimelist'   => $emptimelist,
            'welfarelist'   => $welfarelist,
            'comjobs'       => $comjobs,
        ]);
    }

    public function editComjobs()
    {
        $workerid = $this->access_worker['id'];
        $user     = UserModel::findOrEmpty($this->access_worker['userid']);
        if ($user->isEmpty()) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "用户信息不存在",
            ]));
        }
        $param = ParamModel::where(1)->findOrEmpty();
        $id    = input('id/d', 0);

        $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'             => 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', 0),
            'picall'           => input('picall/a', []),
            'recruit_num'      => input('recruit_num/d', 1),
            'wtype'            => $wtype,
            'sex'              => input('sex/d', 0),
            'bwagall'          => input('bwagall/s', ""),
            'zwagall'          => $zwagall,
            'fwagall'          => input('fwagall/s', ""),
            'telephone'        => input('telephone/s', ""),
            'remark'           => input('remark/s', ""),
            'status'           => input('status/d', 1),
            'num'              => input('num/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', [])),
        ];

        if ($data['recruitment_cate'] == 2 && $data['retmoney'] <= 0) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "悬赏金额必须大于0",
            ]));
        }

        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->addcomjobs) {
                    page_result1(1, "每次发布招聘信息需要扣除" . $param->addcomjobs . "积分，你当前积分不足。");
                }
            }*/

            $data['priority']   = 0;
            $data['video']      = input('new_video/s', "");
            $data['updatetime'] = time();
            $data['createtime'] = time();
            $data['status']     = (int)2;
            $data['volume']     = 0;
            $comjobs            = ComjobsModel::create($data);
            /*$intdata            = [
                'userid'      => $user->id,
                'title'       => "发布招聘信息扣除",
                'intvalue'    => 0 - $param->addcomjobs,
                '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->addcomjobs);
            $user->save([
                'integral' => $integral,
            ]);*/
        } else {
            $data['updatetime'] = time();
            $data['status']     = 2;
            $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);
        }

        //审核通知短信
        if ($data['status'] == 2) {
            $sms = new SmsService();
            $sms->examineSend('comjobs_examine', [$comjobs['id']]);
        }

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

    public function comjobsFormWyp()
    {
        $worker   = $this->access_worker;
        $id       = input('id/d, 0');
        $comjobs  = ComjobsModel::findOrEmpty($id);
        $catelist = ComjobsCateModel::order(['priority' => 'desc', 'id' => 'desc'])->select();
        return view('comjobs/comjobsformWyp', [
            'catelist' => $catelist,
            'worker'   => $worker,
            'id'       => $id,
            'comjobs'  => $comjobs,
        ]);
    }

    public function editComjobsWyp()
    {
        $workerid = $this->access_worker['id'];
        $user     = UserModel::findOrEmpty($this->access_worker['userid']);
        if ($user->isEmpty()) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "用户信息不存在",
            ]));
        }
        $param = ParamModel::where(1)->findOrEmpty();
        $id    = input('id/d', 0);

        $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', ""),
            'retmoney'         => input('retmoney/d', ""),
            'picall'           => input('picall/a', []),
            'companydetails'   => input('companydetails/s', ""),
            'wtype'            => $wtype,
            'bwagall'          => input('bwagall/s', ""),
            'zwagall'          => $zwagall,
            'fwagall'          => input('fwagall/s', ""),
            'telephone'        => input('telephone/s', ""),
            'remark'           => input('remark/s', ""),
            'recruitment_cate' => (int)2,
        ];

        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->addcomjobswyp) {
                    page_result1(1, "每次发布招聘信息需要扣除" . $param->addcomjobswyp . "积分，你当前积分不足。");
                }
            }

            $data['priority']   = 0;
            $data['video']      = input('new_video/s', "");
            $data['updatetime'] = time();
            $data['createtime'] = time();
            $data['status']     = (int)2;
            $data['volume']     = 0;
            $comjobs            = ComjobsModel::create($data);
            $intdata            = [
                'userid'      => $user->id,
                'title'       => "发布招聘信息扣除",
                'intvalue'    => 0 - $param->addcomjobs,
                '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->addcomjobswyp);
            $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);
            $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()
    {
        $workerid = $this->access_worker['id'];
        $id       = input('id/d', 0);
        $comjobs  = ComjobsModel::where(['workerid' => $workerid])->findOrEmpty($id);
        if ($comjobs->isEmpty()) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "信息不存在",
            ]));
        } else {
            $comjobs->save([
                'telephone' => input('value'),
            ]);
        }
        exit(json_encode([
            'code' => 0,
        ]));
    }

    public function delComjobs()
    {
        $workerid = $this->access_worker['id'];
        $idarr    = input('idarr/a');

        $comjobs_data = Db::name('comjobs')
            ->where(['workerid' => $workerid])
            ->whereIn('id', $idarr)
            ->update(['del_status' => 1]);

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

    public function listComjobs()
    {
        $workerid = $this->access_worker['id'];
        $limit    = input('limit/d', 20);
        $page     = input('page/d', 1);
        $map      = [];
        $map[]    = ['workerid', '=', $workerid];
        $keywords = input('keywords/s', "");
        if (!empty($keywords)) {
            $map[] = ['title', 'like', '%' . $keywords . '%'];
        }
        $status = input('status/d');
        if (!empty($status)) {
            $map[] = ['status', '=', $status];
        }
        $cateid = input('cateid/d', 0);
        if (!empty($cateid)) {
            $map[] = ['cateid', '=', $cateid];
        }
        $wtype = input('wtype/d');
        if (!empty($wtype)) {
            $map[] = ['wtype', '=', $wtype];
        }
        $recruitment_cate = input('recruitment_cate/d');
        if (!empty($recruitment_cate)) {
            $map[] = ['recruitment_cate', '=', $recruitment_cate];
        }

        $list  = ComjobsModel::with(['worker', 'comjobsCate'])
            ->withCount(['comjobsLog'])
            ->where('del_status', 0)
            ->where($map)
            ->order('id desc')
            ->limit($limit)
            ->page($page)
            ->append(['wtype_text', 'status_text', 'recruitmentcate_text'])
            ->select();
        $count = ComjobsModel::where($map)->count();

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

    public function importView()
    {
        return view('comjobs/importview');
    }

    public function import()
    {
        $workerid = $this->access_worker['id'];
        $file_url = input('file_url/s', "");
        if (!file_exists($file_url)) {
            exit(json_encode([
                'code' => 1,
                'msg'  => "文件不存在",
            ]));
        }

        $service = new ComjobsService();
        $res     = $service->importComjobs($file_url, $workerid);
        if (empty($res['code'])) {
            exit(json_encode([
                'code' => 1,
                'msg'  => $res['msg'],
            ]));
        }

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