<?php

namespace App\Http\Controllers\Web\Content;

use App\Http\Controllers\Web\WebBaseController;
use App\Models\Article;
use App\Models\MemberInfo;
use App\Models\SmsTemplate;
use App\Models\TalentHouse;
use App\Models\TalentHouseApply;
use App\Models\TalentHousePeople;
use App\Services\Content\ArticleService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;


class BuyhouseController extends WebBaseController
{
    private $street = [
        '青阳街道', '梅岭街道', '西园街道', '罗山街道', '灵源街道', '新塘街道', '陈埭镇', '池店镇', '安海镇', '磁灶镇', '内坑镇', '紫帽镇', '东石镇', '永和镇', '英林镇', '金井镇', '龙湖镇', '深沪镇', '西滨镇',
    ];
    private $house_status = ['未知', '未开始', '申报中', '已结束'];
    private $tag_status = ['', 'info', 'success', 'danger', 'danger'];
    private $apply_status = ['未知', '审核中', '审核通过', '审核驳回', '审核不通过'];
    private $check_type = ['', 'warning', 'success', 'error', 'error'];
    private $talent_level = ['不是人才', '第一层次', '第二层次', '第三层次', '第四层次', '第五层次', '第六层次', '第七层次'];
    protected $articleService;

    /**
     * ArticleController constructor.
     * @param $articleService
     * @param $articleCategoryService
     */
    public function __construct(ArticleService $articleService)
    {
        $this->articleService = $articleService;
    }

    /**
     * 登录
     */
    public function login()
    {
        $user_id     = auth('web-member')->id();
        $return_data = ['user_id' => $user_id ?: 0, 'apply' => '[]'];

        //房源
        $house = TalentHouse::orderBy('apply_time_start', 'desc')->limit(8)->get();
        foreach ($house as $v) {
            $v['status']           = $this->_get_status($v);
            $v['apply_time_start'] = date('Y-m-d', strtotime($v['apply_time_start']));
            $v['apply_time_end']   = date('Y-m-d', strtotime($v['apply_time_end']));
            $v['status_text']      = $this->house_status[$v['status']];
            $v['status_tag']       = $this->tag_status[$v['status']];
            $v['url']              = route('buyhouse.detail', ['id' => $v['id']]);
        }
        $return_data['house'] = $house;

        //新闻
        $news = Article::where('type_id', 56)
            ->where('is_display', 1)
            ->select(['id', 'title', 'updated_at', 'created_at'])
            ->orderByRaw('list_order desc,created_at desc')
            ->limit(6)
            ->get();
        foreach ($news as $v) {
            $v['created_at_text'] = date('Y-m-d', strtotime($v['created_at']));
            $v['updated_at_text'] = date('Y-m-d', strtotime($v['updated_at']));
            $v['url']             = route('news.show', ['id' => $v['id']]);
        }
        $return_data['news'] = $news;

        //我的申报
        if ($user_id > 0) {
            $apply = TalentHouseApply::with('house')
                ->select(['id', 'house_id', 'status'])
                ->where('is_draft', 2)
                ->where('is_back', 2)
                ->where('user_id', $user_id)
                ->get();
            foreach ($apply as $v) {
                $v['status_text'] = $this->apply_status[$v['status']];
                $v['status_tag']  = $this->tag_status[$v['status']];
                $v['url']         = route('buyhouse.list', ['id' => $v['house_id']]);
            }
            $return_data['apply'] = $apply;

            //用户信息
            $memberInfo                 = MemberInfo::where('uid', $user_id)->first();
            $return_data['member_info'] = $memberInfo;
        }

        return view('app.content.buyhouse.login', $return_data);
    }

    /**
     * 完善信息
     */
    public function perfect(Request $request)
    {
        $user_id = auth('web-member')->id();
        if (empty($user_id)) {
            return response()->json(['status' => 0, 'msg' => '请先登录']);
        }

        $data = $request->only(['realname', 'card_t_cn', 'id_card']);
        MemberInfo::where('uid', $user_id)->update($data);

        return response()->json(['status' => 1, 'msg' => '修改成功']);
    }

    /**
     * 房源信息
     */
    public function house()
    {
        $lists = TalentHouse::orderBy('apply_time_start', 'desc')->paginate(10);
        foreach ($lists as $v) {
            $v['status']           = $this->_get_status($v);
            $v['apply_time_start'] = date('Y-m-d', strtotime($v['apply_time_start']));
            $v['apply_time_end']   = date('Y-m-d', strtotime($v['apply_time_end']));
            $v['status_text']      = $this->house_status[$v['status']];
            $v['status_tag']       = $this->tag_status[$v['status']];
        }

        $return_data = [
            'articles' => $lists,
            'now_cate' => '房源信息',
        ];
        return view('app.content.buyhouse.house', $return_data);
    }

