<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace app\enterprise\controller;

use app\enterprise\common\EnterpriseController;
use app\common\state\CommonConst;
use app\common\api\BatchApi;
use app\common\api\TalentAllowanceApi;
use app\common\state\ProjectState;
use app\common\api\DictApi;
use app\common\state\MainState;
use app\common\model\TalentAllowance as TaModel;
use app\common\state\AllowanceProjectEnum;
use app\common\model\TalentChecklog;
use think\facade\Db;
use app\common\api\Response;
use app\common\api\UploadApi;
use app\enterprise\model\TalentTypeChange;
use app\common\state\AllowanceTypeEnum;
use app\common\state\AllowanceStateEnum;

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

    public function index() {
        $tpl = "";
        switch ($this->user["type"]) {
            case CommonConst::ENTERPRISE_WJ:
            case CommonConst::ENTERPRISE_GJ:
            case CommonConst::ENTERPRISE_JC:
                $tpl = "indexIC";
                break;
        }
        $templateFile = "gjjbtbiao.xlsx";
        if ($this->user["type"] == CommonConst::ENTERPRISE_GJ) {
            $need_extra_project = getJsonConfig("../sys_config.json", "talent_allowance_need_extra_project");
            if ($need_extra_project[$this->user["uid"]]) {
                if ($need_extra_project[$this->user["uid"]][1] == AllowanceProjectEnum::PROJECT_TRAINING_PROGRAM) {
                    $templateFile = "gjjbtbiao_2.xlsx";
                } else {
                    $templateFile = "gjjbtbiao_1.xlsx";
                }
            }
        }
        return view($tpl, ['type' => $this->user["type"], "templateFile" => $templateFile]);
    }

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

    public function calculator($id) {
        $cal = TalentAllowanceApi::validateAllowanceType($id);
        return json($cal);
    }

    /**
     * 申请
     */
    public function apply(\think\Request $request) {
        $param = $request->param();
        $id = isset($param["id"]) ? $param["id"] : 0;
        $info = null;
        if ($id) {
            $info = TalentAllowanceApi::getInfoById($id);
            $this->translateToChinese($info);
        }
        if ($request->isPost()) {
            return $this->save($info, $request);
        }
        $batch = $info["year"] ?: BatchApi::getValidBatch(ProjectState::JBT, $this->user["type"])["batch"];
        if ($this->user["type"] == CommonConst::ENTERPRISE_GJ) {
            $need_choose_post_type = getJsonConfig("../sys_config.json", "talent_allowance_need_choose_post_type");
            $need_choose_institution = getJsonConfig("../sys_config.json", "talent_allowance_need_choose_institution");
            if ($need_choose_post_type[$this->user["uid"]]) {
                $postTypes = DictApi::findChildDictByCode("PostType");
                foreach ($postTypes as $key => $pt) {
                    if (!in_array($pt["code"], $need_choose_post_type[$this->user["uid"]])) {
                        unset($postTypes[$key]);
                    }
                }
            }
            if (in_array($this->user["uid"], $need_choose_institution)) {
                $institutions = DictApi::findChildDictByCode("institution");
            }
        }
        return view("", ["year" => $batch, "type" => $this->user["type"], "row" => $info, "postTypes" => $postTypes, "institutions" => $institutions]);
    }

    /**
     * 批量提交申请
     * @return Response
     */
    public function batchApply() {
        $ids = $this->request["ids"];
        $ids = array_filter(explode(",", $ids));
        $allowanceType = $this->request["allowanceType"];

        $batch = BatchApi::getValidBatch(ProjectState::JBT, $this->user["type"])["batch"];
        if (!$batch) {
            return new Response(Response::ERROR, "当前并无有效的申报批次进行中");
        }

        for ($i = 0; $i < count($ids); $i++) {
            queue("app\job\TalentAllowance", ["type" => 1, "method" => 1, "talentId" => $ids[$i], "enterprise" => $this->user, "year" => $batch, "allowanceType" => $allowanceType]);
        }
        return new Response(Response::SUCCESS, "已经成功添加到计划任务，请稍候查看申报列表进行确认");
    }

    /**
     * 批量导入申请
     * @return Response
     */
    public function batchImportApply() {
        $maxFileSize = 10; //mb
        $tmp = $this->request->file("file");

        $batch = BatchApi::getValidBatch(ProjectState::JBT, $this->user["type"])["batch"];
        if (!$batch) {
            return \StrUtil::back(new Response(Response::ERROR, "当前并无有效的申报批次进行中"), "TalentAllowanceInfo.importCallBack");
        }
        if (!$tmp) {
            return \StrUtil::back(new Response(Response::ERROR, "没有上传批量申请文档"), "TalentAllowanceInfo.importCallBack");
        }
        if (!isExcelFile($tmp->getMime())) {
            //return \StrUtil::back(new Response(Response::ERROR, "只能识别Excel文档"), "TalentAllowanceInfo.importCallBack");
        }
        if (round($tmp->getSize() / 1024 / 1024, 2) > $maxFileSize) {
            return \StrUtil::back(new Response(Response::ERROR, "文档大小不能超过10MB"), "TalentAllowanceInfo.importCallBack");
        }
        $filepath = $tmp->getPathname();
        try {
            $rows = getExcelDatas($filepath);
        } catch (\PhpOffice\PhpSpreadsheet\Exception $e) {
            return \StrUtil::back(new Response(Response::ERROR, "文件识别错误！"), "TalentAllowanceInfo.importCallBack");
        }
        array_shift($rows); //去标题行
        //检查excel文件有没有问题
        $checkMonths = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
        $need_extra_project = getJsonConfig("../sys_config.json", "talent_allowance_need_extra_project");
        if ($this->user["type"] == CommonConst::ENTERPRISE_GJ) {
            $titles = ["姓名", "身份证", "申请补贴类型", "个税缴纳月份", "工资发放月份", "考勤情况", "养老保险"];
            if ($need_extra_project[$this->user["uid"]]) {
                for ($i = 0; $i < count($need_extra_project[$this->user["uid"]]); $i++) {
                    $titles[] = AllowanceProjectEnum::getProjectName($need_extra_project[$this->user["uid"]][$i]);
                }
            }
        } else {
            $titles = ["姓名", "身份证", "申请补贴类型", "个税缴纳月份", "工资发放月份", "考勤情况", "养老保险", "失业保险", "医疗保险"];
        }
        $allowanceTypes = ["工作津贴", "一次性交通补贴"];
        $idCards = [];
        foreach ($rows as $key => $row) {
            $no = $key + 2;
            $idCard = trim($row[1]);
            $allowanceType = trim($row[2]);
            if (!$idCard) {
                return \StrUtil::back(new Response(Response::ERROR, sprintf("第%d行身份证不能放空，请仔细检查内容完整后再重新提交", $no)), "TalentAllowanceInfo.importCallBack");
            }
            if (in_array($idCard, $idCards)) {
                return \StrUtil::back(new Response(Response::ERROR, sprintf("第%d行身份证存在重复，请请仔细检查内容无误后再重新提交", $no)), "TalentAllowanceInfo.importCallBack");
            } else {
                $idCards[] = $idCard;
            }
            if (!in_array($allowanceType, $allowanceTypes)) {
                return \StrUtil::back(new Response(Response::ERROR, sprintf("第%d行申请补贴类型错误，请仔细检查内容无误后再重新提交", $no)), "TalentAllowanceInfo.importCallBack");
            }
            if ($allowanceType == "工作津贴") {
                $projects = AllowanceProjectEnum::getProjectsByEnterpriseType($this->user["type"], $this->user["uid"]);
                for ($i = 3; $i < 9; $i++) {
                    $project = 1;
                    switch ($i) {
                        case 3:
                            $project = AllowanceProjectEnum::PROJECT_TAX;
                            break;
                        case 4:
                            $project = AllowanceProjectEnum::PROJECT_WAGES;
                            break;
                        case 5:
                            $project = AllowanceProjectEnum::PROJECT_ATTENDANCE;
                            break;
                        case 6:
                            $project = AllowanceProjectEnum::PROJECT_SB_PENSION;
                            break;
                        case 7:
                            if ($this->user["type"] == CommonConst::ENTERPRISE_GJ && $need_extra_project[$this->user["uid"]]) {
                                $project = $need_extra_project[$this->user["uid"]][0];
                            } else {
                                $project = AllowanceProjectEnum::PROJECT_SB_UNEMPLOYMENT;
                            }
                            break;
                        case 8:
                            if ($this->user["type"] == CommonConst::ENTERPRISE_GJ && $need_extra_project[$this->user["uid"]]) {
                                $project = $need_extra_project[$this->user["uid"]][1];
                            } else {
                                $project = AllowanceProjectEnum::PROJECT_SB_MEDICA;
                            }
                            break;
                    }
                    if (!in_array($project, $projects))
                        continue;
                    $monthstr = str_replace([" ", "，"], ",", trim($row[$i]));
                    $months = array_filter(explode(",", $monthstr));
                    if (!$months)
                        return \StrUtil::back(new Response(Response::ERROR, sprintf("第%d行%s不能为空，请仔细检查内容完整后再重新提交", $no, $titles[$i])), "TalentAllowanceInfo.importCallBack");
                    if (array_diff($months, $checkMonths))
                        return \StrUtil::back(new Response(Response::ERROR, sprintf("第%d行%s错误，请查看模板文档对应列说明修改后再重新提交", $no, $titles[$i])), "TalentAllowanceInfo.importCallBack");
                }
            } else {
                $monthstr = str_replace([" ", "，"], ",", trim($row[5]));
                $monthstr = str_replace("：", ":", $monthstr);
                $months = array_filter(explode(",", $monthstr));
                if (!$months)
                    return \StrUtil::back(new Response(Response::ERROR, sprintf("第%d行%s不能为空，请仔细检查内容完整后再重新提交", $no, $titles[5])), "TalentAllowanceInfo.importCallBack");
                foreach ($months as $m) {
                    list($a, $b) = explode(":", $m);
                    if (!in_array($a, $checkMonths) || !is_numeric($b) || $b > 31 || $b < 0)
                        return \StrUtil::back(new Response(Response::ERROR, sprintf("第%d行%s错误，请查看模板文档对应列说明修改后再重新提交", $no, $titles[5])), "TalentAllowanceInfo.importCallBack");
                }
            }
        }

        for ($i = 0; $i < count($rows); $i++) {
            queue("app\job\TalentAllowance", ["type" => 1, "method" => 2, "data" => $rows[$i], "enterprise" => $this->user, "year" => $batch, "allowanceType" => trim($rows[$i][2]) == "工作津贴" ? 1 : 2]);
        }
        return \StrUtil::back(new Response(Response::SUCCESS, "已经成功添加到计划任务，请稍候查看申报列表进行确认"), "TalentAllowanceInfo.importCallBack");
    }

    private function save($talentAllowance, \think\Request $request) {
        $response = new \stdClass();
        $response->code = 500;
        $param = $request->param();
        if (!$param) {
            $response->msg = "请填写信息后在提交";
            return $response;
        }
        if (\StrUtil::isEmpOrNull($param["talentId"])) {
            $response->msg = "请选择申报对象";
            return $response;
        }
        if (!$param["id"]) {
            $where = [];
            $where[] = ["year", "=", $param["year"]];
            $where[] = ["idCard", "=", $param["idCard"]];
            $where[] = ["delete", "=", 0];
            $where[] = ["checkState", "not in", [MainState::NOTPASS, MainState::PASS]];
            $exists = TaModel::where($where)->find();
            if ($exists) {
                $response->msg = "当前申请对象在当前批次中存在申请中的记录，请等待申请结束后再操作";
                return $response;
            }

            $user = $this->user;
            $ti = \app\common\api\VerifyApi::getTalentInfoById($param["talentId"]);
            if ($ti["talent_type"] == 1 && $ti["enterpriseType"] == CommonConst::ENTERPRISE_WJ && $param["allowanceType"] == AllowanceTypeEnum::JBT_JT) {
                $response->msg = "现有人才暂时不能申请一次性交通贴补";
                return $response;
            }
            $data = [
                "talentId" => $param["talentId"],
                "enterpriseId" => $ti["enterprise_id"],
                "enterpriseName" => $user["name"],
                "year" => $param["year"],
                "source" => $ti["source"],
                "qzgccrcActiveTime" => $ti["certificateExpireTime"],
                "talentType" => $ti["enterpriseTag"],
                "address" => $ti["street"],
                "name" => $ti["name"],
                "sex" => $ti["sex"],
                "cardType" => $ti["card_type"],
                "idCard" => $ti["card_number"],
                "firstInJJTime" => $ti["fst_work_time"],
                "entryTime" => $ti["cur_entry_time"],
                "post" => $ti["position"],
                "phone" => $ti["phone"],
                "talentArrange" => $ti["talent_arrange"],
                "identifyCondition" => $ti["talent_condition"],
                "identifyGetTime" => $ti["identifyGetTime"],
                "identifyOutTime" => $ti["identifyExpireTime"],
                "identifyConditionName" => $ti["identifyConditionName"],
                "identifyMonth" => $ti["identifyMonth"],
                "bank" => $ti["bank"],
                "bankNetwork" => $ti["bank_branch_name"],
                "bankAccount" => $ti["bank_account"],
                "bankNumber" => $ti["bank_number"],
                "checkState" => 1,
                "type" => $user["type"],
                "provinceCode" => $ti["province"],
                "provinceName" => \app\common\api\LocationApi::getNameByCode($ti["province"]),
                "cityCode" => $ti["city"],
                "cityName" => \app\common\api\LocationApi::getNameByCode($ti["city"]),
                "countyCode" => $ti["county"],
                "countyName" => \app\common\api\LocationApi::getNameByCode($ti["county"]),
                "isSupple" => 2,
                "createTime" => date("Y-m-d H:i:s"),
                "createUser" => $user["uid"],
                "id" => getStringId(),
                "wage" => $param["wage"],
                "allowanceType" => $param["allowanceType"],
                "postType" => $param["postType"] ?: 0,
                "institution" => $param["institution"] ?: 0
            ];

            $submitTime = $ti["first_submit_time"] ? $ti["first_submit_time"] : $ti["new_submit_time"];
            $identifyYear = date("Y", strtotime($submitTime));
            $year = substr($param["year"], 0, 4);
            if ((($ti["enterpriseType"] == CommonConst::ENTERPRISE_JC) || (in_array($ti["enterpriseType"], [CommonConst::ENTERPRISE_WJ, CommonConst::ENTERPRISE_GJ]) && $year != 2023)) && $identifyYear > $year) {
                $response->msg = "该人员的人才认定时间晚于申报津补贴的年份，不符合申报条件";
                return $response;
            }

            /*             * 1.获取上一年度的人才层次 */
            $arrangeList = $this->getLastYearTalentType($data, $ti);
            if (!$arrangeList) {
                if ($ti["enterpriseType"] == CommonConst::ENTERPRISE_JC) {
                    $batchYear = substr($data["year"], 0, 4);
                    $identifyYear = substr($data["identifyMonth"], 0, 4);
                    if (!$batchYear || !$identifyYear || $identifyYear > $batchYear) {
                        $response->msg = "上一年度暂无有效的人才层次";
                        return $response;
                    }
                } else {
                    $response->msg = "上一年度暂无有效的人才层次";
                    return $response;
                }
            }
            /*             * 2.获取上一年度所在单位* */
            $contractDetailList = $this->getConcatList($ti, $data, $year); //保存上一年度的工作单位
            if (!$contractDetailList) {
                $response->msg = "申报失败,原因为：申报年度不存在有效的工作单位";
                return $response;
            }
            TaModel::insert($data);
            \app\common\model\TalentAllowancecontractDetail::insertAll($contractDetailList);
            /**
             * 4.添加津补贴核查项目
             */
            //核查项目详情表
            $this->createAllowanceProject($data, $contractDetailList);
            \app\common\model\TalentAllowanceArrange::insertAll($arrangeList);
            //添加日志
            TalentChecklog::create([
                'id' => getStringId(),
                'mainId' => $data['id'],
                'type' => intval(ProjectState::JBT),
                'typeFileId' => null,
                'active' => 1,
                'state' => 1,
                'step' => 0,
                'stateChange' => "保存未提交",
                'description' => "添加津补贴申报",
                'createTime' => date("Y-m-d H:i:s", time()),
                'createUser' => sprintf("%s(%s)", $this->user["account"], $this->user["companyName"])
            ]);
            $response->msg = "保存成功";
            $response->code = 200;
            $response->obj = $data;
            return $response;
        } else {
            TaModel::update($param);
            $response->msg = "修改成功";
            $response->code = 200;
            return $response;
        }
    }

    public function getInfoByIdAndYear($id, $year) {
        $ti = \app\common\api\VerifyApi::getTalentInfoById($id);
        $data = [
            "talentId" => $id,
            "year" => $year,
            "idCard" => $ti["card_number"],
            "id" => getStringId(),
            "type" => $ti["enterpriseType"]
        ];
        $submitTime = $ti["first_submit_time"] ? $ti["first_submit_time"] : $ti["new_submit_time"];
        $identifyYear = date("Y", strtotime($submitTime));
        $year = substr($year, 0, 4);
        if ((($ti["enterpriseType"] == CommonConst::ENTERPRISE_JC) || (in_array($ti["enterpriseType"], [CommonConst::ENTERPRISE_WJ, CommonConst::ENTERPRISE_GJ]) && $year != 2023)) && $identifyYear > $year) {
            return new Response(Response::ERROR, "该人员的人才认定时间晚于申报津补贴的年份，不符合申报条件");
        }
        /*         * 1.获取上一年度的人才层次 */
        $arrangeList = $this->getLastYearTalentType($data, $ti);
        if (!$arrangeList) {
            if ($ti["enterpriseType"] == CommonConst::ENTERPRISE_JC) {
                $identifyYear = substr($ti["identifyMonth"], 0, 4);
                if (!$year || !$identifyYear || $identifyYear > $year) {
                    return new Response(Response::ERROR, "该人员上一年度暂无有效的人才层次");
                }
            } else {
                return new Response(Response::ERROR, "该人员上一年度暂无有效的人才层次");
            }
        }
        /*         * 2.获取上一年度所在单位* */
        $contractDetailList = $this->getConcatList($ti, $data, $year); //保存上一年度的工作单位
        if (!$contractDetailList) {
            return new Response(Response::ERROR, "该人员申报年度不存在有效的工作单位");
        }
        return new Response(Response::SUCCESS, "", $ti);
    }

    /**
     * 删除优秀人才津补贴
     */
    public function delete() {
        $id = $this->request["id"];
        $info = TalentAllowanceApi::getInfoById($id);
        if ($info["checkState"] != 1) {
            return new Response(Response::ERROR, "删除失败！此数据已提交审核，无法删除！");
        }
        Db::startTrans();
        try {
            /* 硬删
              //删除核查项目表
              Db::table("un_talent_allowance_project")->where("mainId", $id)->delete();
              //删除合同情况表
              Db::table("un_talent_allowancecontract_detail")->where("mainId", $id)->delete();
              //删除人才层次变更表
              Db::table("un_talent_allowance_arrange")->where("mainId", $id)->delete();
              //删除日志
              $where[] = ["mainId", "=", $id];
              $where[] = ["type", "=", ProjectState::JBT];
              Db::table("new_talent_checklog")->where($where)->delete();
              //删除主表
              Db::table("un_talent_allowance_info")->delete($id);
             * 
             */
            $data["id"] = $id;
            $data["delete"] = 1;
            $data["deleteUser"] = $this->user["uid"];
            $data["deleteTime"] = date("Y-m-d H:i:s");
            Db::table("un_talent_allowance_info")->update($data);
            Db::commit();
            return new Response(Response::SUCCESS, "删除成功");
        } catch (think\db\exception\DbException $e) {
            Db::rollback();
            return new Response(Response::ERROR, $e->getMessage());
        }
    }

    public function detail(\think\Request $request) {
        $param = $request->param();
        $id = $param["id"];
        $info = TalentAllowanceApi::getInfoById($id);
        $this->translateToChinese($info);
        if ($this->user["type"] == CommonConst::ENTERPRISE_GJ) {
            $need_choose_post_type = getJsonConfig("../sys_config.json", "talent_allowance_need_choose_post_type");
            $need_choose_institution = getJsonConfig("../sys_config.json", "talent_allowance_need_choose_institution");
            if ($need_choose_post_type[$this->user["uid"]]) {
                $postTypes = DictApi::findChildDictByCode("PostType");
                foreach ($postTypes as $key => $pt) {
                    if (!in_array($pt["code"], $need_choose_post_type[$this->user["uid"]])) {
                        unset($postTypes[$key]);
                    }
                }
            }
            if (in_array($this->user["uid"], $need_choose_institution)) {
                $institutions = DictApi::findChildDictByCode("institution");
            }
        }
        return view("", ["row" => $info, "postTypes" => $postTypes, "institutions" => $institutions]);
    }

    private function translateToChinese(&$obj) {
        if (\StrUtil::isNotEmpAndNull($obj["address"])) {
            $obj["addressName"] = DictApi::findByParentCodeAndCode("street", $obj["address"])["name"];
        }
        if (\StrUtil::isNotEmpAndNull($obj["talentType"])) {
            $obj["talentTypeName"] = DictApi::findByParentCodeAndCode("enterprise_tag", $obj["talentType"])["name"];
        }
        if (\StrUtil::isNotEmpAndNull($obj["talentArrange"])) {
            $obj["talentArrangeName"] = DictApi::findByParentCodeAndCode("talent_arrange", $obj["talentArrange"])["name"];
        }
        if (\StrUtil::isNotEmpAndNull($obj["identifyCondition"])) {
            $obj["identifyConditionText"] = \app\common\api\TalentConditionApi::getOne($obj["identifyCondition"])["name"];
        }
        if (\StrUtil::isNotEmpAndNull($obj["introductionMode"])) {
            $obj["introductionModeName"] = DictApi::findByParentCodeAndCode("import_way", $obj["introductionMode"])["name"];
        }
    }

    /*     * 获取上一年度的人才层次变更信息 */

    private function getLastYearTalentType($info, $talentInfo) {
        $year = substr($info["year"], 0, 4);
        $arrangeList = [];
        /*         * * 添加人才层次记录 */
        $oldStartTimeField = "oldIdentifyMonth";
        $newStartTimeField = "newIdentifyMonth";
        if ($info["type"] == CommonConst::ENTERPRISE_JC) {
            $oldStartTimeField = "oldIdentifyGetTime";
            $newStartTimeField = "newIdentifyGetTime";
        }
        if (in_array($info["type"], [CommonConst::ENTERPRISE_WJ]) && date("Y", strtotime($talentInfo["identifyMonth"])) == "2023") {
            $talentInfo["identifyMonth"] = "2022-12-01"; //让卫健包含2023全年
        }

        $where = [];
        $where[] = ["idCard", "=", $info["idCard"]];
        $where[] = ["checkState", "=", MainState::PASS];
        $where[] = ["isPublic", "=", 6];
        $where[] = [$oldStartTimeField, "<=", $year . "-12-31"];
        $where[] = ["createTime", ">=", "2022-10-01 00:00:00"];
        $typeList = TalentTypeChange::where($where)->field("oldTalentArrange,oldIdentifyCondition,oldIdentifyGetTime,oldIdentifyOutTime,oldIdentifyMonth,oldCertificateStartTime,oldCertificateOutTime,newIdentifyMonth,newIdentifyGetTime")->order("createTime desc")->select()->toArray();

        $typeList[] = [
            "oldTalentArrange" => $talentInfo["talent_arrange"],
            "oldIdentifyCondition" => $talentInfo["talent_condition"],
            "oldIdentifyGetTime" => $talentInfo["identifyGetTime"],
            "oldIdentifyOutTime" => $talentInfo["identifyExpireTime"],
            "oldIdentifyMonth" => $talentInfo["identifyMonth"],
            "oldCertificateStartTime" => $talentInfo["certificateGetTime"],
            "oldCertificateOutTime" => $talentInfo["certificateExpireTime"],
            "newIdentifyMonth" => $year . "-12-31",
            "newIdentifyGetTime" => $year . "-12-31"
        ];
        if (in_array($info["idCard"], \app\common\api\VerifyApi::getTwiceIdentifyPersons())) {
            $whr = [];
            $whr[] = ["ti.checkState", "=", \app\common\api\TalentState::CERTIFICATED];
            $whr[] = ["ti.enterprise_id", "=", $this->user["uid"]];
            $whr[] = ["e.type", "=", $this->user["type"]];
            $whr[] = ["ti.id", "<>", $talentInfo["id"]];
            $whr[] = ["card_number", "=", $info["idCard"]];
            $otherChangeList = \app\enterprise\model\Talent::alias("ti")->leftJoin("un_enterprise e", "e.id=ti.enterprise_id")->field("ti.*,e.`type` as eType")->order("identifyMonth desc")->where($whr)->select()->toArray();
            foreach ($otherChangeList as $k => $oc) {
                if ($k == 0) {
                    $newIdentifyMonth = $talentInfo["identifyMonth"];
                    $newIdentifyGetTime = $talentInfo["identifyGetTime"];
                } else {
                    $newIdentifyMonth = $oc[$k - 1]["identifyMonth"];
                    $newIdentifyGetTime = $oc[$k - 1]["identifyGetTime"];
                }
                $typeList[] = [
                    "oldTalentArrange" => $oc["talent_arrange"],
                    "oldIdentifyCondition" => $oc["talent_condition"],
                    "oldIdentifyGetTime" => $oc["identifyGetTime"],
                    "oldIdentifyOutTime" => $oc["identifyExpireTime"],
                    "oldIdentifyMonth" => $oc["identifyMonth"],
                    "oldCertificateStartTime" => $oc["certificateGetTime"],
                    "oldCertificateOutTime" => $oc["certificateExpireTime"],
                    "newIdentifyMonth" => $newIdentifyMonth,
                    "newIdentifyGetTime" => $newIdentifyGetTime
                ];
            }
        }

        $totalMonth = \DateUtil::getMonthBetweenDates($year . "-01-01", $year . "-12-31");
        /*         * 获取上一年度有效的人才层次 */
        usort($typeList, function($a, $b) {
            return (int) $b["oldTalentArrange"] - (int) $a["oldTalentArrange"];
        });
        $commonMonth = [];
        foreach ($typeList as $talentTypeChange) {
            $startTime = $talentTypeChange[$oldStartTimeField];
            $endTime = $talentTypeChange[$newStartTimeField];
            if (in_array($info["type"], [CommonConst::ENTERPRISE_GJ])) {
                $monthList = \DateUtil::getMonthBetweenDatesNotEnd($startTime, $endTime);
                if ($endTime == $year . "-12-31") {
                    $monthList[] = $year . "-12";
                }
            } else {
                $monthList = \DateUtil::getMonthBetweenDatesNotBegin($startTime, $endTime);
            }
            if ($monthList) {
                $monthList = array_intersect($monthList, $totalMonth);
            }
            if ($monthList) {
                $months = implode(",", $monthList);
                $monthList = array_filter($monthList, function($value) use ($commonMonth) {
                    return !in_array($value, $commonMonth);
                });
                $commonMonth = array_filter(array_merge($commonMonth, $monthList));
                if (count($monthList) > 0) {
                    $arrange = [
                        "id" => getStringId(),
                        "mainId" => $info["id"],
                        "talentArrange" => $talentTypeChange["oldTalentArrange"],
                        "identifyCondition" => $talentTypeChange["oldIdentifyCondition"],
                        "startTime" => $startTime,
                        "endTime" => $endTime,
                        "prepareMonths" => null,
                        "description" => "申报年度有效月份：" . $months,
                        "identifyConditionName" => $talentTypeChange["oldIdentifyConditionName"],
                        "identifyConditionGetTime" => $talentTypeChange["oldIdentifyGetTime"],
                    ];
                    $sb = '';
                    foreach ($monthList as $month) {
                        $sb .= substr($month, 5, 2) . ",";
                    }
                    $arrange["prepareMonths"] = rtrim($sb, ",");
                    $arrangeList[] = $arrange;
                }
            }
        }
        return $arrangeList;
    }

    /**
     * @param
     * @returns void
     * @author Liu
     * @date 2020/4/26
     * @description 获取上一年度所在单位
     * */
    private function getConcatList($talentInfo, $info, $year) {
        $totalMonth = \DateUtil::getMonthBetweenDates($year . "-01-01", $year . "-12-31");
        /** 添加申报人才上一年度工作单位记录 */
        $where = [];
        $where[] = ["idCard", "=", $talentInfo["card_number"]];
        $where[] = ["checkState", "=", 3];
        $quitList = \app\common\model\TalentQuit::where($where)->field("enterpriseId,enterpriseName,talentType,identifyGetTime,starttime,endtime,entryTime,quitTime,post")->select()->toArray();

        /*         * * 将最新的人才数据转为工作变更记录（为了统一处理） */
        if ($talentInfo["active"] == 1) {
            $labor_contract_rangetime = explode(" - ", $talentInfo["labor_contract_rangetime"]);
            $starttime = $labor_contract_rangetime[0];
            $endtime = $labor_contract_rangetime[1];
            $quitList[] = [
                "enterpriseId" => $talentInfo["enterprise_id"],
                "enterpriseName" => $talentInfo["enterpriseName"],
                "talentType" => $talentInfo["enterpriseTag"],
                "identifyGetTime" => $talentInfo["identifyGetTime"],
                "starttime" => $starttime,
                "endtime" => $endtime,
                "entryTime" => $talentInfo["cur_entry_time"],
                "quitTime" => null,
                "post" => $talentInfo["position"]
            ];
        }
        $list = [];
        foreach ($quitList as $quit) {
            $monthList = \DateUtil::getMonthBetweenDates($quit["entryTime"], \StrUtil::isEmpOrNull($quit["quitTime"]) ? $year . "-12-31" : $quit["quitTime"]);
            $monthList = array_intersect($monthList, $totalMonth);
            if ($monthList) {
                $sb = '';
                foreach ($monthList as $month) {
                    $sb .= substr($month, 5, 2) . ",";
                }
                $list[] = [
                    "id" => getStringId(),
                    "mainId" => $info["id"],
                    "enterpriseId" => $quit["enterpriseId"],
                    "talentType" => $quit["talentType"],
                    "startTime" => $quit["starttime"],
                    "endTime" => $quit["endtime"],
                    "entryTime" => $quit["entryTime"],
                    "quitTime" => \StrUtil::isEmpOrNull($quit["quitTime"]) ? $year . "-12-31" : $quit["quitTime"],
                    "letterTime" => $quit["letterTime"],
                    "gygb" => $quit["gygb"],
                    "identifyGetTime" => $quit["identifyGetTime"],
                    "isQuit" => \StrUtil::isEmpOrNull($quit["quitTime"]) ? 2 : 1,
                    "post" => $quit["post"],
                    "months" => rtrim($sb, ",")
                ];
            }
        }
        return $list;
    }

    private function createAllowanceProject($info, $contractList) {
        $count = 0;
        foreach ($contractList as $detail) {
            $count++;
            $projects = AllowanceProjectEnum::getProjectsByEnterpriseType($info["type"], $info["enterpriseId"]);
            $list = [];
            foreach ($projects as $project) {
                $months = "";
                if ($count == count($contractList) && $info["allowanceType"] == AllowanceTypeEnum::JBT_TALENT)
                    $months = "01,02,03,04,05,06,07,08,09,10,11,12";
                $list[] = [
                    "mainId" => $info["id"],
                    "baseId" => $detail["id"],
                    "enterpriseId" => $detail["enterpriseId"],
                    "project" => $project,
                    "months" => $months,
                    "isLock" => 1,
                    "createTime" => date("Y-m-d H:i:s")
                ];
            }
            \app\common\model\TalentAllowanceProject::insertAll($list);
        }
    }

    /**
     * 查询工作单位
     */
    public function findAllowanceContractDetail() {
        $mainId = $this->request["mainId"];
        $offset = $this->request["offset"] ?: 0;
        $limit = $this->request["limit"] ?: 1000;
        $count = \app\common\model\TalentAllowancecontractDetail::where("mainId", $mainId)->count();
        $list = \app\common\model\TalentAllowancecontractDetail::where("mainId", $mainId)->limit($offset, $limit)->select()->toArray();
        $enterpriseMap = \app\common\model\Enterprise::column("name", "id");
        foreach ($list as &$row) {
            $row["enterpriseName"] = $enterpriseMap[$row["enterpriseId"]];
        }unset($row);
        return json(["rows" => $list, "total" => $count]);
    }

    /**
     * 查询核查项目情况
     */
    public function findAllowanceProject() {
        $mainId = $this->request["mainId"];
        $baseId = $this->request["baseId"];
        $offset = $this->request["offset"] ?: 0;
        $limit = $this->request["limit"] ?: 1000;
        $where = [];
        $where[] = ["mainId", "=", $mainId];
        $where[] = ["baseId", "=", $baseId];
        $count = \app\common\model\TalentAllowanceProject::where($where)->count();
        $list = \app\common\model\TalentAllowanceProject::where($where)->limit($offset, $limit)->select()->toArray();
        $info = TalentAllowanceApi::getInfoById($mainId);
        foreach ($list as &$project) {
            $project["projectName"] = AllowanceProjectEnum::getProjectName($project["project"]);
            if ($info["checkState"] == 1) {
                $project["isEdit"] = in_array($project["project"], [
                            //AllowanceProjectEnum::PROJECT_CONTRACT,
                            AllowanceProjectEnum::PROJECT_TAX,
                            AllowanceProjectEnum::PROJECT_WAGES,
                            AllowanceProjectEnum::PROJECT_ATTENDANCE,
                            AllowanceProjectEnum::PROJECT_SB_PENSION,
                            AllowanceProjectEnum::PROJECT_SB_UNEMPLOYMENT,
                            AllowanceProjectEnum::PROJECT_SB_MEDICA,
                            AllowanceProjectEnum::PROJECT_TEACHING,
                            AllowanceProjectEnum::PROJECT_LESSON,
                            AllowanceProjectEnum::PROJECT_TRAINING_PROGRAM,
                                //AllowanceProjectEnum::PROJECT_WORKDAY
                        ]) ? 1 : 2;
            } else if ($info["checkState"] == 10 || $info["checkState"] == 8) {
                $projects = explode(",", $info["projects"]);
                if (in_array($project["id"], $projects)) {
                    $project["isEdit"] = 1;
                } else {
                    $project["isEdit"] = 2;
                }
            } else {
                $project["isEdit"] = 2;
            }
        }unset($project);
        return json(["rows" => $list, "total" => $count]);
    }

    /**
     * 查询人才层次变更记录
     */
    public function findAllowanceArrange() {
        $mainId = $this->request["mainId"];
        $offset = $this->request["offset"] ?: 0;
        $limit = $this->request["limit"] ?: 1000;
        $where = [];
        $where[] = ["mainId", "=", $mainId];
        $count = \app\common\model\TalentAllowanceArrange::where($where)->count();
        $list = \app\common\model\TalentAllowanceArrange::where($where)->limit($offset, $limit)->select()->toArray();
        foreach ($list as &$arrange) {
            $condition = \app\common\api\TalentConditionApi::getOne($arrange["identifyCondition"]);
            $arrange["identifyConditionText"] = $condition["name"];
            $arrange["talentArrangeName"] = CommonConst::getLayerNameByLayer($arrange["talentArrange"]);
        }unset($arrange);
        return json(["rows" => $list, "total" => $count]);
    }

    /**
     * 修改合同起止时间
     */
    public function editContract() {
        $response = new \stdClass();
        $response->code = 500;
        $param = $this->request->param();
        if (!$param["id"]) {
            $response->msg = "系统错误，请联系管理员";
            return $response;
        }
        $detail = \app\common\model\TalentAllowancecontractDetail::find($param["id"]);
        $info = TalentAllowanceApi::getInfoById($detail["mainId"]);
        if (\StrUtil::isEmpOrNull($param["startTime"])) {
            $response->msg = "请选择合同起始时间";
            return $response;
        }
        if (\StrUtil::isEmpOrNull($param["endTime"])) {
            $response->msg = "请选择合同截止时间";
            return $response;
        }
        \app\common\model\TalentAllowancecontractDetail::update($param);
        //添加日志
        TalentChecklog::create([
            'id' => getStringId(),
            'mainId' => $info['id'],
            'type' => intval(ProjectState::JBT),
            'typeFileId' => $param["id"],
            'active' => 1,
            'state' => null,
            'step' => 0,
            'stateChange' => null,
            'description' => "修改工作单位合同时间为：" . $param["startTime"] . "至" . $param["endTime"],
            'createTime' => date("Y-m-d H:i:s", time()),
            'createUser' => sprintf("%s(%s)", $this->user["account"], $this->user["companyName"])
        ]);
        $response->msg = "修改成功";
        $response->code = 200;
        return $response;
    }

    /**
     * 修改项目
     */
    public function editProject() {
        $response = new \stdClass();
        $response->code = 500;
        $param = $this->request->param();
        if (!$param["id"]) {
            $response->msg = "系统错误，请联系管理员";
            return $response;
        }
        $detail = \app\common\model\TalentAllowanceProject::find($param["id"]);
        $info = TalentAllowanceApi::getInfoById($detail["mainId"]);
        \app\common\model\TalentAllowanceProject::update($param);
        //添加日志
        TalentChecklog::create([
            'id' => getStringId(),
            'mainId' => $info['id'],
            'type' => intval(ProjectState::JBT),
            'typeFileId' => $param["id"],
            'active' => 1,
            'state' => null,
            'step' => 0,
            'stateChange' => null,
            'description' => "修改项目名：" . AllowanceProjectEnum::getProjectName($detail["project"]) . "的值为：" . $param["months"] . ";备注为：" . $param["description"],
            'createTime' => date("Y-m-d H:i:s", time()),
            'createUser' => sprintf("%s(%s)", $this->user["account"], $this->user["companyName"])
        ]);
        $response->msg = "修改成功";
        $response->code = 200;
        return $response;
    }

    /**
     * 判断是否可以修改
     */
    public function validateIsEdit() {
        $id = $this->request["id"];
        $type = $this->request["type"];
        $info = null;
        if ($type == 1) {                //编辑合同
            $detail = \app\common\model\TalentAllowancecontractDetail::find($id);
        } else if ($type == 2) {          //编辑项目
            $detail = \app\common\model\TalentAllowanceProject::find($id);
        }
        $info = TalentAllowanceApi::getInfoById($detail["mainId"]);
        if ($info["checkState"] != 1 && $info["checkState"] != 10) {
            if ($info["checkState"] == -1) {
                return new Response(Response::ERROR, "您的申报审核不通过，无法操作");
            } else if ($info["checkState"] == 30) {
                return new Response(Response::ERROR, "您的申报已审核通过，无法操作");
            } else {
                return new Response(Response::ERROR, "您的申报正在审核中，请耐心等待");
            }
        }
        return new Response(Response::SUCCESS, "");
    }

    /**
     * 提交审核
     */
    public function submitToCheck() {
        $data = $this->request->param();
        $response = new \stdClass();
        $response->code = 500;
        if (!$data || !$data["id"]) {
            $response->msg = "提交审核失败，请先填写基础信息";
            return $response;
        }
        $old = TalentAllowanceApi::getInfoById($data["id"]);
        $batch = BatchApi::checkBatchValid(["type" => ProjectState::JBT, "year" => $old["year"], "first_submit_time" => $old["firstSubmitTime"]], $this->user["type"]);
        if ($batch["code"] != 200) {
            $response->msg = $batch["msg"];
            return $response;
        }
        if ($old["checkState"] != 1 && $old["checkState"] != 10 && $old["checkState"] != 8) {
            $response->msg = "不能重复提交审核";
            return $response;
        }
        if (!$old["allowanceType"]) {
            $response->msg = "没有明确津贴类型";
            return $response;
        }
        //因为工作津贴和交通补贴两者的考勤分别记录的是月份和天数，如果没有手动修改值会导致数据不对口，如修改类型却未修改考勤记录，则手动改为空。
        $where = [];
        $where[] = ["project", "=", AllowanceProjectEnum::PROJECT_ATTENDANCE];
        $where[] = ["mainId", "=", $data["id"]];
        $attendanceList = \app\common\model\TalentAllowanceProject::where($where)->select()->toArray();
        if ($old["allowanceType"] == AllowanceTypeEnum::JBT_JT) {
            //因为天数保存格式为 月份=天数 如 01=31,02=20,03=15,月份保存格式为01,02,03,所以可以从有没有=号判断是否有进行考勤的修改保存操作
            foreach ($attendanceList as $a) {
                //$a["months"]有值但是没有包含=号则一般可认为是类型修改为交通补贴而未修改考勤，此时的months字段数据是错误的，修改为空。
                if ($a["months"] && strpos($a["months"], "=") === false) {
                    $_updProject["id"] = $a["id"];
                    $_updProject["months"] = "";
                    \app\common\model\TalentAllowanceProject::update($_updProject);
                }
            }
        } else {
            foreach ($attendanceList as $a) {
                //$a["months"]有值但是包含了=号则一般可认为是类型修改为工作津贴而未修改考勤，此时的months字段数据是错误的，修改为空。
                if ($a["months"] && strpos($a["months"], "=") !== false) {
                    $_updProject["id"] = $a["id"];
                    $_updProject["months"] = "";
                    \app\common\model\TalentAllowanceProject::update($_updProject);
                }
            }
        }
        $where = [];
        $where[] = ["type", "=", $old["type"]];
        $where[] = ["project", "=", ProjectState::JBT];
        $where[] = ["isConditionFile", "=", $old["allowanceType"]];
        $where[] = ["active", "=", 1];
        $where[] = ["delete", "=", 0];
        $filetypes = Db::table("new_common_filetype")->where($where)->order("sn asc")->select()->toArray();

        $where = [];
        $where[] = ["enterpriseId", "=", $old["enterpriseId"]];
        $where[] = ["batch", "=", $old["year"]];
        $commonFiles = Db::table("un_talent_allowance_common_file")->alias("f")->leftJoin("new_common_filetype ft", "ft.id=f.fileTypeId")->field("f.*,ft.relationIds")->where($where)->select()->toArray();
        $relationIds = [];
        foreach ($commonFiles as $key => $row) {
            $_relationIds = array_filter(explode(",", $row["relationIds"]));
            $relationIds = array_merge($relationIds, $_relationIds);
        }
        foreach ($filetypes as $key => $filetype) {
            if (in_array($filetype["id"], $relationIds)) {
                $filetypes[$key]["must"] = 2;
            }
        }

        $sb = [];
        $sb[] = "以下为必传附件：";
        foreach ($filetypes as $filetype) {
            if ($filetype["must"] == 1) {
                $where = [];
                $where[] = ["mainId", "=", $data["id"]];
                $where[] = ["typeId", "=", $filetype["id"]];
                $count = Db::table("new_talent_file")->where($where)->count();
                if ($count == 0) {
                    $sb[] = $filetype["name"] . ";";
                }
            }
        }
        if (count($sb) > 1) {
            $response->msg = implode("<br>", $sb);
            return $response;
        }

        /**
         * 初步判断合同是否满两年
         */
        $detailList = \app\common\model\TalentAllowancecontractDetail::where("mainId", $old["id"])->select()->toArray();
        foreach ($detailList as $detail) {
            if (\StrUtil::isEmpOrNull($detail["startTime"]) || \StrUtil::isEmpOrNull($detail["endTime"])) {
                $response->msg = "合同起止时间不能为空";
                return $response;
            }
        }
        foreach ($detailList as $detail) {
            $contractEndTime = strtotime($detail["endTime"]);
            $contractStartTimeAdd2Years = strtotime("+2 years -1 day {$detail['startTime']}");
            $where = [];
            $where[] = ["mainId", "=", $data["id"]];
            $where[] = ["baseId", "=", $detail["id"]];
            $where[] = ["project", "=", AllowanceProjectEnum::PROJECT_CONTRACT];
            $updProject["months"] = $contractEndTime >= $contractStartTimeAdd2Years ? "是" : "否";
            \app\common\model\TalentAllowanceProject::where($where)->update($updProject);
        }
        $data["checkMsg"] = "";
        $data["checkState"] = AllowanceStateEnum::NEED_CHECK;
        $afterState = 7; //待初审
        /* $ep = \app\common\api\EnterpriseApi::getOne($this->user["uid"]);
          if ($ep->isGeneral == 2 && \app\common\api\Nhc::hasGeneralHospital($ep->medicalCommunityId)) {
          $data["checkState"] = AllowanceStateEnum::NEED_GENERAL_CHECK; //分院并且有总院
          $afterState = 3; //待审核
          } */
        $data["files"] = "";
        $data["projects"] = "";
        $data["concats"] = "";
        $data["fields"] = "";
        $data["toDep"] = "";
        $data["process"] = null;
        if (!$old["firstSubmitTime"]) {
            $data["firstSubmitTime"] = date("Y-m-d H:i:s");
        }
        $data["newSubmitTime"] = date("Y-m-d H:i:s");
        TaModel::update($data);
        //添加日志
        TalentChecklog::create([
            'id' => getStringId(),
            'mainId' => $data['id'],
            'type' => intval(ProjectState::JBT),
            'typeFileId' => null,
            'active' => 1,
            'state' => 1,
            'step' => 0,
            'stateChange' => sprintf("%s->%s", MainState::getStateDesc(1), MainState::getStateDesc($afterState)),
            'description' => "确认提交审核",
            'createTime' => date("Y-m-d H:i:s", time()),
            'createUser' => sprintf("%s(%s)", $this->user["account"], $this->user["companyName"])
        ]);
        $response->msg = "提交审核成功";
        $response->code = 200;
        $response->obj = 5;
        return $response;
    }

    public function updateSuppleState() {
        $id = $this->request["id"];
        $response = new \stdClass();
        $response->code = 500;
        if (\StrUtil::isEmpOrNull($id)) {
            $response->msg = "系统错误，请联系管理员";
            return $response;
        }
        $data["id"] = $id;
        $data["isSupple"] = 1;
        TaModel::update($data);
        $response->msg = "状态更新成功";
        $response->code = 200;
        return $response;
    }

    public function uploadCommonFile() {
        $batchId = $this->request["batch"];
        if (!$batchId) {
            return json(new Response(Response::ERROR, "没有提交批次信息，无法按批次归档，上传被中止"));
        }
        $batchInfo = BatchApi::getOne($batchId);

        if (!$batchInfo) {
            return json(new Response(Response::ERROR, "批次信息不存在，无法按批次归档，上传被中止"));
        }

        if (!$this->request->file()) {
            return json(new Response(Response::ERROR, "没有上传任何材料"));
        }
        $file = $this->request->file("file");
        $upload = new UploadApi();
        $result = $upload->uploadOne($file, "system", "talent/TalentAllowanceCommonFile");
        if ($result->code != 200) {
            return json(new Response(Response::ERROR, $result->msg));
        }
        $data["id"] = getStringId();
        $data["enterpriseId"] = $this->user["uid"];
        $data["batchId"] = $batchId;
        $data["batch"] = $batchInfo["batch"];
        $data["url"] = $result->filepath;
        $data["originalName"] = $file->getOriginalName();
        $data["createTime"] = date("Y-m-d H:i:s");
        $data["createUser"] = $this->user["uid"];
        $res = Db::table("un_talent_allowance_common_file")->insert($data);

        return json(new Response(Response::SUCCESS, "上传成功"));
    }

    public function listCommonFile() {
        $param = $this->request->param();
        $batchId = $param["batch"];
        $where = [["batchId", "=", $batchId], ["enterpriseId", "=", $this->user["uid"]]];
        $list = Db::table("un_talent_allowance_common_file")->where($where)->select()->toArray();

        $whr[] = ["type", "=", $this->user["type"]];
        $whr[] = ["project", "=", ProjectState::JBT];
        $whr[] = ["isConditionFile", "=", 0];
        $whr[] = ["delete", "=", 0];
        if ($this->user["type"] == CommonConst::ENTERPRISE_JC) {
            $commonFileTypes = Db::table("new_common_filetype")->where($whr)->whereRaw("find_in_set(:enterpriseId,enterpriseIds)", ["enterpriseId" => $this->user["uid"]])->select()->toArray();
        } else {
            $commonFileTypes = Db::table("new_common_filetype")->where($whr)->select()->toArray();
        }

        foreach ($list as $key => $item) {
            $list[$key]["ext"] = pathinfo($item["url"])["extension"];
            $list[$key]["url"] = getStoragePath($item["url"]);
            $list[$key]["fileTypes"] = $commonFileTypes;
        }
        return json(["rows" => $list]);
    }

    public function bindCommonFileWithFileType() {
        $params = $this->request->param();
        $fileId = $params["fileId"];
        $fileTypeId = $params["fileTypeId"];
        $upd["id"] = $fileId;
        $upd["fileTypeId"] = $fileTypeId ?: 0;
        $upd["updateTime"] = date("Y-m-d H:i:s");
        $upd["updateUser"] = $this->user["uid"];
        try {
            Db::table("un_talent_allowance_common_file")->update($upd);
            if ($fileTypeId > 0) {
                $msg = "关联成功";
            } else {
                $msg = "取消关联成功";
            }
            return json(new Response(Response::SUCCESS, $msg));
        } catch (\think\db\exception\DbException $e) {
            return json(new Response(Response::ERROR, $e->getMessage()));
        }
    }

    public function deleteCommonFile() {
        $id = $this->request["id"];
        $where = [];
        $where[] = ["id", "=", $id];
        $where[] = ["enterpriseId", "=", $this->user["uid"]];
        $file = Db::table("un_talent_allowance_common_file")->where($where)->find();
        if (!$file) {
            return json(new Response(Response::ERROR, "不存在的文件，删除失败"));
        }
        if (Db::table("un_talent_allowance_common_file")->where($where)->delete()) {
            if (!empty($file["url"])) {
                $filepath = "storage/" . $file["url"];
                if (file_exists($filepath)) {
                    unlink($filepath);
                }
            }
            return json(new Response(Response::SUCCESS, "删除成功"));
        }
    }

    public function findTalentAllowance() {
        $res = [];
        $batch = BatchApi::getValidBatch(ProjectState::JBT, $this->user["type"]);
        $year = $batch["batch"];
        if ($year) {
            $ids = null;
            //根据申报年度查询当前企业已申报的人才
            $where = [];
            $where[] = ["year", "=", $year];
            $where[] = ["enterpriseId", "=", $this->user["uid"]];
            $talentAllowances = TaModel::where($where)->select()->toArray();
            $ids = array_unique(array_column($talentAllowances, "talentId"));
            $whr = [];
            $whr[] = ["ti.checkState", "=", \app\common\api\TalentState::CERTIFICATED];
            $whr[] = ["ti.enterprise_id", "=", $this->user["uid"]];
            $whr[] = ["e.type", "=", $this->user["type"]];
            $whr[] = ["ti.id", "not in", $ids];
            $twiceIdentifyPersons = \app\common\api\VerifyApi::getTwiceIdentifyPersons();
            if ($twiceIdentifyPersons) {
                $_whr = $whr;
                $whr[] = ["card_number", "not in", $twiceIdentifyPersons];
                $_whr[] = ["card_number", "in", $twiceIdentifyPersons];
                $tmpList = \app\enterprise\model\Talent::alias("ti")->leftJoin("un_enterprise e", "e.id=ti.enterprise_id")->field("ti.id,ti.name,ti.card_number as idCard,ti.cur_entry_time,e.`type` as eType")->where($_whr)->select()->toArray();

                $twiceIdentifyPersonList = [];
                $otherTypeChangeList = [];
                foreach ($tmpList as $person) {
                    if (!$twiceIdentifyPersonList[$person["idCard"]]) {
                        $twiceIdentifyPersonList[$person["idCard"]] = $person;
                    } else {
                        if ($person["talent_arrange"] < $twiceIdentifyPersonList[$person["idCard"]]["talent_arrange"]) {
                            $otherTypeChangeList[$person["idCard"]][] = ["oldIdentifyMonth" => $twiceIdentifyPersonList[$person["idCard"]]["identifyMonth"], "oldIdentifyGetTime" => $twiceIdentifyPersonList[$person["idCard"]]["identifyGetTime"]];
                            $twiceIdentifyPersonList[$person["idCard"]] = $person;
                        } else {
                            $otherTypeChangeList[$person["idCard"]][] = ["oldIdentifyMonth" => $person["identifyMonth"], "oldIdentifyGetTime" => $person["identifyGetTime"]];
                        }
                    }
                }
                sort($twiceIdentifyPersonList);
            }
            $list = \app\enterprise\model\Talent::alias("ti")->leftJoin("un_enterprise e", "e.id=ti.enterprise_id")->field("ti.id,ti.name,ti.card_number as idCard,ti.cur_entry_time,e.`type` as eType")->where($whr)->select()->toArray();
            if ($twiceIdentifyPersonList) {
                $list = array_merge((array) $list, $twiceIdentifyPersonList);
            }
            foreach ($list as $info) {
                $identifyTime = $info["identifyMonth"];
                if ($info["eType"] == CommonConst::ENTERPRISE_JC) {
                    $identifyTime = $info["identifyGetTime"] ?: $info["identifyMonth"];
                }
                if (strtotime($year . "-12-31") >= strtotime($identifyTime)) {
                    $res[] = $info;
                } else {
                    $whereTypeChange = [];
                    $whereTypeChange[] = ["idCard", "=", $info["idCard"]];
                    $whereTypeChange[] = ["checkState", "=", MainState::PASS];
                    $whereTypeChange[] = ["isPublic", "=", 6];
                    $whereTypeChange[] = ["createTime", ">=", "2022-10-01 00:00:00"];
                    $typeChanges = TalentTypeChange::where($whereTypeChange)->select()->toArray();
                    if ($otherTypeChangeList[$info["idCard"]]) {
                        $typeChanges = array_merge($otherTypeChangeList[$info["idCard"]], (array) $typeChanges);
                    }
                    foreach ($typeChanges as $typeChange) {
                        $oldIdentifyTime = $typeChange["oldIdentifyMonth"];
                        if ($typeChange["type"] == CommonConst::ENTERPRISE_JC) {
                            $oldIdentifyTime = $typeChange["oldIdentifyGetTime"] ?: $typeChange["oldIdentifyMonth"];
                        }
                        if (strtotime($year . "-12-31") >= strtotime($oldIdentifyTime)) {
                            $res[] = $info;
                            break;
                        }
                    }
                }
            }
        }
        return new Response(Response::SUCCESS, "", ["rows" => $res, "total" => count($res)]);
    }

    public function export() {
        $obj["year"] = \StrUtil::getRequestDecodeParam($this->request, "year");
        $obj["name"] = \StrUtil::getRequestDecodeParam($this->request, "name");
        $obj["talentArrange"] = \StrUtil::getRequestDecodeParam($this->request, "talentArrange");
        $obj["allowanceType"] = \StrUtil::getRequestDecodeParam($this->request, "allowanceType");
        $obj["address"] = \StrUtil::getRequestDecodeParam($this->request, "address");
        $obj["identifyCondition"] = \StrUtil::getRequestDecodeParam($this->request, "identifyCondition");
        $where = [];
        $where[] = ["ta.delete", "=", 0];
        $where[] = ["ta.enterpriseId", "=", $this->user["uid"]];
        if (\StrUtil::isNotEmpAndNull($obj["year"])) {
            $where[] = ["ta.year", "like", "%" . $obj["year"] . "%"];
        }
        if (\StrUtil::isNotEmpAndNull($obj["name"])) {
            $where[] = ["ta.name", "like", "%" . $obj["name"] . "%"];
        }
        if (\StrUtil::isNotEmpAndNull($obj["talentArrange"])) {
            $where[] = ["ta.talentArrange", "=", $obj["talentArrange"]];
        }
        if (\StrUtil::isNotEmpAndNull($obj["allowanceType"])) {
            $where[] = ["ta.allowanceType", "=", $obj["allowanceType"]];
        }
        if (\StrUtil::isNotEmpAndNull($obj["address"])) {
            $where[] = ["ta.address", "=", $obj["address"]];
        }
        if (\StrUtil::isNotEmpAndNull($obj["identifyCondition"])) {
            $where[] = ["ta.identifyCondition", "=", $obj["identifyCondition"]];
        }
        $projects = [
            AllowanceProjectEnum::PROJECT_TAX,
            AllowanceProjectEnum::PROJECT_WAGES,
            AllowanceProjectEnum::PROJECT_ATTENDANCE,
            AllowanceProjectEnum::PROJECT_SB_PENSION,
            AllowanceProjectEnum::PROJECT_SB_UNEMPLOYMENT,
            AllowanceProjectEnum::PROJECT_SB_MEDICA,
        ];
        $months = [];
        for ($m = 1; $m <= 12; $m++) {
            $months[] = $m . "月";
        }
        $columns = [["年度", [1, 2]], ["所属镇街", [1, 2]], ["姓名", [1, 2]], ["性别", [1, 2]], ["证件号码", [1, 2]], ["人才层次", [1, 2]], ["认定条件", [1, 2]], ["认定条件取得时间", [1, 2]], ["认定条件名称", [1, 2]], ["公布入选月份", [1, 2]], ["津补贴类型", [1, 2]], ["试算结果", [1, 2]], ["兑现月份", [1, 2]], ["兑现金额", [1, 2]], ["金额说明", [1, 2]], ["审核状态", [1, 2]], ["缴纳单位", [1, 2]]];
        $infoCols = count($columns);
        for ($i = 0; $i < count($projects); $i++) {
            $columns[] = [AllowanceProjectEnum::getProjectName($projects[$i]), $months];
        }
        $list = \app\common\model\TalentAllowanceProject::alias("pro")
                        ->field("ta.id,ta.year,ta.enterpriseId as curEnterpriseId,ta.address,ta.name,ta.sex,ta.idCard,ta.talentArrange,ta.identifyCondition,ta.identifyGetTime,ta.identifyConditionName,ta.virtualAmount,ta.identifyMonth,ta.allowanceType,ta.months,ta.money,ta.moneyDesc,ta.checkState,ta.publicState,pro.project,pro.months as pre_months,con.enterpriseId,con.startTime,con.endTime,con.entryTime,con.quitTime,con.isQuit")
                        ->leftJoin("un_talent_allowance_info ta", "ta.id=pro.mainId")
                        ->leftJoin("un_talent_allowancecontract_detail con", "pro.baseId=con.id")
                        ->where($where)
                        ->order("ta.year desc,ta.createTime desc,pro.project asc")
                        ->select()->toArray();
        $tmpList = [];

        $levelMap = DictApi::selectByParentCode("talent_arrange");
        $streetMap = DictApi::selectByParentCode("street");
        $where = [];
        $where[] = ["id", "in", array_column($list, "identifyCondition")];
        $icmap = \app\common\model\TalentCondition::where($where)->column("name", "id");

        $where = [];
        $where[] = ["id", "in", array_column($list, "enterpriseId")];
        $enterpriseMap = \app\common\model\Enterprise::where($where)->column("name", "id");
        foreach ($list as $item) {
            //组装数据
            if (!$tmpList[$item["id"]]) {
                $tmpList[$item["id"]]["curEnterpriseId"] = $item["curEnterpriseId"];
                $tmpList[$item["id"]]["info"] = [$item["year"], $streetMap[$item["address"]], $item["name"], $item["sex"] == 1 ? "男" : "女", $item["idCard"], $levelMap[$item["talentArrange"]],
                    $icmap[$item["identifyCondition"]], $item["identifyGetTime"], $item["identifyConditionName"], $item["identifyMonth"], AllowanceTypeEnum::getTypeName($item["allowanceType"]), $item["virtualAmount"], $item["months"], $item["money"],
                    $item["moneyDesc"], $this->getCheckStateName($item["checkState"], $item["publicState"], $item["allowanceType"])];
            }
            if (!$tmpList[$item["id"]]["enterprise"][$item["enterpriseId"]]) {
                $tmpList[$item["id"]]["enterprise"][$item["enterpriseId"]] = [
                    "startTime" => $item["startTime"],
                    "endTime" => $item["endTime"],
                    "entryTime" => $item["entryTime"],
                    "isQuit" => $item["isQuit"]
                ];
            }
            $tmpList[$item["id"]]["enterprise"][$item["enterpriseId"]]["projects"][$item["project"]] = $item["pre_months"];
        }
        $rows = [];
        $colorset = [];
        foreach ($tmpList as $id => $item) {
            foreach ($item["enterprise"] as $enterpriseId => $enterprise) {
                $row = $item["info"];
                $row[] = $this->user["uid"] == $enterpriseId ? "本单位" : $enterpriseMap[$enterpriseId];
                for ($i = 0; $i < count($projects); $i++) {
                    if (strpos($enterprise["projects"][$projects[$i]], "=") === false) {
                        $months = array_filter(explode(",", $enterprise["projects"][$projects[$i]]));
                        for ($m = 1; $m <= 12; $m++) {
                            $_month = str_pad($m, 2, "0", STR_PAD_LEFT);
                            if (in_array($_month, $months)) {
                                $row[] = "✔";
                                $colorset[] = [sprintf("%s%d", getExcelColumnByIndex($infoCols + $i * 12 + $m - 1), count($rows) + 3), "29dd23"];
                            } else {
                                $row[] = "";
                            }
                        }
                    } else {
                        $months = array_filter(explode(",", $enterprise["projects"][$projects[$i]]));
                        $_months = [];
                        foreach ($months as $month) {
                            $kv = explode("=", $month);
                            $_months[$kv[0]] = $kv[1];
                        }
                        for ($m = 1; $m <= 12; $m++) {
                            $_month = str_pad($m, 2, "0", STR_PAD_LEFT);
                            $days = $_months[$_month];
                            if ($days && $days > 0) {
                                $row[] = $days . "天";
                                $colorset[] = [sprintf("%s%d", getExcelColumnByIndex($infoCols + $i * 12 + $m - 1), count($rows) + 3), "29dd23"];
                            } else {
                                $row[] = "";
                            }
                        }
                    }
                }
                $rows[] = $row;
            }
        }
        $cols = $infoCols + count($projects) * 12 - 1;
        $settings = [
            "width" => [["A", 8], ["C", 12], ["D", 6], ["E", 20], ["F", 12], ["G", 70], ["H", 12], ["I", 15], ["J", 12], ["K", 12], ["P", 30]],
            "height" => [18],
            "freeze" => "D3",
            "color" => $colorset
        ];
        for ($i = 0; $i < count($projects) * 12; $i++) {
            $settings["width"][] = [getExcelColumnByIndex($infoCols + $i), 6]; //批设置项目的宽度
        }
        $settings["background-color"][] = [sprintf("%s2:%s2", getExcelColumnByIndex($infoCols), getExcelColumnByIndex($cols)), "E1F1DE"];
        export($columns, $rows, "津补贴申报名单", $settings);
    }

    /**
     * 审核列表页
     */
    public function examineCenter() {
        $tpl = "";
        switch ($this->user["type"]) {
            case CommonConst::ENTERPRISE_WJ:
                $tpl = "/talent_allowance/examine_center"; //卫健医院
                break;
        }
        return view($tpl);
    }

    /**
     * 审核列表页
     */
    public function examineList() {
        $res = TalentAllowanceApi::getHospitalExamineList($this->request);
        return json($res);
    }

    /**
     * 审核页面
     * @return type
     */
    public function toCheckPage() {
        $id = $this->request["id"];
        $process = $this->request["process"];
        $obj = TalentAllowanceApi::getInfoById($id);
        $this->translateToChinese($obj);
        return view("check", ["row" => $obj, "process" => $process]);
    }

    /**
     * 查看详情
     * @return type
     */
    public function toSelectPage() {
        $id = $this->request["id"];
        $process = $this->request["process"];
        $obj = TalentAllowanceApi::getInfoById($id);
        $this->translateToChinese($obj);
        return view("check", ["row" => $obj, "process" => $process]);
    }

    /**
     * 审核保存
     */
    public function check() {
        $obj = $this->request->param();
        if (!$obj["checkState"]) {
            return new Response(Response::ERROR, "请选择审核状态");
        }

        $oldObj = TalentAllowanceApi::getInfoById($obj["id"]);

        if (!$oldObj) {
            return new Response(Response::ERROR, "审核对象不存在");
        }
        $ep = \app\common\api\EnterpriseApi::getOne($oldObj["enterpriseId"]);
        if (!$this->checkExaminePriv($ep->isGeneral, $ep->medicalCommunityId)) {
            return new Response(Response::ERROR, "不在审核范围内");
        }
        if ($oldObj["checkState"] != AllowanceStateEnum::NEED_GENERAL_CHECK && $oldObj["checkState"] != AllowanceStateEnum::FIRST_REJECT) {
            return new Response(Response::ERROR, "不在审核范围内");
        }

        $newObj = [];
        $newObj["id"] = $obj["id"];
        $projectList = [];
        $fileList = [];
        if (\StrUtil::isNotEmpAndNull($obj["projects"])) {
            $projectList = array_filter(explode(",", $obj["projects"]));
            $newObj["projects"] = implode(",", $projectList);
        }
        if (\StrUtil::isNotEmpAndNull($obj["files"])) {
            $fileList = array_filter(explode(",", $obj["files"]));
            $newObj["files"] = implode(",", $fileList);
        }
        $newObj["concats"] = $obj["concats"];
        $newObj["fields"] = $obj["fields"];
        //}
        TaModel::update($newObj);
        //添加日志
        TalentChecklog::create([
            'id' => getStringId(),
            'mainId' => $obj['id'],
            'type' => intval(ProjectState::JBT),
            'typeFileId' => null,
            'active' => 2,
            'state' => $obj["checkState"],
            'step' => -2,
            'stateChange' => null,
            'description' => $obj["checkMsg"],
            'createTime' => date("Y-m-d H:i:s", time()),
            'createUser' => sprintf("%s(%s)", $this->user["account"], $this->user["companyName"])
        ]);
        return new Response(Response::SUCCESS, "审核成功");
    }

    /**
     * 提交审核
     * @return Response
     */
    public function submitCheck() {
        $id = $this->request["id"];
        $process = -2;
        $old = TalentAllowanceApi::getInfoById($id);
        if (!$old) {
            return new Response(Response::ERROR, "审核对象不存在");
        }
        $ep = \app\common\api\EnterpriseApi::getOne($old["enterpriseId"]);
        if (!$this->checkExaminePriv($ep->isGeneral, $ep->medicalCommunityId)) {
            return new Response(Response::ERROR, "不在审核范围内");
        }
        if ($old["checkState"] != AllowanceStateEnum::NEED_GENERAL_CHECK && $old["checkState"] != AllowanceStateEnum::FIRST_REJECT) {
            return new Response(Response::ERROR, "不在审核范围内");
        }
        $updCheck = [];
        $updCheck["id"] = $id;
        $updCheck["type"] = $old["type"];
        /*         * 查询审核日志 */
        $log = \app\common\api\TalentLogApi::getLastLogByStep($id, ProjectState::JBT, $process);
        if (!$log) {
            return new Response(Response::ERROR, "请先审核后再提交");
        }
        $updCheck["checkMsg"] = $log["description"];
        /*         * 判断到达的最高流程 */
        $updCheck["highProcess"] = !$old["highProcess"] || $old["highProcess"] < $process ? $process : $old["highProcess"];

        switch ($log["state"]) {
            case 3:
                $updCheck["precheckPassTime"] = $old["precheckPassTime"];
                if (!$old["precheckPassTime"]) {
                    $updCheck["precheckPassTime"] = date("Y-m-d H:i:s");
                }
                $updCheck["submitTime"] = date("Y-m-d H:i:s");
                $updCheck["checkState"] = AllowanceStateEnum::NEED_CHECK;
                break;
            case 2:
                $updCheck["checkState"] = AllowanceStateEnum::GENERAL_REJECT;
                break;
            case -1:
                $updCheck["checkState"] = AllowanceStateEnum::NOTPASS;
                $updCheck["recommendAllowanceType"] = 3;
                $updCheck["recommendMoney"] = 0;
                $updCheck["recommendAllowanceMsg"] = "审核不通过，不予兑现";
                break;
            default:
                return new Response(Response::ERROR, "未知的审核状态");
        }
        //添加日志
        TalentChecklog::create([
            'id' => getStringId(),
            'mainId' => $id,
            'type' => intval(ProjectState::JBT),
            'typeFileId' => null,
            'active' => 1,
            'state' => $log["state"],
            'step' => $process,
            'stateChange' => AllowanceStateEnum::getStateName($old["checkState"]) . "->" . AllowanceStateEnum::getStateName($updCheck["checkState"]),
            'description' => $log["description"],
            'createTime' => date("Y-m-d H:i:s", time()),
            'createUser' => sprintf("%s(%s)", $this->user["account"], $this->user["companyName"])
        ]);
        TalentChecklog::where("id", $log["id"])->delete();
        TaModel::update($updCheck);
        return new Response(Response::SUCCESS, "提交审核成功");
    }

    /**
     * 校验是否在审核范围内
     */
    public function validateIsCheck() {
        $id = $this->request["id"];
        $type = $this->request["type"];
        $info = null;
        switch ($type) {
            case 1:                 //编辑合同
                $detail = \app\common\model\TalentAllowancecontractDetail::find($id);
                $info = TalentAllowanceApi::getInfoById($detail["mainId"]);
                break;
            case 2:                 //编辑项目
                $project = \app\common\model\TalentAllowanceProject::find($id);
                $info = TalentAllowanceApi::getInfoById($project["mainId"]);
                break;
            case 3:
                $info = TalentAllowanceApi::getInfoById($id);
                break;
        }
        if (!$info) {
            return new Response(Response::ERROR, "校验不通过，无法操作");
        }
        $ep = \app\common\api\EnterpriseApi::getOne($info["enterpriseId"]);
        if (!$this->checkExaminePriv($ep->isGeneral, $ep->medicalCommunityId)) {
            return new Response(Response::ERROR, "不在审核范围内");
        }
        $where = [];
        $where[] = ["mainId", "=", $info["id"]];
        $where[] = ["step", "=", -2];
        $where[] = ["active", "=", 2];

        $log = null;
        if ($info["checkState"] != AllowanceStateEnum::NEED_GENERAL_CHECK && $info["checkState"] != AllowanceStateEnum::FIRST_REJECT) {
            return new Response(Response::ERROR, "不在审核范围内");
        }
        $log = TalentChecklog::where($where)->order("createTime desc")->find();
        if ($log != null) {
            $info["checkState"] = $log["state"];
            $info["checkMsg"] = $log["description"];
        } else {
            $info["checkState"] = null;
            $info["checkMsg"] = "";
        }
        $res = [];
        $res["info"] = $info;
        if ($type == 3) {
            $enterpriseMap = \app\common\model\Enterprise::where("type", $this->user["type"])->column("name", "id");
            $where = [];
            $where[] = ["mainId", "=", $id];
            $where[] = ["isLock", "=", 1];
            $projectList = \app\common\model\TalentAllowanceProject::where($where)->select()->toArray();
            $detailList = \app\common\model\TalentAllowancecontractDetail::where("mainId", $id)->select()->toArray();
            $detailMap = array_reduce($detailList, function ($result, $item) {
                $key = $item["id"];
                $result[$key] = $item;
                return $result;
            }, []);
            foreach ($detailList as &$detail) {
                $detail["enterpriseName"] = sprintf("%s(%s至%s)", $enterpriseMap[$detail["enterpriseId"]], $detail["startTime"], $detail["endTime"]);
            }unset($detail);
            foreach ($projectList as &$project) {
                $detail = $detailMap[$project["baseId"]];
                $project["projectName"] = sprintf("%s(%s(%s至%s))", AllowanceProjectEnum::getProjectName($project["project"]), $enterpriseMap[$project["enterpriseId"]], $detail["startTime"], $detail["endTime"]);
            }
            $where = [];
            $where[] = ["type", "=", $info["type"]];
            $where[] = ["project", "=", \app\common\state\ProjectState::JBT];
            $where[] = ["active", "=", 1];
            $where[] = ["delete", "=", 0];
            $filetypes = Db::table("new_common_filetype")->where($where)->order("sn asc")->select()->toArray();
            $res["files"] = $filetypes;
            $res["projects"] = $projectList;
            $res["concats"] = $detailList;
        }
        return new Response(Response::SUCCESS, "不在审核范围内", $res);
    }

    /**
     *  初始化可修改的项目/附件/合同
     * */
    public function findFieldsAndFiles() {
        $id = $this->request["id"];
        if (\StrUtil::isEmpOrNull($id)) {
            return new Response(Response::ERROR, "请选择需要修改的对象");
        }
        $info = TalentAllowanceApi::getInfoById($id);
        if (!$info) {
            return new Response(Response::ERROR, "系统错误，请联系管理员");
        }
        if ($info["checkState"] != AllowanceStateEnum::GENERAL_REJECT) {
            return new Response(Response::ERROR, "只能修改总院驳回的数据");
        }
        $res = [];
        $enterpriseMap = \app\common\model\Enterprise::where("type", $this->user["type"])->column("name", "id");
        $where = [];
        $where[] = ["mainId", "=", $id];
        $where[] = ["isLock", "=", 1];
        $projectList = \app\common\model\TalentAllowanceProject::where($where)->select()->toArray();
        $detailList = \app\common\model\TalentAllowancecontractDetail::where("mainId", $id)->select()->toArray();

        foreach ($detailList as &$detail) {
            $detail["enterpriseName"] = $enterpriseMap[$detail["enterpriseId"]];
        }unset($detail);
        foreach ($projectList as &$project) {
            $detail = $detailMap[$project["baseId"]];
            $project["projectName"] = sprintf("%s(%s)", AllowanceProjectEnum::getProjectName($project["project"]), $enterpriseMap[$project["enterpriseId"]]);
        }unset($project);

        $where = [];
        $where[] = ["type", "=", $info["type"]];
        $where[] = ["project", "=", \app\common\state\ProjectState::JBT];
        $where[] = ["active", "=", 1];
        $where[] = ["delete", "=", 0];
        $filetypes = Db::table("new_common_filetype")->where($where)->order("sn asc")->select()->toArray();
        $res["files"] = $filetypes;
        $res["projects"] = $projectList;
        $res["concats"] = $detailList;
        $res["info"] = $info;
        return new Response(Response::SUCCESS, "", $res);
    }

    /**
     * 修改驳回项目/附件/合同
     * */
    public function updateFieldsAndFiles() {
        $data = $this->request->param();
        if (!$data["id"]) {
            return new Response(Response::ERROR, "系统错误，请联系管理员");
        }
        $old = TalentAllowanceApi::getInfoById($data["id"]);
        if (!$old) {
            return new Response(Response::ERROR, "审核对象不存在");
        }
        $ep = \app\common\api\EnterpriseApi::getOne($old["enterpriseId"]);
        if (!$this->checkExaminePriv($ep->isGeneral, $ep->medicalCommunityId)) {
            return new Response(Response::ERROR, "不在审核范围内");
        }
        if ($old["checkState"] != AllowanceStateEnum::GENERAL_REJECT) {
            return new Response(Response::ERROR, "只能修改总院驳回的数据");
        }
        TaModel::update($data);
        return new Response(Response::SUCCESS, "修改成功");
    }

    private function checkExaminePriv($isGeneral, $medicalCommunityId) {
        if ($this->user["medicalCommunityId"] == $medicalCommunityId && $this->user["isGeneral"] == 1 && $isGeneral == 2) {
            return true;
        }
        return false;
    }

    private function getCheckStateName($checkState, $publicState, $allowanceType) {
        switch ($checkState) {
            case 1:
                return "待提交";
            case 3:
            case 5:
            case 13:
            case 15:
            case 20:
            case 25:
            case 35:
                return "审核中";
            case 8:
                return "总院驳回";
            case 9:
            case 10:
                return "已驳回";
            case - 1:
                if ($publicState >= 3) {
                    return "审核不通过";
                } else {
                    return "审核中";
                }
                break;
            case 30:
                if ($publicState == 1) {
                    return "待核查征信";
                } else if ($publicState == 2) {
                    return "待公示";
                } else if ($publicState == 3) {
                    return "公示中";
                } else if ($publicState == 4) {
                    return $allowanceType != 3 ? "待兑现" : "不予兑现";
                } else if ($publicState == 5) {
                    return "已兑现";
                }
            default:
                return "未知状态";
        }
    }

}
