<?php

namespace app\enterprise\controller;

use app\enterprise\common\EnterpriseController;
use app\common\model\TalentQuit as TqModel;
use app\common\api\TalentLogApi;
use app\common\state\ProjectState;
use app\common\model\TalentLog;
use think\facade\Db;

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

    public function index() {
        return view("", ["type" => $this->user["type"]]);
    }

    public function list() {
        $type = $this->user["type"];
        $params = \StrUtil::batchGetRequestDecodeParam($this->request);
        $order = $params["order"] ?: "desc";
        $offset = $params["offset"] ?: 0;
        $limit = $params["limit"] ?: 10;
        $where = [];
        $where[] = ["enterpriseId", "=", $this->user["uid"]];
        $where[] = ["delete", "=", 0];
        if ($params["talentName"]) {
            $where[] = ["talentName", "like", "%" . $params["talentName"] . "%"];
        }
        if ($params["idCard"]) {
            $where[] = ["idCard", "like", "%" . $params["idCard"] . "%"];
        }
        if ($params["enterpriseName"]) {
            $where[] = ["enterpriseName", "like", "%" . $params["enterpriseName"] . "%"];
        }
        if ($params["talentArrange"]) {
            $where[] = ["talentArrange", "=", $params["talentArrange"]];
        }
        if ($params["checkState"]) {
            $where[] = ["checkState", "=", $params["checkState"]];
        }
        $count = TqModel::where($where)->count();
        $list = TqModel::where($where)->limit($offset, $limit)->order("createTime " . $order)->select()->toArray();
        $talentArrangeMap = \app\common\api\DictApi::selectByParentCode("talent_arrange");
        foreach ($list as &$item) {
            $item["talentArrangeName"] = $talentArrangeMap[$item["talentArrange"]];
        }unset($item);

        return json(["total" => $count, "rows" => $list]);
    }

    public function apply() {
        $request = $this->request;
        $id = isset($request["id"]) ? $request["id"] : 0;
        $info = TqModel::where("id", $id)->find();
        if (strlen($info["talentId"]) == 19) {
            $newTalentInfo = $this->getTalentInfoByIdCard($info["idCard"]);
            $info["talentId"] = $newTalentInfo["id"];
        }
        if ($this->request->isPost()) {
            $response = new \stdClass();
            $response->code = 500;
            $data = $request->param();
            $check = $this->dataCheck($data);
            if ($check->code == 500) {
                return $check;
            }
            $talentInfo = \app\common\api\VerifyApi::getTalentInfoById($request["talentId"]);
            if ($data["id"]) {
                unset($data["year"]);
                $data["updateUser"] = $this->user["uid"];
                $data["updateTime"] = date("Y-m-d H:i:s");
                TqModel::update($data);
                $response->code = 200;
                $response->msg = "修改成功";
                return $response;
            } else {
                $data["id"] = getStringId();
                $data["identifyGetTime"] = $talentInfo["identifyGetTime"];
                $data["talentType"] = $talentInfo["enterpriseTag"];
                $data["checkState"] = -1;
                $data["createUser"] = $this->user["uid"];
                $data["createTime"] = date("Y-m-d H:i:s");
                $data["post"] = $talentInfo["position"];
                TqModel::create($data);

                $user = $this->user;
                $log["id"] = getStringId();
                $log["active"] = 1;
                $log["state"] = 1;
                $log["step"] = 0;
                $log["stateChange"] = "";
                $log["type"] = ProjectState::QUIT;
                $log["mainId"] = $data["id"];
                $log["description"] = "添加离职申报";
                $log["createUser"] = $user ? sprintf("%s(%s)", $user["account"], $user["companyName"] ?: $user["rolename"]) : "系统";
                $log["createTime"] = date("Y-m-d H:i:s");
                TalentLog::create($log);
                $response->code = 200;
                $response->msg = "添加成功";
                $response->obj = $data;
                return $response;
            }
        }
        $year = $info["year"] ?: $request["year"];
        return view("", ["type" => $this->user["type"], "year" => $year, "row" => $info]);
    }

    public function view() {
        $id = $this->request["id"];
        $info = TqModel::where("id", $id)->find();
        if (strlen($info["talentId"]) == 19) {
            $newTalentInfo = $this->getTalentInfoByIdCard($info["idCard"]);
            $info["talentId"] = $newTalentInfo["id"];
        }
        return view("", ["row" => $info]);
    }

    public function submitToCheck() {
        $response = new \stdClass();
        $response->code = 500;
        $id = $this->request["id"];
        $info = TqModel::where("id", $id)->find();
        if (!$info) {
            $response->msg = "提交审核失败，请先填写基础信息";
            return $response;
        }
        if ($info["checkState"] != -1 && $info["checkState"] != 2) {
            $response->msg = "不能重复提交审核";
            return $response;
        }
        $where = [];
        $where[] = ["type", "=", $info["type"]];
        $where[] = ["project", "=", ProjectState::QUIT];
        $where[] = ["active", "=", 1];
        $filetypes = Db::table("new_common_filetype")->where($where)->order("sn asc")->select()->toArray();
        $sb = [];
        $sb[] = "以下为必传附件：";
        foreach ($filetypes as $filetype) {
            if ($filetype["must"] == 1) {
                $where = [];
                $where[] = ["mainId", "=", $id];
                $where[] = ["typeId", "=", $filetype["id"]];
                $count = Db::table("new_talent_common_file")->where($where)->count();
                if ($count == 0) {
                    $sb[] = $filetype["name"] . ";";
                }
            }
        }
        if (count($sb) > 1) {
            $response->msg = implode("<br>", $sb);
            return $response;
        }
        $data["id"] = $id;
        $data["checkState"] = $info["checkState"] == 2 ? 9 : 1;
        TqModel::update($data);
        $user = $this->user;
        $log["id"] = getStringId();
        $log["active"] = 1;
        $log["state"] = 1;
        $log["step"] = 0;
        $log["stateChange"] = "<span class='label'>待提交</span>-><span class='label label-success'>待审核</span>";
        $log["type"] = ProjectState::QUIT;
        $log["mainId"] = $id;
        $log["description"] = "确认提交审核";
        $log["createUser"] = $user ? sprintf("%s(%s)", $user["account"], $user["companyName"] ?: $user["rolename"]) : "系统";
        $log["createTime"] = date("Y-m-d H:i:s");
        TalentLog::create($log);
        $response->code = 200;
        $response->msg = "提交审核成功";
        $response->obj = 1;
        return $response;
    }

    public function delete() {
        $response = new \stdClass();
        $response->code = 500;
        $info = TqModel::where("id", $this->request["id"])->find();
        if ($info["checkState"] != -1) {
            $response->msg = "已提交审核，无法删除";
            return $response;
        }
        $data["id"] = $info["id"];
        $data["delete"] = 1;
        $data["deleteTime"] = date("Y-m-d H:i:s");
        TqModel::update($data);
        $response->code = 200;
        $response->msg = "删除成功";
        return $response;
    }

    public function findByIdCard() {
        $responseObj = new \stdClass();
        $responseObj->code = 500;
        $idCard = $this->request["idCard"];
        $where = [];
        $where[] = ["idCard", "=", $idCard];
        $where[] = ["checkState", "not in", [3, -2]];
        $where[] = ["delete", "=", 0];
        $count = TqModel::where($where)->count();
        if ($count > 0) {
            $responseObj->msg = "你输入的身份证正在变更申请";
            return $responseObj;
        }
        unset($where);
        $where[] = ["idCard", "=", $idCard];
        $where[] = ["checkState", "=", 3];
        $where[] = ["delete", "=", 0];
        $talentQuit = TqModel::where($where)->order("createTime desc")->find();
        if (!$talentQuit) {
            $responseObj->msg = "你输入的身份证未在离职名单";
            return $responseObj;
        }
        $ti = \app\common\api\VerifyApi::getTalentInfoById($talentQuit["talentId"]);
        if (!$ti) {
            $ti = $this->getTalentInfoByIdCard($idCard, 2);
            $talentQuit["talentId"] = $ti["id"];
        }
        if (!$ti) {
            $responseObj->msg = "未匹配到人才数据";
            return $responseObj;
        }
        if ($ti["active"] == 1) {
            $responseObj->msg = "您所申报的人才处于在职状态，请先办理离职后再做申请！";
            return $responseObj;
        }
        if ($ti["isEffect"] == 4) {
            $responseObj->msg = "您所申报的人才已失效，无法申请变更！";
            return $responseObj;
        }
        $talentQuit["talentType"] = $ti["enterpriseTag"];
        $talentQuit["phone"] = $ti["phone"];
        $return = ["info" => $talentQuit, "user" => $this->user];
        $responseObj->obj = $return;
        $responseObj->code = 200;
        return $responseObj;
    }

    private function getTalentInfoByIdCard($idCard, $active = null) {
        //$where[] = ["enterprise_id", "=", $this->user["uid"]];
        $where[] = ["card_number", "=", $idCard];
        $where[] = ["checkState", "=", \app\common\api\TalentState::CERTIFICATED];
        $where[] = ["delete", "=", 0];
        if ($active) {
            $where[] = ["active", "=", $active];
        }
        $ti = \app\enterprise\model\Talent::where($where)->order("talent_arrange asc")->find();
        return $ti;
    }

    private function dataCheck($data) {
        $response = new \stdClass();
        $response->code = 500;
        if (\StrUtil::isEmpOrNull($data["starttime"])) {
            $response->msg = "合同开始时间不能为空";
            return $response;
        }
        if (\StrUtil::isEmpOrNull($data["endtime"])) {
            $response->msg = "合同结束时间不能为空";
            return $response;
        }
        if (\StrUtil::isEmpOrNull($data["phone"])) {
            $response->msg = "手机号码不能为空";
            return $response;
        }
        if (\StrUtil::isEmpOrNull($data["quitTime"])) {
            $response->msg = "离职时间不能为空";
            return $response;
        }
        if ($data["type"] == 1) {
            if (\StrUtil::isEmpOrNull($data["quitReason"])) {
                $response->msg = "离职原因不能为空";
                return $response;
            }
        }
        $response->code = 200;
        return $response;
    }

}