    /**
     * 公告
     */
    public function news()
    {
        $lists = $this->articleService->list('', 56, '10');

        $return_data = [
            'articles' => $lists,
            'now_cate' => '公告',
        ];

        return view('app.content.buyhouse.news', $return_data);
    }

    public function detail(Request $request)
    {
        $id = $request->get('id');
        if (empty($id)) {
            $back_url = \Illuminate\Support\Facades\URL::previous();
            return $this->showMessage('该房源不存在或已删除', $back_url, true, '上一页', '3');
        }

        //房源信息
        $house = TalentHouse::where('id', $id)->first();
        if (empty($house)) {
            $back_url = \Illuminate\Support\Facades\URL::previous();
            return $this->showMessage('该房源不存在或已删除', $back_url, true, '上一页', '3');
        }

        $house['status']      = $this->_get_status($house);
        $house['status_text'] = $this->house_status[$house['status']];
        $house['status_tag']  = $this->tag_status[$house['status']];
        $house['url']         = route('buyhouse.list', ['id' => $house['id']]);
        $house['apply_time']  = date('Y-m-d', strtotime($house['apply_time_start'])) . ' - ' . date('Y-m-d', strtotime($house['apply_time_end']));

        $return_data = [
            'info' => $house,
        ];

        return view('app.content.buyhouse.detail', $return_data);
    }

