<?php
namespace app\model;

/**
 * 业绩详情
 * Class AchievementInfo
 * @package app\model
 */
class AchievementInfo extends Base
{
    public static function onAfterInsert($achievementInfo)
    {
        $achievementInfo->sort = $achievementInfo->id;
        $achievementInfo->save();
    }

    /**
     * 根据业绩ID查询是否有关联的详情记录
     * @param int $achievementId
     * @return bool
     */
    public static function hasByAchievementId($achievementId)
    {
        $resp = false;
        $count = self::where('achievement_id', $achievementId)->count();
        if($count) {
            $resp = true;
        }
        return $resp;
    }

    /**
     * 删除业绩相关的详情记录
     * @param $achievementId
     * @return bool
     */
    public static function delByAchievementId($achievementId)
    {
       return self::where('achievement_id', $achievementId)->delete();
    }

    /**
     * 获取业绩相关的详情记录
     * @param int $achievementId
     * @param bool $onlyVisible
     * @param array $order
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getByAchievementId($achievementId, $onlyVisible = false, $order = [])
    {
        if(empty($order)) {
            $order = ['sort'=>'desc'];
        }
        return self::where('achievement_id', $achievementId)
        ->when($onlyVisible, function ($query) {
            $query->where('visible', 1);
        })
        ->order($order)
        ->select()
        ->toArray();
    }

    /**
     * 查询业绩相关的项目并以业绩ID进行分组返回
     * @param array $achievementIds
     * @param bool $onlyVisible
     * @param array $order
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getGroupByAchievementIds($achievementIds, $onlyVisible = false, $order = [])
    {
        $data = [];
        if(empty($order)) {
            $order = ['sort'=>'desc'];
        }
        $items = self::whereIn('achievement_id', $achievementIds)
            ->when($onlyVisible, function ($query) {
                $query->where('visible', 1);
            })
            ->order($order)
            ->select()
            ->toArray();
        if(count($items) > 0) {
            foreach ($items as $item) {
                $data[$item['achievement_id']][] = $item;
            }
        }
        return $data;
    }
}