<?php

namespace app\job;

use think\queue\Job;
use think\facade\Log;
use think\facade\Db;
use app\common\api\TalentState;
use app\common\state\ProjectState;
use app\common\model\TalentChecklog;
use app\common\model\TalentAllowance as TaModel;
use app\common\state\MainState;
use app\common\api\LocationApi;
use app\enterprise\model\TalentTypeChange;
use app\common\state\AllowanceProjectEnum;
use app\common\state\AllowanceTypeEnum;

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

    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:
                //添加保存未提交的津补贴申报
                try {
                    $method = $data["method"];
                    $talentId = $data["talentId"];
                    $importRow = $data["data"];
                    $enterprise = $data["enterprise"];
                    $year = $data["year"];
                    $allowanceType = $data["allowanceType"];
                    if ($method == 1) {
                        $ti = \app\common\api\VerifyApi::getTalentInfoById($talentId);
                        if ($ti["talent_type"] == 1 && $ti["enterpriseType"] == \app\common\state\CommonConst::ENTERPRISE_WJ && $allowanceType == AllowanceTypeEnum::JBT_JT) {
                            return false;
                        }
                    } else {
                        $where[] = ["card_number", "=", $importRow[1]];
                        $where[] = ["delete", "=", 0];
                        $where[] = ["checkState", "=", TalentState::CERTIFICATED];
                        $ti = Db::table("new_talent_info")->where($where)->order("talent_arrange asc")->find();
                        $talentId = $ti["id"];
                        $ti = \app\common\api\VerifyApi::getTalentInfoById($talentId);
                        if ($ti["talent_type"] == 1 && $ti["enterpriseType"] == \app\common\state\CommonConst::ENTERPRISE_WJ && $allowanceType == AllowanceTypeEnum::JBT_JT) {
                            return false;
                        }
                    }
                    if ($ti["checkState"] != TalentState::CERTIFICATED || $ti["enterprise_id"] != $enterprise["uid"] || !$year || !$allowanceType) {
                        return false;
                    }

                    $where = [];
                    $where[] = ["year", "=", $year];
                    $where[] = ["delete", "=", 0];
                    $where[] = ["idCard", "=", $ti["card_number"]];
                    $where[] = ["checkState", "not in", [MainState::NOTPASS, MainState::PASS]];
                    $exists = TaModel::where($where)->find();
                    if ($exists) {
                        return false;
                    }

                    $data = [
                        "talentId" => $talentId,
                        "enterpriseId" => $ti["enterprise_id"],
                        "enterpriseName" => $enterprise["name"],
                        "year" => $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" => $enterprise["type"],
                        "provinceCode" => $ti["province"],
                        "provinceName" => LocationApi::getNameByCode($ti["province"]),
                        "cityCode" => $ti["city"],
                        "cityName" => LocationApi::getNameByCode($ti["city"]),
                        "countyCode" => $ti["county"],
                        "countyName" => LocationApi::getNameByCode($ti["county"]),
                        "isSupple" => 2,
                        "createTime" => date("Y-m-d H:i:s"),
                        "createUser" => $enterprise["uid"],
                        "id" => getStringId(),
                        "allowanceType" => $allowanceType
                    ];

                    $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"] == \app\common\state\CommonConst::ENTERPRISE_JC) || (in_array($ti["enterpriseType"], [\app\common\state\CommonConst::ENTERPRISE_WJ, \app\common\state\CommonConst::ENTERPRISE_GJ]) && $year != 2023)) && $identifyYear > $year) {
                        return false;
                    }

                    /*                     * 1.获取上一年度的人才层次 */
                    $arrangeList = $this->getLastYearTalentType($data, $ti);
                    if (!$arrangeList) {
                        if ($ti["enterpriseType"] == \app\common\state\CommonConst::ENTERPRISE_JC) {
                            $identifyYear = substr($ti["identifyMonth"], 0, 4);
                            if (!$year || !$identifyYear || $identifyYear > $year) {
                                return false;
                            }
                        } else {
                            return false;
                        }
                    }
                    /*                     * 2.获取上一年度所在单位* */
                    $contractDetailList = $this->getConcatList($ti, $data, $year); //保存上一年度的工作单位
                    if (!$contractDetailList) {
                        return false;
                    }
                    TaModel::insert($data);
                    \app\common\model\TalentAllowancecontractDetail::insertAll($contractDetailList);
                    /**
                     * 4.添加津补贴核查项目
                     */
                    //核查项目详情表
                    if ($method == 1) {
                        $this->createAllowanceProject($data, $contractDetailList);
                    } else {
                        $this->createAllowanceProject_m2($data, $contractDetailList, $importRow);
                    }
                    \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)", $enterprise["account"], $enterprise["companyName"])
                    ]);
                    return true;
                } catch (\Exception $e) {
                    Log::write($e->getMessage(), "error");
                }
                break;
        }
        return false;
    }

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

    private function getLastYearTalentType($info, $talentInfo) {
        $year = substr($info["year"], 0, 4);
        $arrangeList = [];
        /*         * * 添加人才层次记录 */
        $oldStartTimeField = "oldIdentifyMonth";
        $newStartTimeField = "newIdentifyMonth";
        if ($info["type"] == \app\common\state\CommonConst::ENTERPRISE_JC) {
            $oldStartTimeField = "oldIdentifyGetTime";
            $newStartTimeField = "newIdentifyGetTime";
        }
        if (in_array($info["type"], [\app\common\state\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", "=", TalentState::CERTIFICATED];
            $whr[] = ["ti.enterprise_id", "=", $talentInfo["enterpriseId"]];
            $whr[] = ["e.type", "=", $talentInfo["enterpriseType"]];
            $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"], [\app\common\state\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);
        }
    }

    private function createAllowanceProject_m2($info, $contractList, $rowdata) {
        $count = 0;
        $projects = AllowanceProjectEnum::getProjectsByEnterpriseType($info["type"], $info["enterpriseId"]);
        $need_extra_project = getJsonConfig("../sys_config.json", "talent_allowance_need_extra_project");
        foreach ($contractList as $detail) {
            $count++;
            $list = [];

            for ($i = 3; $i < count($rowdata); $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 ($info["type"] == \app\common\state\CommonConst::ENTERPRISE_GJ && $need_extra_project[$info["enterpriseId"]]) {
                            $project = $need_extra_project[$info["enterpriseId"]][0];
                        } else {
                            $project = AllowanceProjectEnum::PROJECT_SB_UNEMPLOYMENT;
                        }
                        break;
                    case 8:
                        if ($info["type"] == \app\common\state\CommonConst::ENTERPRISE_GJ && $need_extra_project[$info["enterpriseId"]]) {
                            $project = $need_extra_project[$info["enterpriseId"]][1];
                        } else {
                            $project = AllowanceProjectEnum::PROJECT_SB_MEDICA;
                        }
                        break;
                }
                if (!in_array($project, $projects))
                    continue;
                $months = "";
                if ($count == count($contractList)) {
                    if ($info["allowanceType"] == 2 && $i == 5) {
                        $monthstr = str_replace([" ", "，"], ",", trim($rowdata[5]));
                        $monthstr = str_replace("：", ":", $monthstr);
                        $months = array_filter(explode(",", $monthstr));
                        $tmp = [];
                        for ($n = 0; $n < count($months); $n++) {
                            list($a, $b) = explode(":", $months[$n]);
                            $a = str_pad($a, 2, 0, STR_PAD_LEFT);
                            $tmp[] = sprintf("%s=%s", $a, $b);
                        }
                        $months = $tmp ? implode(",", $tmp) : "";
                    } else {
                        $monthstr = str_replace([" ", "，"], ",", trim($rowdata[$i]));
                        $months = array_filter(explode(",", $monthstr));
                        for ($n = 0; $n < count($months); $n++) {
                            $months[$n] = str_pad($months[$n], 2, 0, STR_PAD_LEFT);
                        }
                        $months = $months ? implode(",", $months) : "";
                    }
                }
                $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);
        }
    }

}
