<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace app\enterprise\controller;

use app\enterprise\common\EnterpriseController;
use app\common\state\CommonConst;
use app\common\api\BatchApi;
use app\common\api\TalentAllowanceApi;
use app\common\state\ProjectState;
use app\common\api\DictApi;
use app\common\state\MainState;
use app\common\model\TalentAllowance as TaModel;
use app\common\state\AllowanceProjectEnum;
use app\common\model\TalentChecklog;
use think\facade\Db;
use app\common\api\Response;
use app\common\api\UploadApi;
use app\enterprise\model\TalentTypeChange;
use app\common\state\AllowanceTypeEnum;

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

    public function index() {
        $tpl = "";
        switch ($this->user["type"]) {
            case CommonConst::ENTERPRISE_JC:
                $tpl = "indexIC";
                break;
        }
        return view($tpl, ['type' => $this->user["type"]]);
    }

    public function list() {
        $res = TalentAllowanceApi::getList($this->request);
        return json($res);
    }

    /**
     * 申请
     */
    public function apply(\think\Request $request) {
        $param = $request->param();
        $id = isset($param["id"]) ? $param["id"] : 0;
        $info = null;
        if ($id) {
            $info = TalentAllowanceApi::getInfoById($id);
            $this->translateToChinese($info);
        }
        if ($request->isPost()) {
            return $this->save($info, $request);
        }
        $batch = $info["year"] ?: BatchApi::getValidBatch(ProjectState::JBT, $this->user["type"])["batch"];
        return view("", ["year" => $batch, "type" => $this->user["type"], "row" => $info]);
    }

    public function batchApply() {
        $ids = $this->request["ids"];
        $ids = array_filter(explode(",", $ids));
        $allowanceType = $this->request["allowanceType"];

        $batch = BatchApi::getValidBatch(ProjectState::JBT, $this->user["type"])["batch"];
        if (!$batch) {
            return new Response(Response::ERROR, "当前并无有效的申报批次进行中");
        }

        for ($i = 0; $i < count($ids); $i++) {
            queue("app\job\TalentAllowance", ["type" => 1, "talentId" => $ids[$i], "enterprise" => $this->user, "year" => $batch, "allowanceType" => $allowanceType]);
        }
        return new Response(Response::SUCCESS, "已经成功添加到计划任务,请稍候查看申报列表进行确认");
    }

    private function save($talentAllowance, \think\Request $request) {
        $response = new \stdClass();
        $response->code = 500;
        $param = $request->param();
        if (!$param) {
            $response->msg = "请填写信息后在提交";
            return $response;
        }
        if (\StrUtil::isEmpOrNull($param["talentId"])) {
            $response->msg = "请选择申报对象";
            return $response;
        }
        if (!$param["id"]) {
            $where = [];
            $where[] = ["year", "=", $param["year"]];
            $where[] = ["idCard", "=", $param["idCard"]];
            $where[] = ["checkState", "not in", [MainState::NOTPASS, MainState::PASS]];
            $exists = TaModel::where($where)->find();
            if ($exists) {
                $response->msg = "当前申请对象在当前批次中存在申请中的记录,请等待申请结束后再操作";
                return $response;
            }

            $user = $this->user;
            $ti = \app\common\api\VerifyApi::getTalentInfoById($param["talentId"]);
            $data = [
                "talentId" => $param["talentId"],
                "enterpriseId" => $ti["enterprise_id"],
                "enterpriseName" => $user["name"],
                "year" => $param["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" => $user["type"],
                "provinceCode" => $ti["province"],
                "provinceName" => \app\common\api\LocationApi::getNameByCode($ti["province"]),
                "cityCode" => $ti["city"],
                "cityName" => \app\common\api\LocationApi::getNameByCode($ti["city"]),
                "countyCode" => $ti["county"],
                "countyName" => \app\common\api\LocationApi::getNameByCode($ti["county"]),
                "isSupple" => 2,
                "createTime" => date("Y-m-d H:i:s"),
                "createUser" => $user["uid"],
                "id" => getStringId(),
                "wage" => $param["wage"],
                "allowanceType" => $param["allowanceType"]
            ];
            /*             * 1.获取上一年度的人才层次 */
            $arrangeList = $this->getLastYearTalentType($data, $ti);
            if (!$arrangeList) {
                $response->msg = "上一年度暂无有效的人才层次";
                return $response;
            }
            /*             * 2.获取上一年度所在单位* */
            $contractDetailList = $this->getConcatList($ti, $data, $param["year"]); //保存上一年度的工作单位
            if (!$contractDetailList) {
                $response->msg = "申报失败,原因为:申报年度不存在有效的工作单位";
                return $response;
            }
            TaModel::insert($data);
            \app\common\model\TalentAllowancecontractDetail::insertAll($contractDetailList);
            /**
             * 4.添加津补贴核查项目
             */
            //核查项目详情表
            $this->createAllowanceProject($data, $contractDetailList);
            \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)", $this->user["account"], $this->user["companyName"])
            ]);
            $response->msg = "保存成功";
            $response->code = 200;
            $response->obj = $data;
            return $response;
        } else {
            TaModel::update($param);
            $response->msg = "修改成功";
            $response->code = 200;
            return $response;
        }
    }

    public function getInfoByIdAndYear($id, $year) {
        $ti = \app\common\api\VerifyApi::getTalentInfoById($id);
        $data = [
            "talentId" => $id,
            "year" => $year,
            "idCard" => $ti["card_number"],
            "id" => getStringId()
        ];
        /*         * 1.获取上一年度的人才层次 */
        $arrangeList = $this->getLastYearTalentType($data, $ti);
        if (!$arrangeList) {
            return new Response(Response::ERROR, "该人员上一年度暂无有效的人才层次");
        }
        /*         * 2.获取上一年度所在单位* */
        $contractDetailList = $this->getConcatList($ti, $data, $year); //保存上一年度的工作单位
        if (!$contractDetailList) {
            return new Response(Response::ERROR, "该人员申报年度不存在有效的工作单位");
        }
        return new Response(Response::SUCCESS, "", $ti);
    }

    /**
     * 删除优秀人才津补贴
     */
    public function delete() {
        $id = $this->request["id"];
        $response = new \stdClass();
        $response->code = 500;
        $info = TalentAllowanceApi::getInfoById($id);
        if ($info["checkState"] != 1) {
            $response->msg = "删除失败!此数据已提交审核,无法删除!";
            return $response;
        }
        Db::startTrans();
        try {
            //删除核查项目表
            Db::table("un_talent_allowance_project")->where("mainId", $id)->delete();
            //删除合同情况表
            Db::table("un_talent_allowancecontract_detail")->where("mainId", $id)->delete();
            //删除人才层次变更表
            Db::table("un_talent_allowance_arrange")->where("mainId", $id)->delete();
            //删除日志
            $where[] = ["mainId", "=", $id];
            $where[] = ["type", "=", ProjectState::JBT];
            Db::table("new_talent_checklog")->where($where)->delete();
            //删除主表
            Db::table("un_talent_allowance_info")->delete($id);
            Db::commit();
            $response->code = 200;
            $response->msg = "删除成功";
            return $response;
        } catch (think\db\exception\DbException $e) {
            Db::rollback();
            $response->msg = $e->getMessage();
            return $response;
        }
    }

    public function detail(\think\Request $request) {
        $param = $request->param();
        $id = $param["id"];
        $info = TalentAllowanceApi::getInfoById($id);
        $this->translateToChinese($info);
        return view("", ["row" => $info]);
    }

    private function translateToChinese(&$obj) {
        if (\StrUtil::isNotEmpAndNull($obj["address"])) {
            $obj["addressName"] = DictApi::findByParentCodeAndCode("street", $obj["address"])["name"];
        }
        if (\StrUtil::isNotEmpAndNull($obj["talentType"])) {
            $obj["talentTypeName"] = DictApi::findByParentCodeAndCode("enterprise_tag", $obj["talentType"])["name"];
        }
        if (\StrUtil::isNotEmpAndNull($obj["talentArrange"])) {
            $obj["talentArrangeName"] = DictApi::findByParentCodeAndCode("talent_arrange", $obj["talentArrange"])["name"];
        }
        if (\StrUtil::isNotEmpAndNull($obj["identifyCondition"])) {
            $obj["identifyConditionText"] = \app\common\api\TalentConditionApi::getOne($obj["identifyCondition"])["name"];
        }
        if (\StrUtil::isNotEmpAndNull($obj["introductionMode"])) {
            $obj["introductionModeName"] = DictApi::findByParentCodeAndCode("import_way", $obj["introductionMode"])["name"];
        }
    }

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

    private function getLastYearTalentType($info, $talentInfo) {
        $arrangeList = [];
        /*         * * 添加人才层次记录 */
        $where = [];
        $where[] = ["idCard", "=", $info["idCard"]];
        $where[] = ["checkState", "=", MainState::PASS];
        $where[] = ["isPublic", ">=", 5];
        $where[] = ["oldIdentifyMonth", "<=", $info["year"] . "-12-31"];
        $typeList = TalentTypeChange::where($where)->field("oldTalentArrange,oldIdentifyCondition,oldIdentifyGetTime,oldIdentifyOutTime,oldIdentifyMonth,oldCertificateStartTime,oldCertificateOutTime,newIdentifyMonth")->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" => $info["year"] . "-12-31"
        ];
        $totalMonth = \DateUtil::getMonthBetweenDates($info["year"] . "-01-01", $info["year"] . "-12-31");
        /*         * 获取上一年度有效的人才层次 */
        usort($typeList, function($a, $b) {
            return (int) $b["oldTalentArrange"] - (int) $a["oldTalentArrange"];
        });
        $commonMonth = [];
        foreach ($typeList as $talentTypeChange) {
            $startTime = $talentTypeChange["oldIdentifyMonth"];
            $endTime = $talentTypeChange["newIdentifyMonth"];
            $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) {
        foreach ($contractList as $detail) {
            $projects = [
                //AllowanceProjectEnum::PROJECT_CONTRACT,
                AllowanceProjectEnum::PROJECT_TAX,
                AllowanceProjectEnum::PROJECT_WAGES,
                AllowanceProjectEnum::PROJECT_ATTENDANCE,
                AllowanceProjectEnum::PROJECT_SB_PENSION,
                AllowanceProjectEnum::PROJECT_SB_UNEMPLOYMENT,
                AllowanceProjectEnum::PROJECT_SB_MEDICA,
                    //AllowanceProjectEnum::PROJECT_WORKDAY,
            ];
            $list = [];
            foreach ($projects as $project) {
                $list[] = [
                    "mainId" => $info["id"],
                    "baseId" => $detail["id"],
                    "enterpriseId" => $detail["enterpriseId"],
                    "project" => $project,
                    "isLock" => 1,
                    "createTime" => date("Y-m-d H:i:s")
                ];
            }
            \app\common\model\TalentAllowanceProject::insertAll($list);
        }
    }

    /**
     * 查询工作单位
     */
    public function findAllowanceContractDetail() {
        $mainId = $this->request["mainId"];
        $offset = $this->request["offset"] ?: 0;
        $limit = $this->request["limit"] ?: 1000;
        $count = \app\common\model\TalentAllowancecontractDetail::where("mainId", $mainId)->count();
        $list = \app\common\model\TalentAllowancecontractDetail::where("mainId", $mainId)->limit($offset, $limit)->select()->toArray();
        $enterpriseMap = \app\common\model\Enterprise::column("name", "id");
        foreach ($list as &$row) {
            $row["enterpriseName"] = $enterpriseMap[$row["enterpriseId"]];
        }unset($row);
        return json(["rows" => $list, "total" => $count]);
    }

    /**
     * 查询核查项目情况
     */
    public function findAllowanceProject() {
        $mainId = $this->request["mainId"];
        $baseId = $this->request["baseId"];
        $offset = $this->request["offset"] ?: 0;
        $limit = $this->request["limit"] ?: 1000;
        $where = [];
        $where[] = ["mainId", "=", $mainId];
        $where[] = ["baseId", "=", $baseId];
        $count = \app\common\model\TalentAllowanceProject::where($where)->count();
        $list = \app\common\model\TalentAllowanceProject::where($where)->limit($offset, $limit)->select()->toArray();
        $info = TalentAllowanceApi::getInfoById($mainId);
        foreach ($list as &$project) {
            $project["projectName"] = AllowanceProjectEnum::getProjectName($project["project"]);
            if ($info["checkState"] == 1) {
                $project["isEdit"] = in_array($project["project"], [
                            //AllowanceProjectEnum::PROJECT_CONTRACT,
                            AllowanceProjectEnum::PROJECT_TAX,
                            AllowanceProjectEnum::PROJECT_WAGES,
                            AllowanceProjectEnum::PROJECT_ATTENDANCE,
                            AllowanceProjectEnum::PROJECT_SB_PENSION,
                            AllowanceProjectEnum::PROJECT_SB_UNEMPLOYMENT,
                            AllowanceProjectEnum::PROJECT_SB_MEDICA,
                                //AllowanceProjectEnum::PROJECT_WORKDAY
                        ]) ? 1 : 2;
            } else if ($info["checkState"] == 10) {
                $projects = explode(",", $info["projects"]);
                if (in_array($project["id"], $projects)) {
                    $project["isEdit"] = 1;
                } else {
                    $project["isEdit"] = 2;
                }
            } else {
                $project["isEdit"] = 2;
            }
        }unset($project);
        return json(["rows" => $list, "total" => $count]);
    }

    /**
     * 查询人才层次变更记录
     */
    public function findAllowanceArrange() {
        $mainId = $this->request["mainId"];
        $offset = $this->request["offset"] ?: 0;
        $limit = $this->request["limit"] ?: 1000;
        $where = [];
        $where[] = ["mainId", "=", $mainId];
        $count = \app\common\model\TalentAllowanceArrange::where($where)->count();
        $list = \app\common\model\TalentAllowanceArrange::where($where)->limit($offset, $limit)->select()->toArray();
        foreach ($list as &$arrange) {
            $condition = \app\common\api\TalentConditionApi::getOne($arrange["identifyCondition"]);
            $arrange["identifyConditionText"] = $condition["name"];
            $arrange["talentArrangeName"] = app\common\state\CommonConst::getLayerNameByLayer($arrange["talentArrange"]);
        }unset($arrange);
        return json(["rows" => $list, "total" => $count]);
    }

    /**
     * 修改合同起止时间
     */
    public function editContract() {
        $response = new \stdClass();
        $response->code = 500;
        $param = $this->request->param();
        if (!$param["id"]) {
            $response->msg = "系统错误,请联系管理员";
            return $response;
        }
        $detail = \app\common\model\TalentAllowancecontractDetail::find($param["id"]);
        $info = TalentAllowanceApi::getInfoById($detail["mainId"]);
        if (\StrUtil::isEmpOrNull($param["startTime"])) {
            $response->msg = "请选择合同起始时间";
            return $response;
        }
        if (\StrUtil::isEmpOrNull($param["endTime"])) {
            $response->msg = "请选择合同截止时间";
            return $response;
        }
        \app\common\model\TalentAllowancecontractDetail::update($param);
        //添加日志
        TalentChecklog::create([
            'id' => getStringId(),
            'mainId' => $info['id'],
            'type' => intval(ProjectState::JBT),
            'typeFileId' => $param["id"],
            'active' => 1,
            'state' => null,
            'step' => 0,
            'stateChange' => null,
            'description' => "修改工作单位合同时间为:" . $param["startTime"] . "至" . $param["endTime"],
            'createTime' => date("Y-m-d H:i:s", time()),
            'createUser' => sprintf("%s(%s)", $this->user["account"], $this->user["companyName"])
        ]);
        $response->msg = "修改成功";
        $response->code = 200;
        return $response;
    }

    /**
     * 修改项目
     */
    public function editProject() {
        $response = new \stdClass();
        $response->code = 500;
        $param = $this->request->param();
        if (!$param["id"]) {
            $response->msg = "系统错误,请联系管理员";
            return $response;
        }
        $detail = \app\common\model\TalentAllowanceProject::find($param["id"]);
        $info = TalentAllowanceApi::getInfoById($detail["mainId"]);
        \app\common\model\TalentAllowanceProject::update($param);
        //添加日志
        TalentChecklog::create([
            'id' => getStringId(),
            'mainId' => $info['id'],
            'type' => intval(ProjectState::JBT),
            'typeFileId' => $param["id"],
            'active' => 1,
            'state' => null,
            'step' => 0,
            'stateChange' => null,
            'description' => "修改项目名:" . AllowanceProjectEnum::getProjectName($detail["project"]) . "的值为:" . $param["months"] . ";备注为:" . $param["description"],
            'createTime' => date("Y-m-d H:i:s", time()),
            'createUser' => sprintf("%s(%s)", $this->user["account"], $this->user["companyName"])
        ]);
        $response->msg = "修改成功";
        $response->code = 200;
        return $response;
    }

    /**
     * 判断是否可以修改
     */
    public function validateIsEdit() {
        $id = $this->request["id"];
        $type = $this->request["type"];
        $info = null;
        if ($type == 1) {                //编辑合同
            $detail = \app\common\model\TalentAllowancecontractDetail::find($id);
        } else if ($type == 2) {          //编辑项目
            $detail = \app\common\model\TalentAllowanceProject::find($id);
        }
        $info = TalentAllowanceApi::getInfoById($detail["mainId"]);
        if ($info["checkState"] != 1 && $info["checkState"] != 10) {
            if ($info["checkState"] == -1) {
                return new Response(Response::ERROR, "您的申报审核不通过,无法操作");
            } else if ($info["checkState"] == 30) {
                return new Response(Response::ERROR, "您的申报已审核通过,无法操作");
            } else {
                return new Response(Response::ERROR, "您的申报正在审核中,请耐心等待");
            }
        }
        return new Response(Response::SUCCESS, "");
    }

    /**
     * 提交审核
     */
    public function submitToCheck() {
        $data = $this->request->param();
        $response = new \stdClass();
        $response->code = 500;
        if (!$data || !$data["id"]) {
            $response->msg = "提交审核失败,请先填写基础信息";
            return $response;
        }
        $old = TalentAllowanceApi::getInfoById($data["id"]);
        $batch = BatchApi::checkBatchValid(["type" => ProjectState::JBT, "year" => $old["year"], "first_submit_time" => $old["firstSubmitTime"]], $this->user["type"]);
        if ($batch["code"] != 200) {
            $response->msg = $batch["msg"];
            return $response;
        }
        if ($old["checkState"] != 1 && $old["checkState"] != 10) {
            $response->msg = "不能重复提交审核";
            return $response;
        }
        if (!$old["allowanceType"]) {
            $response->msg = "没有明确津贴类型";
            return $response;
        }
        //因为工作津贴和交通补贴两者的考勤分别记录的是月份和天数,如果没有手动修改值会导致数据不对口,如修改类型却未修改考勤记录,则手动改为空。
        $where = [];
        $where[] = ["project", "=", AllowanceProjectEnum::PROJECT_ATTENDANCE];
        $where[] = ["mainId", "=", $data["id"]];
        $attendanceList = \app\common\model\TalentAllowanceProject::where($where)->select()->toArray();
        if ($old["allowanceType"] == AllowanceTypeEnum::JBT_JT) {
            //因为天数保存格式为 月份=天数 如 01=31,02=20,03=15,月份保存格式为01,02,03,所以可以从有没有=号判断是否有进行考勤的修改保存操作
            foreach ($attendanceList as $a) {
                //$a["months"]有值但是没有包含=号则一般可认为是类型修改为交通补贴而未修改考勤,此时的months字段数据是错误的,修改为空。
                if ($a["months"] && strpos($a["months"], "=") === false) {
                    $_updProject["id"] = $a["id"];
                    $_updProject["months"] = "";
                    \app\common\model\TalentAllowanceProject::update($_updProject);
                }
            }
        } else {
            foreach ($attendanceList as $a) {
                //$a["months"]有值但是包含了=号则一般可认为是类型修改为工作津贴而未修改考勤,此时的months字段数据是错误的,修改为空。
                if ($a["months"] && strpos($a["months"], "=") !== false) {
                    $_updProject["id"] = $a["id"];
                    $_updProject["months"] = "";
                    \app\common\model\TalentAllowanceProject::update($_updProject);
                }
            }
        }
        $where = [];
        $where[] = ["type", "=", $old["type"]];
        $where[] = ["project", "=", ProjectState::JBT];
        $where[] = ["isConditionFile", "in", [0, $old["allowanceType"]]];
        $where[] = ["active", "=", 1];
        $where[] = ["delete", "=", 0];
        $filetypes = Db::table("new_common_filetype")->where($where)->order("sn asc")->select()->toArray();
        $sb = [];
        $sb[] = "以下为必传附件:";
        foreach ($filetypes as $filetype) {
            if ($filetype["must"] == 1) {
                $where = [];
                $where[] = ["mainId", "=", $data["id"]];
                $where[] = ["typeId", "=", $filetype["id"]];
                $count = Db::table("new_talent_file")->where($where)->count();
                if ($count == 0) {
                    $sb[] = $filetype["name"] . ";";
                }
            }
        }
        if (count($sb) > 1) {
            $response->msg = implode("<br>", $sb);
            return $response;
        }

        /**
         * 初步判断合同是否满两年
         */
        $detailList = \app\common\model\TalentAllowancecontractDetail::where("mainId", $old["id"])->select()->toArray();
        foreach ($detailList as $detail) {
            if (\StrUtil::isEmpOrNull($detail["startTime"]) || \StrUtil::isEmpOrNull($detail["endTime"])) {
                $response->msg = "合同起止时间不能为空";
                return $response;
            }
        }
        foreach ($detailList as $detail) {
            $contractEndTime = strtotime($detail["endTime"]);
            $contractStartTimeAdd2Years = strtotime("+2 years -1 day {$detail['startTime']}");
            $where = [];
            $where[] = ["mainId", "=", $data["id"]];
            $where[] = ["baseId", "=", $detail["id"]];
            $where[] = ["project", "=", AllowanceProjectEnum::PROJECT_CONTRACT];
            $updProject["months"] = $contractEndTime >= $contractStartTimeAdd2Years ? "是" : "否";
            \app\common\model\TalentAllowanceProject::where($where)->update($updProject);
        }
        $data["checkMsg"] = "";
        $data["checkState"] = 5;
        $data["files"] = "";
        $data["projects"] = "";
        $data["concats"] = "";
        $data["fields"] = "";
        $data["toDep"] = "";
        $data["process"] = null;
        if (!$old["firstSubmitTime"]) {
            $data["firstSubmitTime"] = date("Y-m-d H:i:s");
        }
        $data["newSubmitTime"] = date("Y-m-d H:i:s");
        TaModel::update($data);
        //添加日志
        TalentChecklog::create([
            'id' => getStringId(),
            'mainId' => $data['id'],
            'type' => intval(ProjectState::JBT),
            'typeFileId' => null,
            'active' => 1,
            'state' => 1,
            'step' => 0,
            'stateChange' => sprintf("%s->%s", MainState::getStateDesc(1), MainState::getStateDesc(7)),
            'description' => "确认提交审核",
            'createTime' => date("Y-m-d H:i:s", time()),
            'createUser' => sprintf("%s(%s)", $this->user["account"], $this->user["companyName"])
        ]);
        $response->msg = "提交审核成功";
        $response->code = 200;
        $response->obj = 5;
        return $response;
    }

    public function updateSuppleState() {
        $id = $this->request["id"];
        $response = new \stdClass();
        $response->code = 500;
        if (\StrUtil::isEmpOrNull($id)) {
            $response->msg = "系统错误,请联系管理员";
            return $response;
        }
        $data["id"] = $id;
        $data["isSupple"] = 1;
        TaModel::update($data);
        $response->msg = "状态更新成功";
        $response->code = 200;
        return $response;
    }

    public function uploadCommonFile() {
        $batchId = $this->request["batch"];
        if (!$batchId) {
            return json(new Response(Response::ERROR, "没有提交批次信息,无法按批次归档,上传被中止"));
        }
        $batchInfo = BatchApi::getOne($batchId);

        if (!$batchInfo) {
            return json(new Response(Response::ERROR, "批次信息不存在,无法按批次归档,上传被中止"));
        }

        if (!$this->request->file()) {
            return json(new Response(Response::ERROR, "没有上传任何材料"));
        }
        $file = $this->request->file("file");
        $upload = new UploadApi();
        $result = $upload->uploadOne($file, "system", "talent/TalentAllowanceCommonFile");
        if ($result->code != 200) {
            return json(new Response(Response::ERROR, $result->msg));
        }
        $data["id"] = getStringId();
        $data["enterpriseId"] = $this->user["uid"];
        $data["batchId"] = $batchId;
        $data["batch"] = $batchInfo["batch"];
        $data["url"] = $result->filepath;
        $data["originalName"] = $file->getOriginalName();
        $data["createTime"] = date("Y-m-d H:i:s");
        $data["createUser"] = $this->user["uid"];
        $res = Db::table("un_talent_allowance_common_file")->insert($data);

        return json(new Response(Response::SUCCESS, "上传成功"));
    }

    public function listCommonFile() {
        $param = $this->request->param();
        $batchId = $param["batch"];
        $where = [["batchId", "=", $batchId], ["enterpriseId", "=", $this->user["uid"]]];
        $list = Db::table("un_talent_allowance_common_file")->where($where)->select()->toArray();
        foreach ($list as $key => $item) {
            $list[$key]["ext"] = pathinfo($item["url"])["extension"];
            $list[$key]["url"] = getStoragePath($item["url"]);
        }
        return json(["rows" => $list]);
    }

    public function deleteCommonFile() {
        $id = $this->request["id"];
        $where = [];
        $where[] = ["id", "=", $id];
        $where[] = ["enterpriseId", "=", $this->user["uid"]];
        $file = Db::table("un_talent_allowance_common_file")->where($where)->find();
        if (!$file) {
            return json(new Response(Response::ERROR, "不存在的文件,删除失败"));
        }
        if (Db::table("un_talent_allowance_common_file")->where($where)->delete()) {
            if (!empty($file["url"])) {
                $filepath = "storage/" . $file["url"];
                if (file_exists($filepath)) {
                    unlink($filepath);
                }
            }
            return json(new Response(Response::SUCCESS, "删除成功"));
        }
    }

    public function findTalentAllowance() {
        $res = [];
        $batch = BatchApi::getValidBatch(ProjectState::JBT, $this->user["type"]);
        $year = $batch["batch"];
        if ($year) {
            $ids = null;
            //根据申报年度查询当前企业已申报的人才
            $where = [];
            $where[] = ["year", "=", $year];
            $where[] = ["enterpriseId", "=", $this->user["uid"]];
            $talentAllowances = TaModel::where($where)->select()->toArray();
            $ids = array_unique(array_column($talentAllowances, "talentId"));
            $whr = [];
            $whr[] = ["ti.checkState", "=", \app\common\api\TalentState::CERTIFICATED];
            $whr[] = ["ti.enterprise_id", "=", $this->user["uid"]];
            $whr[] = ["e.type", "=", $this->user["type"]];
            $whr[] = ["ti.id", "not in", $ids];
            $list = \app\enterprise\model\Talent::alias("ti")->leftJoin("un_enterprise e", "e.id=ti.enterprise_id")->field("ti.id,ti.name,ti.card_number as idCard")->where($whr)->select()->toArray();
            foreach ($list as $info) {
                if (strtotime($year . "-12-31") >= strtotime($info["identifyMonth"])) {
                    $res[] = $info;
                } else {
                    $whereTypeChange = [];
                    $whereTypeChange[] = ["idCard", "=", $info["idCard"]];
                    $whereTypeChange[] = ["checkState", "=", MainState::PASS];
                    $whereTypeChange[] = ["isPublic", "=", 6];
                    $typeChanges = TalentTypeChange::where($whereTypeChange)->select()->toArray();
                    foreach ($typeChanges as $typeChange) {
                        if (strtotime($year . "-12-31") >= strtotime($typeChange["oldIdentifyMonth"])) {
                            $res[] = $info;
                            break;
                        }
                    }
                }
            }
        }
        return new Response(Response::SUCCESS, "", ["rows" => $res, "total" => count($res)]);
    }

    public function export() {
        $obj["year"] = \StrUtil::getRequestDecodeParam($this->request, "year");
        $obj["name"] = \StrUtil::getRequestDecodeParam($this->request, "name");
        $obj["talentArrange"] = \StrUtil::getRequestDecodeParam($this->request, "talentArrange");
        $obj["address"] = \StrUtil::getRequestDecodeParam($this->request, "address");
        $obj["identifyCondition"] = \StrUtil::getRequestDecodeParam($this->request, "identifyCondition");
        $where = [];
        $where[] = ["ta.enterpriseId", "=", $this->user["uid"]];
        if (\StrUtil::isNotEmpAndNull($obj["year"])) {
            $where[] = ["ta.year", "like", "%" . $obj["year"] . "%"];
        }
        if (\StrUtil::isNotEmpAndNull($obj["name"])) {
            $where[] = ["ta.name", "like", "%" . $obj["name"] . "%"];
        }
        if (\StrUtil::isNotEmpAndNull($obj["talentArrange"])) {
            $where[] = ["ta.talentArrange", "=", $obj["talentArrange"]];
        }
        if (\StrUtil::isNotEmpAndNull($obj["address"])) {
            $where[] = ["ta.address", "=", $obj["address"]];
        }
        if (\StrUtil::isNotEmpAndNull($obj["identifyCondition"])) {
            $where[] = ["ta.identifyCondition", "=", $obj["identifyCondition"]];
        }
        $projects = [
            AllowanceProjectEnum::PROJECT_TAX,
            AllowanceProjectEnum::PROJECT_WAGES,
            AllowanceProjectEnum::PROJECT_ATTENDANCE,
            AllowanceProjectEnum::PROJECT_SB_PENSION,
            AllowanceProjectEnum::PROJECT_SB_UNEMPLOYMENT,
            AllowanceProjectEnum::PROJECT_SB_MEDICA,
        ];
        $months = [];
        for ($m = 1; $m <= 12; $m++) {
            $months[] = $m . "月";
        }
        $columns = [["年度", [1, 2]], ["所属镇街", [1, 2]], ["姓名", [1, 2]], ["性别", [1, 2]], ["证件号码", [1, 2]], ["人才层次", [1, 2]], ["认定条件", [1, 2]], ["认定条件取得时间", [1, 2]], ["认定条件名称", [1, 2]], ["公布入选月份", [1, 2]], ["津补贴类型", [1, 2]], ["兑现月份", [1, 2]], ["兑现金额", [1, 2]], ["金额说明", [1, 2]], ["审核状态", [1, 2]], ["缴纳单位", [1, 2]]];
        $infoCols = count($columns);
        for ($i = 0; $i < count($projects); $i++) {
            $columns[] = [AllowanceProjectEnum::getProjectName($projects[$i]), $months];
        }
        $list = \app\common\model\TalentAllowanceProject::alias("pro")
                        ->field("ta.id,ta.year,ta.enterpriseId as curEnterpriseId,ta.address,ta.name,ta.sex,ta.idCard,ta.talentArrange,ta.identifyCondition,ta.identifyGetTime,ta.identifyConditionName,ta.identifyMonth,ta.allowanceType,ta.months,ta.money,ta.moneyDesc,ta.checkState,ta.publicState,pro.project,pro.months as pre_months,con.enterpriseId,con.startTime,con.endTime,con.entryTime,con.quitTime,con.isQuit")
                        ->leftJoin("un_talent_allowance_info ta", "ta.id=pro.mainId")
                        ->leftJoin("un_talent_allowancecontract_detail con", "pro.baseId=con.id")
                        ->where($where)
                        ->order("ta.year desc,ta.createTime desc,pro.project asc")
                        ->select()->toArray();
        $tmpList = [];

        $levelMap = DictApi::selectByParentCode("talent_arrange");
        $streetMap = DictApi::selectByParentCode("street");
        $where = [];
        $where[] = ["id", "in", array_column($list, "identifyCondition")];
        $icmap = \app\common\model\TalentCondition::where($where)->column("name", "id");

        $where = [];
        $where[] = ["id", "in", array_column($list, "enterpriseId")];
        $enterpriseMap = \app\common\model\Enterprise::where($where)->column("name", "id");
        foreach ($list as $item) {
            //组装数据
            if (!$tmpList[$item["id"]]) {
                $tmpList[$item["id"]]["curEnterpriseId"] = $item["curEnterpriseId"];
                $tmpList[$item["id"]]["info"] = [$item["year"], $streetMap[$item["address"]], $item["name"], $item["sex"] == 1 ? "男" : "女", $item["idCard"], $levelMap[$item["talentArrange"]],
                    $icmap[$item["identifyCondition"]], $item["identifyGetTime"], $item["identifyConditionName"], $item["identifyMonth"], AllowanceTypeEnum::getTypeName($item["allowanceType"]), $item["months"], $item["money"],
                    $item["moneyDesc"], $this->getCheckStateName($item["checkState"], $item["publicState"], $item["allowanceType"])];
            }
            if (!$tmpList[$item["id"]]["enterprise"][$item["enterpriseId"]]) {
                $tmpList[$item["id"]]["enterprise"][$item["enterpriseId"]] = [
                    "startTime" => $item["startTime"],
                    "endTime" => $item["endTime"],
                    "entryTime" => $item["entryTime"],
                    "isQuit" => $item["isQuit"]
                ];
            }
            $tmpList[$item["id"]]["enterprise"][$item["enterpriseId"]]["projects"][$item["project"]] = $item["pre_months"];
        }
        $rows = [];
        $colorset = [];
        foreach ($tmpList as $id => $item) {
            foreach ($item["enterprise"] as $enterpriseId => $enterprise) {
                $row = $item["info"];
                $row[] = $this->user["uid"] == $enterpriseId ? "本单位" : $enterpriseMap[$enterpriseId];
                for ($i = 0; $i < count($projects); $i++) {
                    if (strpos($enterprise["projects"][$projects[$i]], "=") === false) {
                        $months = array_filter(explode(",", $enterprise["projects"][$projects[$i]]));
                        for ($m = 1; $m <= 12; $m++) {
                            $_month = str_pad($m, 2, "0", STR_PAD_LEFT);
                            if (in_array($_month, $months)) {
                                $row[] = "✔";
                                $colorset[] = [sprintf("%s%d", getExcelColumnByIndex($infoCols + $i * 12 + $m - 1), count($rows) + 3), "29dd23"];
                            } else {
                                $row[] = "";
                            }
                        }
                    } else {
                        $months = array_filter(explode(",", $enterprise["projects"][$projects[$i]]));
                        $_months = [];
                        foreach ($months as $month) {
                            $kv = explode("=", $month);
                            $_months[$kv[0]] = $kv[1];
                        }
                        for ($m = 1; $m <= 12; $m++) {
                            $_month = str_pad($m, 2, "0", STR_PAD_LEFT);
                            $days = $_months[$_month];
                            if ($days && $days > 0) {
                                $row[] = $days . "天";
                                $colorset[] = [sprintf("%s%d", getExcelColumnByIndex($infoCols + $i * 12 + $m - 1), count($rows) + 3), "29dd23"];
                            } else {
                                $row[] = "";
                            }
                        }
                    }
                }
                $rows[] = $row;
            }
        }
        $cols = $infoCols + count($projects) * 12 - 1;
        $settings = [
            "width" => [["A", 8], ["C", 12], ["D", 6], ["E", 20], ["F", 12], ["G", 70], ["H", 12], ["I", 15], ["J", 12], ["K", 12], ["P", 30]],
            "height" => [18],
            "freeze" => "D3",
            "color" => $colorset
        ];
        for ($i = 0; $i < count($projects) * 12; $i++) {
            $settings["width"][] = [getExcelColumnByIndex($infoCols + $i), 6]; //批设置项目的宽度
        }
        $settings["background-color"][] = [sprintf("%s2:%s2", getExcelColumnByIndex($infoCols), getExcelColumnByIndex($cols)), "E1F1DE"];
        export($columns, $rows, "津补贴申报名单", $settings);
    }

    private function getCheckStateName($checkState, $publicState, $allowanceType) {
        switch ($checkState) {
            case 1:
                return "待提交";
            case 5:
            case 13:
            case 15:
            case 20:
            case 25:
            case 35:
                return "审核中";
            case 10:
                return "已驳回";
            case - 1:
                if ($publicState >= 3) {
                    return "审核不通过";
                } else {
                    return "审核中";
                }
                break;
            case 30:
                if ($publicState == 1) {
                    return "待核查征信";
                } else if ($publicState == 2) {
                    return "待公示";
                } else if ($publicState == 3) {
                    return "公示中";
                } else if ($publicState == 4) {
                    return $allowanceType != 3 ? "待兑现" : "不予兑现";
                } else if ($publicState == 5) {
                    return "已兑现";
                }
            default:
                return "未知状态";
        }
    }

}