<?php

namespace app\model\api;

use think\Model;

    /**
    * 教育模型
    */
class EducationModel extends Model
{
     protected $table = 'table_education_cate';
     const CATE_TABLE_NAME = 'table_education_cate';


    public static function getInstance()
    {
        return new self;
    }

    /**
     * 获取所有分类
     *
     * @return mixed
     */
    public function getCate()
    {
        $items = $this->table(self::CATE_TABLE_NAME)
            ->where(['status' => 'Y'])
            ->order('sort', 'asc')
            ->column('id,pid,name,sort', 'id');

        $tree = array();
        foreach ($items as $key => $item) {
            $items[$key]['oriName'] = $item['name'];
            if (isset ($items [$item ['pid']])) {
                $items [$item ['pid']] ['children'] [$item ['id']] = &$items [$item ['id']];
            } else {
                $tree [$item ['id']] = &$items [$item ['id']];
            }
        }

        // 递归将children属性转换为数组
        $tree = array_values($tree);
        $tree = $this->convertChildrenToArray($tree);

        return $tree;
    }

    /**
     * 递归将children属性转换为数组
     *
     * @param $items
     * @return mixed
     */
    private function convertChildrenToArray($items)
    {
        foreach ($items as &$item) {
            if (isset($item['children']) && is_array($item['children'])) {
                $item['children'] = array_values($item['children']);
                $item['children'] = $this->convertChildrenToArray($item['children']);
            }
        }
        return $items;
    }

//    public function getGrList($userId)
//    {
//        return $this->where('user', $userId)->order('create_time', 'desc')->select()->toArray();
//    }


    /**
     * 获取所有文章列表
     *
     * @param int|null $excludeCourseId 需要排除的课程 ID
     * @return array
     */
    public function getCourseList($excludeCourseId = null)
    {
        $query = $this->where(['status' => 'Y']);

        if ($excludeCourseId !== null) {
            $query->where('id', '<>', $excludeCourseId);
        }

        $query->order('sort', 'asc');

        return $query->select()->toArray();
    }


    /**
     * 获取顶级类
     */
    public function getTopCate()
    {
        $items = $this->where(['status' => 'Y', 'pid' => 0])
            ->order('sort', 'asc')
            ->field('id,pid,name,sort')
            ->select()
            ->toArray();

        return $items;
    }


    /**
     *获取指定ID列表
     */
    public function getSubcatesByTopCate($cates, &$subcates = array())
    {
        foreach ($cates as $cate) {
            $subcates[] = $cate['id'];
            if (isset($cate['son'])) {
                $this->getSubcatesByTopCate($cate['son'], $subcates);
            }
        }
        return $subcates;
    }

//    /**
//     * 去除分类名称中的前缀
//     *
//     * @param string $dirtyName 脏分类名称
//     * @return string
//     */
//    public static function getPureCateName($dirtyName)
//    {
//        return strtr($dirtyName, [self::CATE_TREE_PREFIX => '']);
//    }



    /**
     * 根据 ID 获取记录
     *
     * @param int $id 记录 ID
     * @return mixed
     */
    public function get($id)
    {
        $result = $this->where(['id' => $id])->find();
        if ($result) {
            return $result;
        }
        return null;
    }


    /**
     * 修改分类
     *
     * @param int $id 类目ID
     * @param int $sort 排序
     * @param string $name 分类名称
     * @return bool
     */
    public function editCate($id, $sort, $name)
    {
        $data = [
            'sort' => $sort,
            'name' => $name,
        ];
        $cate = $this->get($id);
        if (!$cate) {
            return false;
        }
        $cate->allowField(['sort', 'name']);
        $result = $cate->save($data);
        if ($result !== false) {
            return true;
        }
        return false;
    }

    /**
     * 增加一个分类
     *
     * @param array $data
     * @return bool|mixed
     */
    public function addCate(array $data)
    {
        $data['status'] = 'Y';
        if ($this->save($data)) {
            return $this->id;
        } else {
            return false;
        }
    }


    public function getCourseListByCates($cates = array(), $pageSize = 3, $page = 1, $userInfo=null)
    {
        $firstRow = (($page < 1) ? 0 : ($page - 1)) * $pageSize;
        $where = array(
            'course_audit' => 1,
            'course_status' => 1,
            'course_only_for_employee' => 0,
            'course_cate_id' => array('in', $cates)
        );
        $fields = 'course_id, course_cate_id, course_topic, course_intro, course_cover, course_speaker_intro, course_play_count, ';
        if ($userInfo){
            // 假如当前用户是从业人员，那就删除条件
            if ($userInfo["is_employee"]){
                unset($where["course_only_for_employee"]);
            }

            // 根据用户类型选择不同字段
            switch ($userInfo["user_type"]){
                case "1":
                    $fields .= "course_price_2 as course_price";
                    break;
                case "2":
                    $fields .= "course_price_3 as course_price";
                    break;
                default :
                    $fields .= "course_price";
            }
        }else{
            $fields .= "course_price";
        }

        $result = array();
        if ($cates) {
            $result = $this->where( $where )
                ->order('course_id desc')
                ->limit($firstRow, $pageSize)
                ->column($fields);
        }

        return (array)$result;
    }




    public function getCourseListLikeTopic($topic, $pageSize = 50, $page = 1)
    {
        $firstRow = (($page < 1) ? 0 : ($page - 1)) * $pageSize;
        $result = array();
        if ($topic) {
            $result = $this->where(
                array(
                    'course_audit' => 1,
                    'course_status' => 1,
                    'course_topic' => array('like', '%' . $topic . '%')
                )
            )
                ->order('course_id desc')
                ->limit($firstRow, $pageSize)
                ->column(
                    'course_id,
                    course_cate_id,
                    course_topic,
                    course_price,
                    course_intro,
                    course_cover,
                    course_speaker_intro,
                    course_play_count,
                    gr_id'
                );
        }

        return (array)$result;
    }





}



