<?php

namespace app\admin\controller;

use app\admin\common\AdminController;
use app\common\state\MainState;
use think\facade\Db;
use app\enterprise\model\TalentTypeChange as ttcModel;
use app\common\api\TalentConditionApi;
use app\common\api\DictApi;
use app\common\state\CommonConst;
use app\common\state\ProjectState;
use app\common\api\TalentLogApi;
use app\common\model\TalentChecklog;
use app\common\api\TalentTypeChangeApi as ttcApi;

class TalentTypeChange extends AdminController {

    public function gotoIndex() {
        $tpl = null;
        $process = $this->request->param('process');
        $assigns = [];
        $assigns["enterprises"] = \app\common\api\EnterpriseApi::getSimpleList();
        switch ($process) {
            case -1:
                $tpl = "dept_before"; //移除部门初审
                break;
            case 1:
                $tpl = "fst_verify"; //初审
                break;
            case 2:
                $tpl = "dept_verify"; //部门审核
                break;
            case 3:
                $tpl = "re_verify"; //复审
                break;
            case 4:
                $tpl = "prepare"; //预备库
                $msgBody = [];
                switch ($this->user["type"]) {
                    case 1:
                        $msgBody["typeName"] = "晋江市现代产业体系人才层次变更";
                        $msgBody["address"] = "聚才网/人才晋江微信公众号";
                        $msgBody["dep"] = "中共晋江市委人才办、晋江市纪委监委驻市人力资源和社会保障局纪检监察组或晋江市公共就业和人才服务中心";
                        $msgBody["phone"] = "0595-85633128";
                        $msgBody["email"] = "jjrc85661234@163.com";
                        break;
                    case 2:
                        $msgBody["typeName"] = "晋江市集成电路产业优秀人才层次变更";
                        $msgBody["address"] = "福建（晋江）集成电路产业园官方网站及微信公众号";
                        $msgBody["dep"] = "集成电路产业园区";
                        $msgBody["phone"] = "0595-82250007、0595-82250001";
                        $msgBody["email"] = "jjjcdr@163.com";
                        break;
                }
                $assigns["message"] = $msgBody;
                break;
            case 5:
                $tpl = "library"; //正式库
                break;
        }

        return view($tpl, $assigns);
    }

    public function list() {
        $params = $this->request->param();
        $offset = $params["offset"] ?: 0;
        $order = $params["order"] ?: "desc";
        $limit = $params["limit"] ?: 10;
        $process = $params["process"];
        $where = [];
        $this->setTalentTypeChange($where, $params);
        $this->setTypeChangeCheckStateCondition($where, $params, $process);
        //$whereRaw = "length(talentId) <> 19";
        $where[] = ["delete", "=", 0];
        switch ($process) {
            case -1:
                $where[] = ["createTime", ">=", "2022-10-01 00:00:00"];
                $where[] = ["type", "=", $this->user["type"]];
                $company = \app\common\api\CompanyApi::getOne($this->user["companyId"]);
                $where[] = ["beforeCheckCompany", "EXP", Db::raw("is not null")];
                if ($this->user["code"] != $company["code"]) {
                    $where[] = ["beforeCheckCompany", "=", $company["id"]];
                }
                break;
            case 1:
                $where[] = ["createTime", ">=", "2022-10-01 00:00:00"];
                $where[] = ["type", "=", $this->user["type"]];
                $where[] = ["checkState", "not in", [3, 5]];
                break;
            case 2:
                //$where[] = ["ttc.type", "=", $this->user["type"]];
                $where[] = ["ttc.createTime", ">=", "2022-10-01 00:00:00"];
                if (ttcApi::chkUserInSuperDeptUsers()) {
                    $where[] = ["ttc.type", "=", $this->user["type"]];
                } else {
                    $companyId = $this->user["companyId"];
                    $where[] = ["td.companyId", "=", $companyId];
                }
                $where[] = ["td.type", "=", ProjectState::LEVELCHANGE];
                switch ($params["checkState"]) {
                    case 1:
                    case 2:
                    case 3:
                        $where[] = ["td.state", "=", $params["checkState"]];
                        break;
                    case 5:
                        $where[] = ["ttc.highProcess", ">=", 2];
                        $where[] = ["td.state", "=", 1];
                        break;
                }
                $count = ttcModel::alias("ttc")->leftJoin("un_talent_depcheckstate td", "td.mainId=ttc.id")->where($where)->count();
                $list = ttcModel::alias("ttc")->field("ttc.*,td.companyId,td.state as depState")->leftJoin("un_talent_depcheckstate td", "td.mainId=ttc.id")->where($where)->limit($offset, $limit)->order("ttc.createTime {$order}")->select()->toArray();
                break;
            case 3:
                $where[] = ["createTime", ">=", "2022-10-01 00:00:00"];
                $where[] = ["type", "=", $this->user["type"]];
                $whereRaw = "firstDepPassTime is not null or (checkCompanyIds is null and highProcess >=1)";
                break;
            case 4:
                $where[] = ["createTime", ">=", "2022-10-01 00:00:00"];
                $where[] = ["type", "=", $this->user["type"]];
                $where[] = ["checkState", "in", [-1, 35]];
                break;
            case 5:
                $where[] = ["createTime", ">=", "2022-10-01 00:00:00"];
                $where[] = ["type", "=", $this->user["type"]];
                $where[] = ["checkState", "=", 35];
                $where[] = ["isPublic", "=", 6];
                break;
        }

        $levelMap = DictApi::selectByParentCode("talent_arrange");
        if ($process != 2) {
            if ($whereRaw) {
                $count = ttcModel::where($where)->whereRaw($whereRaw)->count();
                $list = ttcModel::where($where)->whereRaw($whereRaw)->limit($offset, $limit)->order("createTime {$order}")->select()->toArray();
            } else {
                $count = ttcModel::where($where)->count();
                $list = ttcModel::where($where)->limit($offset, $limit)->order("createTime {$order}")->select()->toArray();
            }
        }
        foreach ($list as $key => $item) {
            if ($item["beforeCheckCompany"]) {
                $list[$key]["beforeCheckCompanyName"] = getCacheById("Company", $item["beforeCheckCompany"], "name");
            }
            if ($item["companyId"]) {
                $list[$key]["companyName"] = getCacheById("Company", $item["companyId"], "name");
            }
            $list[$key]["oldTalentArrangeName"] = $levelMap[$item["oldTalentArrange"]];
            $list[$key]["newTalentArrangeName"] = $levelMap[$item["newTalentArrange"]];
            if ($item["oldIdentifyCondition"]) {
                if (strlen($item["oldIdentifyCondition"]) == 19) {
                    $oldCondition = Db::table("un_identify_condition")->find($item["oldIdentifyCondition"]);
                    $list[$key]["oldIdentifyConditionCH"] = $oldCondition["name"];
                } else {
                    $oldCondition = TalentConditionApi::getOne($item["oldIdentifyCondition"]);
                    $list[$key]["oldIdentifyConditionCH"] = $oldCondition["name"];
                }
            }
            if ($item["newIdentifyCondition"]) {
                if (strlen($item["newIdentifyCondition"]) == 19) {
                    $newCondition = Db::table("un_identify_condition")->find($item["newIdentifyCondition"]);
                    $list[$key]["newIdentifyConditionCH"] = $newCondition["name"];
                } else {
                    $newCondition = TalentConditionApi::getOne($item["newIdentifyCondition"]);
                    $list[$key]["newIdentifyConditionCH"] = $newCondition["name"];
                }
            }
        }
        return json(["rows" => $list, "total" => $count]);
    }

    public function toCommonCheck($id, $process) {
        $info = ttcApi::getOne($id);
        $arrangeMap = DictApi::selectByParentCode("talent_arrange");
        $importMap = DictApi::selectByParentCode("import_way");
        $info["oldTalentArrangeName"] = $arrangeMap[$info["oldTalentArrange"]];
        $info["oldIntroductionModeName"] = $importMap[$info["oldIntroductionMode"]];
        $info["newTalentArrangeName"] = $arrangeMap[$info["newTalentArrange"]];
        $info["newIntroductionModeName"] = $importMap[$info["newIntroductionMode"]];
        $info["process"] = $process;
        if ($info["type"] == CommonConst::ENTERPRISE_NORMAL) {
            $sourceMap = DictApi::selectByParentCode("source");
            $info["oldSourceName"] = $sourceMap[$info["oldSource"]];
            $info["newSourceName"] = $sourceMap[$info["newSource"]];
        }
        $talentCatMap = DictApi::selectByParentCode("talent_condition_cats");
        if (strlen($info["oldIdentifyCondition"]) == 19) {
            $oldCondition = Db::table("un_identify_condition")->find($info["oldIdentifyCondition"]);
            $info["oldIdentifyConditionCH"] = $oldCondition["name"];
        } else {
            $oldCondition = TalentConditionApi::getOne($info["oldIdentifyCondition"]);
            if ($oldCondition["talentLevelCat"]) {
                $info["oldIdentifyConditionCategoryName"] = $talentCatMap[$oldCondition["talentLevelCat"]];
            }
            $info["oldIdentifyConditionCH"] = $oldCondition["name"];
        }
        if (strlen($info["newIdentifyCondition"]) == 19) {
            $newCondition = Db::table("un_identify_condition")->find($info["newIdentifyCondition"]);
            $info["newIdentifyConditionCH"] = $newCondition["name"];
        } else {
            $newCondition = TalentConditionApi::getOne($info["newIdentifyCondition"]);
            if ($newCondition["talentLevelCat"]) {
                $info["newIdentifyConditionCategoryName"] = $talentCatMap[$newCondition["talentLevelCat"]];
            }
            $info["newIdentifyConditionCH"] = $newCondition["name"];
        }
        return view("", ["info" => $info]);
    }

    public function toDepCheck($id, $companyId) {
        $info = ttcApi::getOne($id);
        $arrangeMap = DictApi::selectByParentCode("talent_arrange");
        $importMap = DictApi::selectByParentCode("import_way");
        $info["oldTalentArrangeName"] = $arrangeMap[$info["oldTalentArrange"]];
        $info["oldIntroductionModeName"] = $importMap[$info["oldIntroductionMode"]];
        $info["newTalentArrangeName"] = $arrangeMap[$info["newTalentArrange"]];
        $info["newIntroductionModeName"] = $importMap[$info["newIntroductionMode"]];
        $info["process"] = 2;
        if ($info["type"] == CommonConst::ENTERPRISE_NORMAL) {
            $sourceMap = DictApi::selectByParentCode("source");
            $info["oldSourceName"] = $sourceMap[$info["oldSource"]];
            $info["newSourceName"] = $sourceMap[$info["newSource"]];
        }
        $talentCatMap = DictApi::selectByParentCode("talent_condition_cats");
        if (strlen($info["oldIdentifyCondition"]) == 19) {
            $oldCondition = Db::table("un_identify_condition")->find($info["oldIdentifyCondition"]);
            $info["oldIdentifyConditionCH"] = $oldCondition["name"];
        } else {
            $oldCondition = TalentConditionApi::getOne($info["oldIdentifyCondition"]);
            if ($oldCondition["talentLevelCat"]) {
                $info["oldIdentifyConditionCategoryName"] = $talentCatMap[$oldCondition["talentLevelCat"]];
            }
            $info["oldIdentifyConditionCH"] = $oldCondition["name"];
        }
        if (strlen($info["newIdentifyCondition"]) == 19) {
            $newCondition = Db::table("un_identify_condition")->find($info["newIdentifyCondition"]);
            $info["newIdentifyConditionCH"] = $newCondition["name"];
        } else {
            $newCondition = TalentConditionApi::getOne($info["newIdentifyCondition"]);
            if ($newCondition["talentLevelCat"]) {
                $info["newIdentifyConditionCategoryName"] = $talentCatMap[$newCondition["talentLevelCat"]];
            }
            $info["newIdentifyConditionCH"] = $newCondition["name"];
        }
        return view("to_common_check", ["info" => $info, "companyId" => $companyId]);
    }

