<?php

namespace app\enterprise\controller;

use app\enterprise\common\EnterpriseController;
use app\enterprise\api\TalentApi;
use app\enterprise\model\Talent as TalentModel;
use think\facade\Db;
use app\common\api\TalentLogApi;
use app\common\api\TalentState;

// 0正在填写 1保存未提交 2已提交未审核 3已审核 4驳回 5保存补充材料未提交 6提交补充材料进入初审 7初审通过 8初审驳回 9部门审核通过 10部门审核驳回 11复核通过 12复核驳回 13复核失败

/**
 * Description of Talent
 *
 * @author sgq
 */
class Talent extends EnterpriseController {

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

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

    public function add() {
        $request = $this->request;
        $param = $request->param();
        $id = isset($param["id"]) ? $param["id"] : 0;
        $info = self::chkIsOwner($id, $this->user["uid"]);
        if ($info && in_array($info["checkState"], [TalentState::BASE_VERIFY_PASS, TalentState::SCND_SAVE])) {
            return $this->second($request);
            exit();
        }
        if ($request->isPost()) {
            if ($id) {
                $data["id"] = $id;
                if (!$info) {
                    $res = ["msg" => "没有对应的人才认定申报信息"];
                    echo sprintf("<script>parent.TalentInfoInfoDlg.infoCallback(%s);</script>", json_encode($res));
                    exit;
                }
                if ($info["checkState"] == TalentState::REVERIFY_FAIL) {
                    $res = ["msg" => "审核失败，不能再修改"];
                    echo sprintf("<script>parent.TalentInfoInfoDlg.infoCallback(%s);</script>", json_encode($res));
                    exit;
                }
                if (!in_array($info["checkState"], [TalentState::FST_SAVE, TalentState::BASE_VERIFY_PASS, TalentState::SCND_SAVE])) {
                    $res = ["msg" => "审核中，不能修改"];
                    echo sprintf("<script>parent.TalentInfoInfoDlg.infoCallback(%s);</script>", json_encode($res));
                    exit;
                }
            }

            $data["enterprise_id"] = $this->user["uid"];
            $data["talent_type"] = $param["talent_type"];
            $data["tax_insurance_month"] = $param["tax_insurance_month"];
            $data["labor_contract_rangetime"] = $param["labor_contract_rangetime"];
            $data["name"] = $param["name"];
            $data["card_type"] = $param["card_type"];
            $data["card_number"] = $param["card_number"];
            $data["sex"] = $param["sex"];
            $data["birthday"] = $param["birthday"];
            $data["nationality"] = $param["nationality"];
            $data["province"] = $param["province"];
            $data["city"] = $param["city"];
            $data["county"] = $param["county"];
            $data["nation"] = $param["nation"];
            $data["politics"] = $param["politics"];
            if ($request->file()) {
                $headimg = $request->file("photo");
                if ($info) {
                    $old_head_url = "storage/" . $info["headimgurl"];
                    if (file_exists($old_head_url))
                        unlink($old_head_url);
                }
                $upload = new \app\common\api\UploadApi();
                $result = $upload->uploadOne($headimg, "image", "talent/photo");
                $data["headimgurl"] = $result->filepath;
            }
            if ($id > 0) {
                TalentModel::update($data);
            } else {
                $data["checkState"] = TalentState::FST_SAVE;
                $id = TalentModel::insertGetId($data);
                TalentLogApi::write(1, $id, TalentState::FST_SAVE, "添加人才认定申报", 1);
            }
            if ($id) {
                $res = ["code" => 200, "msg" => "保存成功", "obj" => ["id" => $id, "checkState" => TalentState::FST_SAVE]];
                echo sprintf("<script>parent.TalentInfoInfoDlg.infoCallback(%s);</script>", json_encode($res));
            } else {
                $res = ["msg" => "保存失败"];
                echo sprintf("<script>parent.TalentInfoInfoDlg.infoCallback(%s);</script>", json_encode($res));
            }
            exit();
        }
        $checkState = $info["checkState"] ?: 0;
        $enterprise_info = \app\common\model\Enterprise::find($this->user["uid"]);

        $info["enterprise"] = $enterprise_info;
        $info["talent_type_list"] = \app\common\api\DictApi::findChildDictByCode("talent_type");
        return view("first", ["year" => date("Y"), "checkState" => $checkState, "row" => $info]);
    }

