<?php

namespace app\person\controller;

use app\person\common\PersonController;
use app\common\model\Person as PersonModel;
use app\common\api\UserApi;
use think\facade\Db;

/**
 * Description of UserInfo
 *
 * @author sgq
 */
class UserInfo extends PersonController {

    public function index() {
        return view();
    }

    public function changeBasic() {
        $uid = $this->user["uid"];
        $response_object = new \StdClass();
        $response_object->code = 500;
        $data = [
            //'name' => \StrUtil::getRequestDecodeParam($this->request, 'name'),
            //'idCard' => \StrUtil::getRequestDecodeParam($this->request, 'idCard'),
            //'sex' => \StrUtil::getRequestDecodeParam($this->request, 'sex'),
            //'email' => \StrUtil::getRequestDecodeParam($this->request, 'email'),
            'address' => \StrUtil::getRequestDecodeParam($this->request, 'address')
        ];
        try {
            validate(\app\common\validate\Person::class)->batch(true)->scene('basic')->check($data);
            $data["id"] = $uid;
            $data["updateUser"] = $uid;
            $data["updateTime"] = date("Y-m-d H:i:s");
            PersonModel::update($data);

            $user = new UserApi($this->user["account"], "", 3);
            $user->setSession();

            $response_object->code = 200;
            $response_object->msg = "修改完成!";
            return json($response_object);
        } catch (\Exception $ex) {
            $response_object->msg = $ex->getMessage();
            return json($response_object);
        }
    }

    public function changePwd() {
        $uid = $this->user["uid"];
        $response_object = new \StdClass();
        $response_object->code = 500;
        $params = [
            'password' => \StrUtil::getRequestDecodeParam($this->request, 'password'),
            'newPassword' => \StrUtil::getRequestDecodeParam($this->request, 'newPassword'),
            'newRePassword' => \StrUtil::getRequestDecodeParam($this->request, 'newRePassword')
        ];
        //新密码 与  原始密码不能为空
        if (!$params["password"]) {
            $response_object->msg = "请填写原密码!";
            return json($response_object);
        }
        if (!$params["newPassword"]) {
            $response_object->msg = "请填写新密码!";
            return json($response_object);
        }
        if (!$params["newRePassword"]) {
            $response_object->msg = "请填写重复新密码!";
            return json($response_object);
        }
        if ($params["newPassword"] != $params["newRePassword"]) {
            $response_object->msg = "两次输入的新密码不一致!";
            return json($response_object);
        }
        if (!preg_match("/^(?=.*\\d)(?=.*[A-Za-z]).{8,}$/", $params["newPassword"])) {
            $response_object->msg = "密码必须包含字母、数字、特殊符号且长度超过8位!";
            return json($response_object);
        }
        $userInfo = PersonModel::where("id", $uid)->find();
        if ($userInfo["password"] != md5($params ["password"])) {
            $response_object->msg = "原密码错误!";
            return json($response_object);
        }
        try {
            $data["id"] = $uid;
            $data["password"] = md5($params["newPassword"]);
            $data["updateTime"] = date("Y-m-d H:i:s");
            PersonModel::update($data);

            $user = new UserApi($userInfo["username"], "", 3);
            $user->setSession();

            $response_object->code = 200;
            $response_object->msg = "修改成功!";
            return json($response_object);
        } catch (\Exception $e) {
            $response_object->msg = $ex->getMessage();
            return json($response_object);
        }
    }