    public function findFieldsAndFiles() {
        $response = new \stdClass();
        $response->code = 500;
        $params = $this->request->param();
        $id = $params["id"];
        $info = ttcApi::getOne($id);
        if (!$info) {
            $response->msg = "请选择需要修改的对象";
            return $response;
        }
        if ($info["checkState"] != MainState::FIRST_REJECT) {
            $response->msg = "只能修改初审驳回的数据";
            return $response;
        }
        $talentInfo = \app\common\api\VerifyApi::getOne($info["talentId"]);
        if (!$talentInfo || $talentInfo["checkState"] != \app\common\api\TalentState::CERTIFICATED || $talentInfo["delete"] == 1) {
            $response->msg = "系统错误，请联系管理员";
            return $response;
        }
        $fields = DictApi::getTalentTypeChangeFields($this->user["type"]);

        $field_tmp = [];
        if ($fields) {
            foreach ($fields as $key => $field) {
                $field_tmp[] = ["key" => $key, "value" => $field];
            }
        }
        $condition = TalentConditionApi::getOne($info["newIdentifyCondition"]);
        $where = [];
        $whr = [];
        $where[] = ["project", "=", ProjectState::LEVELCHANGE];
        $where[] = ["active", "=", 1];
        $where[] = ["type", "=", $info["type"]];
        $where[] = ["isConditionFile", "<>", 1];
        $where[] = ["delete", "=", 0];
        if ($condition && $condition["bindFileTypes"]) {
            $companyWithFileType = array_filter(explode(";", $condition["companyWithFileType"]));
            $cfKv = [];
            for ($i = 0; $i < count($companyWithFileType); $i++) {
                $setting = explode(":", $companyWithFileType[$i]);
                $_companyId = $setting[0];
                $_files = explode(",", $setting[1]);
                $cfKv[$_companyId] = $_files;
            }
            $whr[] = ["id", "in", explode(",", $condition["bindFileTypes"])];
            $files = Db::table("new_common_filetype")->whereOr([$where, $whr])->order("sn asc")->select()->toArray();
            for ($i = 0; $i < count($files); $i++) {
                foreach ($cfKv as $_companyId => $_files) {
                    if (in_array($files[$i]["id"], $_files)) {
                        $company = getCacheById("Company", $_companyId);
                        $files[$i]["name"] .= sprintf("<span style='color:red;'>（%s）</span>", $company["name"]);
                        break;
                    }
                }
            }
        } else {
            $files = Db::table("new_common_filetype")->where($where)->order("sn asc")->select()->toArray();
        }
        $response->code = 200;
        $response->id = $id;
        $response->fileList = $files;
        $response->fieldList = $field_tmp;
        $response->select = [
            "files" => array_filter(explode(",", $info["files"])),
            "fields" => array_filter(explode(",", $info["fields"]))
        ];
        return $response;
    }

    public function updateFieldsAndFiles() {
        $response = new \stdClass();
        $response->code = 500;
        $params = $this->request->param();
        $info = ttcModel::find($params["id"]);
        if (!$info) {
            $response->msg = "请选择需要修改的对象";
            return $response;
        }
        if ($info["checkState"] != MainState::FIRST_REJECT) {
            $response->msg = "只能修改初审驳回的数据";
            return $response;
        }
        $fields = array_filter(explode(",", $params["fields"]));
        $files = array_filter(explode(",", $params["files"]));
        if (!$fields && !$files) {
            $response->msg = "请选择驳回的字段或者附件";
            return $response;
        }
        $data["id"] = $params["id"];
        $data["fields"] = $fields ? implode(",", $fields) : "";
        $data["files"] = $files ? implode(",", $files) : "";
        if (ttcModel::update($data)) {
            $response->msg = "修改成功";
            $response->code = 200;
        } else {
            $response->msg = "修改失败";
        }
        return $response;
    }

    public function validateIsCheck() {
        $id = $this->request->param("id");
        $companyId = $this->request->param("companyId");
        $process = $this->request->param("process");
        $response = new \stdClass();
        $response->code = 500;
        $info = ttcApi::getOne($id);
        if (!$info || $info["delete"] == 1 || $info["type"] != $this->user["type"]) {
            $response->msg = "没有对应的人才变更记录";
            return $response;
        }
        if (!$info["talentId"]) {
            $response->msg = "没有对应的人才信息";
            return $response;
        }
        if (!$info["newIdentifyCondition"]) {
            $response->msg = "没有对应的认定条件";
            return $response;
        }
        $where = [];
        $where[] = ["step", "=", $process];
        $where[] = ["active", "=", 0];
        $lastLog = [];
        switch ($process) {
            case -1:
                if ($info["checkState"] != MainState::NEED_CHECK) {
                    $response->msg = "该申报不在审核范围内，无法审核";
                } else {
                    $lastLog = TalentLogApi::getLastLogEx($id, ProjectState::LEVELCHANGE, 0, $where);
                    $response->code = 200;
                }
                break;
            case 1:
                if ($info["checkState"] != MainState::NEED_FIRST_CHECK && $info["checkState"] != MainState::DEP_REJECT) {
                    $response->msg = "该申报不在审核范围内，无法审核";
                } else {
                    $lastLog = TalentLogApi::getLastLogEx($id, ProjectState::LEVELCHANGE, 0, $where);
                    $response->code = 200;
                }
                break;
            case 2:
                if ($this->user["companyId"] != $companyId) {
                    $response->msg = "非审核部门，审核失败";
                    return $response;
                }
                if ($info["checkState"] != MainState::NEED_DEP_CHECK) {
                    $response->msg = "该申报不在审核范围内，无法审核";
                } else {
                    $where[] = ["companyId", "=", $companyId];
                    $lastLog = TalentLogApi::getLastLogEx($id, ProjectState::LEVELCHANGE, 0, $where);
                    $response->code = 200;
                }
                break;
            case 3:
                if ($info["checkState"] != MainState::NEED_THIRD) {
                    $response->msg = "该申报不在审核范围内，无法审核";
                } else {
                    $lastLog = TalentLogApi::getLastLogEx($id, ProjectState::LEVELCHANGE, 0, $where);
                    $response->code = 200;
                }
                break;
            case 4:
                break;
        }
        if ($response->code == 200) {
            if ($lastLog) {
                $info["checkState"] = $lastLog["state"];
                $info["checkMsg"] = $lastLog["description"];
            } else {
                $info["checkState"] = null;
                $info["checkMsg"] = "";
            }
            $response->data = $info;

            $condition = TalentConditionApi::getOne($info["newIdentifyCondition"]);
            $whrFile = [];
            $whrOr = [];
            $whrFile[] = ["project", "=", ProjectState::LEVELCHANGE];
            $whrFile[] = ["active", "=", 1];
            $whrFile[] = ["type", "=", $info["type"]];
            $whrFile[] = ["isConditionFile", "<>", 1];
            $whrFile[] = ["delete", "=", 0];
            if ($condition && $condition["bindFileTypes"]) {
                $companyWithFileType = array_filter(explode(";", $condition["companyWithFileType"]));
                $cfKv = [];
                for ($i = 0; $i < count($companyWithFileType); $i++) {
                    $setting = explode(":", $companyWithFileType[$i]);
                    $_companyId = $setting[0];
                    $_files = explode(",", $setting[1]);
                    $cfKv[$_companyId] = $_files;
                }
                $whrOr[] = ["id", "in", explode(",", $condition["bindFileTypes"])];
                $files = \app\common\model\FileType::whereOr([$whrFile, $whrOr])->order("sn asc")->select()->toArray();
                for ($i = 0; $i < count($files); $i++) {
                    foreach ($cfKv as $_companyId => $_files) {
                        if (in_array($files[$i]["id"], $_files)) {
                            $company = getCacheById("Company", $_companyId);
                            $files[$i]["name"] .= sprintf("<span style='color:red;'>（%s）</span>", $company["name"]);
                            break;
                        }
                    }
                }
            } else {
                $files = \app\common\model\FileType::where($whrFile)->order("sn asc")->select()->toArray();
            }
            $response->fileList = $files;

            $fieldList = DictApi::getTalentTypeChangeFields($info["type"]);
            $field_tmp = [];
            foreach ($fieldList as $key => $field) {
                $field_tmp[] = ["key" => $key, "value" => $field];
            }
            $response->fieldList = $field_tmp;
        }
        return $response;
    }

    public function check() {
        $response = new \stdClass();
        $response->code = 500;
        $talentTypeChange = $this->request->param();
        $id = $talentTypeChange["id"];
        $process = $talentTypeChange["process"];
        $checkState = $talentTypeChange["checkState"];
        $checkMsg = $talentTypeChange["checkMsg"];
        $fields = $talentTypeChange["fields"];
        $files = $talentTypeChange["files"];
        Db::startTrans();
        try {
            if (!$checkState) {
                $response->msg = "请选择审核状态";
                return $response;
            }
            if ($process == 1 || $process == 3) {
                $upd["id"] = $id;
                $upd["fields"] = $fields;
                $upd["files"] = $files;
                Db::table("un_talent_type_change")->update($upd);
            }
            $where[] = ["active", "=", "0"];
            $where[] = ["step", "=", $process];
            $lastLog = TalentLogApi::getLastLogEx($id, ProjectState::LEVELCHANGE, 0, $where);
            $user = $this->user;

            $log["active"] = 0;
            $log["state"] = $checkState;
            $log["step"] = $process;
            $log["companyId"] = $user["companyId"];
            $log["stateChange"] = "保存未提交";
            $log["type"] = ProjectState::LEVELCHANGE;
            $log["mainId"] = $id;
            $log["description"] = $checkMsg;
            if ($lastLog) {
                $log["id"] = $lastLog["id"];
                $log["updateUser"] = $user ? sprintf("%s(%s)", $user["account"], $user["companyName"] ?: $user["rolename"]) : "系统";
                $log["updateTime"] = date("Y-m-d H:i:s");
                Db::table("new_talent_checklog")->update($log);
            } else {
                $log["id"] = getStringId();
                $log["createUser"] = $user ? sprintf("%s(%s)", $user["account"], $user["companyName"] ?: $user["rolename"]) : "系统";
                $log["createTime"] = date("Y-m-d H:i:s");
                Db::table("new_talent_checklog")->insert($log);
            }
            Db::commit();
            $response->msg = "审核成功";
            $response->code = 200;
            return $response;
        } catch (\think\db\exception\DbException $e) {
            Db::rollback();
            $response->msg = "审核失败：" . $e->getMessage();
            return $response;
        }
    }

