<?php

namespace app\common\api;

use app\common\model\TalentAllowance as TaModel;
use app\common\state\MainState;
use think\facade\Db;
use app\common\state\CommonConst;
use app\common\state\AllowanceProjectEnum;
use app\common\model\TalentAllowanceArrange;
use app\common\model\AmountStandard as AsModel;
use app\common\state\AllowanceStateEnum;

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

    public static function getList($params) {
        $user = session("user");
        $order = trim($params["order"]) ?: "desc";
        $offset = trim($params["offset"]) ?: 0;
        $limit = trim($params["limit"]) ?: 10;
        $where = [];
        $where[] = ["ta.delete", "=", 0];
        $where[] = ["ta.enterpriseId", "=", $user["uid"]];
        if ($_where = self::setTalentAllowanceInfo($params)) {
            $where = array_merge($where, $_where);
        }
        $whereRaw = "ta.id>0";
        if (\StrUtil::isNotEmpAndNull($params["checkState"])) {
            switch ($params["checkState"]) {
                case 1:
                    $where[] = ["ta.checkState", "=", AllowanceStateEnum::SAVE];
                    break;
                case 5:
                    $where[] = ["ta.publicState", "<>", 5];
                    $whereRaw = "ta.checkState=5 or ta.checkState >= 13";
                    break;
                case 10:
                    $where[] = ["ta.checkState", "=", AllowanceStateEnum::FIRST_REJECT];
                    break;
                case 30:
                    $where[] = ["ta.checkState", "=", AllowanceStateEnum::REVIEW_PASS];
                    $where[] = ["ta.publicState", "=", 5];
                    break;
                case -1:
                    $where[] = ["ta.checkState", "=", AllowanceStateEnum::NOTPASS];
                    break;
            }
        }
        $count = TaModel::where($where)->whereRaw($whereRaw)->alias("ta")->leftJoin("un_enterprise e", "e.id=ta.enterpriseId")->count();
        $list = TaModel::where($where)->whereRaw($whereRaw)->alias("ta")->leftJoin("un_enterprise e", "e.id=ta.enterpriseId")->field("ta.*")->limit($offset, $limit)->order("year {$order},ta.createTime {$order}")->select()->toArray();
        $levelList = DictApi::selectByParentCode("talent_arrange");
        $talentTypeList = DictApi::selectByParentCode("enterprise_tag");
        $streetList = DictApi::selectByParentCode("street");
        $identifyConditionIds = array_filter(array_unique(array_column($list, "identifyCondition")));
        $whr[] = ["id", "in", $identifyConditionIds];
        $whr[] = ["type", "=", $user["type"]];
        $identifyConditionKvList = TalentConditionApi::getKvList($whr);
        foreach ($list as $key => $item) {
            $list[$key]["talentArrangeName"] = $levelList[$item["talentArrange"]];
            $list[$key]["talentTypeName"] = $talentTypeList[$item["talentType"]];
            $list[$key]["addressName"] = $streetList[$item["address"]];
            $list[$key]["identifyConditionText"] = $identifyConditionKvList[$item["identifyCondition"]];
        }
        return ["total" => $count, "rows" => $list];
    }

    public static function getHospitalExamineList($params) {
        $user = session("user");
        $order = trim($params["order"]) ?: "desc";
        $offset = trim($params["offset"]) ?: 0;
        $limit = trim($params["limit"]) ?: 10;
        $where = [];
        $where[] = ["ta.delete", "=", 0];
        $where[] = ["ta.type", "=", 5];
        $where[] = ["e.medicalCommunityId", "=", $user["medicalCommunityId"]];
        $where[] = ["e.isGeneral", "=", 2];
        if ($_where = self::setTalentAllowanceInfo($params)) {
            $where = array_merge($where, $_where);
        }
        $whereRaw = "ta.id>0";
        if (\StrUtil::isNotEmpAndNull($params["checkState"])) {
            switch ($params["checkState"]) {
                case -1:
                    $where[] = ["ta.checkState", "=", AllowanceStateEnum::NOTPASS];
                    break;
                case -2:
                    $where[] = ["ta.checkState", "=", AllowanceStateEnum::SAVE];
                    break;
                case 1:
                    $where[] = ["ta.checkState", "=", AllowanceStateEnum::NEED_GENERAL_CHECK];
                    $whereRaw = "ta.highProcess is null or ta.highProcess < 1";
                    break;
                case 2:
                    $where[] = ["ta.checkState", "=", AllowanceStateEnum::GENERAL_REJECT];
                    break;
                case 3:
                    $where[] = ["ta.checkState", "=", AllowanceStateEnum::REVIEW_PASS];
                    $where[] = ["ta.publicState", "=", 5];
                    break;
                case 4:
                    $where[] = ["ta.checkState", "=", AllowanceStateEnum::FIRST_REJECT];
                    break;
                case 5:
                    $where[] = ["ta.checkState", "=", AllowanceStateEnum::FIRST_REJECT_BRANCH];
                    break;
                case 6:
                    $where[] = ["ta.publicState", "<>", 5];
                    $whereRaw = "ta.checkState=5 or ta.checkState >= 13";
                    break;
                case 9:
                    $where[] = ["ta.checkState", "=", AllowanceStateEnum::NEED_GENERAL_CHECK];
                    $whereRaw = "ta.highProcess is not null and ta.highProcess >= 1";
                    break;
            }
        }
        $count = TaModel::where($where)->whereRaw($whereRaw)->alias("ta")->leftJoin("un_enterprise e", "e.id=ta.enterpriseId")->count();
        $list = TaModel::where($where)->whereRaw($whereRaw)->alias("ta")->leftJoin("un_enterprise e", "e.id=ta.enterpriseId")->field("ta.*")->limit($offset, $limit)->order("year {$order},ta.createTime {$order}")->select()->toArray();
        $levelList = DictApi::selectByParentCode("talent_arrange");
        $talentTypeList = DictApi::selectByParentCode("enterprise_tag");
        $streetList = DictApi::selectByParentCode("street");
        $identifyConditionIds = array_filter(array_unique(array_column($list, "identifyCondition")));
        $whr[] = ["id", "in", $identifyConditionIds];
        $whr[] = ["type", "=", $user["type"]];
        $identifyConditionKvList = TalentConditionApi::getKvList($whr);
        foreach ($list as $key => $item) {
            $list[$key]["talentArrangeName"] = $levelList[$item["talentArrange"]];
            $list[$key]["talentTypeName"] = $talentTypeList[$item["talentType"]];
            $list[$key]["addressName"] = $streetList[$item["address"]];
            $list[$key]["identifyConditionText"] = $identifyConditionKvList[$item["identifyCondition"]];
        }
        return ["total" => $count, "rows" => $list];
    }

    public static function setTalentAllowanceInfo($params) {
        $where = [];
        if (\StrUtil::isNotEmpAndNull($params["year"])) {
            $where[] = ["ta.year", "=", $params["year"]];
        }
        if (\StrUtil::isNotEmpAndNull($params["enterpriseName"])) {
            $where[] = ["ta.enterpriseName", "like", "%" . $params["enterpriseName"] . "%"];
        }
        if (\StrUtil::isNotEmpAndNull($params["name"])) {
            $where[] = ["ta.name", "like", "%" . $params["name"] . "%"];
        }
        if (\StrUtil::isNotEmpAndNull($params["talentType"])) {
            $where[] = ["ta.talentType", "=", $params["talentType"]];
        }
        if (\StrUtil::isNotEmpAndNull($params["talentArrange"])) {
            $where[] = ["ta.talentArrange", "=", $params["talentArrange"]];
        }
        if (\StrUtil::isNotEmpAndNull($params["identiryCondition"])) {
            $where[] = ["ta.identifyCondition", "=", $params["identifyCondition"]];
        }
        if (\StrUtil::isNotEmpAndNull($params["allowanceType"])) {
            $where[] = ["ta.allowanceType", "=", $params["allowanceType"]];
        }
        if (\StrUtil::isNotEmpAndNull($params["address"])) {
            $where[] = ["ta.address", "=", $params["address"]];
        }
        return $where;
    }

    public static function getInfoById($id) {
        return TaModel::findOrEmpty($id)->toArray();
    }

    public static function getApplyCountByIdCard($idCard) {
        $where = [];
        $where[] = ["idCard", "=", $idCard];
        $where[] = ["checkState", "<>", MainState::NOTPASS];
        $list = TaModel::where($where)->distinct(true)->field("substr(year,1,4) as year")->select()->toArray();
        $years = array_column($list, "year");
        return $years;
    }

    public static function getPassYearsByIdCard($idCard) {
        $where = [];
        $where[] = ["idCard", "=", $idCard];
        $where[] = ["checkState", "=", MainState::PASS];
        $list = TaModel::where($where)->distinct(true)->field("substr(year,1,4) as year")->select()->toArray();
        $passYears = array_column($list, "year");
        return $passYears;
    }

    public static function validateAllowanceType($id) {
        $info = ["id" => $id];
        $old = self::getInfoById($id);
        $info["type"] = $old["type"];
        $info["backWork"] = $old["backWork"];
        $info["allowanceType"] = $old["allowanceType"];
        $info["otherEnjoyedMoney"] = $old["otherEnjoyedMoney"];
        $info["otherEnjoyedDescription"] = $old["otherEnjoyedDescription"];
        $enterpriseMap = \app\common\model\Enterprise::where("type", $old["type"])->column("name", "id");
        /*         * 查询工作单位记录 */
        $initDetailList = \app\common\model\TalentAllowancecontractDetail::where("mainId", $info["id"])->select()->toArray();
        $detaiPdList = [];                //用于判定类型
        $detailMonthList = [];            //用于计算月份

        foreach ($initDetailList as $detail) {
            $projectList = \app\common\model\TalentAllowanceProject::where("baseId", $detail["id"])->select()->toArray();
            $projectMap = [];
            foreach ($projectList as $project) {
                $projectMap[$project["project"]] = $project;
            }
            $detail["list"] = $projectList;
            $detail["projectMap"] = $projectMap;
            $detail["enterpriseName"] = $enterpriseMap[$detail["enterpriseId"]];
            /*             * 筛选符合条件的人才标签 */
            $detaiPdList[] = $detail;
            $detailMonthList[] = $detail;
        }
        $monthMap = self::mergeMonth($detailMonthList);
        $monthAndDayMap = self::mergeMonthNeedDay($detailMonthList);
        $info["recommendAllowanceType"] = $old["allowanceType"];
        $info["recommendAllowanceMsg"] = [];
        $projectList = \app\common\model\TalentAllowanceProject::where("mainId", $id)->select()->toArray();
        $set = self::valideAllowanceType($info, $projectList, $monthMap, $monthAndDayMap);
        $info["recommendAllowanceMsg"][] = "综合以上所有判断得到最终补贴类型为:";
        if ($info["recommendAllowanceType"] == 1) {
            $info["recommendAllowanceMsg"][] = "<span style='color:red;font-weight:bold;'>工作津贴</span>;";
            $info["recommendAllowanceMsg"][] = "可享受月份为:";
            $info["recommendAllowanceMsg"][] = "<span style='color:red;font-weight:bold;'>" . implode(",", $set) . "</span>;";
        }
        if ($info["recommendAllowanceType"] == 2)
            $info["recommendAllowanceMsg"][] = "<span style='color:red;font-weight:bold;'>一次性交通补贴</span>;";
        if ($info["recommendAllowanceType"] == 3)
            $info["recommendAllowanceMsg"][] = "<span style='color:red;font-weight:bold;'>不予兑现</span>;";
        usort($set, function($a, $b) {
            return (int) $a - (int) $b;
        });
        $info["recommendMonths"] = implode(",", $set);
        self::calculateAllowance($info, $set, $detailMonthList);
        return $info;
    }

    /**
     * 集成电路津补贴总校验
     * */
    private static function valideAllowanceType(&$info, $projectList, $monthMap, $monthAndDayMap) {
        $set = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"];
        /*         * 2.判定合同月份、工作月份、五险和个税是否满足重叠6个月要求* */
        $contractSet = self::chkMonths($monthMap[AllowanceProjectEnum::PROJECT_CONTRACT], $info, "上年度合同月份", "①");
        $workdaySet = self::chkMonths($monthMap[AllowanceProjectEnum::PROJECT_ATTENDANCE], $info, "上年度工作月份", "②");
        $wageSet = self::chkMonths($monthMap[AllowanceProjectEnum::PROJECT_WAGES], $info, "上年度工资发放月份", "③");
        $pensionSet = self::chkMonths($monthMap[AllowanceProjectEnum::PROJECT_SB_PENSION], $info, "养老保险", "④");
        $unemploymentSet = self::chkMonths($monthMap[AllowanceProjectEnum::PROJECT_SB_UNEMPLOYMENT], $info, "失业保险", "⑤");
        $medicaSet = self::chkMonths($monthMap[AllowanceProjectEnum::PROJECT_SB_MEDICA], $info, "医疗保险", "⑥");
        $taxSet = self::chkMonths($monthMap[AllowanceProjectEnum::PROJECT_TAX], $info, "个税", "⑦");
        $str = "工作合同月份、考勤月份、工资发放月份";
        if ($info["type"] == CommonConst::ENTERPRISE_WJ) {
            $str = "工作合同月份、考勤月份";
            $set = array_intersect($set, $contractSet);
            $set = array_intersect($set, $workdaySet);
            $checkSet = $set;
            //$set = array_intersect($set, $pensionSet);
            //$set = array_intersect($set, $taxSet);
        } else if ($info["type"] == CommonConst::ENTERPRISE_GJ) {
            if ($info["backWork"] == 1) {
                $str = "工资发放月份、个税缴交月份";
                $set = array_intersect($set, $wageSet);
                $set = array_intersect($set, $taxSet);
                $checkSet = $set;
                //$set = array_intersect($set, $contractSet);
                //$set = array_intersect($set, $pensionSet);
                //$set = array_intersect($set, $workdaySet);
            } else {
                $str = "养老保险缴交月份、工资发放月份、个税缴交月份";
                $set = array_intersect($set, $pensionSet);
                $set = array_intersect($set, $wageSet);
                $set = array_intersect($set, $taxSet);
                $checkSet = $set;
                //$set = array_intersect($set, $contractSet);
                //$set = array_intersect($set, $workdaySet);
            }
        } else {
            $set = array_intersect($set, $contractSet);
            $set = array_intersect($set, $workdaySet);
            $set = array_intersect($set, $wageSet);
            $checkSet = $set;
            $set = array_intersect($set, $pensionSet);
            $set = array_intersect($set, $unemploymentSet);
            $set = array_intersect($set, $medicaSet);
            $set = array_intersect($set, $taxSet);
        }
        usort($set, function($a, $b) {
            return (int) $a - (int) $b;
        });
        if ($info["recommendAllowanceType"] == 1) {
            if (count($checkSet) < 6) {
                //如果全部满足6个月，但是重叠时间不满足6个月，开始检测是否符合交通补贴要求
                $info["recommendAllowanceType"] = 3;
                $info["recommendAllowanceMsg"][] = "上年度{$str}交集月份不满足6个月（" . implode(",", $checkSet) . "），无法享受工作津贴（×）";
            } else {
                //检查连续缴纳月份是否满足6个月
                $count = 1;
                foreach ($checkSet as $s) {
                    $currentVal = intval($s);
                    $nextVal = $currentVal + 1;
                    $nextKey = str_pad($nextVal, 2, "0", STR_PAD_LEFT);
                    if (in_array($nextKey, $checkSet)) {
                        $count++;
                        if ($count >= 6) {
                            break;
                        }
                    } else {
                        $count = 1;
                    }
                }
                if ($count < 6) {
                    $info["recommendAllowanceType"] = 3;
                    $info["recommendAllowanceMsg"][] = "上年度{$str}交集月份不满足连续缴纳6个月（" . implode(",", $checkSet) . "），无法享受工作津贴（×）";
                }
            }
        }
        if ($info["recommendAllowanceType"] == 2) {
            //判断境内工作时间是否大于30天
            if ($info["allowanceType"] == 2) {
                $totalDays = 0;
                $workmonths = $monthAndDayMap[AllowanceProjectEnum::PROJECT_ATTENDANCE];
                foreach ($workmonths as $days) {
                    $totalDays += $days;
                }
                if ($totalDays < 30) {
                    $info["recommendAllowanceType"] = 3;
                    $info["recommendAllowanceMsg"][] = "全年在我市工作仅{$totalDays}天，未达到30天，无法享受一次性交通津贴（×）";
                }
            } else {
                if (count($workdaySet) == 0) {
                    $info["recommendAllowanceType"] = 3;
                    $info["recommendAllowanceMsg"][] = "全年在我市工作未达到30天，无法享受一次性交通津贴（×）";
                } else {
                    $info["recommendAllowanceType"] = 2;
                    $info["recommendAllowanceMsg"][] = "*首选为工作津贴，未录入实际工作天数，需要进一步核实提交的相关附件是否满足全年在我市工作30天";
                }
            }
        }
        return $set;
    }

    /**
     * 计算津补贴
     */
    private static function calculateAllowance(&$info, $retainMonths, $detailMonthList) {
        /*         * 查询人才层次变更记录 */
        $arrangeList = TalentAllowanceArrange::where("mainId", $info["id"])->order("talentArrange")->select()->toArray();
        foreach ($arrangeList as &$arrange) {
            $where = [];
            $where[] = ["type", "=", $info["type"]];
            $where[] = ["allowanceType", "in", [1, 2]];
            $where[] = ["talentArrange", "=", $arrange["talentArrange"]];
            $list = AsModel::where($where)->field("money,allowanceType")->select()->toArray();
            foreach ($list as $amount) {
                if ($amount["allowanceType"] == 1) {
                    $arrange["jobMoney"] = $amount["money"];
                }
                if ($amount["allowanceType"] == 2) {
                    $arrange["jtMoney"] = $amount["money"];
                }
            }
        }unset($arrange);

        /*         * * 容器 */
        $jobMoney = 0.00;               //计算所得工作津贴
        $jtMoney = 0.00;               //计算所得一次性交通补贴
        $recommendMonths = []; //推荐月份
        $talentArrange = null;
        /*         * *********计算************* */
        $msgBulider = [];
        $identifyExpiredName = "人才证书有效期";
        if ($info["type"] == CommonConst::ENTERPRISE_JC) {
            $identifyExpiredName = "认定条件有效期";
        }
        switch ($info["recommendAllowanceType"]) {
            case 1:
                foreach ($arrangeList as &$arrange) {
                    if (\StrUtil::isNotEmpAndNull($arrange["prepareMonths"])) {
                        $levelList = array_filter(explode(",", $arrange["prepareMonths"]));
                        $levelList = array_intersect($levelList, $retainMonths);
                        $total = round($arrange["jobMoney"] * count($levelList), 2);
                        $jobMoney += $total;
                        $msgBulider[] = sprintf("%d(%s)x%s(第%d层次)", count($levelList), $levelList ? implode(",", $levelList) : "", $arrange["jobMoney"], $arrange["talentArrange"]);
                        $recommendMonths = array_merge($recommendMonths, $levelList);
                        usort($recommendMonths, function($a, $b) {
                            return (int) $a - (int) $b;
                        });
                        $arrange["months"] = implode(",", $levelList);
                        $arrange["count"] = count($levelList);
                        $arrange["total"] = $total;
                    } else {
                        $msgBulider[] = sprintf("0()x%s(第%d层次)", $arrange["jobMoney"], $arrange["talentArrange"]);
                        $arrange["count"] = 0;
                        $arrange["total"] = 0.00;
                    }
                }unset($arrange);
                $info["recommendMonths"] = implode(",", $recommendMonths);
                $info["recommendAllowanceMsg"][] = "通过与{$identifyExpiredName}取交集得到最终可享受月份:";
                $info["recommendAllowanceMsg"][] = "<span style='color:red;font-weight:bold;'>" . implode(",", $recommendMonths) . "</span>;";
                $info["recommendAllowanceMsg"][] = "经过计算：兑现月份" . count($recommendMonths) . "个月，人才津贴为<span style='color:red;font-weight:bold;'>" . $jobMoney . "</span>;";
                $finnalMoney = $jobMoney;
                if ($info["otherEnjoyedMoney"] > 0) {
                    $finnalMoney = number_format($jobMoney - $info["otherEnjoyedMoney"], 2);
                    $info["recommendAllowanceMsg"][] = "扣除其它已享受补贴金额" . $info["otherEnjoyedMoney"] . "元，最终可享受人才津贴为<span style='color:red;font-weight:bold;'>" . number_format($jobMoney - $info["otherEnjoyedMoney"], 2) . "</span>;";
                }
                $info["finnalMoney"] = $finnalMoney;
                $info["recommendMoney"] = $jobMoney;
                $info["recommendMoneyDesc"] = implode("+", $msgBulider);
                $updAllowance["id"] = $info["id"];
                $updAllowance["virtualAmount"] = $jobMoney;
                TaModel::update($updAllowance);

                break;
            case 2:
                foreach ($arrangeList as $arrange) {
                    $jtMoney = $arrange["jtMoney"];
                    $talentArrange = $arrange["talentArrange"];
                }
                $info["recommendMoney"] = $jtMoney;
                $info["recommendMonths"] = "";
                $info["recommendMoneyDesc"] = "一次性交通补贴";
                $info["workAllowanceMoney"] = 0.00;
                $info["developAllowanceMoney"] = 0.00;
                $info["recommendTalentArrange"] = $talentArrange;
                $updAllowance["id"] = $info["id"];
                $updAllowance["virtualAmount"] = $jtMoney;
                $finnalMoney = $jobMoney;
                if ($info["otherEnjoyedMoney"] > 0) {
                    $finnalMoney = number_format($jobMoney - $info["otherEnjoyedMoney"], 2);
                    $info["recommendAllowanceMsg"][] = "扣除其它已享受补贴金额" . $info["otherEnjoyedMoney"] . "元，最终可享受人才津贴为<span style='color:red;font-weight:bold;'>" . number_format($jobMoney - $info["otherEnjoyedMoney"], 2) . "</span>;";
                }
                $info["finnalMoney"] = $finnalMoney;
                TaModel::update($updAllowance);
                break;
            case 3:
                $info["recommendMoney"] = 0.00;
                $info["recommendMonths"] = "";
                $info["recommendMoneyDesc"] = "不予兑现";
                $info["workAllowanceMoney"] = 0.00;
                $info["developAllowanceMoney"] = 0.00;
                break;
        }
        return $arrangeList;
    }

    /**
     * 判定是否交足6个月（集成电路）
     * @param set
     * @param info
     * @param name
     */
    private static function chkMonths($set, &$info, $name, $sort) {
        if ($name == "上年度工作月份") {
            if ($info["allowanceType"] == 2) {
                $tmp = [];
                foreach ($set as $s) {
                    $_s = explode("=", $s);
                    $month = $_s[0];
                    $days = $_s[1];
                    if ($days > 0) {
                        $tmp[] = $month;
                    }
                }
                $set = $tmp;
            }
        }
        $preCheckProjects = ["①", "②", "③"];
        if ($info["type"] == CommonConst::ENTERPRISE_WJ) {
            $preCheckProjects = ["①", "②"];
        }
        if ($info["type"] == CommonConst::ENTERPRISE_GJ) {
            if ($info["backWork"] == 1) {
                $preCheckProjects = ["③", "⑦"];
            } else {
                $preCheckProjects = ["③", "④", "⑦"];
            }
        }
        if ($info["recommendAllowanceType"] == 1 && (!$set || count($set) < 6) && in_array($sort, $preCheckProjects)) {
            $info["recommendAllowanceType"] = 3;
            $info["recommendAllowanceMsg"][] = $sort . $name . "不足6个月，无法享受工作津贴（×）";
        }
        return $set;
    }

    //合并所有项目的月份
    private static function mergeMonth($detailList) {
        $contractList = [];
        $taxList = [];
        $wagesList = [];
        $pensionList = [];
        $unemploymentList = [];
        $medicaList = [];
        $attendanceList = [];
        $workdayList = [];
        foreach ($detailList as $detail) {
            $projectMap = $detail["projectMap"];
            if ($detail["months"]) {
                $tmp = array_filter(explode(",", $detail["months"]));
                $contractList = array_merge($contractList, $tmp);
            }
            if ($projectMap[AllowanceProjectEnum::PROJECT_TAX] && \StrUtil::isNotEmpAndNull($projectMap[AllowanceProjectEnum::PROJECT_TAX]["months"])) {
                $tmp = array_filter(explode(",", $projectMap[AllowanceProjectEnum::PROJECT_TAX]["months"]));
                $taxList = array_merge($taxList, $tmp);
            }
            if ($projectMap[AllowanceProjectEnum::PROJECT_WAGES] && \StrUtil::isNotEmpAndNull($projectMap[AllowanceProjectEnum::PROJECT_WAGES]["months"])) {
                $tmp = array_filter(explode(",", $projectMap[AllowanceProjectEnum::PROJECT_WAGES]["months"]));
                $wagesList = array_merge($wagesList, $tmp);
            }
            if ($projectMap[AllowanceProjectEnum::PROJECT_SB_PENSION] && \StrUtil::isNotEmpAndNull($projectMap[AllowanceProjectEnum::PROJECT_SB_PENSION]["months"])) {
                $tmp = array_filter(explode(",", $projectMap[AllowanceProjectEnum::PROJECT_SB_PENSION]["months"]));
                $pensionList = array_merge($pensionList, $tmp);
            }
            if ($projectMap[AllowanceProjectEnum::PROJECT_SB_UNEMPLOYMENT] && \StrUtil::isNotEmpAndNull($projectMap[AllowanceProjectEnum::PROJECT_SB_UNEMPLOYMENT]["months"])) {
                $tmp = array_filter(explode(",", $projectMap[AllowanceProjectEnum::PROJECT_SB_UNEMPLOYMENT]["months"]));
                $unemploymentList = array_merge($unemploymentList, $tmp);
            }
            if ($projectMap[AllowanceProjectEnum::PROJECT_SB_MEDICA] && \StrUtil::isNotEmpAndNull($projectMap[AllowanceProjectEnum::PROJECT_SB_MEDICA]["months"])) {
                $tmp = array_filter(explode(",", $projectMap[AllowanceProjectEnum::PROJECT_SB_MEDICA]["months"]));
                $medicaList = array_merge($medicaList, $tmp);
            }
            if ($projectMap[AllowanceProjectEnum::PROJECT_ATTENDANCE] && \StrUtil::isNotEmpAndNull($projectMap[AllowanceProjectEnum::PROJECT_ATTENDANCE]["months"])) {
                $tmp = array_filter(explode(",", $projectMap[AllowanceProjectEnum::PROJECT_ATTENDANCE]["months"]));
                $attendanceList = array_merge($attendanceList, $tmp);
            }
            if ($projectMap[AllowanceProjectEnum::PROJECT_WORKDAY] && \StrUtil::isNotEmpAndNull($projectMap[AllowanceProjectEnum::PROJECT_WORKDAY]["months"])) {
                $tmp = array_filter(explode(",", $projectMap[AllowanceProjectEnum::PROJECT_WORKDAY]["months"]));
                $workdayList = array_merge($workdayList, $tmp);
            }
        }
        $map = [
            AllowanceProjectEnum::PROJECT_CONTRACT => $contractList,
            AllowanceProjectEnum::PROJECT_TAX => $taxList,
            AllowanceProjectEnum::PROJECT_WAGES => $wagesList,
            AllowanceProjectEnum::PROJECT_SB_PENSION => $pensionList,
            AllowanceProjectEnum::PROJECT_SB_UNEMPLOYMENT => $unemploymentList,
            AllowanceProjectEnum::PROJECT_SB_MEDICA => $medicaList,
            AllowanceProjectEnum::PROJECT_ATTENDANCE => $attendanceList,
            AllowanceProjectEnum::PROJECT_WORKDAY => $workdayList,
        ];
        return $map;
    }

    /**
     * 合并多个单位带有天数的项目的月份如考勤1月30天，
     * */
    private static function mergeMonthNeedDay($detailList) {
        $attendMap = [];
        $workDayMap = [];
        foreach ($detailList as $detail) {
            $attendMap = self::getMergeMonthNeedDayMap($detail["projectMap"][AllowanceProjectEnum::PROJECT_ATTENDANCE], $attendMap);
            $workDayMap = self::getMergeMonthNeedDayMap($detail["projectMap"][AllowanceProjectEnum::PROJECT_WORKDAY], $workDayMap);
        }
        $res = [
            AllowanceProjectEnum::PROJECT_ATTENDANCE => $attendMap,
            AllowanceProjectEnum::PROJECT_WORKDAY => $workDayMap
        ];
        return $res;
    }

    private static function getMergeMonthNeedDayMap($project, $map) {
        if (\StrUtil::isNotEmpAndNull($project["months"])) {
            $monthAndDayList = array_filter(explode(",", $project["months"]));
            for ($i = 0; $i < count($monthAndDayList); $i++) {
                $obj = explode("=", $monthAndDayList[$i]);
                $month = $obj[0];
                $day = is_numeric($obj[1]) ? $obj[1] : 0;
                $count = $map[$month];
                if ($count == 0) {
                    $map[$month] = $day;
                } else {
                    $map[$month] = $day + $count;
                }
            }
        }
        return $map;
    }

}