    /**
     * 报名列表
     */
    public function list(Request $request)
    {
        $login = $this->checkLogin();
        if ($login) {
            return $login;
        }

        $user_id = auth('web-member')->id();
        if (empty($user_id)) {
            $back_url = route('buyhouse.login');
            return $this->showMessage('登录过期,请先登录', $back_url, true, '上一页', '3');
        }
        //拉黑
        $people = TalentHousePeople::where('user_id', $user_id)->first();
        if (!empty($people) && $people['status'] == 2) {
            $back_url = \Illuminate\Support\Facades\URL::previous();
            return $this->showMessage('无法进入申报系统,请联系相关单位', $back_url, true, '上一页', '3');
        }

        $id = $request->get('id');
        if (empty($id)) {
            $back_url = \Illuminate\Support\Facades\URL::previous();
            return $this->showMessage('该房源不存在或已删除', $back_url, true, '上一页', '3');
        }

        //是否报名其他
        $sock = TalentHouseApply::where('user_id', $user_id)->where('house_id', '<>', $id)->where('is_sock', 1)->where('is_draft', 2)->first();
        if (!empty($sock)) {
            $back_url = \Illuminate\Support\Facades\URL::previous();
            return $this->showMessage('不可以同时申报多个房源', $back_url, true, '上一页', '3');
        }

        //房源信息
        $house = TalentHouse::where('id', $id)->first();
        if (empty($house)) {
            $back_url = \Illuminate\Support\Facades\URL::previous();
            return $this->showMessage('该房源不存在或已删除', $back_url, true, '上一页', '3');
        }
        $house['declare_time_text'] = date('Y-m-d', strtotime($house['declare_time']));
        $house['status']            = $this->_get_status($house);
        $house['status_text']       = $this->house_status[$house['status']];
        $house['status_tag']        = $this->tag_status[$house['status']];
        $house['apply_time']        = date('Y-m-d', strtotime($house['apply_time_start'])) . ' - ' . date('Y-m-d', strtotime($house['apply_time_end']));

        //报名信息
        $apply = TalentHouseApply::where('house_id', $id)->where('is_back', 2)->where('user_id', $user_id)->first();
        $check = [];
        $time  = time();
        if ($apply) {
            if ($house['status'] != 2 && $apply['is_draft'] == 1) {
                $back_url = \Illuminate\Support\Facades\URL::previous();
                return $this->showMessage('该房源未在申报时间', $back_url, true, '上一页', '3');
            }
            //审核状态
            if ($apply['is_draft'] == 2) {
                if ($apply['rs_check_status'] != 2) {
                    if ($apply['type'] == 1) {
                        $check['status_text'] = '人社局' . $this->apply_status[$apply['rs_check_status']];
                    } else {
                        $check['status_text'] = '集成电路' . $this->apply_status[$apply['rs_check_status']];
                    }
                    $check['comment'] = $apply['rs_check_status'] == 1 ? '' : $apply['rs_check_comment'];
                    $check['type']    = $this->check_type[$apply['rs_check_status']];
                } elseif ($apply['zj_check_status'] != 2 || $apply['zr_check_status'] != 2) {
                    $check['status_text'] = '住建局' . $this->apply_status[$apply['zj_check_status']] . '<br/>' . '自然资源局' . $this->apply_status[$apply['zr_check_status']];
                    $comment              = [];
                    if ($apply['zj_check_status'] != 1 && !empty($apply['zj_check_comment'])) {
                        $comment[] = '住建局:' . $apply['zj_check_comment'];
                    }
                    if ($apply['zr_check_status'] != 1 && !empty($apply['zr_check_comment'])) {
                        $comment[] = '自然资源局:' . $apply['zr_check_comment'];
                    }
                    $check['comment'] = implode(';', $comment);
                    $check_status     = $apply['zj_check_status'] > $apply['zr_check_status'] ? $apply['zj_check_status'] : $apply['zr_check_status'];
                    $check['type']    = $this->check_type[$check_status];
                } else {
                    $check['title']       = '';
                    $check['status_text'] = '审核通过';
                    $check['comment']     = '';
                    $check['type']        = 'success';
                }
            }
        } else {
            if ($house['status'] != 2) {
                $back_url = \Illuminate\Support\Facades\URL::previous();
                return $this->showMessage('该房源未在申报时间', $back_url, true, '上一页', '3');
            }
            $infos = MemberInfo::where('uid', $user_id)->first();
            if (empty($infos['id_card'])) {
                $back_url = route('person.resume');
                return $this->showMessage('请先填写身份证号', $back_url, true, '上一页', '3');
            }
            $request_post = [
                'idCards' => [$infos['id_card']],
                'sign'    => mb_strtoupper(md5("timestr={$time}&key=rsKVyec52fqEKpk4RRD2TU8fKvPxt6ombKg0qSq1velPQtBHVi")),
                'timeStr' => (string)$time,
            ];
            $res          = https_request('https://rc.jucai.gov.cn/api/dataInterface/findTalentInfoByIdCards', json_encode($request_post), ['Content-Type:application/json']);
            $talent       = json_decode($res, true);
            if (empty($talent['obj'])) {
                $back_url = \Illuminate\Support\Facades\URL::previous();
                return $this->showMessage('您还未认定人才,暂无申报资格', $back_url, true, '上一页', '3');
            }
            $talent = $talent['obj'][0];
            if ($talent['talentArrange'] > 5) {
                $back_url = \Illuminate\Support\Facades\URL::previous();
                return $this->showMessage('目前仅支持一到五层次人才申报', $back_url, true, '上一页', '3');
            }
            if ($talent['type'] > 2) {
                $back_url = \Illuminate\Support\Facades\URL::previous();
                return $this->showMessage('其他人才暂不支持', $back_url, true, '上一页', '3');
            }
            if (!empty($talent['activeDate']) && strtotime($talent['activeDate']) < time()) {
                $back_url = \Illuminate\Support\Facades\URL::previous();
                return $this->showMessage('人才证有效期为' . $talent['activeDate'] . ',人才证已过期,请重新认证', $back_url, true, '上一页', '3');
            }

            $add   = [
                'user_id'              => $user_id,
                'house_id'             => $id,
                'type'                 => $talent['type'],
                'name'                 => $talent['name'],
                'mobile'               => $talent['phone'],
                'native'               => $talent['nativePlace'],
                'email'                => $talent['email'],
                'talent_level'         => $this->talent_level[$talent['talentArrange']],
                'talent_card_validity' => $talent['activeDate'],
                'talent_tags'          => $talent['talentType'],
                'talent_condition'     => $talent['identifyCondition'],
                'company'              => $talent['company'],
                'street'               => $talent['street'],
                'family'               => json_encode([['relation' => '配偶', 'realname' => '', 'idcard' => '']]),
                'certificates'         => '[]',
                'marry_prove'          => '[]',
                'household_register'   => '[]',
                'work_prove'           => '[]',
                'created_at'           => date('Y-m-d H:i:s'),
                'updated_at'           => date('Y-m-d H:i:s'),
            ];
            $id    = TalentHouseApply::insertGetId($add);
            $apply = TalentHouseApply::find($id);

            //报名人员列表
            $memberInfo = MemberInfo::where('uid', $user_id)->first();
            if (empty($people)) {
                TalentHousePeople::insert([
                    'user_id'    => $user_id,
                    'realname'   => $memberInfo['realname'] ?: '',
                    'mobile'     => $memberInfo['phone'] ?: '',
                    'email'      => $memberInfo['email'] ?: '',
                    'card_t_cn'  => $memberInfo['card_t_cn'] ?: 306,
                    'id_card'    => $memberInfo['id_card'] ?: '',
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s'),
                ]);
            } else {
                TalentHousePeople::where('user_id', $user_id)->update([
                    'realname'   => $memberInfo['realname'] ?: '',
                    'mobile'     => $memberInfo['mobile'] ?: '',
                    'email'      => $memberInfo['email'] ?: '',
                    'card_t_cn'  => $memberInfo['card_t_cn'] ?: 306,
                    'id_card'    => $memberInfo['id_card'] ?: '',
                    'updated_at' => date('Y-m-d H:i:s'),
                ]);
            }
        }

        $apply['family']             = json_decode($apply['family'], true);
        $apply['certificates']       = json_decode($apply['certificates'], true);
        $apply['marry_prove']        = json_decode($apply['marry_prove'], true);
        $apply['household_register'] = json_decode($apply['household_register'], true);
        $apply['work_prove']         = json_decode($apply['work_prove'], true);
        $apply['checked']            = true;

        //是否可填表格
        $formDisable = 'true';
        if ($apply['is_draft'] == 1) {
            //草稿
            $formDisable = 'false';
        } else {
            if ($time < strtotime($house['apply_time_end']) && $apply['status'] == 3) {
                $formDisable = 'false';
            } else {
                if ($time < strtotime($house['supply_time']) && ($apply['rs_check_status'] == 3 || $apply['zj_check_status'] == 3)) {
                    $formDisable = 'false';
                }
            }

        }

        $return_data = [
            'formDisable' => $formDisable,
            'check'       => $check,
            'apply'       => json_encode($apply),
            'house'       => json_encode($house),
            'module'      => ['identification'],
        ];

        return view('app.content.buyhouse.list', $return_data);
    }

