<?php

declare(strict_types=1);

namespace app\common\model\book;

use mb\helper\Collection;
use think\facade\Db;
use Exception;
use think\facade\Log;

/**
 * Class Volume
 * @package app\common\model\book
 */
class Volume
{
    /**
     * @param array $filter
     * @param int $pIndex
     * @param int $pSize
     * @param int $total
     * @return array
     */
    public static function search(array $filter, int $pIndex = 1, int $pSize = 10, &$total = 0)
    {
        $where = [];
        if (!empty($filter['subjectId'])) {
            $where[] = ['subject_id', '=', $filter['subjectId']];
        }
        if (!empty($filter['title'])) {
            $where[] = ['title', '=', $filter['title']];
        }
        if (!empty($filter['ids'])) {
            $where[] = ['subject_id', 'in', "{$filter['ids']}"];
        }
        try {
            $total = Db::table('book_volume')
                ->where($where)->count();
            $query = Db::table('book_volume')->where($where);
            if (!empty($pIndex)) {
                $query->page($pIndex, $pSize);
            }
            $dataSet = $query->select()->toArray();
            if (!empty($dataSet)) {
                $dataSet = array_map(function ($row) {
                    $row = Collection::keyStyle($row, Collection::NAME_STYLE_JAVA);
                    return $row;
                }, $dataSet);
                return $dataSet;
            } else {
                return [];
            }
        } catch (Exception $e) {
            Log::channel('myError')->write($e->getMessage(), \think\Log::ERROR);
        }
        return [];
    }

    /**
     * @param array $data
     * @param int $id
     * @return int|string
     */
    public static function modify(array $data, int $id = 0)
    {
        $data = Collection::keyStyle($data, Collection::NAME_STYLE_C);
        $data = Collection::elements(['subject_id', 'title'], $data);
        try {
            if (empty($id)) {
                $id = Db::table('book_volume')->insertGetId($data);
            } else {
                Db::table('book_volume')->where(['id' => $id])->update($data);
            }
            return $id;
        } catch (Exception $e) {
            Log::channel('myError')->write($e->getMessage(), \think\Log::ERROR);
        }
        return 0;
    }

    /**
     * @param array $where
     * @return bool
     */
    public static function delete(array $where)
    {
        try {
            $offect = Db::table('book_volume')->where($where)->delete();
            if ($offect === 1) {
                return true;
            } else {
                return false;
            }
        } catch (Exception $e) {
            Log::channel('myError')->write($e->getMessage(), \think\Log::ERROR);
        }
        return false;
    }
}