<?php

namespace app\job;

use think\queue\Job;
use think\facade\Log;
use think\facade\Db;
use app\common\api\ChuanglanSmsApi;
use app\common\model\MessageRecord;
use app\common\api\TalentLogApi;
use app\common\api\TalentConditionApi;
use app\common\api\TalentState;
use app\enterprise\model\Talent as TalentModel;
use app\common\state\ProjectState;
use app\common\state\CommonConst;

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

    public function fire(Job $job, $data) {
        if ($this->deal($data)) {
            $job->delete();
            return true;
        }
        if ($job->attempts() >= 3) {
            $job->delete();
            return false;
        }
        $job->release(10); //10秒后重试
    }

    /**
     * 处理业务逻辑
     * @param type $data
     * @return bool
     */
    public function deal($data): bool {
        switch ($data["type"]) {
            case 1:
                //部门超时驳回
                $mainId = $data["id"];
                $where[] = ["ti.id", "=", $mainId];
                $where[] = ["ti.checkState", "=", TalentState::FST_VERIFY_PASS];
                $where[] = ["ti.pass_dept_check", "=", 0];
                $talent_info = TalentModel::alias("ti")
                                ->leftJoin("new_talent_condition tc", "tc.id=ti.talent_condition")
                                ->leftJoin("un_enterprise e", "e.id=ti.enterprise_id")
                                ->leftJoin("(select description,mainId,last_state,new_state,state,createTime from new_talent_checklog where md5(concat(createTime,mainId,`type`)) in (select md5(concat(max(createTime),mainId,`type`)) from `new_talent_checklog` where `type`=1 and `step` is null and active=1 and typeFileId is null group by mainId,`type`)) tl", "`tl`.`mainId`=ti.id")
                                ->where($where)->field("ti.*,tc.companyIds,tc.companyWithFileType,e.type as enterpriseType")->find();
                if ($talent_info && !in_array($talent_info["enterpriseType"], [CommonConst::ENTERPRISE_WJ, CommonConst::ENTERPRISE_GJ])) {
                    $weekDay = date("w"); //0周日，6周六
                    if ($weekDay == 6) {
                        $delay = 2 * 24 * 3600;
                        queue("app\job\Talent", ["type" => 1, "id" => $mainId], $delay);
                        return true;
                    }
                    if (!$weekDay || $weekDay == 0) {
                        $delay = 1 * 24 * 3600;
                        queue("app\job\Talent", ["type" => 1, "id" => $mainId], $delay);
                        return true;
                    }
                    $modify_files = array_filter(explode(",", $talent_info["modify_files"]));
                    $companyAndTypes = [];
                    $companyWithFileType = array_filter(explode(";", $talent_info["companyWithFileType"]));
                    foreach ($companyWithFileType as $c) {
                        list($companyId, $fileTypesStr) = array_filter(explode(":", $c));
                        $companyAndTypes[$companyId] = array_filter(explode(",", $fileTypesStr));
                    }

                    $companyIds = array_filter(explode(",", $talent_info["companyIds"]));
                    if ($companyIds) {
                        /* if ($talent_info["re_check_companys"]) {
                          $unpass_companyIds = array_filter(explode(",", $talent_info["re_check_companys"]));
                          } else {
                          //这边去除已经审核通过的单位，主要通过日志是否存在记录。
                          $pass_companyIds = TalentLogApi::getPassDepts($talent_info["id"]); //已经通过的单位
                          $unpass_companyIds = array_diff($companyIds, (array) $pass_companyIds); //排除已经通过的单位
                          } */
                        $pass_companyIds = TalentLogApi::getPassDepts($talent_info["id"]); //已经通过的单位
                        $re_check_companys = $talent_info["re_check_companys"] ? array_filter(explode(",", $talent_info["re_check_companys"])) : [];
                        $companyIds = \app\common\api\VerifyApi::getNewReCheckCompanyIds($re_check_companys, $companyIds, $pass_companyIds);
                        $unpass_companyIds = array_diff($companyIds, (array) $pass_companyIds); //排除已经通过的单位
                        if (!$unpass_companyIds) {
                            //没有未审部门
                            return true;
                        }
                        //开始驳回操作
                        $fst_dept_check_time = $talent_info["first_dept_check_time"];
                        $log_checkState = TalentState::FST_VERIFY_PASS; //当前状态不变
                        $checkState = TalentState::SCND_SUBMIT; //退回待初审
                        foreach ($unpass_companyIds as $companyId) {
                            $fileTypes = $companyAndTypes[$companyId];
                            $modify_files = array_unique((array_merge((array) $modify_files, (array) $fileTypes)));
                            $dept_log = TalentLogApi::getLogByCompanyId($talent_info["id"], $companyId, $fst_dept_check_time);
                            if ($dept_log) {
                                TalentLogApi::rewrite($dept_log["id"], [$log_checkState, $checkState], "审核超时，系统自动驳回", 1);
                            } else {
                                TalentLogApi::write(ProjectState::TALENT, $talent_info["id"], [$log_checkState, $checkState, 3], "审核超时，系统自动驳回", 1, null, null, $companyId); //补一条记录
                                sleep(1);
                            }
                        }
                        $log_checkState = TalentState::DEPT_VERIFY_REJECT;
                        $save["id"] = $talent_info["id"];
                        $save["modify_files"] = implode(",", $modify_files);
                        $save["checkState"] = $checkState;
                        $save["highProcess"] = $talent_info["highProcess"] > 3 ? $talent_info["highProcess"] : 3;
                        $save["first_dept_check_time"] = null;
                        $save["re_check_companys"] = null;
                        TalentModel::update($save);
                        TalentLogApi::write(1, $talent_info["id"], [$log_checkState, $checkState], "审核超时，系统自动驳回，部门审核结束", 1);
                    }
                    return true;
                }
                break;
            case 2:
                //超过批次提交时间审核失败
                $talentInfo = $data["talentInfo"];
                $projectType = ProjectState::TALENT; //项目类型
                $mainId = $talentInfo["id"]; //申报id
                $checkState = TalentState::FST_VERIFY_FAIL; //系统审核失败状态，初审不通过
                if ($talentInfo["checkState"] == TalentState::SCND_SAVE) {
                    $where = [];
                    $where[] = ["active", "=", 1];
                    $where[] = ["type", "=", $projectType];
                    $where[] = ["source", "=", $talentInfo["enterpriseType"]];
                    $where[] = ["batch", "=", $talentInfo["apply_year"]];
                    $whereRaw = sprintf("submitEndTime is not null and submitEndTime<>'' and submitEndTime < '%s'", date("Y-m-d H:i:s"));
                    $batch = \app\common\model\Batch::where($where)->whereRaw($whereRaw)->find();
                    if ($batch) {
                        $save["id"] = $mainId;
                        $save["checkState"] = $checkState;
                        TalentModel::update($save);
                        TalentLogApi::write($projectType, $mainId, $checkState, "超过该批次提交截止时间未提交审核，系统自动结束该申报", 1);
                    }
                    return true;
                }
                break;
            case 3:
                //撤销超时审核失败
                $talentInfo = $data["talentInfo"];
                $projectType = ProjectState::TALENT; //项目类型
                $mainId = $talentInfo["id"]; //申报id
                $checkState = TalentState::SCND_SAVE; //系统审核失败状态，初审不通过
                $last_log = TalentLogApi::getLastLog($mainId, $projectType, 0, ["active", "=", 1]);
                if ($talentInfo["checkState"] == TalentState::FST_VERIFY_FAIL && $last_log["state"] == TalentState::FST_VERIFY_FAIL && $last_log["createUser"] == "系统") {
                    $where = [];
                    $where[] = ["active", "=", 1];
                    $where[] = ["type", "=", $projectType];
                    $where[] = ["source", "=", $talentInfo["enterpriseType"]];
                    $where[] = ["batch", "=", $talentInfo["apply_year"]];
                    $whereRaw = sprintf("submitEndTime is null or submitEndTime<>'' or submitEndTime > '%s'", date("Y-m-d H:i:s"));
                    $batch = \app\common\model\Batch::where($where)->whereRaw($whereRaw)->find();
                    $extra_where[] = ["active", "=", 1];
                    $extra_where[] = ["createUser", "<>", "系统"];
                    $last_log = TalentLogApi::getLastLogEx($mainId, $projectType, 0, $extra_where);
                    if ($batch && $last_log) {
                        $save["id"] = $mainId;
                        $save["checkState"] = $checkState;
                        TalentModel::update($save);
                        TalentLogApi::write($projectType, $mainId, [$last_log["state"], $last_log["new_state"]], "该批次经人社局操作，已延长申报提交截止时间，现由人才办交办，对被自动审核失败的申报进行状态处理，恢复至初审驳回。该申报已处理。", 1);
                    }
                    return true;
                }
                break;
            case 4:
                //发放人才码后增加积分记录
                try {
                    $mainId = $data["id"];
                    $where = [];
                    $where[] = ["ti.id", "=", $mainId];
                    $where[] = ["ti.checkState", "=", TalentState::CERTIFICATED];
                    $talentInfo = TalentModel::alias("ti")->leftJoin("un_enterprise e", "e.id=ti.enterprise_id")->field("ti.*,e.type as enterpriseType")->where($where)->find();
                    $where = [];
                    $where[] = ["mainId", "=", $mainId];
                    $where[] = ["mainType", "=", "talent"];
                    $integralLog = Db::table("new_integral_log")->where($where)->find();
                    if ($talentInfo && !$integralLog) {
                        $level = $talentInfo["talent_arrange"];
                        $name = $talentInfo["name"]; //姓名
                        $cardType = $talentInfo["card_type"]; //身份证类型
                        $cardNumber = $talentInfo["card_number"]; //身份证
                        $type = $talentInfo["enterpriseType"]; //企业类型
                        $lastPoints = 0; //上次积分
                        $gainPoints = CommonConst::getLayerPointsByLayer($level); //增加积分
                        $desc = sprintf("经人才申报审核通过，认定为集成电路（%s）优秀人才，基础分变更为%d分。", CommonConst::getLayerNameByLayer($level), $gainPoints); //详情

                        /* 查询是否升级 */
                        $where = [];
                        $where[] = ["id", "<>", $mainId];
                        //$where[] = ["name", "=", $name];
                        $where[] = ["card_type", "=", $cardType];
                        $where[] = ["card_number", "=", $cardNumber];
                        $where[] = ["checkState", "=", TalentState::CERTIFICATED];
                        $talentBeforeInfo = TalentModel::where($where)->order("createTime desc")->find();
                        if ($talentBeforeInfo && $level < $talentBeforeInfo["talent_arrange"]) {
                            $beforeLevelName = CommonConst::getLayerNameByLayer($talentBeforeInfo["talent_arrange"]); //之前层次
                            $beforeLevelPoints = CommonConst::getLayerPointsByLayer($talentBeforeInfo["talent_arrange"]); //之前基础分
                            $nowLevelName = CommonConst::getLayerNameByLayer($level); //现在层次
                            $nowLevelPoints = CommonConst::getLayerPointsByLayer($level); //现在基础分
                            $gainPoints -= $beforeLevelPoints;
                            $desc = sprintf("人才层次晋升（%s->%s），基础分增加%d（%d->%d）分。", $beforeLevelName, $nowLevelName, $gainPoints, $beforeLevelPoints, $nowLevelPoints);
                        }

                        /* 查询最后一条积分日志 */
                        $where = [];
                        //$where[] = ["name", "=", $name];
                        $where[] = ["card_type", "=", $cardType];
                        $where[] = ["card_number", "=", $cardNumber];
                        $last_log = Db::table("new_integral_log")->where($where)->order("createTime desc")->find();
                        $lastPoints = $last_log["nowPoints"] ?: 0;

                        $log["id"] = getStringId();
                        $log["type"] = $type;
                        $log["mainType"] = "talent";
                        $log["mainId"] = $mainId;
                        $log["enterprise_id"] = $talentInfo["enterprise_id"];
                        $log["name"] = $name;
                        $log["card_type"] = $cardType;
                        $log["card_number"] = $cardNumber;
                        $log["talentLevel"] = $level;
                        $log["lastPoints"] = $lastPoints;
                        $log["gainPoints"] = $gainPoints;
                        $log["nowPoints"] = $lastPoints + $gainPoints;
                        $log["description"] = $desc;
                        $log["createTime"] = date("Y-m-d H:i:s");
                        Db::table("new_integral_log")->insert($log);
                        return true;
                    }
                } catch (\Exception $e) {
                    Log::write($e->getMessage(), "error");
                }
                break;
            case 5:
                //人才层次变更变更积分
                try {
                    $mainId = $data["id"];
                    $where = [];
                    $where[] = ["id", "=", $mainId];
                    $where[] = ["checkState", "=", \app\common\state\MainState::PASS];
                    $where[] = ["isPublic", "=", 6];
                    $where[] = ["createTime", ">=", "2022-10-01 00:00:00"];
                    $talentTypeChange = \app\enterprise\model\TalentTypeChange::where($where)->find();
                    if (strlen($talentTypeChange["talentId"]) == 19) {
                        $where = [];
                        $where[] = ["card_number", "=", $talentTypeChange["idCard"]];
                        $where[] = ["checkState", "=", TalentState::CERTIFICATED];
                        $talentInfo = TalentModel::where($where)->find();
                    } else {
                        $where = [];
                        $where[] = ["id", "=", $talentTypeChange["talentId"]];
                        $where[] = ["checkState", "=", TalentState::CERTIFICATED];
                        $talentInfo = TalentModel::where($where)->find();
                    }
                    $where = [];
                    $where[] = ["mainId", "=", $mainId];
                    $where[] = ["mainType", "=", "talentTypeChange"];
                    $integralLog = Db::table("new_integral_log")->where($where)->find();
                    if ($talentTypeChange && $talentInfo && !$integralLog) {
                        $newLevel = $talentTypeChange["newTalentArrange"];
                        $oldLevel = $talentTypeChange["oldTalentArrange"];
                        $name = $talentInfo["name"]; //姓名
                        $cardType = $talentInfo["card_type"]; //身份证类型
                        $cardNumber = $talentInfo["card_number"]; //身份证
                        $type = $talentTypeChange["type"]; //企业类型
                        $lastPoints = 0; //上次积分
                        //$gainPoints = CommonConst::getLayerPointsByLayer($level); //增加积分
                        //$desc = sprintf("经人才申报审核通过，认定为集成电路（%s）优秀人才，基础分变更为%d分。", CommonConst::getLayerNameByLayer($level), $gainPoints); //详情

                        /* 查询是否升级 */
                        if ($newLevel < $oldLevel) {
                            $beforeLevelName = CommonConst::getLayerNameByLayer($oldLevel); //之前层次
                            $beforeLevelPoints = CommonConst::getLayerPointsByLayer($oldLevel); //之前基础分
                            $nowLevelName = CommonConst::getLayerNameByLayer($newLevel); //现在层次
                            $nowLevelPoints = CommonConst::getLayerPointsByLayer($newLevel); //现在基础分
                            $gainPoints = $nowLevelPoints - $beforeLevelPoints;
                            $desc = sprintf("人才层次变更（%s->%s），基础分增加%d（%d->%d）分。", $beforeLevelName, $nowLevelName, $gainPoints, $beforeLevelPoints, $nowLevelPoints);


                            /* 查询最后一条积分日志 */
                            $where = [];
                            //$where[] = ["name", "=", $name];
                            $where[] = ["card_type", "=", $cardType];
                            $where[] = ["card_number", "=", $cardNumber];
                            $last_log = Db::table("new_integral_log")->where($where)->order("createTime desc")->find();
                            $lastPoints = $last_log["nowPoints"] ?: 0;

                            $log["id"] = getStringId();
                            $log["type"] = $type;
                            $log["mainType"] = "talentTypeChange";
                            $log["mainId"] = $mainId;
                            $log["enterprise_id"] = $talentInfo["enterprise_id"];
                            $log["name"] = $name;
                            $log["card_type"] = $cardType;
                            $log["card_number"] = $cardNumber;
                            $log["talentLevel"] = $newLevel;
                            $log["lastPoints"] = $lastPoints;
                            $log["gainPoints"] = $gainPoints;
                            $log["nowPoints"] = $lastPoints + $gainPoints;
                            $log["description"] = $desc;
                            $log["createTime"] = date("Y-m-d H:i:s");
                            Db::table("new_integral_log")->insert($log);
                            return true;
                        }
                    }
                } catch (\Exception $e) {
                    Log::write($e->getMessage(), "error");
                }
                break;
            case 6://卫健批量审核
                $condition = null;
                $upddata["pass_dept_check"] = 0;
                $talent_info = \app\common\api\VerifyApi::getTalentInfoById($data["id"]);
                if ($talent_info && $talent_info["checkState"] == TalentState::SCND_SUBMIT) {
                    if ($data["checkState"] == 3) {
                        //审核成功,并取消设置越过部门并审
                        $log_checkState = $checkState = TalentState::FST_VERIFY_PASS; //初审成功
                    } else {
//审核驳回并记录需要修改的字段和上传文件
                        if (in_array("talent_condition", $data["fields"])) {
                            $condition = TalentConditionApi::getOne($talent_info["talent_condition"]);
                            $data["files"] = array_merge($data["files"], (array) explode(",", $condition["bindFileTypes"]));
                        }
                        if ($talent_info["enterpriseType"] == CommonConst::ENTERPRISE_WJ) {
                            if ($data["checkState"] == 6) {
                                //驳回到分院
                                if ($talent_info["isGeneral"] == 1) {
                                    //总院不能驳回到分院,自动变更为退回总院
                                    $checkState = TalentState::SCND_SAVE;
                                } else {
                                    $checkState = TalentState::FST_SAVE;
                                }
                            } else {
                                if ($talent_info["isGeneral"] == 1) {
                                    $checkState = TalentState::SCND_SAVE; //退回材料编辑状态
                                } else {
                                    if (\app\common\api\Nhc::hasGeneralHospital($talent_info["medicalCommunityId"])) {
                                        $checkState = TalentState::FST_SUBMIT;
                                    } else {
                                        $checkState = TalentState::FST_SAVE;
                                    }
                                }
                            }
                        } else {
                            $checkState = TalentState::SCND_SAVE; //退回材料编辑状态
                        }
                        $log_checkState = TalentState::FST_VERIFY_REJECT; //日志记录拒绝状态
                    }

                    $nowProcess = 3;
                    if ($checkState == TalentState::FST_VERIFY_PASS) {
                        $upddata["highProcess"] = $nowProcess > $talent_info["highProcess"] ? $nowProcess : $talent_info["highProcess"];
                    }
                    $userIds = [];
                    if ($log_checkState == TalentState::FST_VERIFY_PASS) {
                        $upddata["first_dept_check_time"] = date("Y-m-d H:i:s");
                        $condition = $condition ? $condition : TalentConditionApi::getOne($talent_info["talent_condition"]);
                        $companyIds = array_filter(explode(",", $condition["companyIds"])); //该条件下需要审核的所有单位
                        if ($talent_info["re_check_companys"]) {
                            $unpass_companyIds = array_filter(explode(",", $talent_info["re_check_companys"]));
                        } else {
//这边去除已经审核通过的单位，主要通过日志是否存在记录。
                            $pass_companyIds = TalentLogApi::getPassDepts($data["id"]); //已经通过的单位
                            $unpass_companyIds = array_diff($companyIds, (array) $pass_companyIds); //排除已经通过的单位
                            if (!$unpass_companyIds) {
                                $data["pass_dept_check"] = 1; //部门已经全部审核过了，跳过部门审核
                            }
                        }
                        if ($unpass_companyIds) {
                            sort($unpass_companyIds);
                            $delay = 9 * 24 * 3600; //9天的秒数
                            queue("app\job\Talent", ["type" => 1, "id" => $data["id"]], $delay); //加入部门审核超期处理队列，延迟7天执行
                            TalentLogApi::writeDeptLogs($data["id"], $unpass_companyIds, TalentState::FST_VERIFY_PASS);

                            /*
                              //初审通过发送短信通知并审部门
                              $codes = ["talentInfo_depCheck"];
                              $menuIds = MenuApi::getMenuIdsByCodes($codes);

                              $where = [];
                              $where[] = ["menuid", "in", $menuIds];
                              $roleIds = SysRelation::where($where)->group("roleid")->having("count(*)=" . count($codes))->column("roleid");

                              $where = [];
                              $where[] = ["status", "=", 1];
                              //$where[] = ["type", "=", $this->user["type"]];
                              $where[] = ["companyId", "in", $unpass_companyIds];
                              $where[] = ["roleid", "<>", 1];
                              $regstr = ",(" . implode("|", $roleIds) . "),";
                              $whereRaw = "concat(',',roleid,',') REGEXP '$regstr'";
                              $userIds = User::where($where)->whereRaw($whereRaw)->column("id");
                             */
                        }
                    }

                    $log = TalentLogApi::getLastLog($data["id"], 1);
                    if (!$log && !$talent_info["oldId"])
                        return json(["msg" => "日志数据异常,保存失败"]);
                    if ($log["active"] === 0) {
                        TalentLogApi::rewrite($log["id"], [$log_checkState, $checkState], $data["checkMsg"], 1, $data["user"]);
                    } else {
                        TalentLogApi::write(1, $data["id"], [$log_checkState, $checkState], $data["checkMsg"], 1, null, null, null, $data["user"]);
                    }

                    $upddata["id"] = $talent_info["id"];
                    $upddata["modify_files"] = $data["files"] ? implode(",", $data["files"]) : "";
                    $upddata["modify_fields"] = $data["fields"] ? implode(",", $data["fields"]) : "";
                    $upddata["checkState"] = $checkState;
                    TalentModel::update($upddata);
                    return true;
                }
                break;
        }
        return false;
    }

}