    public function submitCheck() {
        $response = new \stdClass();
        $response->code = 500;
        $talentTypeChange = $this->request->param();
        $id = $talentTypeChange["id"];
        $companyId = $talentTypeChange["companyId"];
        $process = $talentTypeChange["process"];
        $where = [];
        if ($process == 2) {
            $where[] = ["companyId", "=", $companyId];
        }
        $where[] = ["active", "=", "0"];
        $where[] = ["step", "=", $process];
        $lastLog = TalentLogApi::getLastLogEx($id, ProjectState::LEVELCHANGE, 0, $where);
        if (!$lastLog) {
            $response->msg = "请先审核后再提交";
            return $response;
        }
        $checkState = $lastLog["state"];
        $checkMsg = $lastLog["description"];
        $data["id"] = $id;
        $data["checkMsg"] = $checkMsg;
        $old = ttcModel::find($id);
        //判断到达的最高流程
        $data["highProcess"] = !$old["highProcess"] ? $process : ($old["highProcess"] < $process ? $process : $old["highProcess"]);

        $user = $this->user;
        Db::startTrans();
        try {
            switch ($process) {
                case -1:
                    if ($checkState == -1) {
                        $data["checkState"] = MainState::NOTPASS;
                    }
                    if ($checkState == 2) {
                        $data["checkState"] = MainState::BEFORE_REJECT;
                    }
                    if ($checkState == 3) {
                        $data["checkState"] = MainState::NEED_FIRST_CHECK;
                        $data["firstBeforeSubmitTime"] = date("Y-m-d H:i:s");
                    }
                    $log["id"] = $lastLog["id"];
                    $log["active"] = 1;
                    $log["state"] = 8;
                    $log["stateChange"] = MainState::getStateDesc($old["checkState"]) . "->" . MainState::getStateDesc($data["checkState"]);
                    $log["updateUser"] = $user ? sprintf("%s(%s)", $user["account"], $user["companyName"] ?: $user["rolename"]) : "系统";
                    $log["updateTime"] = date("Y-m-d H:i:s");
                    Db::table("new_talent_checklog")->update($log);
                    Db::table("un_talent_type_change")->update($data);
                    break;
                case 1:
                    if ($checkState == -1) {
                        $data["checkState"] = MainState::NOTPASS;
                    }
                    if ($checkState == 2) {
                        $data["checkState"] = MainState::FIRST_REJECT;
                    }
                    if ($checkState == -2) {
                        $data["checkState"] = MainState::FIRST_REJECT_BRANCH;
                    }
                    //审核通过
                    if ($checkState == 3) {
                        $talent_condition = TalentConditionApi::getOne($old["newIdentifyCondition"]);
                        $companyIds = array_filter(explode(",", $talent_condition["companyIds"]));
                        $tdList = Db::table("un_talent_depcheckstate")->where("mainId", $id)->select()->toArray();
                        $ids = [];
                        $oldCompanyIds = [];
                        foreach ($tdList as $td) {
                            $ids[] = $td["id"];
                            $oldCompanyIds[] = $td["companyId"];
                        }
                        if ($companyIds) {
                            $addList = [];
                            $deleteDepList = [];
                            foreach ($companyIds as $_companyId) {
                                if (!in_array($_companyId, $oldCompanyIds)) {
                                    $dep["id"] = getStringId();
                                    $dep["type"] = ProjectState::LEVELCHANGE;
                                    $dep["mainId"] = $id;
                                    $dep["companyId"] = $_companyId;
                                    $dep["state"] = 1;
                                    $dep["createUser"] = $this->user["name"];
                                    $dep["createTime"] = date("Y-m-d H:i:s");
                                    $addList[] = $dep;
                                }
                            }
                            foreach ($oldCompanyIds as $_ocompanyId) {
                                if (!in_array($_ocompanyId, $companyIds)) {
                                    $deleteDepList[] = $_ocompanyId;
                                }
                            }
                            if ($addList) {
                                Db::table("un_talent_depcheckstate")->insertAll($addList);
                            }
                            if ($deleteDepList) {
                                $where = [];
                                $where[] = ["mainId", "=", $id];
                                $where[] = ["companyId", "in", $deleteDepList];
                                Db::table("un_talent_depcheckstate")->where($where)->delete();
                            }
                            $where = [];
                            $where[] = ["mainId", "=", $id];
                            $updTd["state"] = 1;
                            Db::table("un_talent_depcheckstate")->where($where)->update($updTd);
                            $data["checkCompanyIds"] = implode(",", $companyIds);
                            $data["checkState"] = MainState::NEED_DEP_CHECK;
                        } else {
                            if ($ids) {
                                $where = [];
                                $where[] = ["id", "in", $ids];
                                Db::table("un_talent_depcheckstate")->where($where)->delete();
                            }
                            $data["checkCompanyIds"] = null;
                            $data["checkState"] = MainState::NEED_THIRD;
                        }
                    }
                    if ($checkState == 4) {//跳过部门并审
                        $data["checkCompanyIds"] = null;
                        $data["checkState"] = MainState::NEED_THIRD;
                    }
                    $log["id"] = $lastLog["id"];
                    $log["active"] = 1;
                    $log["state"] = 8;
                    $log["stateChange"] = MainState::getStateDesc($old["checkState"]) . "->" . MainState::getStateDesc($data["checkState"]);
                    $log["updateUser"] = $user ? sprintf("%s(%s)", $user["account"], $user["companyName"] ?: $user["rolename"]) : "系统";
                    $log["updateTime"] = date("Y-m-d H:i:s");
                    Db::table("new_talent_checklog")->update($log);
                    Db::table("un_talent_type_change")->update($data);
                    break;
                case 2:
                    if ($this->user["companyId"] != $companyId) {
                        $response->msg = "非审核部门，审核失败";
                        return $response;
                    }
                    $where = [];
                    $where[] = ["mainId", "=", $id];
                    $where[] = ["companyId", "=", $companyId];
                    $td = Db::table("un_talent_depcheckstate")->where($where)->find();
                    $updTd = [];
                    $updTd["id"] = $td["id"];
                    $updTd["state"] = $checkState;
                    if ($checkState == 3) {
                        $updTd["submitTime"] = date("Y-m-d H:i:s");
                    }
                    Db::table("un_talent_depcheckstate")->update($updTd);
                    //判断所有部门是否全部通过
                    unset($where);
                    $where[] = ["mainId", "=", $id];
                    $tdList = Db::table("un_talent_depcheckstate")->where($where)->select()->toArray();
                    $needCount = 0;
                    $rejectCount = 0;
                    foreach ($tdList as $td) {
                        if ($td["state"] == 1) {
                            $needCount++;
                        }
                        if ($td["state"] == 2) {
                            $rejectCount++;
                        }
                    }
                    if ($needCount == 0) {
                        if ($rejectCount > 0) {
                            $data["checkState"] = MainState::DEP_REJECT;
                        } else {
                            if (\StrUtil::isEmpOrNull($old["firstDepPassTime"])) {
                                $data["firstDepPassTime"] = date("Y-m-d H:i:s");
                            }
                            $data["checkState"] = MainState::NEED_THIRD;
                        }
                        Db::table("un_talent_type_change")->update($data);
                    }
                    $log["id"] = $lastLog["id"];
                    $log["active"] = 1;
                    $log["state"] = 8;
                    $log["stateChange"] = MainState::getStateDesc($old["checkState"]) . "->" . MainState::getStateDesc($data["checkState"]);
                    $log["updateUser"] = $user ? sprintf("%s(%s)", $user["account"], $user["companyName"] ?: $user["rolename"]) : "系统";
                    $log["updateTime"] = date("Y-m-d H:i:s");
                    Db::table("new_talent_checklog")->update($log);
                    break;
                case 3:
                    if ($checkState == -1) {
                        $data["checkState"] = MainState::NOTPASS;
                    }
                    if ($checkState == 2) {
                        $data["checkState"] = MainState::DEP_REJECT;
                    }
                    if ($checkState == 3) {
                        $data["checkState"] = MainState::PASS;
                    }
                    $log["id"] = $lastLog["id"];
                    $log["active"] = 1;
                    $log["state"] = 8;
                    $log["stateChange"] = MainState::getStateDesc($old["checkState"]) . "->" . MainState::getStateDesc($data["checkState"]);
                    $log["updateUser"] = $user ? sprintf("%s(%s)", $user["account"], $user["companyName"] ?: $user["rolename"]) : "系统";
                    $log["updateTime"] = date("Y-m-d H:i:s");
                    Db::table("new_talent_checklog")->update($log);
                    Db::table("un_talent_type_change")->update($data);
                    break;
                case 4:
                    break;
            }
            Db::commit();
            $response->msg = "提交审核成功";
            $response->code = 200;
            return $response;
        } catch (\think\db\exception\DbException $e) {
            Db::rollback();
            $response->msg = "提交审核失败：" . $e->getMessage();
            return $response;
        }
    }

    public function selectNeedCheckData($type) {
        $info = $this->request->param();
        $response = new \stdClass();
        $where = [];
        $where[] = ["createTime", ">=", "2022-10-01 00:00:00"];
        $where[] = ["type", "=", $this->user["type"]];
        if ($info) {
            if (\StrUtil::isNotEmpAndNull($info["talentName"])) {
                $where[] = ["talentName", "like", "%{$info['talentName']}%"];
            }
            if ($info["checkState"]) {
                $where[] = ["checkState", "=", $info["checkState"]];
            }
        }
        switch ($type) {
            case 1:
                $where[] = ["isPublic", "=", 1];
                $where[] = ["checkState", "in", [-1, 35]];
                break;
            case 2:
                $where[] = ["isPublic", "=", 1];
                $where[] = ["checkState", "in", [-1, 35]];
                break;
            case 3:
            case 7:             //公示预览
                $where[] = ["isPublic", "=", 2];
                $where[] = ["checkState", "in", [-1, 35]];
                break;
            case 4:
                $where[] = ["isPublic", "=", 3];
                $where[] = ["checkState", "in", [-1, 35]];
                break;
            case 5:
            case 8:             //公布预览
                $where[] = ["isPublic", "=", 4];
                $where[] = ["checkState", "in", [-1, 35]];
                break;
            case 6:
                $where[] = ["isPublic", "=", 5];
                $where[] = ["checkState", "in", [35]];
                break;
        }
        //$whereRaw = "length(talentId)<>19";
        $list = ttcModel::where($where)->field("id,idCard,talentName,enterpriseId,checkState")->select()->toArray();
        //查询企业信息
        $enterprises = \app\common\model\Enterprise::column("name", "id");
        foreach ($list as $key => $item) {
            $list[$key]["enterpriseName"] = $enterprises[$item["enterpriseId"]];
        }
        $response->obj = ["rows" => $list, "total" => count($list)];
        $response->code = 200;
        return $response;
    }