    /**
     * 申报提交
     */
    public function listPost(Request $request)
    {
        //数据校验
        $data      = $request->only(['id', 'certificates', 'marry', 'child_num', 'marry_prove', 'household_register', 'family', 'work_prove', 'company', 'street', 'house_condition', 'house_policy']);
        $rules     = [
            'certificates'       => 'required',
            'marry'              => 'required',
            'household_register' => 'required',
            'work_prove'         => 'required',
            'house_condition'    => 'required',
            'house_policy'       => 'required',
        ];
        $messages  = [
            'certificates.required'       => '请上传证件信息',
            'marry.required'              => '请选择婚姻状况',
            'household_register.required' => '请上传户口本',
            'work_prove.required'         => '请上传工作证明',
            'house_condition.required'    => '请填写家庭成员在晋江市行政区域内住房情况',
            'house_policy.required'       => '请填写在晋享受政策性住房或相关优惠情况',
        ];
        $validator = Validator::make($data, $rules, $messages);
        if ($validator->fails()) {
            $msg = $validator->errors()->all();
            return response()->json(['status' => 0, 'msg' => $msg[0]]);
        }
        if ($data['marry'] > 1 && empty($data['marry_prove'])) {
            return response()->json(['status' => 0, 'msg' => '请上传婚姻证明']);
        }

        //报名信息
        $info = TalentHouseApply::find($data['id']);
        if (empty($info)) {
            return response()->json(['status' => 0, 'msg' => '提交格式有误']);
        }

        //房源消息
        $house           = TalentHouse::find($info['house_id']);
        $house['status'] = $this->_get_status($house);
        $time            = time();
        if (strtotime($house['apply_time_start']) > $time) {
            return response()->json(['status' => 0, 'msg' => '申报未开始,无法修改']);
        }
        if ($time > strtotime($house['supply_time'])) {
            return response()->json(['status' => 0, 'msg' => '已超过补件时间,无法修改']);
        }

        //日志
        $log = [
            'house_name' => $house['name'],
            'user_name'  => $info['name'],
            'old'        => $info['is_draft'] == 1 ? '' : json_encode($info),
            'created_at' => date('Y-m-d H:i:s'),
        ];

        //图片
        $images = ['certificates', 'household_register', 'marry_prove', 'work_prove'];
        foreach ($images as $image) {
            if (!empty($data[$image]) && is_array($data[$image])) {
                //删除掉没有成功返回路径的图片
                foreach ($data[$image] as $k => $v) {
                    if (!array_key_exists('response', $v)) {
                        unset($data[$image][$k]);
                    }
                }
                $data[$image] = array_values($data[$image]);
            }
        }

        //更新数据
        $info->certificates = json_encode($data['certificates']);
        $info->marry        = $data['marry'];
        if ($data['marry'] > 1) {
            $info->marry_prove = json_encode($data['marry_prove']);
        }
        $info->household_register = json_encode($data['household_register']);
        $info->family             = json_encode($data['family']);
        $info->work_prove         = json_encode($data['work_prove']);
        $info->street             = $data['street'];
        $info->child_num          = $data['child_num'];
        $info->company            = $data['company'];
        $info->house_condition    = $data['house_condition'];
        $info->house_policy       = $data['house_policy'];
        $info->status             = 1;

        //审核状态
        if ($info->rs_check_status == 1 && $info->type == 1) {
            SmsTemplate::buyHouseCheck('rs');
        }
        if ($info->rs_check_status == 3) {
            $info->rs_check_status = 1;
            if ($info->type == 1) {
                SmsTemplate::buyHouseCheck('rs');
            }
        }
        if ($info->zj_check_status == 3) {
            $info->zj_check_status = 1;
            SmsTemplate::buyHouseCheck('zj');
        }
        if ($info->zr_check_status == 3) {
            $info->zr_check_status = 1;
            SmsTemplate::buyHouseCheck('zr');
        }
        if ($info->is_draft == 1) {
            $info->is_draft = 2;
        }
        if ($info->is_sock == 2) {
            $info->is_sock = 1;
        }
        $info->save();

        //日志
        $log['new'] = json_encode($info);
        DB::table('talent_house_log')->insert($log);

        return response()->json(['status' => 1]);
    }

