<?php

namespace App\Services\BasicManagement;

use Illuminate\Database\Eloquent\Model;
use App\Models\BasicManagement\ProductionContent;
use BlueCity\Core\Service\Service;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use App\Models\Common;
use Illuminate\Support\Facades\DB;
use App\Http\Requests\Validators\BasicManagement\ProductionContentValidator;
use BlueCity\Core\Inc\ErrorInc;

// 基础管理-案例管理-作品内容
class ProductionContentService extends Service
{
    public static $instance;
    public $modelMain = null;
    public $mainValidator = null;

    public function __construct()
    {
        $this->modelMain = new ProductionContent();
        $this->mainValidator = new ProductionContentValidator();
    }

    /**
     * @return mixed
     */
    public static function getInstance()
    {
        if (is_null(static::$instance)) {
            static::$instance = new static;
        }
        return static::$instance;
    }

    /**
     * 根据条件搜索数据内容
     *
     * @param array $param 条件
     * @param array $columns 内容
     * @param int $page 页码
     * @param int $pageSize 页容量
     * @return mixed
     */
    public function searchPage($user_info, $search_data, $show_count = 10)
    {
        // 作品内容表，视频、图文
        $list_data = DB::table('wash_production_content')
            ->where('prco_shop_id', $user_info->adm_shop_id)
            ->where('prco_delete', 1) //是否删除：1正常2已删除
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['name'])) {
                    $query->where('prco_name', 'like', '%' . $search_data['name'] . '%');
                }
            })
            ->where(function ($query) use ($search_data) {
                if (!empty($search_data['state'])) {//状态1启用2停用
                    $query->where('prco_state', $search_data['state']);
                }
                if (!empty($search_data['type'])) {//类型：1视频2图文
                    $query->where('prco_type', $search_data['type']);
                }
                if (!empty($search_data['classify_prma_id'])) { //所属分类id
                    $query->where('prco_classify_prma_id', $search_data['classify_prma_id']);
                }
                if (!empty($search_data['module_prma_id'])) { //所属模块id
                    $query->where('prco_module_prma_id', $search_data['module_prma_id']);
                }
            })
            ->where(function ($query) use ($search_data) { //备注
                if (!empty($search_data['remark'])) {
                    $query->where('prco_remark', 'like', '%' . $search_data['remark'] . '%');
                }
            })
            ->select('prco_id', 'prco_classify_prma_id', 'prco_module_prma_id', 'prco_name', 'prco_type', 'prco_state', 'prco_content', 'prco_path', 'prco_remark', 'prco_covor')
            ->orderBy('prco_id', 'desc')
            ->paginate($show_count);
        $list_items = $list_data->items();
        $parent_data = [];
        if ($list_items) {
            $prco_classify_prma_id = array_filter(array_unique(array_column($list_items, 'prco_classify_prma_id'))); //作品分类id
            $prco_module_prma_id = array_filter(array_unique(array_column($list_items, 'prco_module_prma_id'))); //作品模块
            $prco_parent_id = array_unique(array_merge($prco_classify_prma_id, $prco_module_prma_id));
            if ($prco_parent_id) {
                // 查询上级作品分类数据
                $parent_data = DB::table('wash_production_manage')
                    ->where('prma_shop_id', $user_info->adm_shop_id)
                    ->whereIn('prma_id', $prco_parent_id)
                    ->select('prma_id', 'prma_name')
                    ->get()->toArray();
            }
            foreach ($list_items as $key => $value) {
                $prco_content = json_decode($value->prco_content, true);
                if (isset($prco_content['image'])) {
                    if (!empty($prco_content)) {
                        $image = $prco_content['image'];
                        $new_image = [];
                        if (!empty($image)) {
                            foreach ($image as $key1 => $value1) {
                                $new_image[] = addHttpurl($value1);
                            }
                        }
                        $new_prco_content['content'] = $prco_content['content'];
                        $new_prco_content['image'] = $new_image;
                        if (isset($prco_content['nothing1'])) {
                            $new_prco_content['nothing1'] = $prco_content['nothing1'];
                        }
                        $list_items[$key]->prco_content = json_encode($new_prco_content, true);
                    }
                } else {
                    $new_prco_content = [];
                    if (!empty($prco_content)) {
                        foreach ($prco_content as $k => $v) {
                            $new_image = [];
                            if (isset($v['image'])) {
                                if (!is_array($v['image'])) {
                                    $image = json_decode($v['image'], true);
                                } else {
                                    $image = $v['image'];
                                }
                                if (!empty($image)) {
                                    foreach ($image as $key1 => $value1) {
                                        $new_image[] = addHttpurl($value1);
                                    }
                                }
                            }
                            $new_prco_content[$k]['content'] = $v['content'];
                            $new_prco_content[$k]['image'] = $new_image;
                            if (isset($prco_content['nothing1'])) {
                                $new_prco_content[$k]['nothing1'] = $v['nothing1'];
                            }
                        }
                        $list_items[$key]->prco_content = json_encode($new_prco_content, true);
                    }
                }
                
                if (!empty($value->prco_path)) {
                    $list_items[$key]->prco_path = addHttpurl($value->prco_path);
                }

            }
        }
        $data['current_page'] = $list_data->currentPage();  //当前页面页码
        $data['last_page'] = $list_data->lastPage();        //表示最后一页的页码
        $data['total'] = $list_data->total();               //总数据个数
        $data['current_number'] = $show_count;        //一页显示多少个
        $data['data'] = $list_items;                        //返回数据
        $data['parent_data'] = $parent_data;                        //上级数据
        return $data;
    }

    // 详情
    public static function info($user_info, $request)
    {
        $find_data = DB::table('wash_production_content')
            ->where('prco_shop_id', $user_info->adm_shop_id)
            ->where('prco_type', $request['type'])
            ->where('prco_id', $request['id'])
            ->where('prco_delete', 1) //是否删除：1正常2已删除
            ->select('prco_id', 'prco_classify_prma_id', 'prco_module_prma_id', 'prco_name', 'prco_type', 'prco_state', 'prco_content', 'prco_path', 'prco_remark', 'prco_covor')
            ->first();
        if (empty($find_data)) {
            return ['code'=>ErrorInc::DATA_EMPTY, 'msg'=>'未查到数据', 'data'=>''];
        }
        if (!empty($find_data->prco_path)) {
            $find_data->prco_path = addHttpurl($find_data->prco_path);
        }
        $prco_content = json_decode($find_data->prco_content, true);

        if (isset($prco_content['image'])) {
            if (!empty($prco_content)) {
                $image = $prco_content['image'];
                $new_image = [];
                if (!empty($image)) {
                    foreach ($image as $key1 => $value1) {
                        $new_image[] = addHttpurl($value1);
                    }
                }
                $new_prco_content['content'] = $prco_content['content'];
                $new_prco_content['image'] = $new_image;
                if (isset($prco_content['nothing1'])) {
                    $new_prco_content['nothing1'] = $prco_content['nothing1'];
                }
                $find_data->prco_content = json_encode($new_prco_content, true);
            }
        } else {
            $new_prco_content = [];
            if (!empty($prco_content)) {
                foreach ($prco_content as $k => $v) {
                    $new_image = [];
                    if (isset($v['image'])) {
                        $image = $v['image'];
                        if (!empty($image)) {
                            foreach ($image as $key1 => $value1) {
                                $new_image[] = addHttpurl($value1);
                            }
                        }
                    }
                    $new_prco_content[$k]['content'] = $v['content'];
                    $new_prco_content[$k]['image'] = $new_image;
                    if (isset($v['nothing1'])) {
                        $new_prco_content[$k]['nothing1'] = $v['nothing1'];
                    }
                }
                $find_data->prco_content = json_encode($new_prco_content, true);
            }
        }
        $new_find_data[] = (array)$find_data;
        $prco_classify_prma_id = array_filter(array_unique(array_column($new_find_data, 'prco_classify_prma_id'))); //作品分类id
        $prco_module_prma_id = array_filter(array_unique(array_column($new_find_data, 'prco_module_prma_id'))); //作品模块
        $prco_parent_id = array_unique(array_merge($prco_classify_prma_id, $prco_module_prma_id));
        $parent_data = [];
        if ($prco_parent_id) {
            // 查询上级作品分类数据
            $parent_data = DB::table('wash_production_manage')
                ->where('prma_shop_id', $user_info->adm_shop_id)
                ->whereIn('prma_id', $prco_parent_id)
                ->select('prma_id', 'prma_name')
                ->get()->toArray();
        }
        $data['data'] = $find_data;
        $data['parent_data'] = $parent_data;
        return ['code'=>200, 'msg'=>'success', 'data'=>$data];
    }

    /**
     * 检查是不是存在同名内容
     * @param $name 待检测名称
     * @param $type 类型：1作品分类2作品模块3视频4图文
     * @param int $id 排除这个id
     * @return mixed
     */
    public static function nameExists($user_info, $request, $id = 0)
    {
        if ($id == 0) {
            return ProductionContent::where('prco_cid', $user_info->adm_cid)
                ->where('prco_shop_id', $user_info->adm_shop_id)
                ->where('prco_type', $request['type'])
                ->where('prco_name', $request['name'])
                ->where('prco_delete', 1) //是否删除：1正常2已删除
                ->exists();
        } else {
            return ProductionContent::where('prco_cid', $user_info->adm_cid)
                ->where('prco_shop_id', $user_info->adm_shop_id)
                ->where('prco_type', $request['type'])
                ->where('prco_name', $request['name'])
                ->where('prco_delete', 1) //是否删除：1正常2已删除
                ->where('prco_id', '<>', $id)
                ->exists();
        }
    }

    // 新增
    public static function add($user_info, $request)
    {
        $data['prco_cid'] = $user_info->adm_cid;
        $data['prco_superior_shop_id'] = $user_info->adm_shop_id;
        $data['prco_shop_id'] = $user_info->adm_shop_id;
        $data['prco_name'] = $request['name']; //分类名，模块名
        $data['prco_type'] = $request['type']; //类型：1作品分类2作品模块
        // if (!empty($request['classify_prma_id'])) { //所属分类id
            // $data['prco_classify_prma_id'] = $request['classify_prma_id'];
        // }
        if (!empty($request['module_prma_id'])) { //所属模块id
            $data['prco_module_prma_id'] = $request['module_prma_id'];
        }
        if (!empty($request['prco_path'])) { //视频路径、封面图片路径
            $data['prco_path'] = $request['prco_path'];
        }
        if (!empty($request['prco_covor'])) { //视频封面图片路径
            $data['prco_covor'] = $request['prco_covor'];
        }
        if (!empty($request['prco_content'])) { //图文内容
            $data['prco_content'] = $request['prco_content'];
        }
        if (!empty($request['remark'])) { //备注
            $data['prco_remark'] = $request['remark'];
        }
        $data['prco_update_time'] = date('Y-m-d H:i:s');
        $res = DB::table('wash_production_content')->insert($data);
        if ($res) {
            return ['code'=>200, 'msg'=>'新增成功', 'data'=>''];
        } else {
            return ['code'=>500, 'msg'=>'新增失败', 'data'=>''];
        }
    }

    // 编辑
    public static function edit($user_info, $request)
    {
        $data['prco_cid'] = $user_info->adm_cid;
        $data['prco_superior_shop_id'] = $user_info->adm_shop_id;
        $data['prco_shop_id'] = $user_info->adm_shop_id;
        $data['prco_name'] = $request['name']; //分类名，模块名
        $data['prco_type'] = $request['type']; //类型：1作品分类2作品模块
        // if (!empty($request['classify_prma_id'])) { //所属分类id
        //     $data['prco_classify_prma_id'] = $request['classify_prma_id'];
        // }
        if (!empty($request['module_prma_id'])) { //所属模块id
            $data['prco_module_prma_id'] = $request['module_prma_id'];
        }
        if (!empty($request['prco_path'])) { //视频路径、封面图片路径
            $data['prco_path'] = $request['prco_path'];
        }
        if (!empty($request['prco_covor'])) { //视频封面图片路径
            $data['prco_covor'] = $request['prco_covor'];
        }
        if (!empty($request['prco_content'])) { //图文内容
            $data['prco_content'] = $request['prco_content'];
        }
        if (!empty($request['remark'])) { //备注
            $data['prco_remark'] = $request['remark'];
        } else {
            $data['prco_remark'] = '';
        }
        $data['prco_update_time'] = date('Y-m-d H:i:s');
        $res = DB::table('wash_production_content')
            ->where('prco_shop_id', $user_info->adm_shop_id)
            ->where('prco_type', $request['type'])
            ->where('prco_id', $request['id'])
            ->update($data);
        if ($res) {
            return ['code'=>200, 'msg'=>'编辑成功', 'data'=>''];
        } else {
            return ['code'=>500, 'msg'=>'编辑失败', 'data'=>''];
        }
    }

    /**
     * [getFieldsByIdAll 根据id查询数据，查询多个数据]
     * @param  [object] $user_info [用户信息]
     * @param  [array] $ids       [数组，id]
     * @param  array $fields    [数组，查询字段]
     * @return [type]            [description]
     */
    public static function getFieldsByIdAll($user_info, $request, $fields = '*')
    {
        $entity = ProductionContent::whereIn('prco_id', $request['id'])
            ->where('prco_shop_id', $user_info->adm_shop_id)
            ->where('prco_type', $request['type'])
            ->where('prco_delete', 1)
            ->select($fields)
            ->get()->toArray();
        return $entity;
    }

    /**
     * [getFieldsById 根据id查询数据]
     * @param  [object] $user_info [用户信息]
     * @param  [int] $ids       [id]
     * @param  array $fields    [数组，查询字段]
     * @return [type]            [description]
     */
    public function getFieldsById($user_info, $request, $fields = '*')
    {
        // $entity = ProductionContent::where('prco_id', $request['id'])
        $entity = DB::table('wash_production_content as wpc')
            ->leftjoin('wash_production_manage as wpm', 'wpm.prma_id', '=', 'wpc.prco_module_prma_id')
            // ->where('prco_shop_id', $user_info->adm_shop_id)
            ->where('prco_id', $request['id'])
            // ->where('prco_type', $request['type'])
            ->where('prco_delete', 1)
            ->select($fields)
            ->first();
        if (!empty($entity->prco_path)) {
            $entity->prco_path = addHttpurl($entity->prco_path);
        }
        $prco_content = json_decode($entity->prco_content, true);

        if (isset($prco_content['image'])) {
            if (!empty($prco_content)) {
                $image = $prco_content['image'];
                $new_image = [];
                if (!empty($image)) {
                    foreach ($image as $key1 => $value1) {
                        $new_image[] = addHttpurl($value1);
                    }
                }
                $new_prco_content['content'] = $prco_content['content'];
                $new_prco_content['image'] = $new_image;
                if (isset($prco_content['nothing1'])) {
                    $new_prco_content['nothing1'] = $prco_content['nothing1'];
                }
                $entity->prco_content = json_encode($new_prco_content, true);
            }
        } else {
            $new_prco_content = [];
            if (!empty($prco_content)) {
                foreach ($prco_content as $k => $v) {
                    $new_image = [];
                    if (isset($v['image'])) {
                        if (!is_array($v['image'])) {
                            $image = json_decode($v['image'], true);
                        } else {
                            $image = $v['image'];
                        }
                        if (!empty($image)) {
                            foreach ($image as $key1 => $value1) {
                                $new_image[] = addHttpurl($value1);
                            }
                        }
                    }
                    $new_prco_content[$k]['content'] = $v['content'];
                    $new_prco_content[$k]['image'] = $new_image;
                    if (isset($v['nothing1'])) {
                        $new_prco_content[$k]['nothing1'] = $v['nothing1'];
                    }
                }
                $entity->prco_content = json_encode($new_prco_content, true);
            }
        }
        // $prco_content = json_decode($entity->prco_content, true);
        // if ($entity->prco_type == 1) {//1视频2图文
        //     $new_image[] = addHttpurl($entity->prco_path);
        //     $new_prco_content['content'] = '';
        //     $new_prco_content['image'] = $new_image;
        //     $entity->prco_content = json_encode($new_prco_content, true);
        // } else {
        //     if (!empty($prco_content)) {
        //         foreach ($prco_content as $key => $value) {
        //             $image = $value['image'];
        //             $new_image = [];
        //             if (!empty($image)) {
        //                 foreach ($image as $key1 => $value1) {
        //                     $new_image[] = addHttpurl($value1);
        //                 }
        //             }
        //             $new_prco_content['content'] = $value['content'];
        //             $new_prco_content['image'] = $new_image;
        //             if (isset($value['nothing1'])) {
        //                 $new_prco_content['nothing1'] = $value['nothing1'];
        //             }
        //             $entity->prco_content = json_encode($new_prco_content, true);
        //         }
        //     }
        // }
        return $entity;
    }

    // 启用
    public static function start($user_info, $request)
    {
        $data['prco_state'] = 1; //状态1启用2停用
        $data['prco_update_time'] = date('Y-m-d H:i:s');
        $res = DB::table('wash_production_content')
            ->where('prco_shop_id', $user_info->adm_shop_id)
            ->where('prco_type', $request['type'])
            ->whereIn('prco_id', $request['id'])
            ->update($data);
        if ($res) {
            return ['code'=>200, 'msg'=>'启用成功', 'data'=>''];
        } else {
            return ['code'=>500, 'msg'=>'启用失败', 'data'=>''];
        }
    }

    // 停用
    public static function stop($user_info, $request)
    {
        $data['prco_state'] = 2; //状态1启用2停用
        $data['prco_update_time'] = date('Y-m-d H:i:s');
        $res = DB::table('wash_production_content')
            ->where('prco_shop_id', $user_info->adm_shop_id)
            ->where('prco_type', $request['type'])
            ->whereIn('prco_id', $request['id'])
            ->update($data);
        if ($res) {
            return ['code'=>200, 'msg'=>'停用成功', 'data'=>''];
        } else {
            return ['code'=>500, 'msg'=>'停用失败', 'data'=>''];
        }
    }

    // 删除
    public static function remove($user_info, $request)
    {
        $data['prco_delete'] = 2; //是否删除：1正常2已删除
        $data['prco_update_time'] = date('Y-m-d H:i:s');
        $res = DB::table('wash_production_content')
            ->where('prco_shop_id', $user_info->adm_shop_id)
            ->where('prco_type', $request['type'])
            ->whereIn('prco_id', $request['id'])
            ->update($data);
        if ($res) {
            return ['code'=>200, 'msg'=>'删除成功', 'data'=>''];
        } else {
            return ['code'=>500, 'msg'=>'删除失败', 'data'=>''];
        }
    }
}
