<?php
/**
 * GamePriceModel.php  UTF-8
 * 设置计费点
 *
 * @date    : 2018/8/22 22:29
 *
 * @license 这不是一个自由软件,未经授权不许任何使用和传播。
 * @author  : chenbingling <cbl@huosdk.com>
 * @version : HUOSDK 8.0
 */

namespace huo\model\game;

use huo\model\common\CommonModel;
use huolib\constant\CacheConst;
use huolib\constant\CommonConst;
use think\Cache;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;

class GamePriceModel extends CommonModel {
    protected $name = 'game_price';
    protected $tag  = CacheConst::KEY_CACHE_GAME_PRICE_TAG;
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    /**
     * 添加计费点
     *
     * @param $data
     *
     * @return bool
     */
    public function addData($data) {
        if (empty($data)) {
            return false;
        }
        $_rs = self::insertAll($data, true);

        return $_rs;
    }

    /**
     * 更新计费点
     *
     * @param $id
     * @param $data
     *
     * @return bool|GamePriceModel
     */
    public function updateData($id, $data) {
        if (empty($id)) {
            return false;
        }
        $_map['id'] = $id;
        $_rs = self::update($data, $_map, true);
        if ($_rs) {
            Cache::clear($this->tag);
        }

        return $_rs;
    }

    /**
     * 删除计费点
     *
     * @param $id
     *
     * @return bool|int
     */
    public function deleteData($id) {
        if (empty($id)) {
            return false;
        }
        $_map['id'] = $id;
        $_rs = self::where($_map)->delete();
        if ($_rs) {
            Cache::clear($this->tag);
        }

        return $_rs;
    }

    /**
     * 获取计费点详情
     *
     * @param $map
     *
     * @return array|bool|false|\PDOStatement|string|\think\Model
     */
    public function getGamePrice($map) {
        if (empty($map)) {
            return false;
        }
        $_key = $this->tag.'_'.md5(json_encode($map));
        try {
            $_data = self::where($map)
                         ->cache($_key, CommonConst::CONST_DAY_SECONDS, $this->tag)
                         ->find();
            if (is_object($_data)) {
                $_data = $_data->toArray();
            }

            return $_data;
        } catch (DataNotFoundException $e) {
            return false;
        } catch (ModelNotFoundException $e) {
            return false;
        } catch (DbException $e) {
            return false;
        } catch (Exception $e) {
            return false;
        }
    }
}