<?php

namespace app\common\api;

use app\common\model\Batch;
use app\common\state\CommonConst;

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

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

    public static function getList($request) {
        $order = trim($request->param("order")) ?: "desc";
        $offset = trim($request->param("offset")) ?: 0;
        $limit = trim($request->param("limit")) ?: 10;
        $type = trim($request->param("type"));
        $active = trim($request->param("active"));
        $where = [];
        $where[] = ["source", "=", session("user")["type"]];
        if ($type) {
            $where[] = ["type", "=", $type];
        }
        if ($active) {
            $where[] = ["active", "=", $active];
        }
        $count = Batch::where($where)->count();
        $list = Batch::where($where)->limit($offset, $limit)->order("createTime " . $order)->select()->toArray();
        $projects = DictApi::selectByParentCode("declare_type"); //申报类型
        foreach ($list as $key => $item) {
            $list[$key]["type"] = $projects[$item["type"]];
        }
        return ["total" => $count, "rows" => $list];
    }

    public static function create($params) {
        if (!$params["type"])
            return ["msg" => "申报类别不能为空"];
        if (!$params["batch"])
            return ["msg" => "批次不能为空"];
        if (!in_array(session("user")["type"], [CommonConst::ENTERPRISE_NORMAL, CommonConst::ENTERPRISE_JC]) && $params["type"] == \app\common\state\ProjectState::LIVINGALLOWANCE) {
            return ["msg" => "当前账号类型没有操作权限"];
        }
        $where[] = ["type", "=", $params["type"]];
        $where[] = ["batch", "=", $params["batch"]];
        $where[] = ["source", "=", $params["source"]];
        $count = Batch::where($where)->count();
        if ($count > 0) {
            return ["msg" => "该申报类别的批次重复"];
        }
        if (!strtotime($params["startTime"]) && $params["startTime"]) {
            return ["msg" => "申报开始时间错误"];
        }
        if (!strtotime($params["endTime"]) && $params["endTime"]) {
            return ["msg" => "申报截止时间错误"];
        }
        if (!strtotime($params["submitEndTime"]) && $params["submitEndTime"]) {
            return ["msg" => "提交截止时间错误"];
        }
        if (!strtotime($params["publicStartTime"]) && $params["publicStartTime"]) {
            return ["msg" => "公示开始时间错误"];
        }
        if (!strtotime($params["publicEndTime"]) && $params["publicEndTime"]) {
            return ["msg" => "公示截止时间错误"];
        }
        if ($params["active"] == 1 && !self::checkIsAllowedActive(["startTime" => $params["startTime"], "endTime" => $params["endTime"], "type" => $params["type"], "source" => $params["source"]])) {
            return ["msg" => "申报时间不能与已经开启的批次存在交叉时间，批次添加失败！"];
        }

        $id = getStringId();
        $data["id"] = $id;
        $data["type"] = $params["type"];
        $data["source"] = $params["source"];
        $data["batch"] = $params["batch"];
        $data["active"] = $params["active"] ?: 2;
        $data["description"] = $params["description"];
        $data["type"] = $params["type"];
        $data["startTime"] = $params["startTime"];
        $data["endTime"] = $params["endTime"];
        $data["submitEndTime"] = $params["submitEndTime"];
        $data["publicStartTime"] = $params["publicStartTime"];
        $data["publicEndTime"] = $params["publicEndTime"];
        $data["averageWage"] = $params["averageWage"];
        $data["createTime"] = date("Y-m-d H:i:s");
        $data["createUser"] = session("user")["uid"];
        Batch::insert($data);
        return ["code" => 200, "msg" => "成功"];
    }

    public static function update($params) {
        $batch = self::getOne($params["id"]);
        if (!$batch)
            return ["msg" => "修改的批次信息不存在"];
        if (!$params["type"])
            return ["msg" => "申报类别不能为空"];
        if (!$params["batch"])
            return ["msg" => "批次不能为空"];
        if (!in_array(session("user")["type"], [CommonConst::ENTERPRISE_NORMAL, CommonConst::ENTERPRISE_JC]) && $params["type"] == \app\common\state\ProjectState::LIVINGALLOWANCE) {
            return ["msg" => "当前账号类型没有操作权限"];
        }
        $where[] = ["type", "=", $params["type"]];
        $where[] = ["batch", "=", $params["batch"]];
        $where[] = ["source", "=", $params["source"]];
        $where[] = ["id", "<>", $params["id"]];
        $count = Batch::where($where)->count();
        if ($count > 0) {
            return ["msg" => "该申报类别的批次重复"];
        }
        if (!strtotime($params["startTime"]) && $params["startTime"]) {
            return ["msg" => "申报开始时间错误"];
        }
        if (!strtotime($params["endTime"]) && $params["endTime"]) {
            return ["msg" => "申报截止时间错误"];
        }
        if (!strtotime($params["submitEndTime"]) && $params["submitEndTime"]) {
            return ["msg" => "提交截止时间错误"];
        }
        if (!strtotime($params["publicStartTime"]) && $params["publicStartTime"]) {
            return ["msg" => "公示开始时间错误"];
        }
        if (!strtotime($params["publicEndTime"]) && $params["publicEndTime"]) {
            return ["msg" => "公示截止时间错误"];
        }
        if ($batch["active"] == 1 && !self::checkIsAllowedActive(["id" => $params["id"], "startTime" => $params["startTime"], "endTime" => $params["endTime"], "type" => $params["type"], "source" => $params["source"]])) {
            return ["msg" => "申报时间不能与已经开启的批次存在交叉时间，批次编辑失败！"];
        }

        $data["id"] = $params["id"];
        $data["type"] = $params["type"];
        $data["source"] = $params["source"];
        $data["batch"] = $params["batch"];
        $data["active"] = $batch["active"] ?: 2;
        $data["description"] = $params["description"];
        $data["type"] = $params["type"];
        $data["startTime"] = $params["startTime"];
        $data["endTime"] = $params["endTime"];
        $data["submitEndTime"] = $params["submitEndTime"];
        $data["publicStartTime"] = $params["publicStartTime"];
        $data["publicEndTime"] = $params["publicEndTime"];
        $data["averageWage"] = $params["averageWage"];
        $data["updateTime"] = date("Y-m-d H:i:s");
        $data["updateUser"] = session("user")["uid"];
        \think\facade\Db::table("sys_batch")->update($data);
        return ["code" => 200, "msg" => "成功"];
    }

    public static function delete($id) {
        Batch::where(["id" => $id])->delete();
        return ["code" => 200, "msg" => "成功"];
    }

    public static function setActive($id, $active) {
        if ($active == 1 && !self::checkIsAllowedActive($id)) {
            return ["msg" => "申报时间不能与已经开启的批次存在交叉时间，批次启动失败！"];
        }
        $data["id"] = $id;
        $data["active"] = $active ?: 2;
        Batch::update($data);
        return ["code" => 200, "msg" => "成功"];
    }

    /**
     * 
     * @param type $param 当值为整数时，表示id；当值为array时，表示各种参数的集合
     * @return boolean
     */
    public static function checkIsAllowedActive($params) {
        if (is_array($params)) {
            if ($params["id"]) {
                $where[] = ["id", "<>", $params["id"]];
            }
            $startTime = $params["startTime"];
            $endTime = $params["endTime"];
            $where[] = ["type", "=", $params["type"]];
            $where[] = ["source", "=", $params["source"]];
        } else {
            $id = $params;
            $batch = self::getOne($id);
            $startTime = $batch["startTime"];
            $endTime = $batch["endTime"];
            $where[] = ["id", "<>", $id];
            $where[] = ["type", "=", $batch["type"]];
            $where[] = ["source", "=", $batch["source"]];
        }
        $where[] = ["active", "=", 1];
        //$whereRaw = sprintf("startTime between '%s'and '%s' or endTime between '%s' and '%s'", $startTime, $endTime, $startTime, $endTime);存在错误
        //$exists = Batch::where($where)->whereRaw($whereRaw)->fetchSql(true)->find();
        $activeList = Batch::where($where)->select()->toArray();
        $startTime = strtotime($startTime);
        $endTime = strtotime($endTime);
        $allowed = true;
        while ($active = array_shift($activeList)) {
            $_startTime = strtotime($active["startTime"]);
            $_endTime = strtotime($active["endTime"]);
            if (($startTime >= $_startTime && $startTime <= $_endTime) || ($endTime >= $_startTime && $endTime <= $_endTime)) {
                $allowed = false;
                break;
            }
        }
        return $allowed;
    }

    public static function setOtherNoActive($except_id) {
        $open = self::getOne($except_id);
        if ($open) {
            $where[] = ["type", "=", $open["type"]];
            $where[] = ["source", "=", $open["source"]];
            $where[] = ["id", "<>", $except_id];
            $data["active"] = 2;
            Batch::where($where)->update($data);
        }
    }

    /**
     * 
     * @param type $type 申报类别
     * @param type $talentType 人才类型
     */
    public static function checkBatchValid($params, $talentType) {
        $now = time();
        $where = [];
        if ($params["type"] == \app\common\state\ProjectState::LIVINGALLOWANCE) {
            if ($talentType == CommonConst::ENTERPRISE_JC) {
                $talentType = CommonConst::ENTERPRISE_JC;
            } else {
                $talentType = CommonConst::ENTERPRISE_NORMAL; //除电路外如果是硕博生活补贴申请，跟晋江人才同批次判断（也就是跟人社同批次）
            }
        }
        $where[] = ["source", "=", $talentType];
        if ($params["type"]) {
            $where[] = ["type", "=", $params["type"]];
        }
        if ($params["year"]) {
            //检查指定批次是否存在，再比对时间
            $where[] = ["batch", "=", $params["year"]];
            $batch = Batch::where($where)->order("startTime desc")->order("endTime desc")->find();
            if (!$batch)
                return ["msg" => "不存在该申报批次"];
            if (strtotime($batch["startTime"]) > $now)
                return ["msg" => sprintf("申报还未开始，日期为：%s - %s", $batch["startTime"], $batch["endTime"])];
            if (strtotime($batch["endTime"]) < $now && isset($params["first_submit_time"]) && !$params["first_submit_time"])
                return ["msg" => "申报已结束，无法申报"];
            if ($batch["submitEndTime"] && strtotime($batch["submitEndTime"]) < $now)
                return ["msg" => "提交时间已截止，无法操作"];
        } else {
            $where[] = ["active", "=", 1];
            $date = date("Y-m-d H:i:s");
            $whereRaw = sprintf("startTime < '%s' and endTime > '%s'", $date, $date);
            $batch = Batch::where($where)->whereRaw($whereRaw)->order("startTime desc")->order("endTime desc")->find();
            if (!$batch)
                return ["msg" => "该申报未启动"];
            if (strtotime($batch["startTime"]) > $now)
                return ["msg" => sprintf("申报还未开始，日期为：%s - %s", $batch["startTime"], $batch["endTime"])];
            if (strtotime($batch["endTime"]) < $now)
                return ["msg" => "申报已结束，无法申报"];
        }
        return ["code" => 200, "batch" => $batch["batch"], "id" => $batch["id"]];
    }

    /**
     * 
     * @param type $type 申报项目
     * @param type $talentType 人才类型
     * @return type
     */
    public static function getValidBatch($type, $talentType, $batch = "") {
        $now = date("Y-m-d H:i:s");
        $where = [];
        if ($type == \app\common\state\ProjectState::LIVINGALLOWANCE) {
            if ($talentType == CommonConst::ENTERPRISE_JC) {
                $talentType = CommonConst::ENTERPRISE_JC;
            } else {
                $talentType = CommonConst::ENTERPRISE_NORMAL; //除电路外如果是硕博生活补贴申请，跟晋江人才同批次判断（也就是跟人社同批次）
            }
        }
        if ($batch) {
            $where[] = ["batch", "=", $batch];
        } else {
            $where[] = ["active", "=", 1];
        }
        $where[] = ["type", "=", $type];
        $where[] = ["source", "=", $talentType];
        $where[] = ["startTime", "<", $now];
        $where[] = ["endTime", ">", $now];
        return $batch = Batch::where($where)->order("createTime desc")->findOrEmpty();
    }

    /**
     * 
     * @param type $type 申报项目
     * @param type $talentType 人才类型
     * @return type
     */
    public static function getValidBatchs($type, $talentType) {
        $now = date("Y-m-d H:i:s");
        $where = [];
        if ($type == \app\common\state\ProjectState::LIVINGALLOWANCE) {
            if ($talentType == CommonConst::ENTERPRISE_JC) {
                $talentType = CommonConst::ENTERPRISE_JC;
            } else {
                $talentType = CommonConst::ENTERPRISE_NORMAL; //除电路外如果是硕博生活补贴申请，跟晋江人才同批次判断（也就是跟人社同批次）
            }
        }
        if ($batch) {
            $where[] = ["batch", "=", $batch];
        } else {
            $where[] = ["active", "=", 1];
        }
        $where[] = ["type", "=", $type];
        $where[] = ["source", "=", $talentType];
        return $batch = Batch::where($where)->order("createTime desc")->select()->toArray();
    }

}