    /**
     * 撤消
     */
    public function back(Request $request)
    {
        $id = $request->get('id');
        if (empty($id)) {
            return response()->json(['status' => 1]);
        }

        $apply = TalentHouseApply::find($id);
        if (empty($apply) || $apply['user_id'] != auth('web-member')->id() || $apply['is_back'] == 1) {
            return response()->json(['status' => 1]);
        }
        if ($apply['status'] == 2) {
            return response()->json(['status' => 0, 'msg' => '已通过审核的申报无法撤消']);
        }
        if ($apply['status'] == 4) {
            return response()->json(['status' => 0, 'msg' => '审核不通过的申报无法撤消']);
        }

        $house = TalentHouse::find($apply['house_id']);
        if (strtotime($house['supply_time']) < time()) {
            return response()->json(['status' => 0, 'msg' => '已过补件时间,申报无法撤消']);
        }

        $apply->is_back = 1;
        $apply->is_sock = 2;
        $apply->save();
        return response()->json(['status' => 1]);
    }

    /**
     * 图片上传
     */
    public function upload(Request $request)
    {
        header('Access-Control-Allow-Origin:*');
        header('Access-Control-Allow-Methods:GET,POST,PUT,DELETE');
        header('Access-Control-Allow-Headers:Origin, Content-Type, Cookie, Accept, X-CSRF-TOKEN');
        header('Access-Control-Allow-Credentials:true');

        $file = $request->file('file');
        if ($file->isValid()) { //判断文件是否存在
            //获取文件的扩展名
            $ext = $file->getClientOriginalExtension();

            if (!in_array(strtolower($ext), ['jpg', 'jpeg', 'png', 'doc', 'docx', 'pdf'])) {
                $res['status'] = 0;
                $res['msg']    = '文件格式不正确';
            } else {
                //获取文件的绝对路径
                $path = $file->getRealPath();

                $oldname = $file->getClientOriginalName();

                //定义文件名
                $filename = 'storage/buyhouse/' . uniqid() . mt_rand(10000, 99999) . '.' . $ext;

                //存储文件。disk里面的public。总的来说,就是调用disk模块里的public配置
                Storage::disk('public')->put($filename, file_get_contents($path));

                $res['status']   = 1;
                $res['filename'] = $oldname;
                $res['path']     = "/storage/" . $filename;
                $res['msg']      = '上传成功';
            }
        } else {
            $res['status'] = 0;
            $res['msg']    = '上传失败';
        }
        return response()->json($res);
    }

    /**
     * 登录状态
     */
    private function checkLogin()
    {
        $user_id = auth('web-member')->id();
        if (empty($user_id)) {
            return redirect(route('buyhouse.login'));
        }

        return false;
    }

    /**
     * 状态
     */
    private function _get_status($row)
    {
        $time = time();

        if (strtotime($row['apply_time_start']) > $time) {
            return 1;
        } elseif (strtotime($row['apply_time_end']) < $time) {
            return 3;
        } else {
            return 2;
        }
    }
}