    /**
     * 导出核查征信
     * @return type
     */
    public function exportHczx() {
        $response = new \stdClass();
        $response->code = 500;
        $ids = $this->request->param("ids");
        $ids_arr = array_filter(explode(",", $ids));
        if (!$ids_arr) {
            $response->msg = "没有选择导出的名单";
            return \StrUtil::back($response, "TalentTypeChange.callBack");
        }
        $where = [];
        $where[] = ["ttc.id", "in", $ids_arr];
        $where[] = ["ti.checkState", "=", \app\common\api\TalentState::CERTIFICATED];
        $list = ttcModel::alias("ttc")->leftJoin("new_talent_info ti", "ti.card_number=ttc.idCard")->field("ttc.*,ti.nationality")->where($where)->select()->toArray();
        if (!$list) {
            $response->msg = "没有可以导出的内容";
            return \StrUtil::back($response, "TalentTypeChange.callBack");
        }
        $columns = ["序号", "姓名", "国籍/地区", "证件号码", "工作单位", "备注"];
        $rows = [];
        $i = 1;
        $nationalityMap = DictApi::selectByParentCode("nationality");
        for ($i = 0; $i < count($list); $i++) {
            $item = $list[$i];
            $row = [
                $i + 1, $item["talentName"], $nationalityMap[$item["nationality"]], $item["idCard"], $item["enterpriseName"], $item["description"]
            ];
            $rows[] = $row;
        }
        $filename = "人才层次变更核查征信名单导出";
        if ($rows) {
            export($columns, $rows, $filename);
            exit();
        } else {
            $response->msg = "没有选择导出的名单";
            return \StrUtil::back($response, "TalentTypeChange.callBack");
        }
    }

    /**
     * 征信失信
     * @return \stdClass
     */
    public function hczxReject() {
        $obj = $this->request->param();
        $response = new \stdClass();
        $response->code = 500;
        if (!$obj) {
            $response->msg = "系统错误，请联系管理员";
            return $response;
        }
        $old = ttcModel::find($obj["id"]);
        if ($old["isPublic"] != 1) {
            $response->msg = "当前记录不是待核查征信状态，无法核查";
            return $response;
        }
        Db::startTrans();
        try {
            $upd["id"] = $obj["id"];
            $upd["outMsg"] = $obj["outMsg"];
            $upd["isPublic"] = 2;
            $upd["checkState"] = MainState::NOTPASS;
            Db::table("un_talent_type_change")->update($upd);

            $log["active"] = 1;
            $log["id"] = getStringId();
            $log["state"] = MainState::NOTPASS;
            $log["step"] = 4;
            $log["companyId"] = $this->user["companyId"];
            $log["stateChange"] = MainState::getStateDesc($old["checkState"]) . "->" . MainState::getStateDesc(MainState::NOTPASS);
            $log["type"] = ProjectState::LEVELCHANGE;
            $log["mainId"] = $obj["id"];
            $log["description"] = $obj["outMsg"];
            $log["createUser"] = sprintf("%s(%s)", $this->user["account"], $this->user["companyName"] ?: $this->user["rolename"]);
            $log["createTime"] = date("Y-m-d H:i:s");
            Db::table("new_talent_checklog")->insert($log);

            $response->code = 200;
            $response->msg = "核查征信成功";
            Db::commit();
            return $response;
        } catch (\think\db\exception\DbException $e) {
            Db::rollback();
            $response->msg = "核查征信失败：" . $e->getMessage();
            return $response;
        }
    }

    /**
     * 征信通过
     * @return \stdClass
     */
    public function hczxPass() {
        $response = new \stdClass();
        $response->code = 500;

        $params = $this->request->param();
        $ids = $params["ids"];
        if (\StrUtil::isEmpOrNull($ids)) {
            $response->msg = "请选择核查征信通过的数据";
            return $response;
        }
        $where = [];
        $where[] = ["id", "in", explode(",", $ids)];
        $list = ttcModel::where($where)->select()->toArray();
        Db::startTrans();
        try {
            $logList = [];
            foreach ($list as $key => $item) {
                $data = ["id" => $item["id"], "isPublic" => 2, "outMsg" => ""];
                Db::table("un_talent_type_change")->update($data);
                $logList[] = [
                    "id" => getStringId(),
                    "type" => ProjectState::LEVELCHANGE,
                    "mainId" => $item["id"],
                    "companyId" => $this->user["companyId"],
                    "active" => 1,
                    "state" => MainState::BASIC_PASS,
                    "step" => 4,
                    "stateChange" => "<span class='label label-success'>待核查</span>-><span class='label label-primary'>待公示</span>",
                    "description" => "核查征信通过",
                    "createTime" => date("Y-m-d H:i:s"),
                    "createUser" => sprintf("%s(%s)", $this->user["account"], $this->user["companyName"] ?: $this->user["rolename"])
                ];
            }
            Db::table("new_talent_checklog")->insertAll($logList);
            Db::commit();
            $response->code = 200;
            $response->msg = "核查征信通过成功";
            return $response;
        } catch (\think\db\exception\DbException $e) {
            Db::rollback();
            $response->msg = "核查征信通过失败：" . $e->getMessage();
            return $response;
        }
    }

    /**
     * 公示预览
     */
    public function publicPreview() {
        $params = $this->request->param();
        $ids_arr = array_filter(explode(",", $params["ids"]));
        $columns = ["序号", "姓名", "工作单位", "本人具备的认定条件", "拟认定人才层次", "审核状态", "备注"];
        if ($ids_arr) {
            $where[] = ["id", "in", $ids_arr];
            $list = ttcModel::where($where)->select()->toArray();

            $oldIdentifyConditions = [];
            $newIdentifyConditions = [];

            $rows = [];
            $talentArranges = DictApi::selectByParentCode("talent_arrange");
            for ($i = 0; $i < count($list); $i++) {
                $item = $list[$i];
                $whereLastLog = [];
                $whereLastLog[] = ["step", "=", 3];
                $whereLastLog[] = ["state", "<>", 8];
                $description = $item["description"];
                $stateName = "";
                if ($item["checkState"] == MainState::NOTPASS) {
                    $lastLog = TalentLogApi::getLastLogEx($item["id"], ProjectState::LEVELCHANGE, 0, $whereLastLog);
                    if ($lastLog && $lastLog["state"] == MainState::NOTPASS) {
                        $description = $lastLog["description"];
                    }
                    if (\StrUtil::isNotEmpAndNull($item["outMsg"])) {
                        $description = !$item["description"] ? "" : $item["description"] . $item["outMsg"];
                    }
                    $stateName = "审核不通过";
                }
                if ($item["checkState"] == MainState::PASS) {
                    $stateName = "审核通过";
                }
                $identifyConditionZH = "";
                if (strlen($item["newIdentifyCondition"]) == 19) {
                    if (!$oldIdentifyConditions) {
                        $oldIdentifyConditions = Db::table("un_identify_condition")->where("type", $this->user["type"])->column("name", "id");
                    }
                    $identifyConditionZH = $oldIdentifyConditions[$item["newIdentifyCondition"]];
                } else {
                    if (!$newIdentifyConditions) {
                        $newIdentifyConditions = Db::table("new_talent_condition")->where("type", $this->user["type"])->column("name", "id");
                    }
                    $identifyConditionZH = $newIdentifyConditions[$item["newIdentifyCondition"]];
                }
                $row = [
                    $i + 1, $item["talentName"], $item["enterpriseName"], $identifyConditionZH, $talentArranges[$item["newTalentArrange"]], $stateName, $description
                ];
                $rows[] = $row;
            }
        }
        if ($rows) {
            $filename = sprintf("人才层次变更第%d批次公示导出", date("Ym"));
            export($columns, $rows, $filename);
            exit();
        }
    }

    /**
     * 公示
     */
    public function publicBatch() {
        $response = new \stdClass();
        $response->code = 500;
        //查询需要公示的数据(勾选)
        $params = $this->request->param();
        $ids = array_filter(explode(",", $params["ids"]));
        $publicBatch = $params["batch"];
        $isMessage = $params["isMessage"] == 1 ? true : false;
        if (!$publicBatch || strlen($publicBatch) != 6 || !is_numeric($publicBatch)) {
            $response->msg = "公示批次错误";
            return $response;
        }
        $where = [];
        $where[] = ["ttc.id", "in", $ids];
        $list = ttcModel::alias("ttc")->leftJoin("un_enterprise e", "e.id=ttc.enterpriseId")->where($where)->field("ttc.*,e.agentPhone")->select()->toArray();
        $logList = [];
        $phones = [];
        $success = 0;
        $failure = 0;
        Db::startTrans();
        try {
            for ($i = 0; $i < count($list); $i++) {
                $obj = $list[$i];
                $data = [];
                $data["id"] = $obj["id"];
                if ($obj["checkState"] == MainState::PASS && $obj["isPublic"] == 2) {
                    $data["publicBatch"] = $publicBatch;
                    $data["isPublic"] = 3;
                    Db::table("un_talent_type_change")->update($data);
                    $logList[] = [
                        "id" => getStringId(),
                        "type" => ProjectState::LEVELCHANGE,
                        "mainId" => $obj["id"],
                        "companyId" => $this->user["companyId"],
                        "active" => 1,
                        "state" => MainState::BASIC_PASS,
                        "step" => 5,
                        "stateChange" => "<span class='label label-success'>待公示</span>-><span class='label label-primary'>公示中</span>",
                        "description" => "",
                        "createTime" => date("Y-m-d H:i:s"),
                        "createUser" => sprintf("%s(%s)", $this->user["account"], $this->user["companyName"] ?: $this->user["rolename"])
                    ];
                    $phones[$obj["enterpriseId"]] = $obj["agentPhone"];
                    $success++;
                } else {
                    $failure++;
                }
            }
            $effect = Db::table("new_talent_checklog")->insertAll($logList);
            Db::commit();
            if ($phones && $isMessage && $effect) {
                $tpl_content = sprintf("【晋江市人才服务平台】您好！您提交申请的%s已完成初步审核，现通过%s将审核结果予以公示，公示时间%s至%s。公示期间如有异议，请及时向%s反映。电话%s，电子邮箱%s。",
                        $params["typeName"], $params["address"], $params["publicStartTime"], $params["publicEndTime"], $params["dep"], $params["phone"], $params["email"]);
                foreach ($phones as $enterpriseId => $phone) {
                    queue("app\job\Messenger", ["type" => 5, "userId" => $enterpriseId, "phone" => $phone, "template" => $tpl_content]);
                }
            }
            $response->msg = "公示成功";
            $response->code = 200;
            return $response;
        } catch (\think\db\exception\DbException $e) {
            Db::rollback();
            $response->msg = "公示失败：" . $e->getMessage();
            return $response;
        }
    }

