<?php

declare(strict_types=1);

namespace app\common\model\book;

use app\common\model\account\User as UserModel;
use app\control\model\User;
use mb\helper\Collection;
use think\facade\Db;
use Exception;
use think\facade\Log;

/**
 * Class Chapter
 * @package app\common\model\book
 */
class Chapter
{
    /**
     * caption 节标题
     * subject_id 科目id
     * volume_id  章id
     * volume_title 章名称
     * @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['caption'])) {
            $where[] = ['caption', '=', $filter['caption']];
        }
        if (!empty($filter['subject_id'])) {
            $where[] = ['chapter.subject_id', '=', $filter['subject_id']];
        }
        if (!empty($filter['volume_id'])) {
            $where[] = ['volume_id', '=', $filter['volume_id']];
        }
        if (!empty($filter['volume_title'])) {
            $where[] = ['volume.title', '=', $filter['volume_title']];
        }
        if (!empty($filter['ids'])) {
            $where[] = ['chapter.subject_id', 'in', "{$filter['ids']}"];
        }
        try {
            $total = Db::table('book_chapter')->alias('chapter')->join(
                'book_volume volume',
                'chapter.volume_id = volume.id'
            )->join('exam_subjects subject', 'chapter.subject_id = subject.id')->where($where)->count();
            $query = Db::table('book_chapter')->alias('chapter')->join(
                'book_volume volume',
                'chapter.volume_id = volume.id'
            )->join('exam_subjects subject', 'chapter.subject_id = subject.id')->where($where);
            if (!empty($pIndex)) {
                $query->page($pIndex, $pSize);
            }
            $dataSet = $query->field('chapter.*,volume.title as volumeTitle,subject.title as subjectTitle')
                ->select()->toArray();
            if (!empty($dataSet)) {
                $dataSet = array_map(function ($row) {
                    $row = Collection::keyStyle($row, Collection::NAME_STYLE_JAVA);
                    if (!empty($row['source'])) {
                        $row['source'] = unserialize($row['source']);
                    }
                    $userInfo = UserModel::fetch($row['founder']);
                    $row['founderTitle'] = isset($userInfo['uid']) ? $userInfo['uid'] : '';
                    return $row;
                }, $dataSet);
                return $dataSet;
            } else {
                return [];
            }
        } catch (Exception $e) {
            Log::channel('myError')->write($e->getMessage(), \think\Log::ERROR);
        }
        return [];
    }

    /**
     * subject_id
     * volume_id
     * caption
     * founder
     * @param array $data
     * @return int|string
     */
    public static function add(array $data)
    {
        $data = Collection::keyStyle($data, Collection::NAME_STYLE_C);
        $data = Collection::elements(['subject_id', 'volume_id', 'caption', 'founder'], $data);
        $data['content'] = '';
        $data['source'] = '';
        $data['time_created'] = time();
        $data['view'] = 0;
        try {
            return Db::table('book_chapter')->insertGetId($data);
        } catch (Exception $e) {
            Log::channel('myError')->write($e->getMessage(), \think\Log::ERROR);
        }
        return 0;
    }

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

    /**
     * @param array $where
     * @return bool
     */
    public static function delete(array $where)
    {
        try {
            $offect = Db::table('book_chapter')->where($where)->delete();
            if ($offect === 1) {
                return true;
            } else {
                return false;
            }
        } catch (Exception $e) {
        }
        return false;
    }

    /**
     * @param int $id
     * @return bool
     */
    public static function check(int $id)
    {
        try {
            $detail = Db::table('book_chapter')->where(['id' => $id])->find();
            $user = User::fetchCurrent();
            if (($user['role'] != 'root') && ($detail['founder'] != $user['id'])) {
                return false;
            } else {
                return true;
            }
        } catch (Exception $e) {
            Log::channel('myError')->write($e->getMessage(), \think\Log::ERROR);
        }
        return false;
    }

    public static function fetch(int $id)
    {
        try {
            $info = Db::table('book_chapter')->where(['id' => $id])->find();
            if (!empty($info)) {
                $info['source'] = unserialize($info['source']);
            }
            return $info;
        } catch (Exception $e) {
            Log::channel('myError')->write($e->getMessage(), \think\Log::ERROR);
        }
        return [];
    }
}