    private function second(\think\Request $request) {
        $params = $request->param();
        $id = $params["id"];
        if ($request->isPost()) {
            $batch = \app\common\api\BatchApi::getValidBatch(1, $this->user["type"]);
            if (!$batch) {
                $res = ["msg" => "不在人才认定申报申请时间内"];
                echo sprintf("<script>parent.TalentInfoInfoDlg.infoCallback(%s);</script>", json_encode($res));
                exit;
            }

            $field_dict = \app\common\api\DictApi::getTalentFields(2);
            //可以用匹配键的方式，可以少很多代码。。先这样吧。
            $all_valid_keys = ["applay_year", "fst_work_time", "import_way", "cur_entry_time", "position",
                "source", "source_batch", "fujian_highcert_pubtime", "fujian_highcert_exptime", "quanzhou_highcert_pubtime", "quanzhou_highcert_exptime", "source_city", "source_county",
                "talent_arrange", "talent_condition", "highest_degree", "graduate_school", "major", "professional", "bank", "bank_number", "bank_branch_name", "bank_account",
                "study_abroad", "abroad_school", "abroad_major", "phone", "email"];
            foreach ($all_valid_keys as $key) {
                $data[$key] = trim($params[$key]);
                if (strpos($key, "time") !== false && strtotime($params[$key]) === false) {
                    unset($data[$key]); //时间格式的验证不通过就清掉，下面判断是否为空如果赫然在列就不能通过
                }
            }

            $no_empty = ["talent_arrange", "talent_condition", "highest_degree", "graduate_school", "major", "professional", "bank", "bank_number", "bank_branch_name",
                "bank_account", "study_abroad", "phone", "email", "import_way", "fst_work_time", "cur_entry_time", "cur_entry_time", "position", "source"];

            if ($data["study_abroad"] == 1) {
                $no_empty[] = "abroad_school";
                $no_empty[] = "abroad_major";
            }
            if (in_array($data["source"], [1, 3])) {
                $no_empty[] = "source_batch";
                $no_empty[] = "fujian_highcert_pubtime";
                $no_empty[] = "fujian_highcert_exptime";
                if ($data["source"] == 3) {
                    $no_empty[] = "source_city";
                }
            }
            if (in_array($data["source"], [2, 4])) {
                $no_empty[] = "source_batch";
                $no_empty[] = "quanzhou_highcert_pubtime";
                $no_empty[] = "quanzhou_highcert_exptime";
                if ($data["source"] == 4) {
                    $no_empty[] = "source_county";
                }
            }
            $no_empty = array_filter($no_empty);
            $return = [];
            foreach ($no_empty as $key) {
                if (!$data[$key]) {
                    $return[] = sprintf("请填写“%s”", $field_dict[$key]);
                }
            }
            if (count($return) > 0) {
                $res = ["msg" => implode("<br>", $return)];
                echo sprintf("<script>parent.TalentInfoInfoDlg.infoCallback(%s);</script>", json_encode($res));
                exit;
            }
            if (!preg_match("/^(13|14|15|17|18|19)[\d]{9}$/", $data["phone"])) {
                $res = ["msg" => "手机号码格式错误"];
                echo sprintf("<script>parent.TalentInfoInfoDlg.infoCallback(%s);</script>", json_encode($res));
                exit;
            }
            if (!filter_var($data["email"], FILTER_VALIDATE_EMAIL)) {
                $res = ["msg" => "电子邮箱格式错误"];
                echo sprintf("<script>parent.TalentInfoInfoDlg.infoCallback(%s);</script>", json_encode($res));
                exit;
            }

            if (!in_array($data["talent_arrange"], [1, 2, 3, 4, 5, 6, 7])) {
                $res = ["msg" => "人才层次只能在预设范围内选择"];
                echo sprintf("<script>parent.TalentInfoInfoDlg.infoCallback(%s);</script>", json_encode($res));
                exit;
            }
            if (!in_array($data["source"], [1, 2, 3, 4, 5])) {
                $res = ["msg" => "来源只能在预设范围内选择"];
                echo sprintf("<script>parent.TalentInfoInfoDlg.infoCallback(%s);</script>", json_encode($res));
                exit;
            }

            $where = [];
            $where[] = ["step", "=", 2];
            $where[] = ["project", "=", 1];
            $where[] = ["type", "=", $this->user["type"]];
            $where[] = ["must", "=", 1];
            $filetypes = Db::table("new_common_filetype")->where($where)->select()->toArray();

            $ft_ids = array_column($filetypes, "id");
            $whr = [];
            $whr[] = ["typeId", "in", $ft_ids];
            $whr[] = ["mainId", "=", $id];
            $upload_type_counts = Db::table("new_talent_file")->where($whr)->distinct(true)->field("typeId")->count();
            if ($upload_type_counts != count($ft_ids)) {
                $res = ["msg" => "请留意附件上传栏中带*号的内容均为必传项，请上传完整再提交审核"];
                echo sprintf("<script>parent.TalentInfoInfoDlg.infoCallback(%s);</script>", json_encode($res));
                exit;
            }
            $data["apply_year"] = $batch["batch"];
            $data["id"] = $id;
            $data["checkState"] = TalentState::SCND_SAVE;
            if (TalentModel::update($data)) {
                $res = ["code" => 200, "msg" => "保存成功", "obj" => ["id" => $id, "checkState" => TalentState::SCND_SAVE]];
                echo sprintf("<script>parent.TalentInfoInfoDlg.infoCallback(%s);</script>", json_encode($res));
            } else {
                $res = ["code" => 500, "msg" => "保存失败"];
                echo sprintf("<script>parent.TalentInfoInfoDlg.infoCallback(%s);</script>", json_encode($res));
            }
        }
        $info = \app\common\api\VerifyApi::getTalentInfoById($id);
        $enterprise_info = \app\common\model\Enterprise::find($this->user["uid"]);
        $info["enterprise"] = $enterprise_info;
        $batch = \app\common\api\BatchApi::getValidBatch(1, $enterprise_info["type"]);
        return view("second", ["year" => $batch["batch"], "row" => $info]);
    }