    /**
     * 公示导出
     * @return type
     */
    public function publicExport() {
        $response = new \stdClass();
        $response->code = 500;

        $params = $this->request->param();
        $columns = ["序号", "公示批次", "姓名", "工作单位", "申请认定时间", "本人具备的认定条件", "拟认定人才层次", "审核状态", "备注"];
        $startTime = $params["startTime"];
        $endTime = $params["endTime"];
        if (!strtotime($startTime) || !strtotime($endTime))
            return json(["msg" => "时间格式错误"]);
        $where = [];
        $where[] = ["createTime", ">=", "2022-10-01 00:00:00"];
        $where[] = ["type", "=", $this->user["type"]];
        $where[] = ["publicBatch", "between", [$startTime, $endTime]];
        $list = ttcModel::where($where)->order("publicBatch")->select()->toArray();
        if (!$list) {
            $response->msg = "所选时间段内无公示数据";
            return \StrUtil::back($response, "TalentTypeChange.callBack");
        }

        $oldIdentifyConditions = [];
        $newIdentifyConditions = [];

        $rows = [];
        $i = 1;
        $talentArranges = DictApi::selectByParentCode("talent_arrange");
        for ($i = 0; $i < count($list); $i++) {
            $item = $list[$i];
            $whereLastLog = [];
            $whereLastLog[] = ["step", "=", 3];
            $whereLastLog[] = ["state", "<>", 8];
            $description = $item["description"];
            $stateName = "";
            if ($item["checkState"] == MainState::NOTPASS) {
                $lastLog = TalentLogApi::getLastLogEx($item["id"], ProjectState::LEVELCHANGE, 0, $whereLastLog);
                if ($lastLog && $lastLog["state"] == MainState::NOTPASS) {
                    $description = $lastLog["description"];
                }
                if (\StrUtil::isNotEmpAndNull($item["outMsg"])) {
                    $description = !$item["description"] ? "" : $item["description"] . $item["outMsg"];
                }
                $stateName = "审核不通过";
            }
            if ($item["checkState"] == MainState::PASS) {
                $stateName = "审核通过";
            }
            $identifyConditionZH = "";
            if (strlen($item["newIdentifyCondition"]) == 19) {
                if (!$oldIdentifyConditions) {
                    $oldIdentifyConditions = Db::table("un_identify_condition")->where("type", $this->user["type"])->column("name", "id");
                }
                $identifyConditionZH = $oldIdentifyConditions[$item["newIdentifyCondition"]];
            } else {
                if (!$newIdentifyConditions) {
                    $newIdentifyConditions = Db::table("new_talent_condition")->where("type", $this->user["type"])->column("name", "id");
                }
                $identifyConditionZH = $newIdentifyConditions[$item["newIdentifyCondition"]];
            }
            $row = [
                $i + 1, $item["publicBatch"], $item["talentName"], $item["enterpriseName"], $item["newIdentifyMonth"], $identifyConditionZH, $talentArranges[$item["newTalentArrange"]], $stateName, $description
            ];
            $rows[] = $row;
        }
        if ($rows) {
            $filename = "人才层次变更公示导出";
            export($columns, $rows, $filename);
            exit();
        }
        $response->msg = "所选时间段内无公示数据";
        return \StrUtil::back($response, "TalentTypeChange.callBack");
    }

    /**
     * 公示再审核
     */
    public function afterCheck() {
        $response = new \stdClass();
        $response->code = 500;

        $obj = $this->request->param();
        if (!$obj) {
            $response->msg = "系统错误，请联系管理员";
            return $response;
        }
        $old = ttcModel::find($obj["id"]);
        if ($old["isPublic"] != 3) {
            $response->msg = "当前记录不是公示中状态，无法审核";
            return $response;
        }
        $desc = null;
        $state = $obj["checkState"];
        $data = [];
        $data["id"] = $obj["id"];
        if ($obj["checkState"] == MainState::BASIC_REJECT) {
            $data["checkState"] = MainState::THIRD_REJECT;
            $data["isPublic"] = 1;
            $data["outMsg"] = "";
            $desc = "（公示再审核驳回）审核状态：" . MainState::getStateDesc($old["checkState"]) . "->" . MainState::getStateDesc(MainState::THIRD_REJECT) .
                    ";公示状态：<span class='label label-success'>公示中</span>-><span class='label label-primary'>待核查征信</span>;审核意见:" . $obj["checkMsg"];
        } else {
            $data["checkState"] = MainState::OBJECTION;
            $data["checkMsg"] = $obj["checkMsg"];
            $desc = "（公示再审核通过）审核状态：" . MainState::getStateDesc($old["checkState"]) . "->" . MainState::getStateDesc(MainState::OBJECTION) .
                    ";公示状态：<span class='label label-success'>公示中</span>-><span class='label label-primary'>待公布</span>";
        }
        //添加日志        
        $log = [
            "id" => getStringId(),
            "type" => ProjectState::LEVELCHANGE,
            "mainId" => $obj["id"],
            "companyId" => $this->user["companyId"],
            "active" => 1,
            "state" => $state,
            "step" => 6,
            "stateChange" => $desc,
            "description" => $obj["checkMsg"],
            "createTime" => date("Y-m-d H:i:s"),
            "createUser" => sprintf("%s(%s)", $this->user["account"], $this->user["companyName"] ?: $this->user["rolename"])
        ];
        Db::startTrans();
        try {
            Db::table("un_talent_type_change")->update($data);
            Db::table("new_talent_checklog")->insert($log);
            Db::commit();
            $response->code = 200;
            $response->msg = "审核成功";
            return $response;
        } catch (\think\db\exception\DbException $e) {
            Db::rollback();
            $response->msg = "审核失败：" . $e->getMessage();
            return $response;
        }
    }

    /**
     * 公示通过
     */
    public function publicPass($ids) {
        $response = new \stdClass();
        $response->code = 500;
        $where = [];
        $where[] = ["id", "in", explode(",", $ids)];
        $list = ttcModel::where($where)->select()->toArray();
        if (!$list) {
            $response->msg = "系统错误，请联系管理员";
            return $response;
        }
        //添加日志
        $logList = [];
        Db::startTrans();
        foreach ($list as $obj) {
            //添加日志
            $logList[] = [
                "id" => getStringId(),
                "type" => ProjectState::LEVELCHANGE,
                "mainId" => $obj["id"],
                "companyId" => $this->user["companyId"],
                "active" => 1,
                "state" => 3,
                "step" => 6,
                "stateChange" => "<span class='label label-success'>公示中</span>-><span class='label label-primary'>待公布</span>",
                "description" => "",
                "createTime" => date("Y-m-d H:i:s"),
                "createUser" => sprintf("%s(%s)", $this->user["account"], $this->user["companyName"] ?: $this->user["rolename"])
            ];
        }
        $data["isPublic"] = 4;
        try {
            $res1 = Db::table("un_talent_type_change")->where($where)->update($data);
            $res2 = Db::table("new_talent_checklog")->insertAll($logList);
            if ($res1 && $res2) {
                Db::commit();
                $response->msg = "批量公示通过成功";
                $response->code = 200;
                return $response;
            }
            $response->msg = "批量公示通过失败，没有可更新内容";
            Db::rollback();
            return $response;
        } catch (\think\db\exception\DbException $e) {
            Db::rollback();
            $response->msg = "批量公示通过失败：" . $e->getMessage();
            return $response;
        }
    }

    /**
     * 公布
     */
    public function publish($ids, $batch) {
        $response = new \stdClass();
        $response->code = 500;
        $where = [];
        $where[] = ["id", "in", explode(",", $ids)];
        $list = ttcModel::where($where)->select()->toArray();
        if (!$list) {
            $response->msg = "系统错误，请联系管理员";
            return $response;
        }
        //添加日志
        $logList = [];
        Db::startTrans();
        try {
            for ($i = 0; $i < count($list); $i++) {
                $obj = $list[$i];
                $desc = "";
                $stateChange = "";
                $data = [];
                $data["id"] = $obj["id"];
                if ($obj["checkState"] == MainState::NOTPASS) {
                    $stateChange = "<span class='label label-success'>待公布</span>->" . MainState::getStateDesc(MainState::NOTPASS);
                    $desc = "审核不通过";
                } else {
                    $stateChange = "<span class='label label-success'>待公布</span>-><span class='label label-primary'>待发证</span>";
                    $desc = "批量公布";
                }
                //添加日志
                $logList[] = [
                    "id" => getStringId(),
                    "type" => ProjectState::LEVELCHANGE,
                    "mainId" => $obj["id"],
                    "companyId" => $this->user["companyId"],
                    "active" => 1,
                    "state" => 3,
                    "step" => 7,
                    "stateChange" => $stateChange,
                    "description" => $desc,
                    "createTime" => date("Y-m-d H:i:s"),
                    "createUser" => sprintf("%s(%s)", $this->user["account"], $this->user["companyName"] ?: $this->user["rolename"])
                ];
                if (\StrUtil::isEmpOrNull($obj["newCertificateOutTime"])) {
                    $startDate = date("Y-m-d");
                    $expiredDate = date("Y-m-d", strtotime("+6 years -1 days {$startDate}"));
                    $data["newIdentifyOutTime"] = $expiredDate;
                    $data["newCertificateOutTime"] = $expiredDate;
                    $data["newCertificateStartTime"] = $startDate;
                }
                $data["isPublic"] = 5;
                $data["newIdentifyMonth"] = $batch;
                Db::table("un_talent_type_change")->update($data);
            }
            Db::table("new_talent_checklog")->insertAll($logList);
            Db::commit();
            $response->msg = "公布成功";
            $response->code = 200;
            return $response;
        } catch (\think\db\exception\DbException $e) {
            Db::rollback();
            $response->msg = "公布失败：" . $e->getMessage();
            return $response;
        }
    }