    public function changePhone() {
        $uid = $this->user["uid"];
        $response_object = new \StdClass();
        $response_object->code = 500;
        $params = [
            'phone' => \StrUtil::getRequestDecodeParam($this->request, 'phone'),
            'verificationCode' => \StrUtil::getRequestDecodeParam($this->request, 'verificationCode'),
            'newPhone' => \StrUtil::getRequestDecodeParam($this->request, 'newPhone')
        ];
        //当前号码、验证码、新号码不能为空
        if (!$params["phone"]) {
            $response_object->msg = "当前号码不能为空!";
            return json($response_object);
        }
        if (!$params["verificationCode"]) {
            $response_object->msg = "请填写验证码!";
            return json($response_object);
        }
        if (!$params["newPhone"]) {
            $response_object->msg = "请填写新号码!";
            return json($response_object);
        }
        //新号码格式必须正确
        if (!preg_match("/^1\\d{10}$/", $params["newPhone"])) {
            $response_object->msg = "新号码格式有误!";
            return json($response_object);
        }
        //验证码验证
        $codeVerify = \app\common\api\MessageRecordApi::checkVerificationCode($params["phone"], $params["verificationCode"]);
        if ($codeVerify->code != 200) {
            $response_object->msg = $codeVerify->msg;
            return json($response_object);
        }
        try {
            $userInfo = PersonModel::where("id", $uid)->find();
            $where = [];
            $where[] = ["card_number", "=", $userInfo["idCard"]];
            $where[] = ["checkState", "=", \app\common\api\TalentState::CERTIFICATED];
            $talentInfo = \app\enterprise\model\Talent::where($where)->order("createTime desc")->find();

            $oldWhere = [];
            $oldWhere[] = ["idCard", "=", $userInfo['idCard']];
            $oldWhere[] = ["checkState", "=", \app\common\state\MainState::PASS];
            $oldWhere[] = ["isPublic", "=", 6];
            $oldWhere[] = ["isEffect", "=", 1];
            $oldTalentInfo = Db::table("un_talent_info")->where($oldWhere)->find();
            //查询该证件号码和手机号是否在库
            $phone = $talentInfo ? $talentInfo["phone"] : $oldTalentInfo["phone"];
            if (!$talentInfo && !$oldTalentInfo) {
                $response_object->msg = "人才库中不存在该证件号码，修改失败!";
                return json($response_object);
            }
            if ($phone != $params["newPhone"]) {
                $response_object->msg = "手机号码必须与人才库中一致，可联系企业经办人修改人才库手机号码后再行修改";
                return json($response_object);
            }
            $data["id"] = $uid;
            $data["phone"] = $params["newPhone"];
            $data["updateUser"] = $uid;
            $data["updateTime"] = date("Y-m-d H:i:s");
            PersonModel::update($data);

            $user = new UserApi($userInfo["username"], "", 3);
            $user->setSession();

            $response_object->code = 200;
            $response_object->msg = "修改成功!";
            return json($response_object);
        } catch (\Exception $e) {
            $response_object->msg = $e->getMessage();
            return json($response_object);
        }
    }

    public function gotoChangeHeadPortraitPage() {
        $uid = $this->user["uid"];
        $userInfo = PersonModel::where("id", $uid)->find();
        return view("person_change_head", ["headPortrait" => $userInfo["headPortrait"]]);
    }

    public function changeHeadPortrait() {
        $response = new \stdClass();
        $response->code = 500;

        $uid = $this->user["uid"];
        $userInfo = PersonModel::where("id", $uid)->find();

        if ($this->request->file()) {
            $headPortrait = $this->request->file("headPortrait");
            $upload = new \app\common\api\UploadApi();
            $result = $upload->uploadOne($headPortrait, "image", "person/photo");
            if ($result->code != 200) {
                $response->msg = $result->msg;
                return \StrUtil::back($response, "ech.callback");
            }
            if ($userInfo["headPortrait"]) {
//如果新照片符合像素要求，则删除旧照片
                $old_head_url = "storage/" . $userInfo ["headPortrait"];
                if (file_exists($old_head_url))
                    @unlink(
                                    $old_head_url);
            }
            $data["id"] = $uid;
            $data["headPortrait"] = $result->filepath;
            $data["updateUser"] = $uid;
            $data["updateTime"] = date("Y-m-d H:i:s");
            PersonModel::update($data);

            $user = new UserApi($userInfo["username"], "", 3);
            $user->setSession();

            $response->code = 200;
            $response->msg = "修改成功!";
            $response->url = getStoragePath($result->filepath);
            return \StrUtil::back($response, "ech.callback");
        } else {
            $response->msg = "没有上传新头像";
            return \StrUtil::back($response, "ech.callback");
        }
    }

}