    public function view() {
        $id = $this->request->param("id");
        $info = \app\common\api\VerifyApi::getTalentInfoById($id);
        return view("", ["row" => $info]);
    }

    // 1保存未提交 2已提交未审核 3已审核 4驳回 5保存补充材料未提交 6提交补充材料进入初审 7初审通过 8初审驳回 9部门审核通过 10部门审核驳回 11复核通过 12复核驳回 13复核失败
    public function submit() {
        $id = $this->request->param("id");
        if (!$info = self::chkIsOwner($id, $this->user["uid"]))
            return json(["msg" => "没有对应的人才认定申报信息"]);
        $checkState = $info["checkState"];
        if ($checkState == TalentState::BASE_VERIFY_PASS || $checkState == 0) {
            return json(["msg" => '请先保存资料并上传相应附件后再点击提交审核']);
        } else if ($checkState == TalentState::FST_SAVE) {
            $filed_dict = \app\common\api\DictApi::getTalentFields(1);
            //初次提交材料
            $change_state = TalentState::FST_SUBMIT; //等待审核
            if (!$info["headimgurl"])
                return json(["msg" => "请上传头像"]);
            $no_empty = ["talent_type", "name", "card_type", "card_number", "sex", "birthday", "nationality", "province", "city", "nation", "politics"];

            if (in_array($info["talent_type"], [1, 2]))
                $no_empty[] = "tax_insurance_month";
            if ($info["talent_type"] == 3)
                $no_empty[] = "labor_contract_rangetime";
            $return = [];
            foreach ($no_empty as $key) {
                if (!$info[$key]) {
                    $return[] = sprintf("请填写“%s”", $filed_dict[$key]);
                }
            }
            if (count($return) > 0)
                return json(["msg" => implode("<br>", $return)]);
            $where = [];
            $where[] = ["step", "=", 1];
            $where[] = ["project", "=", 1];
            $where[] = ["type", "=", $this->user["type"]];
            $where[] = ["must", "=", 1];
            $filetypes = Db::table("new_common_filetype")->where($where)->select()->toArray();

            $ft_ids = array_column($filetypes, "id");
            $whr = [];
            $whr[] = ["typeId", "in", $ft_ids];
            $whr[] = ["mainId", "=", $info["id"]];
            $upload_type_counts = Db::table("new_talent_file")->where($whr)->distinct(true)->field("typeId")->count();
            if ($upload_type_counts != count($ft_ids))
                return json(["msg" => "请留意附件上传栏中带*号的内容均为必传项，请上传完整再提交审核"]);

            $data["id"] = $id;
            $data["checkState"] = $change_state;
            $data["active"] = 1;
            TalentModel::update($data);
            TalentLogApi::write(1, $id, $change_state, "提交基础判定材料待审核", 1);
            return json(["code" => 200, "msg" => "提交成功"]);
        } else if ($checkState == TalentState::SCND_SAVE) {
            $change_state = TalentState::SCND_SUBMIT; //等待初审
            $data["id"] = $id;
            $data["checkState"] = $change_state;
            $data["active"] = 1;
            TalentModel::update($data);
            TalentLogApi::write(1, $id, $change_state, "确认提交审核", 1);
            return json(["code" => 200, "msg" => "提交成功"]);
        } else if ($checkState == TalentState::REVERIFY_FAIL) {
            return ["msg" => "审核失败，不能再提交审核"];
        }
        return json(["msg" => "已提交审核，请耐心等待"]);
    }

    public function delete() {
        $id = $this->request->param("talentInfoId");
        $info = Talent::chkIsOwner($id, $this->user["uid"]);
        if (!$info) {
            return json(["msg" => "操作失败"]);
        }
        $checkState = $info["checkState"];
        if (in_array($checkState, [0, 1])) {
            $log = TalentLogApi::getLastLog($id, 1);
            if ($log["state"] > 1) {
                //有提交审核记录
                return json(["msg" => "操作失败"]);
            }
        }
        $data["id"] = $id;
        $data["delete"] = 1;
        TalentModel::update($data);
        return json(["msg" => "删除成功"]);
    }

    static private function chkIsOwner($id, $uid) {
        $where[] = ["id", "=", $id];
        $where[] = ["enterprise_id", "=", $uid];
        $info = TalentModel::where($where)->findOrEmpty()->toArray();
        return $info;
    }

}