    /**
     * 公布预览导出
     */
    public function publishExportBefore($ids) {
        $where = [];
        $where[] = ["id", "in", explode(",", $ids)];
        $list = ttcModel::where($where)->select()->toArray();
        if (!$list) {
            $response->msg = "系统错误，请联系管理员";
            return $response;
        }
        $oldIdentifyConditions = [];
        $newIdentifyConditions = [];

        $columns = ["序号", "批次", "姓名", "工作单位", "申请认定时间", "本人具备的认定条件", "拟认定人才层次", "审核状态", "备注"];
        $rows = [];
        $levelMap = DictApi::selectByParentCode("talent_arrange");
        for ($i = 0; $i < count($list); $i++) {
            $obj = $list[$i];
            $description = $obj["description"];
            $stateName = "";
            $whereLastLog = [];
            $whereLastLog[] = ["step", "=", 3];
            $whereLastLog[] = ["state", "<>", 8];
            if ($obj["checkState"] == MainState::NOTPASS) {
                $lastLog = TalentLogApi::getLastLogEx($obj["id"], ProjectState::LEVELCHANGE, 0, $whereLastLog);
                if ($lastLog && $lastLog["state"] == MainState::NOTPASS) {
                    $description = $lastLog["description"];
                }
                if (\StrUtil::isNotEmpAndNull($obj["outMsg"])) {
                    $description = !$obj["description"] ? "" : $obj["description"] . $obj["outMsg"];
                }
                $stateName = "审核不通过";
            }
            if ($obj["checkState"] == MainState::PASS) {
                $stateName = "审核通过";
            }

            $identifyConditionZH = "";
            if (strlen($obj["newIdentifyCondition"]) == 19) {
                if (!$oldIdentifyConditions) {
                    $oldIdentifyConditions = Db::table("un_identify_condition")->where("type", $this->user["type"])->column("name", "id");
                }
                $identifyConditionZH = $oldIdentifyConditions[$obj["newIdentifyCondition"]];
            } else {
                if (!$newIdentifyConditions) {
                    $newIdentifyConditions = Db::table("new_talent_condition")->where("type", $this->user["type"])->column("name", "id");
                }
                $identifyConditionZH = $newIdentifyConditions[$obj["newIdentifyCondition"]];
            }

            $rows[] = [
                $i + 1, $obj["publicBatch"], $obj["talentName"], $obj["enterpriseName"], $obj["newIdentifyMonth"], $identifyConditionZH, $levelMap[$obj["newTalentArrange"]], $stateName, $description
            ];
        }
        $filename = "人才层次变更公布名单导出";
        if ($rows) {
            export($columns, $rows, $filename);
            exit();
        }
        echo "<script>parent.layer.alert('没有可以导出的数据');</script>";
    }

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

        $params = $this->request->param();
        $columns = ["序号", "姓名", "工作单位", "公布入选月份", "本人具备的认定条件", "认定人才层次", "审核状态", "备注"];
        $startTime = $params["startTime"];
        $endTime = $params["endTime"];
        if (!strtotime($startTime) || !strtotime($endTime))
            return json(["msg" => "时间格式错误"]);
        $where = [];
        $where[] = ["createTime", ">=", "2022-10-01 00:00:00"];
        $where[] = ["type", "=", $this->user["type"]];
        $where[] = ["newIdentifyMonth", "between", [$startTime, $endTime]];
        $list = ttcModel::where($where)->order("newIdentifyMonth")->select()->toArray();
        if (!$list) {
            $response->msg = "所选时间段内无公布数据";
            return \StrUtil::back($response, "TalentTypeChange.callBack");
        }

        $oldIdentifyConditions = [];
        $newIdentifyConditions = [];

