<?php

namespace app\common\api;

use app\common\api\DictApi;
use app\admin\model\Enterprise;
use think\facade\Db;
use app\common\model\IntegralRecord;
use app\common\state\IntegralState;
use app\common\state\CommonConst;

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

    public static function getOne($id) {
        $result = IntegralRecord::where("id", "=", $id)->find();
        $result["enterprise"] = EnterpriseApi::getOne($result["enterprise_id"]);
        $result["apply_year"] = BatchApi::getOne($result["batch_id"])["batch"];
        $result["enterprise"]["streetName"] = DictApi::findDictByCode($result["enterprise"]["street"])["name"];
        if ($result) {
            $result["items"] = $result->detail;
            $result["tips"] = self::getIntegralRecordByIdCard($result["card_type"], $result["card_number"]);
        }
        return $result;
    }

    public static function getList($params) {
        $order = $params["order"] ?: "desc";
        $offset = $params["offset"] ?: 0;
        $limit = $params["limit"] ?: 10;

        $where = [];
        $where[] = ["e.type", "=", session("user")["type"]];

        if (session("user")["usertype"] == 2) {
            $where[] = ["enterprise_id", "=", session("user")["uid"]];
        }
        $where[] = ["ir.delete", "=", 0];
        if ($params["apply_year"]) {
            $where[] = ["b.batch", "like", "%{$params['apply_year']}%"];
        }
        if ($params["name"]) {
            $where[] = ["ir.name", "like", "%{$params['name']}%"];
        }
        if ($params["card_number"]) {
            $where[] = ["ir.card_number", "like", "%{$params['card_number']}%"];
        }
        if ($params["phone"]) {
            $where[] = ["ir.phone", "like", "%{$params['phone']}%"];
        }
        if ($params["email"]) {
            $where[] = ["ir.email", "like", "%{$params['email']}%"];
        }
        if ($params["shareholder"]) {
            $where[] = ["ir.shareholder", "=", $params['shareholder']];
        }
        switch ($params["checkState"]) {
            case -1:
                $where[] = ["tl.state", "in", [IntegralState::VERIFY_FAIL, IntegralState::REVERIFY_FAIL, IntegralState::ZX_FAIL, IntegralState::ANNOUNCED_REVERIFY_FAIL, IntegralState::PUBLISH_FAIL]];
                break;
            case 1:
                $where[] = ["tl.state", "=", IntegralState::SAVE];
                break;
            case 2:
                $where[] = ["tl.state", "in", [IntegralState::VERIFY_REJECT, IntegralState::REVERIFY_REJECT]];
                break;
            case 3:
                $where[] = ["tl.state", "in", [IntegralState::SUBMIT, IntegralState::VERIFY_PASS]];
                break;
            case 4:
                $where[] = ["tl.state", ">=", IntegralState::REVERIFY_PASS];
                $where[] = ["tl.state", "not in", [IntegralState::REVERIFY_REJECT, IntegralState::REVERIFY_FAIL]];
                break;
            case 5:
                $where[] = ["tl.state", "=", IntegralState::SUCCESS];
                break;
        }
        $count = IntegralRecord::alias("ir")
                        ->leftJoin("sys_batch b", "b.id=ir.batch_id")
                        ->leftJoin("(select description,mainId,last_state,new_state,state,createTime from new_talent_checklog where md5(concat(createTime,mainId,`type`)) in (select md5(concat(max(createTime),mainId,`type`)) from `new_talent_checklog` where `type`=20 and `step` is null and active=1 and typeFileId is null group by mainId,`type`)) tl", "`tl`.`mainId`=ir.id")
                        ->leftJoin("un_enterprise e", "e.id=ir.enterprise_id")->where($where)->count();
        $list = IntegralRecord::alias("ir")
                ->leftJoin("sys_batch b", "b.id=ir.batch_id")
                ->leftJoin("(select description,mainId,last_state,new_state,state,createTime from new_talent_checklog where md5(concat(createTime,mainId,`type`)) in (select md5(concat(max(createTime),mainId,`type`)) from `new_talent_checklog` where `type`=20 and `step` is null and active=1 and typeFileId is null group by mainId,`type`)) tl", "`tl`.`mainId`=ir.id")
                ->leftJoin("un_enterprise e", "e.id=ir.enterprise_id")->where($where)->field("ir.*,b.batch as apply_year,tl.state,tl.new_state,if(ir.updateTime is not null,ir.updateTime,ir.createTime) as orderTime")
                ->limit($offset, $limit)
                ->order("orderTime " . $order)
                ->select();
        foreach ($list as $key => $item) {
            $tmp_items = [];
            foreach ($item["detail"] as $_item) {
                $integral_item_info = getCacheById("IntegralItem", $_item["item_id"]);
                $tmp_items[] = sprintf("%s（%s%s）", $integral_item_info["name"], $_item["amount"], $integral_item_info["unit"]);
            }
            $list[$key]["details"] = implode("，", $tmp_items);
            $list[$key]["type"] = session("user")["type"];
            $last_log = TalentLogApi::getLastLog($item["id"], \app\common\state\ProjectState::INTEGRAL);
            $list[$key]["real_state"] = $last_log["state"];
            $list[$key]["last_state"] = $last_log["last_state"];
        }
        return ["total" => $count, "rows" => $list];
    }

    public static function getPublicList($params) {
        $order = $params["order"];
        $offset = $params["offset"];
        $limit = $params["limit"];
        $where = [];
        $where[] = ["e.type", "=", session("user")["type"]];
        if ($params["name"]) {
            $where[] = ["ir.name", "like", "%" . $params["name"] . "%"];
        }
        switch ($params["checkState"]) {
            case 1:
                $where[] = ["ir.checkState", "in", [IntegralState::REVERIFY_PASS, IntegralState::ZX_PASS, IntegralState::ANNOUNCED, IntegralState::ANNOUNCED_REVERIFY_PASS, IntegralState::PUBLISH_PASS]];
                break;
            case 2:
                $where[] = ["ir.checkState", "in", [IntegralState::REVERIFY_FAIL, IntegralState::ZX_FAIL, IntegralState::ANNOUNCED_REVERIFY_FAIL, IntegralState::PUBLISH_FAIL]];
                break;
        }
        $type = $params["type"];
        switch ($type) {
            case 1:
            case 2:
                $where[] = ["ir.checkState", "=", IntegralState::REVERIFY_PASS];
                break;
            case 3:             //公示
            case 7:             //公示预览
                $where[] = ["ir.checkState", "=", IntegralState::ZX_PASS];
                break;
            case 4:             //公示通过
                $where[] = ["ir.checkState", "=", IntegralState::ANNOUNCED];
                break;
            case 5:
            case 8:             //公布预览
                $where[] = ["ir.checkState", "=", IntegralState::ANNOUNCED_REVERIFY_PASS];
                break;
            case 6:
                $where[] = ["ir.checkState", "=", IntegralState::PUBLISH_PASS];
                break;
        }
        $count = IntegralRecord::alias("ir")->leftJoin("un_enterprise e", "e.id=ir.enterprise_id")->where($where)->count();
        $list = IntegralRecord::alias("ir")->leftJoin("un_enterprise e", "e.id=ir.enterprise_id")
                        ->where($where)
                        ->limit($offset, $limit)
                        ->order("ir.createTime " . $order)->field("ir.*,e.name as enterpriseName,e.type as enterprise_type,enterpriseTag")->select()->toArray();
        foreach ($list as &$item) {
            $item["talent_type"] = $item["enterprise_type"] == 1 ? "晋江市现代产业体系人才" : "集成电路优秀人才";
        }unset($item);
        return ["total" => $count, "rows" => $list];
    }

    public static function getListByProcess($params) {
        $order = $params["order"] ?: "desc";
        $offset = $params["offset"] ?: 0;
        $limit = $params["limit"] ?: 10;
        $process = $params["process"] ?: 1;

        $where = [];
        $where[] = ["e.type", "=", session("user")["type"]];
        switch ($process) {
            case 1://初审阶段
                switch ($params["checkState"]) {
                    case 1://待审核
                        $where[] = ["ir.checkState", "=", IntegralState::SUBMIT];
                        $where[] = ["tl.state", "=", IntegralState::SUBMIT];
                        break;
                    case 2://驳回
                        $where[] = ["tl.new_state", "in", [IntegralState::SAVE]];
                        $where[] = ["tl.state", "in", [IntegralState::VERIFY_REJECT]];
                        break;
                    case 3:
                        //审核失败
                        $where[] = ["ir.checkState", "in", [IntegralState::VERIFY_FAIL]];
                        break;
                    default:
                        $where[] = ["tl.state", "in", [IntegralState::SUBMIT, IntegralState::VERIFY_REJECT, IntegralState::VERIFY_FAIL]];
                }
                break;
            case 2://复审阶段
                switch ($params["checkState"]) {
                    case 1://待审核
                        $where[] = ["tl.state", "=", IntegralState::VERIFY_PASS];
                        break;
                    case 3:
                        //审核失败
                        $where[] = ["tl.state", "in", [IntegralState::VERIFY_FAIL]];
                        break;
                    default:
                        $where[] = ["tl.state", "in", [IntegralState::VERIFY_PASS, IntegralState::REVERIFY_FAIL]];
                }
                break;
            case 3://复审后征信公示等状态
                if ($params["checkState"]) {
                    $where[] = ["ir.checkState", "=", $params["checkState"]];
                } else {
                    $where[] = ["ir.checkState", "in", [IntegralState::REVERIFY_PASS, IntegralState::ZX_PASS, IntegralState::ZX_FAIL, IntegralState::ANNOUNCED, IntegralState::ANNOUNCED_REVERIFY_PASS, IntegralState::ANNOUNCED_REVERIFY_FAIL, IntegralState::PUBLISH_PASS, IntegralState::PUBLISH_FAIL, IntegralState::SUCCESS]];
                }
                break;
            case 4:
                return self::getLibraryList($params);
            case 5:
                return self::getIntegralLogs($params);
                break;
        }
        $where[] = ["ir.delete", "=", 0];
        if ($params["apply_year"]) {
            $where[] = ["b.batch", "like", "%{$params['apply_year']}%"];
        }
        if ($params["name"]) {
            $where[] = ["ir.name", "like", "%{$params['name']}%"];
        }
        if ($params["card_number"]) {
            $where[] = ["ir.card_number", "like", "%{$params['card_number']}%"];
        }
        if ($params["phone"]) {
            $where[] = ["ir.phone", "like", "%{$params['phone']}%"];
        }
        if ($params["email"]) {
            $where[] = ["ir.email", "like", "%{$params['email']}%"];
        }
        if ($params["enterprise_id"]) {
            $where[] = ["ir.enterprise_id", "=", $params['enterprise_id']];
        }
        if ($params["shareholder"]) {
            $where[] = ["ir.shareholder", "=", $params['shareholder']];
        }
        $count = IntegralRecord::alias("ir")->where($where)
                ->leftJoin("sys_batch b", "b.id=ir.batch_id")
                ->leftJoin("un_enterprise e", "e.id=ir.enterprise_id")
                ->leftJoin("(select description,mainId,last_state,new_state,state,createTime from new_talent_checklog where md5(concat(createTime,mainId,`type`)) in (select md5(concat(max(createTime),mainId,`type`)) from `new_talent_checklog` where `type`=20 and `step` is null and active=1 and typeFileId is null group by mainId,`type`)) tl", "`tl`.`mainId`=ir.id")
                ->count();
        $list = IntegralRecord::alias("ir")->where($where)
                        ->leftJoin("sys_batch b", "b.id=ir.batch_id")
                        ->leftJoin("un_enterprise e", "e.id=ir.enterprise_id")
                        ->leftJoin("(select description,mainId,last_state,new_state,state,createTime from new_talent_checklog where md5(concat(createTime,mainId,`type`)) in (select md5(concat(max(createTime),mainId,`type`)) from `new_talent_checklog` where `type`=20 and `step` is null and active=1 and typeFileId is null group by mainId,`type`)) tl", "`tl`.`mainId`=ir.id")
                        ->field("ir.*,e.name as enterpriseName,b.batch as apply_year,tl.state as real_state,tl.last_state")->limit($offset, $limit)->order("tl.createTime " . $order)->select();
        foreach ($list as $key => $item) {
            $tmp_items = [];
            foreach ($item["detail"] as $_item) {
                $integral_item_info = getCacheById("IntegralItem", $_item["item_id"]);
                $tmp_items[] = sprintf("%s（%s%s）", $integral_item_info["name"], $_item["amount"], $integral_item_info["unit"]);
            }
            $list[$key]["details"] = implode("；", $tmp_items);
            $list[$key]["type"] = session("user")["type"];
            //$last_log = TalentLogApi::getLastLog($item["id"], \app\common\state\ProjectState::INTEGRAL);
            //$list[$key]["real_state"] = $last_log["state"];
            //$list[$key]["last_state"] = $last_log["last_state"];
        }
        return ["total" => $count, "rows" => $list];
    }

    public static function getLibraryList($params) {
        $order = $params["order"] ?: "desc";
        $offset = $params["offset"] ?: 0;
        $limit = $params["limit"] ?: 10;

        $where = [];
        $where[] = ["e.type", "=", session("user")["type"]];
        if ($params["name"]) {
            $where[] = ["l.name", "like", "%{$params['name']}%"];
        }
        if ($params["card_number"]) {
            $where[] = ["l.card_number", "like", "%{$params['card_number']}%"];
        }
        if ($params["enterprise_id"]) {
            $where[] = ["l.enterprise_id", "=", $params['enterprise_id']];
        }
        if ($params["veto"]) {
            $having = "if(min_shareholder=1 and enterprise_veto = 1,true,false) or personal_veto = 1";
        } else {
            $having = "if(min_shareholder=1 and enterprise_veto = 1,false,true) and personal_veto = 0";
        }
        $count = Db::table("new_integral_log")->alias("l")->where($where)
                ->leftJoin("un_enterprise e", "e.id=l.enterprise_id")
                //->leftJoin("new_integral_veto iv1", "iv1.enterprise_id=l.enterprise_id")
                //->leftJoin("new_integral_veto iv2", "md5(concat(iv2.card_type,iv2.card_number))=md5(concat(l.card_type,l.card_number))")
                //->field("min(shareholder) as min_shareholder,if(iv1.`active`=1,iv1.`active`,0) as enterprise_veto,if(iv2.`active`=1,iv2.`active`,0) as personal_veto")
                ->group("concat(l.card_type,l.card_number)")
                //->having($having)
                ->count();
        $list = Db::table("new_integral_log")->alias("l")->where($where)
                        ->leftJoin("un_enterprise e", "e.id=l.enterprise_id")
                        //->leftJoin("new_integral_veto iv1", "iv1.enterprise_id=ir.enterprise_id")
                        //->leftJoin("new_integral_veto iv2", "md5(concat(iv2.card_type,iv2.card_number))=md5(concat(ir.card_type,ir.card_number))")
                        ->group("concat(l.card_type,l.card_number)")
                        //->having($having)
                        //->field("min(shareholder) as min_shareholder,ir.name,ir.card_type,ir.card_number,ir.enterprise_id,sum(ir.totalPoints) as totalPoints,e.name as enterpriseName,if(iv1.`active`=1,iv1.`active`,0) as enterprise_veto,iv1.description as enterprise_veto_msg,if(iv2.`active`=1,iv2.`active`,0) as personal_veto,iv2.description as personal_veto_msg")
                        ->field("l.*,sum(gainPoints) as totalPoints,e.name as enterpriseName")
                        ->limit($offset, $limit)
                        //->order("b.batch " . $order)
                        ->select()->toArray();
        foreach ($list as $key => $item) {
            $list[$key]["basePoints"] = CommonConst::getLayerPointsByLayer($item["talentLevel"]);
        }
        return ["total" => $count, "rows" => $list];
    }

    public static function getIntegralLogs($params) {
        $order = $params["order"] ?: "desc";
        $offset = $params["offset"] ?: 0;
        $limit = $params["limit"] ?: 10;

        $where = [];
        $where[] = ["e.type", "=", session("user")["type"]];
        if ($params["name"]) {
            $where[] = ["l.name", "like", "%{$params['name']}%"];
        }
        if ($params["card_number"]) {
            $where[] = ["l.card_number", "like", "%{$params['card_number']}%"];
        }
        if ($params["enterprise_id"]) {
            $where[] = ["l.enterprise_id", "=", $params['enterprise_id']];
        }
        $count = Db::table("new_integral_log")->alias("l")->where($where)
                ->leftJoin("un_enterprise e", "e.id=l.enterprise_id")
                ->count();
        $list = Db::table("new_integral_log")->alias("l")
                        ->field("l.*,e.name as enterpriseName")
                        ->leftJoin("un_enterprise e", "e.id=l.enterprise_id")
                        ->where($where)
                        ->limit($offset, $limit)
                        ->order("l.createTime desc")
                        ->select()->toArray();
        foreach ($list as $key => $item) {
            $where = [];
            if ($item["mainType"] == "integral") {
                $where[] = ["ir.id", "=", $item["mainId"]];
                $integralInfo = IntegralRecord::alias("ir")->leftJoin("sys_batch b", "b.id=ir.batch_id")->field("ir.*,b.batch as apply_year")->where($where)->find();
                $list[$key]["apply_year"] = $integralInfo["apply_year"];
                $list[$key]["shareholder"] = $integralInfo["shareholder"];
                $tmp_items = [];
                foreach ($integralInfo["detail"] as $_item) {
                    $integral_item_info = getCacheById("IntegralItem", $_item["item_id"]);
                    $tmp_items[] = sprintf("%s（%s%s）", $integral_item_info["name"], $_item["amount"], $integral_item_info["unit"]);
                }
                $list[$key]["details"] = implode("；", $tmp_items);
                $list[$key]["first_submit_time"] = $integralInfo["first_submit_time"];
                $list[$key]["new_submit_time"] = $integralInfo["new_submit_time"];
            } else {
                $where[] = ["id", "=", $item["mainId"]];
                $talentInfo = Db::table("new_talent_info")->where($where)->find();
                $list[$key]["apply_year"] = $talentInfo["apply_year"];
                $list[$key]["details"] = $item["description"];
                $list[$key]["first_submit_time"] = $talentInfo["first_submit_time"];
                $list[$key]["new_submit_time"] = $talentInfo["new_submit_time"];
            }
        }
        return ["total" => $count, "rows" => $list];
    }

    public static function checkIsEditable($id) {
        $info = self::getOne($id);
        if (!$info || !in_array($info["checkState"], [0, IntegralState::SAVE]))
            return false;
        return true;
    }

    static public function chkIsOwner($id, $uid) {
        $info = self::getOne($id);
        if ($info["enterprise_id"] != $uid)
            return null;
        return $info;
    }

    /**
     * 导出
     * @param type $process
     * @param type $params
     * @return type
     */
    public static function getExportDatas($process, $params) {
        $where[] = [];
        //特殊字段处理
        $fields = [];
        $fields[] = "ir.id";
        foreach ($params as $param) {
            if (!in_array($param, ["enterpriseName", "street", "checkMsg", "project", "year"])) {
                $fields[] = "ir." . $param;
            }
        }
        $fields[] = "e.name as enterpriseName";
        $fields[] = "e.street";
        $fields[] = "tl.description as checkMsg";
        $fields[] = "b.batch as year";
        if (in_array("card_type", $params)) {
            $cardTypes = DictApi::selectByParentCode("card_type");
        }
        if (in_array("street", $params)) {
            $streets = DictApi::selectByParentCode("street");
        }
        $sex = [1 => "男", 2 => "女"];

        $where = [];
        $where[] = ["e.type", "=", session("user")["type"]];
        switch ($process) {
            case 1:
                $where = "ir.checkState in (" . IntegralState::SUBMIT . "," . IntegralState::VERIFY_FAIL . ")";
                break;
            case 2:
                $where = "ir.checkState in (" . IntegralState::VERIFY_PASS . "," . IntegralState::REVERIFY_FAIL . ")";
                break;
            case 3:
                $where = "ir.checkState >= " . IntegralState::REVERIFY_PASS;
                break;
        }
        $list = IntegralRecord::alias("ir")
                        ->field($fields)
                        ->leftJoin("un_enterprise e", "e.id=ir.enterprise_id")
                        ->leftJoin("sys_batch b", "b.id=ir.batch_id")
                        ->leftJoin("(select description,mainId,last_state,new_state,state,createTime from new_talent_checklog where md5(concat(createTime,mainId,`type`)) in (select md5(concat(max(createTime),mainId,`type`)) from `new_talent_checklog` where `type`=20 and `step` is null and active=1 and typeFileId is null group by mainId,`type`)) tl", "`tl`.`mainId`=ir.id")
                        //->leftJoin("new_talent_checklog tl", "tl.mainId=ti.id and tl.id=(select id from new_talent_checklog where mainId=ti.id and `step` is null and active=1 and typeFileId is null order by createTime desc limit 1)")
                        ->whereRaw($where)
                        ->select()->toArray();
        foreach ($list as &$item) {
            $item["card_type"] = $cardTypes[$item["card_type"]];
            $item["street"] = $streets[$item["street"]];
            $item["sex"] = $sex[$item["sex"]];
            $item["checkState"] = IntegralState::getStateName($item["checkState"]);
            $detail = \app\common\model\IntegralDetail::where("record_id", $item["id"])->select();
            $tmp_items = [];
            foreach ($detail as $_item) {
                $integral_item_info = getCacheById("IntegralItem", $_item["item_id"]);
                $tmp_items[] = sprintf("%s（%s%s）", $integral_item_info["name"], $_item["amount"], $integral_item_info["unit"]);
            }
            $item["project"] = implode("；", $tmp_items);
        }unset($item);
        return $list;
    }

    public static function getListByIds($ids) {
        $where[] = ["id", "in", $ids];
        return IntegralRecord::where($where)->select()->toArray();
    }

    /**
     * 计算积分
     * @param type $enterpriseId 企业id
     * @param type $cardType 证件类型
     * @param type $cardNumber 证件号码
     * @param type $itemId 标准id
     * @param type $amount 达成数额
     * @return \stdClass 完整积分记录对象
     */
    public static function calIntegral($enterprise_id, $cardType, $cardNumber, $itemId, $amount) {
        $returnObj = new \stdClass();
        $returnObj->amount = $amount;
        $item = getCacheById("IntegralItem", $itemId);
        $projectRemainderPoints = 0; //项目剩余总上限
        $itemRemainderPoints = 0; //标准剩余总上限
        $points = 0; //当前可获得积分
        if ($item) {
            $project = getCacheById("IntegralProject", $item["projectId"]);
            $projectRemainderPoints = $project["max"]; //初始化项目可获得剩余积分
            $itemRemainderPoints = $item["max"]; //初始化标准可获得剩余积分
            if ($project["limit"] == 1) {
                //项目下所有规则总上限
                $where = [];
                $where[] = ["r.enterprise_id", "=", $enterprise_id];
                $where[] = ["r.card_type", "=", $cardType];
                $where[] = ["r.card_number", "=", $cardNumber];
                $where[] = ["r.checkState", ">=", IntegralState::SUCCESS];
                $where[] = ["i.projectId", "=", $project["id"]];
                if ($project["yearly"] == 1) {
                    //年度重置只算当年度
                    $startTime = date("Y-01-01 00:00:00");
                    $endTime = date("Y-12-31 23:59:59");
                    $where[] = ["r.createTime", "between", [$startTime, $endTime]];
                    $returnObj->projectYearly = 1;
                }
                $totalPoints = Db::table("new_integral_detail")->alias("d")->leftJoin("new_integral_record r", "r.id=d.record_id")->leftJoin("new_integral_item i", "i.id=d.item_id")->where($where)->sum("d.point");
                $projectRemainderPoints -= $totalPoints;
                $returnObj->projectMaxPoints = $project["max"];
                $returnObj->projectRemainderPoints = $projectRemainderPoints;
            }
            if ($item["limit"] == 1) {
                //规则上限
                $where = [];
                $where[] = ["r.enterprise_id", "=", $enterprise_id];
                $where[] = ["r.card_type", "=", $cardType];
                $where[] = ["r.card_number", "=", $cardNumber];
                $where[] = ["r.checkState", ">=", IntegralState::SUCCESS];
                $where[] = ["d.item_id", "=", $itemId];
                if ($item["yearly"] == 1) {
                    //年度重置只算当年度
                    $startTime = date("Y-01-01 00:00:00");
                    $endTime = date("Y-12-31 23:59:59");
                    $where[] = ["r.createTime", "between", [$startTime, $endTime]];
                    $returnObj->itemYearly = 1;
                }
                $totalPoints = Db::table("new_integral_detail")->alias("d")->leftJoin("new_integral_record r", "r.id=d.record_id")->where($where)->sum("d.point");
                $itemRemainderPoints -= $totalPoints;
                $returnObj->itemMaxPoints = $item["max"];
                $returnObj->itemRemainderPoints = $itemRemainderPoints;
            }
            $where = [];
            $where[] = ["r.enterprise_id", "=", $enterprise_id];
            $where[] = ["r.card_type", "=", $cardType];
            $where[] = ["r.card_number", "=", $cardNumber];
            $where[] = ["r.checkState", ">=", IntegralState::SUCCESS];
            $where[] = ["d.item_id", "=", $itemId];
            $fstGain = Db::table("new_integral_detail")->alias("d")->leftJoin("new_integral_record r", "r.id=d.record_id")->where($where)->field("d.*")->order("createTime asc")->find();
            if ($item["stepNeedAmount"] && $item["stepGainPoints"]) {
                $returnObj->stepNeedAmount = $item["stepNeedAmount"];
                $returnObj->stepGainPoints = $item["stepGainPoints"];
                if ($fstGain) {
                    $returnObj->fstGainRecordId = $fstGain["record_id"];
                    $returnObj->fstGainDetailId = $fstGain["id"];
                    //有配置增量积分
                    if ($item["stepIsYear"] == 1) {
                        //较上年度增量
                        $where = [];
                        $where[] = ["r.enterprise_id", "=", $enterprise_id];
                        $where[] = ["r.card_type", "=", $cardType];
                        $where[] = ["r.card_number", "=", $cardNumber];
                        $where[] = ["r.checkState", ">=", IntegralState::SUCCESS];
                        $where[] = ["d.item_id", "=", $itemId];
                        $startTime = date("Y-m-d 00:00:00", strtotime("first day of last year"));
                        $endTime = date("Y-12-31 23:59:59", strtotime("last day of last year"));
                        $where[] = ["r.createTime", "between", [$startTime, $endTime]];
                        $lastYearTotalAmount = Db::table("new_integral_detail")->alias("d")->leftJoin("new_integral_record r", "r.id=d.record_id")->where($where)->sum("d.amount");
                        $newGainAmount = $amount - $lastYearTotalAmount;
                        $times = floor($newGainAmount / $item["stepNeedAmount"]);
                        $returnObj->stepIsYear = 1;
                        $returnObj->lastYearTotalAmount = $lastYearTotalAmount;
                        $returnObj->newGainAmount = $newGainAmount;
                    } else {
                        $times = floor($amount / $item["stepNeedAmount"]);
                        $returnObj->stepAmount = $amount;
                    }
                    $points = $item["stepGainPoints"] * $times;
                    $returnObj->times = $times;
                    $returnObj->points = $returnObj->stepPoints = $points;
                } else {
                    //首次
                    $returnObj->fstNeedAmount = $item["fstNeedAmount"];
                    $returnObj->fstGainPoints = $item["fstGainPoints"];
                    $returnObj->fstAmount = $amount >= $item["fstNeedAmount"] ? $item["fstNeedAmount"] : $amount;
                    $returnObj->fstPoints = $amount >= $item["fstNeedAmount"] ? $item["fstGainPoints"] : 0;
                    if ($item["stepIsYear"] != 1) {
                        //未设置较上年度增量时，首次还需计算增量部分
                        $stepAmount = $amount - $item["fstNeedAmount"];
                        if ($stepAmount > 0) {
                            $times = floor($stepAmount / $item["stepNeedAmount"]);
                            $returnObj->stepAmount = $stepAmount;
                            $returnObj->times = $times;
                            $returnObj->stepPoints = $item["stepGainPoints"] * $times;
                        }
                    } else {
                        $returnObj->stepIsYear = 1;
                    }
                    $returnObj->points = $returnObj->stepPoints ? $returnObj->fstPoints + $returnObj->stepPoints : $returnObj->fstPoints;
                }
            } else {
                //仅首次可得积分
                if ($fstGain) {
                    $returnObj->points = 0;
                    $returnObj->msg = "仅首次能获得积分";
                } else {
                    $returnObj->fstNeedAmount = $item["fstNeedAmount"];
                    $returnObj->fstGainPoints = $item["fstGainPoints"];
                    $returnObj->fstAmount = $amount >= $item["fstNeedAmount"] ? $item["fstNeedAmount"] : $amount;
                    $returnObj->points = $returnObj->fstPoints = $amount >= $item["fstNeedAmount"] ? $item["fstGainPoints"] : 0;
                }
            }
            $point1 = $project["limit"] == 1 ? ($returnObj->projectRemainderPoints > $returnObj->points ? $returnObj->points : $returnObj->projectRemainderPoints) : $returnObj->points;
            $point2 = $item["limit"] == 1 ? ($returnObj->itemRemainderPoints > $returnObj->points ? $returnObj->points : $returnObj->itemRemainderPoints) : $returnObj->points;
            $returnObj->theoretical = $returnObj->points; //理论值
            $returnObj->points = $point1 > $point2 ? $point2 : $point1; //实际值，当有限额时，会与理论值有偏差
        }
        return $returnObj;
    }

    /**
     *  获取是否在库及积分情况
     * @param type $cardType
     * @param type $cardNumber
     * @return array $response
     */
    public static function getIntegralRecordByIdCard($cardType, $cardNumber) {
        if ($cardType && $cardNumber) {
            $where = [];
            $where[] = ["card_type", "=", $cardType];
            $where[] = ["card_number", "=", $cardNumber];
            $where[] = ["checkState", "=", TalentState::CERTIFICATED];
            $talentInfo = Db::table("new_talent_info")->where($where)->find();

            $where = [];
            $where[] = ["card_type", "=", $cardType];
            $where[] = ["card_number", "=", $cardNumber];
            $integralLog = Db::table("new_integral_log")->where($where)->order("createTime desc")->find();
            if (session("user")["usertype"] == 2 && (($talentInfo && session("user")["uid"] != $talentInfo["enterprise_id"]) || ($integralLog && session("user")["uid"] != $integralLog["enterprise_id"]))) {
                $response = [
                    "deny" => 1
                ];
            } else {
                $response = [
                    "isTalentInLibrary" => $talentInfo ? 1 : 0,
                    "levelName" => CommonConst::getLayerNameByLayer($integralLog["talentLevel"]),
                    "level" => $integralLog["talentLevel"],
                    "totalPoints" => $integralLog["nowPoints"] ?: 0
                ];
            }

            if ($response["deny"]) {
                //不是本企业人员
                return "该身份证已经在别的企业申报过优秀人才 / 积分项目";
            } else {
                $levelTypeName = $response["level"] >= 1 && $response["level"] <= 7 ? "在库人才（" . $response["levelName"] . "）" : $response["levelName"];
                return sprintf("该人员为%s，截至目前，已累计%d积分", $levelTypeName, $response["totalPoints"]);
            }
        }
        return "";
    }

    public static function setPublic($mainId, $state, $msg, $batch = null) {
        $data["id"] = $mainId;
        $data["checkState"] = $state;
        switch ($state) {
            case IntegralState::ZX_PASS:
            case IntegralState::ZX_FAIL:
                $data["isPublic"] = 2;
                break;
            case IntegralState::ANNOUNCED:
                $data["isPublic"] = 3;
                $data["publicBatch"] = $batch;
                break;
            case IntegralState::ANNOUNCED_REVERIFY_PASS:
            case IntegralState::ANNOUNCED_REVERIFY_FAIL:
                $data["isPublic"] = 3;
                break;
            case IntegralState::PUBLISH_PASS:
                $data["getTime"] = $batch;
                $data["isPublic"] = 4;
                break;
            case IntegralState::PUBLISH_FAIL:
                $data["isPublic"] = 4;
                break;
        }
        if (IntegralRecord::update($data)) {
            TalentLogApi::write(\app\common\state\ProjectState::INTEGRAL, $mainId, $state, $msg, 1);
            return true;
        }
        return false;
    }

}
