<?php

namespace app\common\api;

use app\common\api\DictApi;
use app\admin\model\Enterprise;
use think\facade\Db;
use app\common\model\IntegralRecord;
use app\common\state\IntegralState;

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

    public static function getOne($id) {
        $result = IntegralRecord::where("id", "=", $id)->find();
        $result["enterprise"] = EnterpriseApi::getOne($result["enterprise_id"]);
        $result["enterprise"]["streetName"] = DictApi::findDictByCode($result["enterprise"]["street"])["name"];
        if ($result) {
            $result["items"] = $result->detail;
        }
        return $result;
    }

    public static function getList($params) {
        $where = [];
        $order = $params["order"] ?: "desc";
        $offset = $params["offset"] ?: 0;
        $limit = $params["limit"] ?: 10;
        $where[] = ["e.type", "=", session("user")["type"]];
        if (session("user")["usertype"] == 2) {
            $where[] = ["enterprise_id", "=", session("user")["uid"]];
        }
        $where[] = ["delete", "=", 0];
        $count = IntegralRecord::alias("ir")->leftJoin("un_enterprise e", "e.id=ir.enterprise_id")->where($where)->count();
        $list = IntegralRecord::where($where)->field("ir.*,if(ir.updateTime is not null,ir.updateTime,ir.createTime) as orderTime")->limit($offset, $limit)->order("orderTime " . $order)->select();
        foreach ($list as $key => $item) {
            $list[$key]["apply_year"] = BatchApi::getOne($item["batch_id"])["batch"];
            $tmp_items = [];
            foreach ($item["detail"] as $_item) {
                $integral_item_info = getCacheById("IntegralItem", $_item["item_id"]);
                $tmp_items[] = sprintf("%s（%s%s）", $integral_item_info["name"], $_item["amount"], $integral_item_info["unit"]);
            }
            $list[$key]["details"] = implode("，", $tmp_items);
            $list[$key]["type"] = session("user")["type"];
            $last_log = TalentLogApi::getLastLog($item["id"], \app\common\state\ProjectState::INTEGRAL);
            $list[$key]["real_state"] = $last_log["state"];
            $list[$key]["last_state"] = $last_log["last_state"];
        }
        return ["total" => $count, "rows" => $list];
    }

    public static function getListByProcess($params) {
        $process = $params["process"] ?: 1;
        $where = [];
        switch ($process) {
            case 1://初审阶段
                $where[] = ["checkState", "in", [IntegralState::SUBMIT]];
                break;
            case 2://复审阶段
                $where[] = ["checkState", "in", [IntegralState::VERIFY_PASS]];
                break;
            case 3://复审后征信公示等状态
                $where[] = ["checkState", "in", [IntegralState::REVERIFY_PASS, IntegralState::ZX_PASS, IntegralState::ZX_FAIL, IntegralState::ANNOUNCED, IntegralState::ANNOUNCED_REVERIFY_PASS, IntegralState::ANNOUNCED_REVERIFY_FAIL, IntegralState::PUBLISH_PASS, IntegralState::PUBLISH_FAIL, IntegralState::SUCCESS]];
                break;
        }
        $order = $params["order"] ?: "desc";
        $offset = $params["offset"] ?: 0;
        $limit = $params["limit"] ?: 10;
        $where[] = ["delete", "=", 0];
        $count = IntegralRecord::where($where)->count();
        $list = IntegralRecord::where($where)->field("*,if(updateTime is not null,updateTime,createTime) as orderTime")->limit($offset, $limit)->order("orderTime " . $order)->select();
        foreach ($list as $key => $item) {
            $list[$key]["apply_year"] = BatchApi::getOne($item["batch_id"])["batch"];
            $tmp_items = [];
            foreach ($item["detail"] as $_item) {
                $integral_item_info = getCacheById("IntegralItem", $_item["item_id"]);
                $tmp_items[] = sprintf("%s（%s%s）", $integral_item_info["name"], $_item["amount"], $integral_item_info["unit"]);
            }
            $list[$key]["details"] = implode("，", $tmp_items);
            $list[$key]["type"] = session("user")["type"];
            $last_log = TalentLogApi::getLastLog($item["id"], \app\common\state\ProjectState::INTEGRAL);
            $list[$key]["real_state"] = $last_log["state"];
            $list[$key]["last_state"] = $last_log["last_state"];
        }
        return ["total" => $count, "rows" => $list];
    }

    public static function checkIsEditable($id) {
        $info = self::getOne($id);
        if (!$info || !in_array($info["checkState"], [0, IntegralState::SAVE]))
            return false;
        return true;
    }

    static public function chkIsOwner($id, $uid) {
        $info = self::getOne($id);
        if ($info["enterprise_id"] != $uid)
            return null;
        return $info;
    }

    public static function calIntegral($enterprise_id, $cardType, $cardNumber, $itemId) {
        $item = getCacheById("IntegralItem", $itemId);
        $projectMax = 0; //项目总上限
        $itemMax = 0; //标准总上限
        if ($item) {
            $project = getCacheById("IntegralProject", $item["projectId"]);
            if ($project["limit"] == 1) {
                //项目下所有规则总上限
                $where = [];
                $where[] = ["r.enterprise_id", "=", $enterprise_id];
                $where[] = ["r.card_type", "=", $cardType];
                $where[] = ["r.card_number", "=", $cardNumber];
                $where[] = ["r.checkState", ">=", IntegralState::SUCCESS];
                $where[] = ["i.projectId", "=", $project["id"]];
                if ($project["yearly"] == 1) {
                    //年度重置只算当年度
                    $startTime = date("Y-01-01 00:00:00");
                    $endTime = date("Y-12-31 23:59:59");
                    $where[] = ["r.createTime", "between", [$startTime, $endTime]];
                }
                $totalPoints = Db::table("new_integral_detail")->alias("d")->leftJoin("new_integral_record r", "r.id=d.record_id")->leftJoin("new_integral_item i", "i.id=d.item_id")->where($where)->sum("d.point");
            }
            if ($item["limit"] == 1) {
                //规则上限
            }

            if ($project["limit"] == 2) {
                //项目没有设置上限
                if ($item["limit"] == 2) {
                    //标准没有设置上限
                } else {
                    //标准有设置上限，并检查标准有没有年度重置
                    if ($item["yearly"] == 1) {
                        //标准有年度重置
                    } else {
                        //标准没有重置
                    }
                }
            } else {
                //有设置上限，并检查有没有年度重置
                if ($project["yearly"] == 1) {
                    //有年度重置
                } else {
                    //没有重置
                }
            }
        }
        return 0;
    }

}