        $rows = [];
        $i = 1;
        $talentArranges = DictApi::selectByParentCode("talent_arrange");
        for ($i = 0; $i < count($list); $i++) {
            $item = $list[$i];
            $whereLastLog = [];
            $whereLastLog[] = ["step", "=", 3];
            $whereLastLog[] = ["state", "<>", 8];
            $description = $item["description"];
            $stateName = "";
            if ($item["checkState"] == MainState::NOTPASS) {
                $lastLog = TalentLogApi::getLastLogEx($item["id"], ProjectState::LEVELCHANGE, 0, $whereLastLog);
                if ($lastLog && $lastLog["state"] == MainState::NOTPASS) {
                    $description = $lastLog["description"];
                }
                if (\StrUtil::isNotEmpAndNull($item["outMsg"])) {
                    $description = !$item["description"] ? "" : $item["description"] . $item["outMsg"];
                }
                $stateName = "审核不通过";
            }
            if ($item["checkState"] == MainState::PASS) {
                $stateName = "审核通过";
            }

            $identifyConditionZH = "";
            if (strlen($item["newIdentifyCondition"]) == 19) {
                if (!$oldIdentifyConditions) {
                    $oldIdentifyConditions = Db::table("un_identify_condition")->where("type", $this->user["type"])->column("name", "id");
                }
                $identifyConditionZH = $oldIdentifyConditions[$item["newIdentifyCondition"]];
            } else {
                if (!$newIdentifyConditions) {
                    $newIdentifyConditions = Db::table("new_talent_condition")->where("type", $this->user["type"])->column("name", "id");
                }
                $identifyConditionZH = $newIdentifyConditions[$item["newIdentifyCondition"]];
            }

            $row = [
                $i + 1, $item["talentName"], $item["enterpriseName"], $item["newIdentifyMonth"], $identifyConditionZH, $talentArranges[$item["newTalentArrange"]], $stateName, $description
            ];
            $rows[] = $row;
        }
        if ($rows) {
            $filename = "人才层次变更公布导出";
            export($columns, $rows, $filename);
            exit();
        }
        $response->msg = "所选时间段内无公示数据";
        return \StrUtil::back($response, "TalentTypeChange.callBack");
    }

    /**
     * 撤销公布
     */
    public function canclePublish($id) {
        $response = new \stdClass();
        $response->code = 500;
        if (\StrUtil::isEmpOrNull($id)) {
            $response->msg = "请选择需要撤销公布的数据";
            return $response;
        }
        $info = ttcModel::find($id);
        if ($info["isPublic"] != 5) {
            $response->msg = "该数据未处于待发证状态，无法撤销";
            return $response;
        }
        try {
            $data["id"] = $id;
            $data["isPublic"] = 4;
            $data["newIdentifyMonth"] = "";
            //添加日志
            $log = [
                "id" => getStringId(),
                "type" => ProjectState::LEVELCHANGE,
                "mainId" => $id,
                "companyId" => $this->user["companyId"],
                "active" => 1,
                "state" => 3,
                "step" => 55,
                "stateChange" => "<span class='label label-success'>待发证</span>-><span class='label label-primary'>待公布</span>",
                "description" => "撤销公布",
                "createTime" => date("Y-m-d H:i:s"),
                "createUser" => sprintf("%s(%s)", $this->user["account"], $this->user["companyName"] ?: $this->user["rolename"])
            ];
            $res1 = Db::table("new_talent_checklog")->insert($log);
            $res2 = Db::table("un_talent_type_change")->update($data);
            if ($res1 && $res2) {
                Db::commit();
                $response->code = 200;
                $response->msg = "撤销公布成功";
            } else {
                Db::rollback();
                $response->msg = "撤销公布失败";
            }
            return $response;
        } catch (\think\db\exception\DbException $e) {
            Db::rollback();
            $response->msg = "撤销公布失败：" . $e->getMessage();
            return $response;
        }
    }

    /**
     * 发证
     */
    public function sendCard() {
        $lockFile = fopen("send_certificate.lock", "a");
        if (flock($lockFile, LOCK_EX | LOCK_NB)) {//文件锁（独占）
//查询所有待发放人才码的数据
            $params = $this->request->param();
            $ids = array_filter(explode(",", $params["ids"]));
//晋江市优秀人才证书：当前年份+层次+四位递增数字
//集成电路优秀人才证书:IC+当前年份+递增四位数，如IC20190001
            Db::startTrans();
            $talent_max_no = [];
            $logList = [];
            $logList2 = [];
            $user = $this->user;
            $_prefix_type = "";
            $subindex = 5;
            switch ($user["type"]) {
                case CommonConst::ENTERPRISE_JC:
                    $_prefix_type = "IC";
                    $subindex += strlen($_prefix_type);
                    break;
            }
            try {
                $where = [];
                $where[] = ["id", "in", $ids];
                $changeList = ttcModel::where($where)->select()->toArray();
                $year = date("Y");
                $translateOldAndNewIdentifyConditionMap = Db::table("un_identify_condition")->alias("o")->leftJoin("new_talent_condition n", "n.name=o.name and n.type=o.type")->where("o.type", $this->user["type"])->column("n.id", "o.id");
                foreach ($changeList as $change) {
                    if ($change["checkState"] != MainState::PASS || $change["isPublic"] != 5) {
                        Db::rollback();
                        return json(["msg" => "只能对公布通过的对象发放人才码，请核查待发放人才码名单后再重新发放人才码"]);
                    }
                    if (strlen($change["talentId"]) == 19) {
                        $newInfo = ttcApi::getOne($id);
                        if ($newInfo) {
                            $change["talentId"] = $newInfo["talentId"];
                            $change["newIdentifyCondition"] = $newInfo["newIdentifyCondition"];
                        }
                    }
                    $no_prefix = $_prefix_type . $year . $change["newTalentArrange"];
                    $where = [];
                    $where[] = ["certificateNo", "like", $no_prefix . "%"];
                    $max_no = $talent_max_no[$change["newTalentArrange"]] ?: Db::table("new_talent_info")->where($where)->max("certificateNo", false);
                    if (!$max_no) {
                        $max_no = $no_prefix . "0001";
                    } else {
                        $new_no = intval(substr($max_no, $subindex)) + 1;
                        $max_no = $no_prefix . str_pad($new_no, 4, "0", STR_PAD_LEFT);
                    }
                    $data["id"] = $change["talentId"];
                    $data["talent_arrange"] = $change["newTalentArrange"];
                    $identifyCondition = $change["newIdentifyCondition"];
                    if (strlen($identifyCondition) == 19) {
                        $identifyCondition = $translateOldAndNewIdentifyConditionMap[$identifyCondition];
                    }
                    $data["talent_condition"] = $identifyCondition;
                    $data["identifyConditionName"] = $change["newIdentifyConditionName"];
                    $data["source"] = $change["newSource"];
                    $data["source_city"] = $change["newFromCity"];
                    $data["source_county"] = $change["newFromCounty"];
                    $data["annual_salary"] = $change["newAnnualSalary"];
                    $data["import_way"] = $change["newIntroductionMode"];
                    $data["apply_year"] = $change["newYear"];
                    $data["identifyGetTime"] = $change["newIdentifyGetTime"];
                    $data["identifyExpireTime"] = $change["newIdentifyOutTime"];
                    $data["certificateNo"] = $max_no;
                    $data["certificateGetTime"] = $change["newCertificateStartTime"];
                    $data["certificateExpireTime"] = $change["newCertificateOutTime"];
                    $data["identifyMonth"] = $change["newIdentifyMonth"];
                    $data["isEffect"] = 1;
                    Db::table("new_talent_info")->update($data);

                    //写入日志
                    $talentLog["id"] = getStringId();
                    $talentLog["active"] = 1;
                    $talentLog["step"] = 20;
                    $talentLog["type"] = ProjectState::TALENT;
                    $talentLog["mainId"] = $change["talentId"];
                    $talentLog["description"] = "人才层次变更通过，同步到人才库";
                    $talentLog["createUser"] = sprintf("%s(%s)", $user["account"], $user["companyName"] ?: $user["rolename"]);
                    $talentLog["createTime"] = date("Y-m-d H:i:s");
                    $logList2[] = $talentLog;

                    $updChangeData["id"] = $change["id"];
                    $updChangeData["isPublic"] = 6;
                    $updChangeData["newCertificateNO"] = $max_no;
                    Db::table("un_talent_type_change")->update($updChangeData);
                    //写入日志
                    $log["id"] = getStringId();
                    $log["state"] = 3;
                    $log["type"] = ProjectState::LEVELCHANGE;
                    $log["step"] = 8;
                    $log["mainId"] = $change["id"];
                    $log["companyId"] = $user["companyId"];
                    $log["active"] = 1;
                    $log["stateChange"] = "<span class='label label-success'>待发证</span>-><span class='label label-primary'>已发证</span>";
                    $log["description"] = "人才码为：" . $max_no;
                    $log["createUser"] = sprintf("%s(%s)", $user["account"], $user["companyName"] ?: $user["rolename"]);
                    $log["createTime"] = date("Y-m-d H:i:s");
                    $logList[] = $log;

                    $talent_max_no[$change["newTalentArrange"]] = $max_no;
                }
                Db::table("new_talent_checklog")->insertAll($logList2);
                Db::table("new_talent_checklog")->insertAll($logList);
                Db::commit();
                if ($user["type"] == 2) {
                    //办法上只写电路人才，所以暂时只给电路增加基础分
                    $_ids = array_column($changeList, "id");
                    for ($i = 0; $i < count($_ids); $i++) {
                        queue("app\job\Talent", ["type" => 5, "id" => $_ids[$i]]);
                    }
                }
                return json(["code" => 200, "msg" => "发放人才码成功"]);
            } catch (\Exception $e) {
                Db::rollback();
                return json(["msg" => "发放人才码失败：" . $e->getMessage()]);
            }
            flock($lockFile, LOCK_UN);
        } else {
            return json(["msg" => "同一时间只能有一个管理员进行发放人才码操作"]);
        }
    }

    public function commonExport() {
        $response = new \stdClass();
        $response->code = 500;
        $where = [];
        //$whereRaw = "length(talentId) <> 19";
        $request = $this->request;
        $talentName = \StrUtil::getRequestDecodeParam($request, "talentName");
        $idCard = \StrUtil::getRequestDecodeParam($request, "idCard");
        $enterpriseName = \StrUtil::getRequestDecodeParam($request, "enterpriseName");
        $oldTalentArrange = \StrUtil::getRequestDecodeParam($request, "oldTalentArrange");
        $oldIdentifyCondition = \StrUtil::getRequestDecodeParam($request, "oldIdentifyCondition");
        $newTalentArrange = \StrUtil::getRequestDecodeParam($request, "newTalentArrange");
        $newIdentifyCondition = \StrUtil::getRequestDecodeParam($request, "newIdentifyCondition");
        $checkStateStr = \StrUtil::getRequestDecodeParam($request, "checkState");
        $isPublicStr = \StrUtil::getRequestDecodeParam($request, "isPublic");
        $process = intval(\StrUtil::getRequestDecodeParam($request, "process"));
        $oldIdentifyMonth = \StrUtil::getRequestDecodeParam($request, "oldIdentifyMonth");
        $newIdentifyMonth = \StrUtil::getRequestDecodeParam($request, "newIdentifyMonth");
        $oldYearStr = \StrUtil::getRequestDecodeParam($request, "oldYear");
        $newYearStr = \StrUtil::getRequestDecodeParam($request, "newYear");
        $checkState = null;
        $isPublic = null;
        $oldYear = null;
        $newYear = null;
        if (\StrUtil::isNotEmpAndNull($checkStateStr)) {
            $checkState = intval($checkStateStr);
        }
        if (\StrUtil::isNotEmpAndNull($isPublicStr)) {
            $isPublic = intval($isPublicStr);
        }
        if (\StrUtil::isNotEmpAndNull($oldYearStr)) {
            $oldYear = intval($oldYearStr);
        }
        if (\StrUtil::isNotEmpAndNull($newYearStr)) {
            $newYear = intval($newYearStr);
        }
        $filters = [
            "talentName" => $talentName,
            "idCard" => $idCard,
            "enterpriseName" => $enterpriseName,
            "oldTalentArrange" => $oldTalentArrange,
            "oldIdentifyCondition" => $oldIdentifyCondition,
            "newTalentArrange" => $newTalentArrange,
            "newIdentifyCondition" => $newIdentifyCondition,
            "checkState" => $checkState,
            "isPublic" => $isPublic,
            "oldYear" => $oldYear,
            "newYear" => $newYear,
            "oldIdentifyMonth" => $oldIdentifyMonth,
            "newIdentifyMonth" => $newIdentifyMonth,
        ];
        $this->setTalentTypeChange($where, $filters);
        $this->setTypeChangeCheckStateCondition($where, $filters, $process);
        switch ($process) {
            case -1:
                $where[] = ["type", "=", $this->user["type"]];
                $where[] = ["createTime", ">=", "2022-10-01 00:00:00"];
                $company = \app\common\api\CompanyApi::getOne($this->user["companyId"]);
                $where[] = ["beforeCheckCompany", "EXP", Db::raw("is not null")];
                if ($this->user["code"] != $company["code"]) {
                    $where[] = ["beforeCheckCompany", "=", $company["id"]];
                }
                break;
            case 1:
                $where[] = ["type", "=", $this->user["type"]];
                $where[] = ["checkState", "not in", [3, 5]];
                $where[] = ["createTime", ">=", "2022-10-01 00:00:00"];
                break;
            case 2:
                //$where[] = ["ttc.type", "=", $this->user["type"]];
                if (ttcApi::chkUserInSuperDeptUsers()) {
                    $where[] = ["ttc.type", "=", $this->user["type"]];
                } else {
                    $companyId = $this->user["companyId"];
                    $where[] = ["td.companyId", "=", $companyId];
                }
                $where[] = ["td.type", "=", ProjectState::LEVELCHANGE];
                $where[] = ["ttc.createTime", ">=", "2022-10-01 00:00:00"];
                switch ($checkState) {
                    case 1:
                    case 2:
                    case 3:
                        $where[] = ["td.state", "=", $checkState];
                        break;
                    case 5:
                        $where[] = ["ttc.highProcess", ">=", 2];
                        $where[] = ["td.state", "=", 1];
                        break;
                }
                $list = ttcModel::alias("ttc")->field("ttc.*,td.companyId,td.state as depState")->leftJoin("un_talent_depcheckstate td", "td.mainId=ttc.id")->where($where)->select()->toArray();
                break;
            case 3:
                $where[] = ["type", "=", $this->user["type"]];
                $where[] = ["createTime", ">=", "2022-10-01 00:00:00"];
                $whereRaw = "firstDepPassTime is not null or (checkCompanyIds is null and highProcess >=1)";
                break;
            case 4:
                $where[] = ["type", "=", $this->user["type"]];
                $where[] = ["checkState", "in", [-1, 35]];
                $where[] = ["createTime", ">=", "2022-10-01 00:00:00"];
                break;
            case 5:
                $where[] = ["type", "=", $this->user["type"]];
                $where[] = ["checkState", "=", 35];
                $where[] = ["isPublic", "=", 6];
                $where[] = ["createTime", ">=", "2022-10-01 00:00:00"];
                break;
        }
        if ($process != 2) {
            if ($whereRaw) {
                $list = ttcModel::where($where)->whereRaw($whereRaw)->select()->toArray();
            } else {
                $list = ttcModel::where($where)->select()->toArray();
            }
            $columns = [
                "姓名", "证件号码", "工作单位", "所属街道", "原申报年度", "原申报来源", "原入选来源地级市", "原入选来源县市区", "原人才层次", "原认定条件", "原认定条件证书取得时间", "原认定条件过期时间", "原认定条件名称",
                "原泉州高层次人才证书发证日期", "原泉州高层次人才证书的有效期", "原引进方式", "原公布入选月份", "原人才编号", "新申报年度", "新申报来源", "新入选来源地级市", "新入选来源县市区",
                "新人才层次", "新认定条件", "新认定条件证书取得时间", "新认定条件过期时间", "新认定条件名称",
                "新泉州高层次人才证书发证日期", "新泉州高层次人才证书的有效期", "新引进方式", "新公布入选月份", "新人才编号",
                "审核状态", "公示状态"
            ];
        } else {
            $columns = [
                "姓名", "证件号码", "工作单位", "所属街道", "原申报年度", "原申报来源", "原入选来源地级市", "原入选来源县市区", "原人才层次", "原认定条件", "原认定条件证书取得时间", "原认定条件过期时间", "原认定条件名称",
                "原泉州高层次人才证书发证日期", "原泉州高层次人才证书的有效期", "原引进方式", "原公布入选月份", "原人才编号", "新申报年度", "新申报来源", "新入选来源地级市", "新入选来源县市区",
                "新人才层次", "新认定条件", "新认定条件证书取得时间", "新认定条件过期时间", "新认定条件名称",
                "新泉州高层次人才证书发证日期", "新泉州高层次人才证书的有效期", "新引进方式", "新公布入选月份", "新人才编号",
                "审核单位", "审核状态", "公示状态"
            ];
        }
        $list = $this->translateToChinese($list, $process);
        $rows = [];
        foreach ($list as $item) {
            if ($item["companyId"]) {
                $rows[] = [
                    $item["talentName"], $item["idCard"], $item["enterpriseName"], $item["streetName"], $item["oldYear"], $item["oldSourceName"], $item["oldFromCityName"], $item["oldFromCountyName"],
                    $item["oldTalentArrangeName"], $item["oldIdentifyConditionCH"], $item["oldIdentifyGetTime"], $item["oldIdentifyOutTime"], $item["oldIdentifyConditionName"],
                    $item["oldCertificateStartTime"], $item["oldCertificateOutTime"], $item["oldIntroductionModeName"], $item["oldIdentifyMonth"], $item["oldCertificateNO"],
                    $item["newYear"], $item["newSourceName"], $item["newFromCityName"], $item["newFromCountyName"],
                    $item["newTalentArrangeName"], $item["newIdentifyConditionCH"], $item["newIdentifyGetTime"], $item["newIdentifyOutTime"], $item["newIdentifyConditionName"],
                    $item["newCertificateStartTime"], $item["newCertificateOutTime"], $item["newIntroductionModeName"], $item["newIdentifyMonth"], $item["newCertificateNO"],
                    getCacheById("Company", $item["companyId"], "name"), $item["checkStateName"], $item["isPublicName"]
                ];
            } else {
                $rows[] = [
                    $item["talentName"], $item["idCard"], $item["enterpriseName"], $item["streetName"], $item["oldYear"], $item["oldSourceName"], $item["oldFromCityName"], $item["oldFromCountyName"],
                    $item["oldTalentArrangeName"], $item["oldIdentifyConditionCH"], $item["oldIdentifyGetTime"], $item["oldIdentifyOutTime"], $item["oldIdentifyConditionName"],
                    $item["oldCertificateStartTime"], $item["oldCertificateOutTime"], $item["oldIntroductionModeName"], $item["oldIdentifyMonth"], $item["oldCertificateNO"],
                    $item["newYear"], $item["newSourceName"], $item["newFromCityName"], $item["newFromCountyName"],
                    $item["newTalentArrangeName"], $item["newIdentifyConditionCH"], $item["newIdentifyGetTime"], $item["newIdentifyOutTime"], $item["newIdentifyConditionName"],
                    $item["newCertificateStartTime"], $item["newCertificateOutTime"], $item["newIntroductionModeName"], $item["newIdentifyMonth"], $item["newCertificateNO"],
                    $item["checkStateName"], $item["isPublicName"]
                ];
            }
        }
        $filename = "人才层次变更导出";
        if ($rows) {
            export($columns, $rows, $filename);
            exit();
        } else {
            echo "<script>parent.layer.alert('没有可以导出的数据');window.history.go(-1);</script>";
        }
    }

    private function setTalentTypeChange(&$where, $data) {
        if (\StrUtil::isNotEmpAndNull($data["talentName"])) {
            $where[] = ["talentName", "like", "%{$data["talentName"]}%"];
        }
        if (\StrUtil::isNotEmpAndNull($data["enterpriseName"])) {
            $where[] = ["enterpriseId", "=", $data["enterpriseName"]];
        }
        if (\StrUtil::isNotEmpAndNull($data["idCard"])) {
            $where[] = ["idCard", "like", "%{$data["idCard"]}%"];
        }
        if (\StrUtil::isNotEmpAndNull($data["oldTalentArrange"])) {
            $where[] = ["oldTalentArrange", "=", $data["oldTalentArrange"]];
        }
        if (\StrUtil::isNotEmpAndNull($data["newTalentArrange"])) {
            $where[] = ["newTalentArrange", "=", $data["newTalentArrange"]];
        }
        if (\StrUtil::isNotEmpAndNull($data["oldIdentifyCondition"])) {
            $where[] = ["oldIdentifyCondition", "=", $data["oldIdentifyCondition"]];
        }
        if (\StrUtil::isNotEmpAndNull($data["newIdentifyCondition"])) {
            $where[] = ["newIdentifyCondition", "=", $data["newIdentifyCondition"]];
        }
        if (\StrUtil::isNotEmpAndNull($data["newIdentifyMonth"])) {
            $where[] = ["oldIdentifyMonth", "=", $data["oldIdentifyMonth"]];
        }
        if (\StrUtil::isNotEmpAndNull($data["newIdentifyMonth"])) {
            $where[] = ["newIdentifyMonth", "=", $data["newIdentifyMonth"]];
        }
        if ($data["isPublic"]) {
            $where[] = ["isPublic", "=", $data["isPublic"]];
        }
        if ($data["oldYear"]) {
            $where[] = ["oldYear", "=", $data["oldYear"]];
        }
        if ($data["newYear"]) {
            $where[] = ["newYear", "=", $data["newYear"]];
        }
    }

    private function setTypeChangeCheckStateCondition(&$where, &$data, $process) {
        $checkState = $data["checkState"];
        if ($checkState) {
            switch ($process) {
                case -1:
                    if ($checkState == MainState::NEED_FIRST_CHECK) {
                        $where[] = ["checkState", ">=", $checkState];
                    } else {
                        $where[] = ["checkState", "=", $checkState];
                    }
                    break;
                case 1:
                    if ($checkState == MainState::NEED_DEP_CHECK) {
                        $where[] = ["checkState", "in", [15, 25, 30, 35]];
                    } else if ($checkState == MainState::BEFORE_REJECT) {
                        $where[] = ["checkState", "=", MainState::NEED_FIRST_CHECK];
                        $where[] = ["highProcess", ">=", 1];
                    } else if ($checkState == MainState::NEED_FIRST_CHECK) {
                        $where[] = ["checkState", "=", MainState::NEED_FIRST_CHECK];
                        $where[] = ["highProcess", "<", 1];
                    } else {
                        $where[] = ["checkState", "=", $checkState];
                    }
                    break;
                case 2:
                    if ($checkState == MainState::BEFORE_REJECT) {
                        $data["highProcess"] = 2;
                        $data["checkState"] = 1;
                    }
                    break;
                case 3:
                    if ($checkState == MainState::THIRD_REJECT) {
                        $where[] = ["checkState", "in", [7, 10, 15, 20, 30]];
                    } else if ($checkState == MainState::BEFORE_REJECT) {            //重新提交
                        $where[] = ["checkState", "=", MainState::NEED_THIRD];
                        $where[] = ["highProcess", ">=", 3];
                    } else if ($checkState == MainState::NEED_THIRD) {               //待复核
                        $where[] = ["checkState", "=", $checkState];
                        $where[] = ["highProcess", "<", 3];
                    } else {
                        $where[] = ["checkState", "=", $checkState];
                    }
                    break;
                case 4:
                    $where[] = ["checkState", "=", $checkState];
                    break;
                case 5:
                    break;
            }
        }
    }

    private function translateToChinese($list, $process) {
        //获取字典表人才层次
        $sourceMap = DictApi::selectByParentCode("source");
        $levelMap = DictApi::selectByParentCode("talent_arrange");
        $importWayMap = DictApi::selectByParentCode("import_way");
        $streetMap = DictApi::selectByParentCode("street");
        $newIdentifyConditions = Db::table("new_talent_condition")->where("type", $this->user["type"])->column("name", "id");
        $oldIdentifyConditions = Db::table("un_identify_condition")->where("type", $this->user["type"])->column("name", "id");
        $whereEp = [];
        $whereEp[] = ["id", "in", array_column($list, "enterpriseId")];
        $enterpriseList = \app\common\model\Enterprise::where($whereEp)->column("street", "id");
        foreach ($list as &$talentTypeChange) {
            $talentTypeChange["oldSourceName"] = $sourceMap[$talentTypeChange["oldSource"]] ?: "无";
            $talentTypeChange["newSourceName"] = $sourceMap[$talentTypeChange["newSource"]] ?: "无";
            $talentTypeChange["oldTalentArrangeName"] = $levelMap[$talentTypeChange["oldTalentArrange"]];
            $talentTypeChange["newTalentArrangeName"] = $levelMap[$talentTypeChange["newTalentArrange"]];
            $talentTypeChange["oldIntroductionModeName"] = $importWayMap[$talentTypeChange["oldIntroductionMode"]];
            $talentTypeChange["newIntroductionModeName"] = $importWayMap[$talentTypeChange["newIntroductionMode"]];
            if (strlen($talentTypeChange["oldIdentifyCondition"]) == 19) {
                $talentTypeChange["oldIdentifyConditionCH"] = $oldIdentifyConditions[$talentTypeChange["oldIdentifyCondition"]];
            } else {
                $talentTypeChange["oldIdentifyConditionCH"] = $newIdentifyConditions[$talentTypeChange["oldIdentifyCondition"]];
            }
            if (strlen($talentTypeChange["newIdentifyCondition"]) == 19) {
                $talentTypeChange["newIdentifyConditionCH"] = $oldIdentifyConditions[$talentTypeChange["newIdentifyCondition"]];
            } else {
                $talentTypeChange["newIdentifyConditionCH"] = $newIdentifyConditions[$talentTypeChange["newIdentifyCondition"]];
            }
            switch ($talentTypeChange["isPublic"]) {
                case 1:
                    $talentTypeChange["isPublicName"] = "待核查征信";
                    break;
                case 2:
                    $talentTypeChange["isPublicName"] = "待公示";
                    break;
                case 3:
                    $talentTypeChange["isPublicName"] = "公示中";
                    break;
                case 4:
                    $talentTypeChange["isPublicName"] = "待发布";
                    break;
                case 5:
                    $talentTypeChange["isPublicName"] = "待发证";
                    break;
                case 6:
                    $talentTypeChange["isPublicName"] = "已发证";
                    break;
            }
            $talentTypeChange["streetName"] = $streetMap[$enterpriseList[$talentTypeChange["enterpriseId"]]];
            if ($process != null) {
                switch ($process) {
                    case -1:
                        break;
                    case 1:
                        if ($talentTypeChange["checkState"] == -1) {
                            $talentTypeChange["checkStateName"] = "审核不通过";
                        } else if ($talentTypeChange["checkState"] == 1) {
                            $talentTypeChange["checkStateName"] = "待提交";
                        } else if ($talentTypeChange["checkState"] == 10) {
                            $talentTypeChange["checkStateName"] = "已驳回";
                        } else if ($talentTypeChange["checkState"] == 15 || $talentTypeChange["checkState"] >= 25) {
                            $talentTypeChange["checkStateName"] = "待提交";
                        } else if ($talentTypeChange["checkState"] == 7) {
                            $talentTypeChange["checkStateName"] = ($talentTypeChange["highProcess"] != null && $talentTypeChange["highProcess"] >= 1) ? "重新提交" : "待审核";
                        } else if ($talentTypeChange["checkState"] == 20) {
                            $talentTypeChange["checkStateName"] = ($talentTypeChange["highProcess"] != null && $talentTypeChange["highProcess"] >= 1) ? "上级驳回" : "待审核";
                        }
                        break;
                    case 2:
                        if ($talentTypeChange["depState"] == 1)
                            $talentTypeChange["checkStateName"] = "待审核";
                        if ($talentTypeChange["depState"] == 2)
                            $talentTypeChange["checkStateName"] = "已驳回";
                        if ($talentTypeChange["depState"] == 3)
                            $talentTypeChange["checkStateName"] = "已通过";
                        break;
                    case 3:
                        if ($talentTypeChange["checkState"] == -1) {
                            $talentTypeChange["checkStateName"] = "审核不通过";
                        } else if ($talentTypeChange["checkState"] == 25) {
                            $talentTypeChange["checkStateName"] = ($talentTypeChange["highProcess"] != null && $talentTypeChange["highProcess"] >= 3) ? "重新提交" : "待审核";
                        } else if ($talentTypeChange["checkState"] == 30 || $talentTypeChange["checkState"] <= 20) {
                            $talentTypeChange["checkStateName"] = "已驳回";
                        } else if ($talentTypeChange["checkState"] == 35) {
                            $talentTypeChange["checkStateName"] = "已通过";
                        }
                        break;
                    case 4:
                        if ($talentTypeChange["checkState"] == -1) {
                            $talentTypeChange["checkStateName"] = "审核不通过";
                        } else if ($talentTypeChange["checkState"] == 35) {
                            $talentTypeChange["checkStateName"] = "已通过";
                        }
                        break;
                }
            }
        }unset($talentTypeChange);
        return $list;
    }

}
