request->param());
        return json($res);
    }
    /**
     * 积分申报入口
     */
    public function apply(\think\Request $request) {
        $type = $this->user["type"];
        $param = $request->param();
        $id = isset($param["id"]) ? $param["id"] : 0;
        $info = IntegralRecordApi::getOne($id);
        $ep = EnterpriseApi::getOne($this->user["uid"]);
        $streetList = DictApi::selectByParentCode('street');
        $ep->streetName = $streetList[$ep->street];
        if ($info) {
            $info["real_state"] = TalentLogApi::getLastLog($id, ProjectState::INTEGRAL)["state"];
        }
        if ($info && in_array($info["checkState"], [IntegralState::VERIFY_PASS, IntegralState::REVERIFY_PASS, IntegralState::REVERIFY_FAIL])) {
            return $this->view($request);
            exit();
        }
        if ($request->isPost()) {
            $checkState = $info["checkState"] ?: 0;
            if ($checkState == IntegralState::SAVE || $checkState == 0) {
                $this->save($info, $request, IntegralState::SAVE);
            } else if (in_array($checkState, [IntegralState::VERIFY_FAIL, IntegralState::REVERIFY_FAIL])) {
                $res = ["msg" => "审核不通过,不能再保存"];
                echo sprintf("", json_encode($res));
                exit;
            }
            $res = ["msg" => "已提交审核,请耐心等待"];
            echo sprintf("", json_encode($res));
            exit;
        }
        $checkState = $info["checkState"] ?: 0;
        $info["enterprise"] = $ep;
        return view("", ["year" => date("Y"), "checkState" => $checkState, "row" => $info]);
    }
    public function view(\think\Request $request) {
        $id = $request->param("id");
        $info = IntegralRecordApi::getOne($id);
        return view("", ["row" => $info]);
    }
    /**
     * 提交申请
     */
    public function submitToCheck() {
        $params = $this->request->param();
        $id = $params["id"];
        $info = IntegralRecordApi::chkIsOwner($id, $this->user["uid"]);
        if ($info) {
            $info["real_state"] = TalentLogApi::getLastLog($id, ProjectState::INTEGRAL)["state"];
        }
        $checkState = $info["checkState"];
        if ($checkState == IntegralState::SAVE || !$id) {
            $field_dict = [
                "name" => "姓名",
                "card_type" => "证件类型",
                "card_number" => "证件号码",
                "phone" => "手机号码",
                "email" => "电子邮箱",
                "shareholder" => "是否股东"
            ];
            $no_empty = ["name", "card_type", "card_number", "phone", "email", "shareholder"];
            $return = [];
            foreach ($no_empty as $key) {
                if (!$params[$key]) {
                    $return[] = sprintf("请填写“%s”", $field_dict[$key]);
                }
            }
            if (count($return) > 0) {
                $res = ["msg" => implode("
", $return)];
                echo sprintf("", json_encode($res));
                exit;
            }
            $insertDetailList = [];
            $tmp_item_ids = [];
            $projectTypes = $params["projectType"];
            $projectIds = $params["projectId"];
            $item_ids = $params["item_id"];
            $amounts = $params["amount"];
            $detailCounts = count($item_ids);
            for ($i = 0; $i < $detailCounts; $i++) {
                if (!in_array($item_ids[$i], $tmp_item_ids)) {
                    $tmp_item_ids[] = $item_ids[$i];
                }
                if (!is_numeric($amounts[$i]) || $amounts[$i] < 0) {
                    $res = ["msg" => sprintf("第%d个积分标准项的数额填写错误,应填入大于0的数字", $i + 1)];
                    echo sprintf("", json_encode($res));
                    exit;
                }
                $integralItemInfo = \app\common\api\IntegralItemApi::getOne($item_ids[$i]);
                if (!$integralItemInfo) {
                    $res = ["msg" => sprintf("第%d个积分标准项不存在", $i + 1)];
                    echo sprintf("", json_encode($res));
                    exit;
                }
                $ft_ids = array_filter(explode(",", $integralItemInfo["fileTypeId"]));
                if ($ft_ids) {
                    $whereFt = [];
                    $whereFt[] = ["id", "in", $ft_ids];
                    $whereFt[] = ["must", "=", 1];
                    $fts = Db::table("new_common_filetype")->where($whereFt)->select()->toArray();
                    $count = count($fts);
                    if ($count > 0) {
                        $_ft_ids = array_column($fts, "id");
                        $whr = [];
                        $whr[] = ["type", "=", ProjectState::INTEGRAL];
                        $whr[] = ["relationId", "=", $item_ids[$i]];
                        $whr[] = ["typeId", "in", $_ft_ids];
                        if ($id) {
                            $whr[] = ["mainId", "=", $id];
                        } else {
                            $whr[] = ["id", "in", $params["uploadFiles"]];
                        }
                        $distinct_filetypes = Db::table("new_talent_file")->where($whr)->distinct(true)->field("typeId")->select();
                        if ($count != count($distinct_filetypes)) {
                            $res = ["msg" => '积分项目"' . $integralItemInfo["name"] . '"缺少必传附件'];
                            echo sprintf("", json_encode($res));
                            exit;
                        }
                    }
                }
            }
            if (count($tmp_item_ids) != $detailCounts) {
                $res = ["msg" => "同一个申报中,同一个积分标准不能申报多次"];
                echo sprintf("", json_encode($res));
                exit;
            }
            $whrCommonFt = [];
            $whrCommonFt[] = ["project", "=", ProjectState::INTEGRAL];
            $whrCommonFt[] = ["active", "=", 1];
            $whrCommonFt[] = ["must", "=", 1];
            $whrCommonFt[] = ["delete", "=", 0];
            $whrCommonFt[] = ["type", "=", $this->user["type"]];
            $whrCommonFt[] = ["isConditionFile", "=", 1];
            $common_fts = Db::table("new_common_filetype")->where($whrCommonFt)->select()->toArray();
            $common_ft_ids = array_column($common_fts, "id");
            if ($common_ft_ids) {
                $whr = [];
                $whr[] = ["type", "=", ProjectState::INTEGRAL];
                $whr[] = ["typeId", "in", $common_ft_ids];
                if ($id) {
                    $whr[] = ["mainId", "=", $id];
                } else {
                    $whr[] = ["id", "in", $params["uploadFiles"]];
                }
                $distinct_filetypes = Db::table("new_talent_file")->where($whr)->distinct(true)->field("typeId")->select();
                $upload_type_counts = count($distinct_filetypes);
                if ($upload_type_counts != count($common_ft_ids)) {
                    $res = ["msg" => "公共附件缺少必传附件"];
                    echo sprintf("", json_encode($res));
                    exit;
                }
            }
            return $this->save($info, $this->request, IntegralState::SUBMIT);
        } else if (in_array($checkState, [IntegralState::VERIFY_FAIL, IntegralState::REVERIFY_FAIL, IntegralState::ZX_FAIL, IntegralState::ANNOUNCED_REVERIFY_FAIL, IntegralState::PUBLISH_FAIL])) {
            $res = ["msg" => "审核不通过,不能再提交审核"];
            echo sprintf("", json_encode($res));
            exit;
        }
        $res = ["msg" => "已提交审核,请耐心等待"];
        echo sprintf("", json_encode($res));
        exit;
    }
    /**
     * 保存申报表单
     * @param type $info talent_info
     * @param type $param request->param();
     */
    private function save($info, \think\Request $request, $checkState) {
        try {
            $param = $request->param();
            $batch = BatchApi::checkBatchValid(["type" => ProjectState::INTEGRAL, "year" => $info["apply_year"], "first_submit_time" => $info["first_submit_time"]], $this->user["type"]);
            if ($batch["code"] != 200) {
                throw new ValidateException($batch["msg"]);
            }
            $data["batch_id"] = $batch["id"];
            validate(IntegralValidator::class)->check($param);
            $id = $param["id"];
            $files = $param["uploadFiles"];
            if ($id) {
                if (!$info || $info["id"] != $id || $info["enterprise_id"] != $this->user["uid"]) {
                    throw new ValidateException("没有对应的积分申报信息");
                }
            }
            $all_valid_keys = ["name", "card_type", "card_number", "phone", "email", "shareholder"];
            foreach ($all_valid_keys as $key) {
                $data[$key] = trim($param[$key]);
            }
            $insertDetailList = [];
            $item_ids = $param["item_id"];
            $amounts = $param["amount"];
            $detailCounts = count($item_ids);
            for ($i = 0; $i < $detailCounts; $i++) {
                if (!is_numeric($amounts[$i]) || $amounts[$i] < 0) {
                    throw new ValidateException(sprintf("第%d个积分标准项的数额填写错误,应填入大于0的数字", $i + 1));
                }
                $tmpItemData = [];
                $tmpItemData = [
                    "id" => getStringId(),
                    "record_id" => "",
                    "item_id" => $item_ids[$i],
                    "amount" => $amounts[$i],
                    "unit" => ""
                ];
                if ($param["card_type"] && $param["card_number"]) {
                    $log = IntegralRecordApi::calIntegral($this->user["uid"], $param["card_type"], $param["card_number"], $item_ids[$i], $amounts[$i]);
                    $tmpItemData["pre_point"] = $log->points;
                    $tmpItemData["log"] = json_encode($log);
                }
                $insertDetailList[] = $tmpItemData;
            }
            if ($info["real_state"] == IntegralState::VERIFY_REJECT) {
                //真实状态是驳回,需要判断什么字段可以提交                
                $modify_fields = array_filter(explode(",", $info["modify_fields"]));
                $tmp_data = $data;
                $data = [];
                foreach ($modify_fields as $field) {
                    $data[$field] = $tmp_data[$field];
                }
                $tmp_item_ids = [];
                if (!$info["modify_files"]) {
                    $insertDetailList = []; //不能修改项目,清空
                }
            }
            $data["checkState"] = $checkState;
            $data["id"] = $id;
            $success_msg = "提交成功";
            $error_msg = "提交失败";
            if ($checkState == IntegralState::SAVE) {
                $success_msg = "保存成功";
                if ($data["id"]) {
                    //编辑
                    $data["updateTime"] = date("Y-m-d H:i:s");
                    \app\common\model\IntegralRecord::update($data);
                    $last_log = TalentLogApi::getLastLog($data["id"], ProjectState::INTEGRAL);
                    if ($last_log["new_state"] != IntegralState::SAVE) {
                        TalentLogApi::write(1, $data["id"], $checkState, "保存未提交", 1);
                    } else {
                        TalentLogApi::setActive($last_log["id"], 1); //更新修改时间
                    }
                } else {
                    //新增
                    $data["id"] = getStringId();
                    $data["enterprise_id"] = $this->user["uid"];
                    $data["createTime"] = date("Y-m-d H:i:s");
                    \app\common\model\IntegralRecord::insert($data);
                    TalentLogApi::write(ProjectState::INTEGRAL, $data["id"], $checkState, "保存未提交", 1);
                    $whr = [];
                    $whr[] = ["fileId", "in", $files];
                    $upd_checklog["mainId"] = $data["id"];
                    Db::table("new_talent_checklog")->where($whr)->save($upd_checklog);
                }
            } else if ($checkState == IntegralState::SUBMIT) {
                if (!$info["first_submit_time"]) {
                    $data["first_submit_time"] = date("Y-m-d H:i:s");
                } else {
                    $data["new_submit_time"] = date("Y-m-d H:i:s");
                }
                if ($data["id"]) {
                    $data["updateTime"] = date("Y-m-d H:i:s");
                    \app\common\model\IntegralRecord::update($data);
                } else {
                    //新增
                    $data["id"] = getStringId();
                    $data["enterprise_id"] = $this->user["uid"];
                    $data["createTime"] = date("Y-m-d H:i:s");
                    \app\common\model\IntegralRecord::insert($data);
                    $whr = [];
                    $whr[] = ["fileId", "in", $files];
                    $upd_checklog["mainId"] = $data["id"];
                    Db::table("new_talent_checklog")->where($whr)->save($upd_checklog);
                }
                TalentLogApi::write(ProjectState::INTEGRAL, $data["id"], $checkState, "确认提交审核", 1);
            } else {
                throw new ValidateException($error_msg);
            }
            if ($data["id"]) {
                if ($insertDetailList) {
                    \app\common\model\IntegralDetail::where("record_id", "=", $data["id"])->delete();
                    foreach ($insertDetailList as $insertItem) {
                        $integralItemInfo = \app\common\api\IntegralItemApi::getOne($item_ids[$i]);
                        $insertItem["record_id"] = $data["id"];
                        $insertItem["unit"] = $integralItemInfo["unit"];
                        \app\common\model\IntegralDetail::insert($insertItem);
                    }
                }
                //删除多余的附件,一般是选择人才类型留下来的
                $whr = [];
                $whr[] = ["mainId", "=", $data["id"]];
                $whr[] = ["type", "=", ProjectState::INTEGRAL];
                $whr[] = ["id", "not in", $files];
                $_wait_del_files = Db::table("new_talent_file")->where($whr)->select()->toArray();
                $_logfileIds[] = [];
                foreach ($_wait_del_files as $_del_file) {
                    $_logfileIds[] = $_del_file["id"];
                    @unlink("storage/" . $_del_file ["url"]);
                }
                Db::table("new_talent_file")->where($whr)->delete();
                if ($_logfileIds) {
                    $whr = [];
                    $whr[] = ["fileId", "in", $_logfileIds];
                    $_upd_checklog["description"] = "删除附件";
                    $_upd_checklog["updateUser"] = sprintf("%s(%s)", $this->user["account"], $this->user["companyName"] ?: $this->user["rolename"]);
                    $_upd_checklog["updateTime"] = date("Y-m-d H:i:s");
                    Db::table("new_talent_checklog")->where($whr)->save($_upd_checklog);
                }
                $whr = [];
                $whr[] = ["id", "in", $files];
                Db::table("new_talent_file")->where($whr)->save(["mainId" => $data["id"]]);
                $res = ["code" => 200, "msg" => $success_msg, "obj" => ["id" => $data["id"], "checkState" => $checkState]];
                $callback = $checkState == IntegralState::SAVE ? "infoCallback" : "submitCallback";
                echo sprintf("", json_encode($res));
                exit();
            } else {
                throw new ValidateException($error_msg);
            }
        } catch (ValidateException $e) {
            $res = ["msg" => $e->getMessage()];
            $callback = $checkState == IntegralState::SAVE ? "infoCallback" : "submitCallback";
            echo sprintf("", json_encode($res));
            exit();
        }
    }
    public function delete() {
        $id = $this->request->param("id");
        $info = IntegralRecordApi::chkIsOwner($id, $this->user["uid"]);
        if (!$info) {
            return json(["msg" => "操作失败"]);
        }
        $checkState = $info["checkState"];
        if (in_array($checkState, [0, 1])) {
            $log = TalentLogApi::getLastLog($id, ProjectState::INTEGRAL);
            if ($log["state"] > 1) {
                //有提交审核记录
                return json(["msg" => "该申报已提交审核,无法删除"]);
            }
        }
        $data["id"] = $id;
        $data["delete"] = 1;
        \app\common\model\IntegralRecord::update($data);
        return json(["msg" => "删除成功"]);
    }
}