<?php

namespace app\job;

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

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

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

    /**
     * 处理业务逻辑
     * @param type $data
     * @return bool
     */
    public function deal($data): bool {
        switch ($data["type"]) {
            case 1:
                //发放积分码后增加积分记录并检查达到晋升分没
                Db::startTrans();
                try {
                    $mainId = $data["id"];
                    $where = [];
                    $where[] = ["ir.id", "=", $mainId];
                    $where[] = ["ir.checkState", "=", IntegralState::SUCCESS];
                    $integralInfo = Db::table("new_integral_record")->alias("ir")->leftJoin("un_enterprise e", "e.id=ir.enterprise_id")->field("ir.*,e.type as enterpriseType")->where($where)->find();
                    $where = [];
                    $where[] = ["mainId", "=", $mainId];
                    $where[] = ["mainType", "=", "integral"];
                    $integralLog = Db::table("new_integral_log")->where($where)->find();
                    if ($integralInfo && !$integralLog) {
                        $name = $integralInfo["name"]; //姓名
                        $cardType = $integralInfo["card_type"]; //身份证类型
                        $cardNumber = $integralInfo["card_number"]; //身份证
                        $type = $integralInfo["enterpriseType"]; //企业类型
                        $lastPoints = 0; //上次积分                    
                        $levelAndPoints = [
                            1 => 6000,
                            2 => 4000,
                            3 => 2000,
                            4 => 1000,
                            5 => 500,
                            6 => 200,
                            7 => 100
                        ];
                        $levelAndNames = [
                            1 => "第一层次",
                            2 => "第二层次",
                            3 => "第三层次",
                            4 => "第四层次",
                            5 => "第五层次",
                            6 => "第六层次",
                            7 => "第七层次",
                        ];
                        $gainPoints = $integralInfo["totalPoints"]; //增加积分
                        $desc = sprintf("积分申报通过，增加%d分。", $gainPoints); //详情

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

                        $nowPoints = $lastPoints + $gainPoints;
                        $level = 1;
                        while ($levelPoints = CommonConst::getLayerPointsByLayer($level)) {
                            if ($nowPoints >= $levelPoints) {
                                break;
                            }
                            $level++;
                        }
                        if ($level >= 1 && $level <= 7) {
                            //积分达到人才标准，检查是否需要增加人才库记录或者晋升
                            $lastTalentLevel = $last_log["talentLevel"] ?: 8;
                            if ($level != $lastTalentLevel && $level < $lastTalentLevel) {
                                $desc .= sprintf("累计积分达到%d分，人才层次晋升（%s->%s）。", $nowPoints, CommonConst::getLayerNameByLayer($lastTalentLevel), CommonConst::getLayerNameByLayer($level));
                                //层级变动，并且当前层级小于日志最后记录的层级，则为晋升
                                /* 身份证提取有用内容填充 */
                                if ($cardType == 1) {
                                    $sex = substr($cardNumber, 16, 1);
                                    if ($sex % 2 == 0) {
                                        $newTalentInfo["sex"] = 2;
                                    } else {
                                        $newTalentInfo["sex"] = 1;
                                    }
                                    $year = substr($cardNumber, 6, 4);
                                    $month = substr($cardNumber, 10, 2);
                                    $day = substr($cardNumber, 12, 2);
                                    $birthday = $year . "-" . $month . "-" . $day;
                                    $newTalentInfo["birthday"] = $birthday;
                                }
                                /* 检查是否有存在人才码，保持同一个人唯一 */
                                $where = [];
                                $where[] = ["card_type", "=", $cardType];
                                $where[] = ["card_number", "=", $cardNumber];
                                $where[] = ["checkState", "=", TalentState::CERTIFICATED];
                                $fstTalentInfo = Db::table("new_talent_info")->where($where)->order("createTime asc")->find(); //取第一条全通记录
                                if ($fstTalentInfo) {
                                    $max_no = $fstTalentInfo["certificateNo"];
                                } else {
                                    /* 生成人才码 */
                                    $_prefix_type = "";
                                    $subindex = 5;
                                    switch ($type) {
                                        case 2:
                                            $_prefix_type = "IC";
                                            $subindex += strlen($_prefix_type);
                                            break;
                                    }
                                    $year = date("Y");
                                    $no_prefix = $_prefix_type . $year . $level;
                                    $where = [];
                                    $where[] = ["certificateNo", "like", $no_prefix . "%"];
                                    $max_no = Db::table("new_talent_info")->where($where)->max("certificateNo", false);
                                    if (!$max_no) {
                                        $max_no = $no_prefix . "0001";
                                    } else {
                                        $new_no = intval(substr($max_no, $subindex)) + 1;
                                        $max_no = $no_prefix . str_pad($new_no, 4, "0", STR_PAD_LEFT);
                                    }
                                }

                                /* 写入人才申报表 */
                                $newTalentInfo["enterprise_id"] = $integralInfo["enterprise_id"];
                                $newTalentInfo["name"] = $name;
                                $newTalentInfo["card_type"] = $cardType;
                                $newTalentInfo["card_number"] = $cardNumber;
                                $newTalentInfo["phone"] = $integralInfo["phone"];
                                $newTalentInfo["email"] = $integralInfo["email"];
                                $newTalentInfo["checkState"] = TalentState::CERTIFICATED;
                                $newTalentInfo["certificateNo"] = $max_no;
                                $newTalentInfo["identifyMonth"] = $integralInfo["getTime"];
                                $newTalentInfo["isEffect"] = 1;
                                $newTalentInfo["isPublic"] = 5;
                                $newTalentInfo["talent_arrange"] = $level;
                                $newTalentInfo["createTime"] = date("Y-m-d H:i:s");
                                $newTalentId = Db::table("new_talent_info")->insertGetId($newTalentInfo);
                                /* 积分申报的最后一条日志中提取有用内容填充下面的人才日志部分字段 */
                                $ir_last_log = TalentLogApi::getLastLog($mainId, ProjectState::INTEGRAL, 0, ["active", "=", 1]);

                                /* 写入人才申报日志表 */
                                $talent_log["last_state"] = 0;
                                $talent_log["id"] = getStringId();
                                $talent_log["state"] = $talent_log["new_state"] = TalentState::CERTIFICATED;
                                $talent_log["type"] = ProjectState::TALENT;
                                $talent_log["mainId"] = $newTalentId;
                                $talent_log["companyId"] = $ir_last_log["companyId"];
                                $talent_log["active"] = 1;
                                $talent_log["description"] = sprintf("人才积分（%d分）达到人才层次（%s）晋升标准（%d分），人才码为：%s", $nowPoints, CommonConst::getLayerNameByLayer($level), CommonConst::getLayerPointsByLayer($level), $max_no);
                                $talent_log["createUser"] = $ir_last_log["createUser"];
                                $talent_log["createTime"] = date("Y-m-d H:i:s");
                                Db::table("new_talent_checklog")->insert($talent_log);
                            }
                        }

                        $log["id"] = getStringId();
                        $log["type"] = $type;
                        $log["mainType"] = "integral";
                        $log["mainId"] = $mainId;
                        $log["enterprise_id"] = $integralInfo["enterprise_id"];
                        $log["name"] = $name;
                        $log["card_type"] = $cardType;
                        $log["card_number"] = $cardNumber;
                        $log["talentLevel"] = $level;
                        $log["lastPoints"] = $lastPoints;
                        $log["gainPoints"] = $gainPoints;
                        $log["nowPoints"] = $nowPoints;
                        $log["description"] = $desc;
                        $log["createTime"] = date("Y-m-d H:i:s");
                        Db::table("new_integral_log")->insert($log);

                        Db::commit();
                        return true;
                    }
                } catch (\Exception $e) {
                    Log::write($e->getMessage(), "error");
                    Db::rollback();
                    return false;
                }
                break;
        }
        return false;
    }

}
