<?php

namespace app\person\controller;

use app\person\common\PersonController;
use app\common\state\ProjectState;
use app\common\state\MainState;
use app\common\api\EducationApi;
use app\common\api\BatchApi;
use app\common\model\EducationSchool as EduModel;
use think\facade\Db;
use app\person\validate\EducationSchoolValidator;
use app\common\model\TalentLog;
use think\facade\Log;
use think\exception\ValidateException;

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

    public function index() {
        return view("", ['type' => session("user")['type']]);
    }

    public function list() {
        $res = EducationApi::getList($this->request);
        return json($res);
    }

    /**
     * 申请
     */
    public function apply(\think\Request $request) {
        $type = $this->user["type"];
        $param = $request->param();
        $id = isset($param["id"]) ? $param["id"] : 0;
        $info = EducationApi::getInfoById($id);
        if (!$info) {
            $where = [];
            $where[] = ["checkState", "=", \app\common\api\TalentState::CERTIFICATED];
            $where[] = ["card_number", "=", $this->user["idCard"]];
            $where[] = ["isEffect", "=", 1];
            $talentInfo = \app\enterprise\model\Talent::where($where)->order("talent_arrange asc")->find();
            if ($talentInfo) {
                $talentCondition = \app\common\api\TalentConditionApi::getOne($talentInfo["talent_condition"]);
                $info["personId"] = $this->user["uid"];
                $info["type"] = $this->user["type"];
                $info["talentId"] = $talentInfo["id"];
                $info["pName"] = $talentInfo["name"];
                $info["pSex"] = $talentInfo["sex"];
                $info["pIdcard"] = $talentInfo["card_number"];
                $info["talentArrange"] = $talentInfo["talent_arrange"];
                $info["identifyCondition"] = $talentCondition["name"];
                $info["certificateStartTime"] = $talentInfo["certificateGetTime"];
                $info["qzgccrcActiveTime"] = $talentInfo["certificateExpireTime"];
                $info["certificateNo"] = $talentInfo["certificateNo"];
                $area = [];
                if ($talentInfo["province"]) {
                    $area[] = Db::table("un_common_location")->where("code", "=", $talentInfo["province"])->findOrEmpty()["name"];
                }
                if ($talentInfo["city"]) {
                    $area[] = Db::table("un_common_location")->where("code", "=", $talentInfo["city"])->findOrEmpty()["name"];
                }
                if ($talentInfo["county"]) {
                    $area[] = Db::table("un_common_location")->where("code", "=", $talentInfo["county"])->findOrEmpty()["name"];
                }
                $info["nativePlace"] = implode("", $area);
                $info["certificateNo"] = $talentInfo["certificateNo"];
                $info["phone"] = $talentInfo["phone"];
            } else {
                $oldWhere = [];
                $oldWhere[] = ["idCard", "=", $this->user["idCard"]];
                $oldWhere[] = ["checkState", "=", MainState::PASS];
                $oldWhere[] = ["isPublic", "=", 6];
                $oldWhere[] = ["isEffect", "=", 1];
                $oldTalentInfo = Db::table("un_talent_info")->where($oldWhere)->find();

                $info["personId"] = $this->user["uid"];
                $info["type"] = $this->user["type"];
                $info["talentId"] = $oldTalentInfo["id"];
                $info["pName"] = $oldTalentInfo["name"];
                $info["pSex"] = $oldTalentInfo["sex"];
                $info["pIdcard"] = $oldTalentInfo["idCard"];
                $info["talentArrange"] = $oldTalentInfo["talentArrange"];
                $info["identifyCondition"] = $oldTalentInfo["identifyConditionName"];
                $info["certificateStartTime"] = $oldTalentInfo["certificateStartTime"];
                $info["qzgccrcActiveTime"] = $oldTalentInfo["qzgccrcActiveTime"];
                $info["certificateNo"] = $oldTalentInfo["certificateNO"];
                $area = [];
                if ($oldTalentInfo["provinceName"]) {
                    $area[] = $oldTalentInfo["provinceName"];
                }
                if ($oldTalentInfo["cityName"]) {
                    $area[] = $oldTalentInfo["cityName"];
                }
                if ($oldTalentInfo["countyName"]) {
                    $area[] = $oldTalentInfo["countyName"];
                }
                $info["nativePlace"] = implode("", $area);
                $info["certificateNo"] = $oldTalentInfo["certificateNO"];
                $info["phone"] = $oldTalentInfo["phone"];
            }
        }
        if ($request->isPost()) {
            return $this->save($info, $request);
        }
        $batch = $info["year"] ?: BatchApi::getValidBatch(ProjectState::EDUCATION, $type)["batch"];
        return view("", ["year" => $batch, "row" => $info]);
    }

    public function detail(\think\Request $request) {
        $param = $request->param();
        $id = $param["id"];
        $info = EducationApi::getInfoById($id);
        return view("apply", ["row" => $info]);
    }

    public function save($info, \think\Request $request) {
        $response = new \stdClass();
        $response->code = 500;
        try {
            $batch = BatchApi::checkBatchValid(["type" => ProjectState::EDUCATION, "year" => $info["year"], "first_submit_time" => $info["firstSubmitTime"]], $this->user["type"]);

            if ($batch["code"] != 200) {
                throw new ValidateException($batch["msg"]);
            }
            $data = $request->param();
            unset($data["jstime"]); //不知道为啥把get的数据也获取了，先这样处理
            $data["year"] = $batch["batch"];
            validate(EducationSchoolValidator::class)->check($data);

            $id = $data["id"];
            if ($id) {
                if (!$info || $info["id"] != $id || $info["personId"] != $this->user["uid"]) {
                    throw new ValidateException("没有对应的子女择校申报信息");
                }
                $data["updateTime"] = date("Y-m-d H:i:s");
                $data["updateUser"] = $this->user["uid"];
                EduModel::update($data);

                $log["stateChange"] = "修改子女就学申报";
                $response->msg = "修改成功";
            } else {
                $talentInfo = \app\enterprise\api\TalentApi::getOne($info["talentId"])->toArray();
                $area = [];
                if ($talentInfo) {
                    if (!$talentInfo || $talentInfo["checkState"] != \app\common\api\TalentState::CERTIFICATED || $talentInfo["isEffect"] != 1) {
                        throw new ValidateException("未查询到有效的人才数据（根据证件号码匹配），无法申报");
                    }
                    if (!strtotime($talentInfo["certificateExpireTime"]) || strtotime($talentInfo["certificateExpireTime"]) < time()) {
                        throw new ValidateException("您的人才证书已过期，请进行人才层次变更后再申报");
                    }
                    if ($this->user["type"] == 1 && $talentInfo["talent_arrange"] > 5) {
                        throw new ValidateException("子女择校政策只针对第一至五层次人才！");
                    }

                    if ($talentInfo["province"]) {
                        $area[] = Db::table("un_common_location")->where("code", "=", $talentInfo["province"])->findOrEmpty()["name"];
                    }
                    if ($talentInfo["city"]) {
                        $area[] = Db::table("un_common_location")->where("code", "=", $talentInfo["city"])->findOrEmpty()["name"];
                    }
                    if ($talentInfo["county"]) {
                        $area[] = Db::table("un_common_location")->where("code", "=", $talentInfo["county"])->findOrEmpty()["name"];
                    }

                    $data["id"] = getStringId();
                    $data["personId"] = $this->user["uid"];
                    $data["pName"] = $talentInfo["name"];
                    $data["pSex"] = $talentInfo["sex"];
                    $data["pIdcard"] = $talentInfo["card_number"];
                    $data["talentArrange"] = $talentInfo["talent_arrange"];
                    $talentCondition = \app\common\api\TalentConditionApi::getOne($talentInfo["talent_condition"]);
                    $data["identifyCondition"] = $talentCondition["name"];
                    $data["certificateNo"] = $talentInfo["certificateNo"];
                    $data["certificateStartTime"] = $talentInfo["certificateGetTime"];
                    $data["qzgccrcActiveTime"] = $talentInfo["certificateExpireTime"];
                } else {
                    $oldTalentInfo = Db::table("un_talent_info")->where("id", $info["talentId"])->find();
                    if (!$oldTalentInfo || $oldTalentInfo["checkState"] != MainState::PASS || $oldTalentInfo["isEffect"] != 1 || $oldTalentInfo["isPublic"] != 6) {
                        throw new ValidateException("未查询到有效的人才数据（根据证件号码匹配），无法申报");
                    }
                    if (!strtotime($oldTalentInfo["qzgccrcActiveTime"]) || strtotime($oldTalentInfo["qzgccrcActiveTime"]) < time()) {
                        throw new ValidateException("您的人才证书已过期，请进行人才层次变更后再申报");
                    }
                    if ($this->user["type"] == 1 && $oldTalentInfo["talentArrange"] > 5) {
                        throw new ValidateException("子女择校政策只针对第一至五层次人才！");
                    }

                    if ($oldTalentInfo["provinceName"]) {
                        $area[] = $oldTalentInfo["provinceName"];
                    }
                    if ($oldTalentInfo["cityName"]) {
                        $area[] = $oldTalentInfo["cityName"];
                    }
                    if ($oldTalentInfo["countyName"]) {
                        $area[] = $oldTalentInfo["countyName"];
                    }

                    $data["id"] = getStringId();
                    $data["personId"] = $this->user["uid"];
                    $data["pName"] = $oldTalentInfo["name"];
                    $data["pSex"] = $oldTalentInfo["sex"];
                    $data["pIdcard"] = $oldTalentInfo["idCard"];
                    $data["talentArrange"] = $oldTalentInfo["talentArrange"];
                    $data["identifyCondition"] = $oldTalentInfo["identifyConditionName"];
                    $data["certificateNo"] = $oldTalentInfo["certificateNO"];
                    $data["certificateStartTime"] = $oldTalentInfo["certificateStartTime"];
                    $data["qzgccrcActiveTime"] = $oldTalentInfo["qzgccrcActiveTime"];
                }
                $data["nativePlace"] = implode("", $area);
                $data["checkState"] = -2;
                $data["createTime"] = date("Y-m-d H:i:s");
                $data["createUser"] = $this->user["uid"];
                EduModel::insert($data);

                $log["stateChange"] = "添加子女就学申报";
                $response->msg = "添加成功";
            }
            $log["id"] = getStringId();
            $log["active"] = 1;
            $log["state"] = -2;
            $log["step"] = 0;
            $log["type"] = ProjectState::EDUCATION;
            $log["mainId"] = $data["id"];
            $log["description"] = "";
            $log["createUser"] = "申报用户";
            $log["createTime"] = date("Y-m-d H:i:s");
            TalentLog::create($log);

            $response->code = 200;
            $response->obj = $data;
            return json($response);
        } catch (ValidateException $e) {
            $response->msg = $e->getMessage();
            return json($response);
        } catch (\think\Exception $e) {
            $response->msg = "发生预料外错误，请联系管理员处理，错误代码：" . $e->getCode();
            $logInfo = [
                "personId" => $this->user["uid"],
                "data" => $data,
                "controller" => $this->request->controller(),
                "action" => $this->request->action(),
                "errCode" => $e->getCode(),
                "errMsg" => $e->getMessage()
            ];
            Log::write($logInfo, "error");
            return json($response);
        }
    }

    /**
     * 提交表单
     */
    public function submitToCheck() {
        $response = new \stdClass();
        $response->code = 500;
        try {
            $id = $this->request["id"];
            $info = EducationApi::getInfoById($id);
            if (!$info) {
                throw new ValidateException("提交审核失败，请先填写基础信息");
            }
            if ($info["personId"] != $this->user["uid"]) {
                throw new ValidateException("没有对应的子女择校申报信息");
            }
            $batch = BatchApi::checkBatchValid(["type" => ProjectState::EDUCATION, "year" => $info["year"], "first_submit_time" => $info["firstSubmitTime"]], $this->user["type"]);
            if ($batch["code"] != 200) {
                throw new ValidateException($batch["msg"]);
            }
            validate(EducationSchoolValidator::class)->check($info);

            $where = [];
            $where[] = ["mainId", "=", $id];
            $where[] = ["type", "=", ProjectState::EDUCATION];
            $uploadedFileTypes = Db::table("new_talent_file")->where($where)->column("distinct typeId");

            $where = [];
            $where[] = ["project", "=", ProjectState::EDUCATION];
            $where[] = ["type", "=", $this->user["type"]];
            $where[] = ["must", "=", 1];
            $where[] = ["active", "=", 1];
            $where[] = ["delete", "=", 0];
            $where[] = ["id", "not in", $uploadedFileTypes];
            $unUploadfiletypes = Db::table("new_common_filetype")->where($where)->select()->toArray();
            if ($unUploadfiletypes) {
                $msg = "以下附件为必传：<br>";
                foreach ($unUploadfiletypes as $ft) {
                    $msg .= "<span style='color:red;'>*</span>" . $ft["name"] . "<br>";
                }
                throw new ValidateException($msg);
            }
            $data["id"] = $id;
            $data["checkState"] = $info["checkState"] == 2 ? 9 : 1;
            if (!$info["firstSubmitTime"]) {
                $data["firstSubmitTime"] = date("Y-m-d H:i:s");
            }
            $data["newSubmitTime"] = date("Y-m-d H:i:s");
            EduModel::update($data);

            $log["id"] = getStringId();
            $log["active"] = 1;
            $log["state"] = $data["checkState"];
            $log["step"] = 0;
            $log["stateChange"] = MainState::getStateDesc($data["checkState"]) . "->" . MainState::getStateDesc(MainState::NEED_CHECK);
            $log["type"] = ProjectState::EDUCATION;
            $log["mainId"] = $id;
            $log["description"] = "确认提交审核";
            $log["createUser"] = "申报用户";
            $log["createTime"] = date("Y-m-d H:i:s");
            TalentLog::create($log);

            $response->msg = "提交审核成功";
            $response->code = 200;
            $response->obj = 1;
            return json($response);
        } catch (ValidateException $e) {
            $response->msg = $e->getMessage();
            return json($response);
        } catch (\think\Exception $e) {
            $response->msg = "发生预料外错误，请联系管理员处理，错误代码：" . $e->getCode();
            $logInfo = [
                "personId" => $this->user["uid"],
                "data" => $data,
                "controller" => $this->request->controller(),
                "action" => $this->request->action(),
                "errCode" => $e->getCode(),
                "errMsg" => $e->getMessage()
            ];
            Log::write($logInfo, "error");
            return json($response);
        }
    }

    public function delete() {
        $id = $this->request->param("id");
        $info = EducationApi::getInfoById($id);
        if (!$info || $info["personId"] != $this->user["uid"]) {
            return json(["msg" => "操作失败"]);
        }
        $checkState = $info["checkState"];
        if ($checkState != MainState::SAVE) {
            return json(["msg" => "该申报已提交审核,无法删除"]);
        }
        EduModel::delete($id);

        $where = [["mainId", "=", $id], ["type", "=", ProjectState::EDUCATION]];
        $list = Db::table("new_talent_file")->where($where)->select()->toArray();
        foreach ($list as $key => $file) {
            if (!empty($file["url"])) {
                $filepath = "storage/" . $file["url"];
                if (file_exists($filepath)) {
                    @unlink($filepath);
                }
            }

            Db::table("new_talent_file")->delete($file["id"]);
        }
        return json(["msg" => "删除成功"]);
    }

    public function validateIsAdd() {
        $response = new \stdClass();
        $response->code = 500;
        $projectType = ProjectState::EDUCATION;
        $source = $this->user["type"];
        $batchResult = BatchApi::checkBatchValid(["type" => $projectType], $source);
        if ($batchResult["code"] != 200) {
            $response->msg = $batchResult["msg"];
            return json($response);
        }
        $batch = $batchResult["batch"];
        $where = [];
        $where[] = ["card_number", "=", $this->user["idCard"]];
        $where[] = ["checkState", "=", \app\common\api\TalentState::CERTIFICATED];
        $where[] = ["isEffect", "=", 1];
        $list = \app\enterprise\model\Talent::where($where)->order("talent_arrange asc")->select()->toArray();

        $whereOld = [];
        $whereOld[] = ["idCard", "=", $this->user["idCard"]];
        $whereOld[] = ["isPublic", "=", 6];
        $whereOld[] = ["checkState", "=", MainState::PASS];
        $whereOld[] = ["isEffect", "=", 1];
        $oldList = Db::table("un_talent_info")->where($whereOld)->order("talentArrange asc")->select()->toArray();
        if (!$list && !$oldList) {
            $response->msg = "未查询到有效的人才数据（根据证件号码匹配），无法申报";
            return json($response);
        }
        $count = $list ? count($list) : count($oldList);
        $expireTime = $list ? $list[0]["certificateExpireTime"] : $oldList[0]["qzgccrcActiveTime"];
        if ($count > 1) {
            //$response->msg = "根据证件号码查询到多条在库数据，无法申报，可联系相关单位取消重复人才资格";
            //return json($response);
        }
        if ($this->user["type"] == 1 && (!strtotime($expireTime) || strtotime($expireTime) < time())) {
            $response->msg = "您的人才证书已过期，请进行人才层次变更后再申报";
            return json($response);
        }
        $response->code = 200;
        $response->batch = $batch;
        return json($response);
    }

}
